Code

Made autonet button work again
[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       /* Remove A record which equals $this->ipHostNumber
160        */
161       $ptr = $this->get_pTRRecord();
162       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
163         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
164           unset($this->dnsEntry['RECORDS'][$key]);
165         }
166         if(($rec['type'] == "pTRRecord") && ($rec['value'] == $ptr)){
167           unset($this->dnsEntry['RECORDS'][$key]);
168         }
169       }
171       /* Get Record types 
172        */
173       $this->RecordTypes  = DNS::getDnsRecordTypes();
175       /* If there is at least one entry in this -> types, we have DNS enabled 
176        */
177       if($this->dnsEntry['exists']){
178         $this->DNS_is_account = true;
179       }else{
180         $this->DNS_is_account = false;
181       }
182     }
184     /* Create a list of used mac and ip addresses.
186        ! We use this optically huge amount of code to fetch all 
187        Mac and IP addresses, because a simple search for mac and IP
188        over the whole ldap server was 10 to 20 times slower.
189      */
190     $deps  = array();
191     $ou = preg_replace("/,.*$/","",get_ou("systemRDN"));
192     $a_ous = array(get_ou("serverRDN"),
193                   get_ou("terminalRDN"),
194                   get_ou("workstationRDN"),
195                   get_ou("printerRDN"),
196                   get_ou("phoneRDN"),
197                   get_ou("componentRDN"));
198   
199     $ldap = $this->config->get_ldap_link();
200     $ldap->cd($this->config->current['BASE']);
201     $ldap->search("(&(objectClass=organizationalUnit)(".$ou."))",array("dn"));
202     while($attrs = $ldap->fetch()){
203       foreach($a_ous as $allowed){
204         $deps[] = $allowed.$attrs['dn'];
205       }
206     }
208     foreach($deps as $dep){
209       $ldap->cd($dep);
210       $ldap->search("(|(macAddress=*)(ipHostNumber=*))",array("macAddress","ipHostNumber"));
211       while($attrs = $ldap->fetch()){
212         if(isset($attrs['ipHostNumber'][0])){
213           $this->used_ip_mac["ip:".$attrs['ipHostNumber'][0]] = "ip:".$attrs['ipHostNumber'][0];
214         }
215         if(isset($attrs['macAddress'][0])){
216           $this->used_ip_mac["mac:".$attrs['macAddress'][0]] = "mac:".$attrs['macAddress'][0];
217         }
218       } 
219     }
221     /* Save initial ip and mac values, to be able 
222         check if the used values are already in use */ 
223     $this->orig_ipHostNumber   = $this->ipHostNumber;  
224     $this->orig_macAddress     = $this->macAddress;
225  
226     /* Store initally account settings 
227      */
228     $this->initially_was_account = $this->DNS_is_account;
230     if($this->DNS_is_account){
231       new log("view","unknown/".get_class($this),$this->dn);
232     }
233   }
236   function netmaskIsCoherent($idZone) 
237   {
238     $netmask = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($idZone)));
239     if(!strstr($this->ipHostNumber, $netmask)){
240       return false;
241     }else{
242       return true;
243     }
244   }
247   function getVarsForSaving($attrs) 
248   {
249     foreach($this->attributes as $attr){
250       if(!empty($this->$attr)){
251         $attrs[$attr] = $this->$attr;
252       }
253     }
254     return($attrs); 
255   }
257   function execute()
258   {
259           /* Call parent execute */
260     $smarty= get_smarty();
261     $smarty->assign("autonetACL",$this->acl_is_writeable("macAddress") && $this->acl_is_writeable("ipHostNumber")?"rw":"");
263     $tmp = $this->plInfo();
264     foreach($tmp['plProvidedAcls'] as $name => $translation){
265       $smarty->assign($name."ACL",$this->getacl($name));
266     }
268     $display= "";
270     /**********
271      * Additional ipHostNumber handling 
272      **********/
273       
274     /* Add a new one */
275     if($this->acl_is_writeable("ipHostNumber")){
276       foreach($_POST as $name => $value){
277         if(preg_match("/^additionalHostNumbers_add/",$name)){
278           $this->additionalHostNumbers[] = "";
279           break;
280         }
282         /* Delete given entry */
283         if(preg_match("/^additionalHostNumbers_del_/",$name)){
284           $id = preg_replace("/^^additionalHostNumbers_del_([0-9]*)_.*/","\\1",$name);
285           if(isset($this->additionalHostNumbers[$id])){
286             unset($this->additionalHostNumbers[$id]);
287             $this->additionalHostNumbers = array_values($this->additionalHostNumbers);
288           }
289           break;
290         } 
291       }
292     }
293  
294     $smarty->assign("additionalHostNumbers",$this->additionalHostNumbers);
295     $smarty->assign("staticAddress", ""); 
296  
297     /**********
298      * Autonet completion
299      **********/
300  
301     /* Check for autonet button */
302     if (isset($_POST['autonet']) && ($this->acl_is_writeable("ipHostNumber") || $this->acl_is_writeable("macAddress"))){
303       $d= new gosaSupportDaemon(TRUE, 0.5);
304       $res= $d->_send("<xml><header>gosa_network_completition</header>".
305           "<source>GOSA</source><target>GOSA</target><hostname>".$this->cn."</hostname></xml>", TRUE);
306       if (isset($res['XML']['IP']) && $this->acl_is_writeable("ipHostNumber")){
307         $this->ipHostNumber= $res['XML']['IP'];
308       }
309       if (isset($res['XML']['MAC']) && $this->acl_is_writeable("macAddress")){
310         $this->macAddress= $res['XML']['MAC'];
311       }
312     }
314   
315     /**********
316      * DHCP Handling
317      **********/
318  
319     if(isset($_POST['dhcpEditOptions']) && $this->acl_is_readable("dhcpSetup")){
320       if(count($this->dhcpHostEntry) == 0){
321         $this->dialog = new dhcpHost($this->parent,$this->dhcpParentNode,TRUE);
322       }else{
323         $this->dialog = new dhcpHost($this->parent,$this->dhcpHostEntry,TRUE);
324       }
325       $this->dialog->cn   = $this->cn;
326       $this->dialog->read_only     = !$this->acl_is_writeable("dhcpSetup");
327       $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress; 
328       if(!empty($this->ipHostNumber)){
329         $this->dialog->statements->set('fixed-address', $this->ipHostNumber); 
330       }
331     }
333     if(isset($_POST['cancel_dhcp'])){
334       $this->dialog = FALSE; 
335     }
337     if(isset($_POST['save_dhcp']) && $this->acl_is_writeable("dhcpSetup") && is_object($this->dialog)){
338       $this->dialog->save_object();
339       $msgs = $this->dialog->check(array());
340       if(count($msgs)){
341         foreach($msgs as $msg){
342           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
343         }
344       }else{
345         $this->dhcpHostEntry = $this->dialog->save();
346         $this->dialog = FALSE; 
347       }
348     }
350     if(is_object($this->dialog)){
351       $this->dialog->save_object();
352       return($this->dialog->execute());
353     }
354  
355     $smarty->assign("dhcpEnabled",    $this->dhcpEnabled && $this->acl_is_readable("dhcpSetup"));
356     $smarty->assign("dhcp_is_Account",$this->dhcp_is_Account);
357     $smarty->assign("dhcpParentNode", $this->dhcpParentNode);
358     $smarty->assign("dhcpParentNodes",$this->dhcpParentNodes);
359     $smarty->assign("dhcpParentNodeCnt",count($this->dhcpParentNodes));
361     /**********
362      * DNS Handling
363      **********/
365     /* There is no dns available
366      */
367     $smarty->assign("DNS_is_account",$this->DNS_is_account);
368     $smarty->assign("DNSenabled",$this->DNSenabled && $this->acl_is_readable("dnsSetup"));
370     if($this->DNSenabled == false){
372       /* Is IP address must ? */
373 #      $smarty->assign("DNS_is_account",false);
374       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
376       /* Assign smarty all non DNs attributes */
377       foreach($this->attributes as $attr){
378         $smarty->assign($attr,$this->$attr);
379       }
380       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
382       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
383     }else{
384  #     $smarty->assign("DNS_is_account",true);
386       /* Add new empty array to our record list */
387       if(isset($_POST['AddNewRecord']) && $this->acl_is_writeable("dnsSetup")){
388         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
389       }
391       /* propose_ip */
392       if(isset($_POST['propose_ip']) && $this->acl_is_writeable("ipHostNumber")){
393         foreach($this->Zones as $key => $name){
394           if($name == $this->dnsEntry['zoneName']){
395             $net = DNS::FlipIp(str_replace(".in-addr.arpa","",DNS::getNameFromMix($key)));
396             $this->ipHostNumber = $this->generateRandomIP($net);
397           }
398         }
399       }
401       /* Handle all posts */
402       $only_once =true;
403       if($this->acl_is_writeable("dnsSetup")){
404         foreach($_POST as $name => $value){
406           /* Check if we have to delete a record entry */
407           if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
409             /* Avoid performing this once again */
410             $only_once = false;
412             /* Extract id for specified entry */
413             $id = preg_replace("/RemoveRecord_/","",$name);
414             $id = preg_replace("/_.*$/","",$id);
416             /* Delete this record, mark edited entries to be able to delete them */
417             if(isset($this->dnsEntry['RECORDS'][$id])){
418               unset($this->dnsEntry['RECORDS'][$id]);
419             }
420           }
421         }
422       }
423       /* Assign smarty all non DNs attributes */
424       foreach($this->attributes as $attr){
425         $smarty->assign($attr,$this->$attr);
426       }
428       /* Assign smarty all DNS attributes */
429       foreach($this->DNSattributes as $attr){
430         $smarty->assign($attr,htmlentities($this->dnsEntry[$attr]));
431       }
433       /* Assign all needed vars */
434  #     $smarty->assign("DNSAccount",$this->DNS_is_account);
435       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
436   
437       $smarty->assign("Zones",$this->Zones);
438       $smarty->assign("ZoneCnt",count($this->Zones));
439       $smarty->assign("ZoneKeys",($this->Zones));
440       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
442       /* Create zone array */
443       $idZones = array();
444       foreach($this->Zones as $id => $zone){
445         if($this->netmaskIsCoherent($id)) {
446           $idZones[$id] = $zone;
447         }else{
448           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
449         }
450       }
451       $smarty->assign("Zones",$idZones);
452       $smarty->assign("ZoneKeys", $this->Zones);
454       $tmp = $this->generateRecordsList();
456       $changeStateForRecords = $tmp['changeStateForRecords'];
458       $smarty->assign("records",$tmp['str']);
459       $smarty->assign("changeStateForRecords",$changeStateForRecords);
460       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
462       $smarty->assign("autonetACL",$this->acl_is_writeable("macAddress") && $this->acl_is_writeable("ipHostNumber")?"rw":"");
464       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
465     }
467     return($display);
468   }
471   function remove_from_parent()
472   {
473     if($this->DNS_is_account){
475       $ldap = $this->config->get_ldap_link();
477       $tmp = array();
478       $this->dnsEntry['exists'] = false;
479       $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
480   
481       /* Delete dns */
482       foreach($tmp['del'] as $dn => $del){
483         $ldap->cd($dn);
484         $ldap->rmdir_recursive($dn);
485         new log("remove","unknown/".get_class($this),$dn);
486         if (!$ldap->success()){
487           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_DEL, get_class()));
488         }
489       }
490     }
491   }
494   /* Save data to object */
495   function save_object()
496   {
498     if(isset($_POST['network_tpl_posted'])){
500       /* Save all posted vars */
501       plugin::save_object();
503       /******
504         Additional IP Host Numbers 
505        ******/
507       /* Get posts for all additionally added ipHostNumbers */
508       if($this->acl_is_writeable("ipHostNumber")){
509         foreach($this->additionalHostNumbers as $id => $value){
510           if(isset($_POST['additionalHostNumbers_'.$id])){
511             $this->additionalHostNumbers[$id] = get_post('additionalHostNumbers_'.$id);
512           }
513         } 
514       } 
517       /******
518         DHCP posts
519        ******/
521       if($this->acl_is_writeable("dhcpSetup") && $this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
522         foreach($this->dhcpAttributes as $attr){
523           if(isset($_POST[$attr])){
524             $this->$attr = $_POST[$attr];
525           }
526         }
527         if(isset($_POST['dhcp_is_Account'])){
528           $this->dhcp_is_Account = TRUE;
529         }else{
530           $this->dhcp_is_Account = FALSE;
531         }
532       }
534       /* Ge all non dns attributes (IP/MAC)*/
535       foreach($this->attributes as $attr){
536         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
537           $this->$attr = $_POST[$attr];
538         }
539       }
542       /******
543         DNS posts
544        ******/
546       /* Check if DNS should be enabled / disabled 
547        *  -skip this, if the dns account is enforced.
548        */
549       if(!$this->hide_dns_check_box){
550         if($this->DNS_is_account && $this->acl_is_writeable("dnsSetup") && !isset($_POST['DNS_is_account'])){
551           $this->DNS_is_account = false;
552         }elseif(!$this->DNS_is_account && $this->acl_is_writeable("dnsSetup") && isset($_POST['DNS_is_account'])){
553           $this->DNS_is_account = true;
554         }
555       }
557       /* Get dns attributes */
558       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted'])) && $this->acl_is_writeable("dnsSetup")){
560         /* Check for posted record changes */
561         if(is_array($this->dnsEntry['RECORDS'])){
562           foreach($this->dnsEntry['RECORDS'] as $key => $value){
564             /* Check if type has changed */
565             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
566               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
567             }
568             /* Check if value has changed */
569             if(isset($_POST['RecordValue_'.$key])){
570               $this->dnsEntry['RECORDS'][$key]['value'] = get_post('RecordValue_'.$key);
571             }
572           }
573         }
575         /* Get all basic DNS attributes (TTL, Clas ..)*/
576         foreach($this->DNSattributes as $attr){
577           if(isset($_POST[$attr])){
578             $this->dnsEntry[$attr] = get_post($attr);
579           }
580         }
581       }
582       if($this->hide_dns_check_box){
583         $this->DNS_is_account = true;
584       }
585     }
586   }
589   /* Check supplied data */
590   function check()
591   {
592     /* Call common method to give check the hook */
593     $message= plugin::check();
595     /******
596       check additional IP Host Numbers 
597      ******/
599     foreach($this->additionalHostNumbers as $id => $value){
600       if(!tests::is_ip($value)){
601         $message[]= msgPool::invalid(sprintf(_("IP address %s"),($id +2)), "", "", "192.168.1.10");
602       }
603     }
606     /* Check if mac and ip are already used */
607     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
608         $this->ipHostNumber != $this->orig_ipHostNumber && 
609         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
610       $message[]= msgPool::duplicated(_("IP address"));
611     }
612     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
613         $this->macAddress != $this->orig_macAddress && 
614         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
615       $message[]= msgPool::duplicated(_("MAC address"));
616     }
618     /* Check if ip must be given
619      */  
620     if(($this->IPisMust)||($this->DNS_is_account)){
621       if (empty($this->ipHostNumber)){
622         $message[]= msgPool::required(_("IP address"));
623       }elseif (!tests::is_ip($this->ipHostNumber)){
624         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
625       }
626     }
628     /* Check if mac is empty 
629      */
630     if($this->MACisMust || $this->dhcp_is_Account){
631       if ($this->macAddress == "" ){
632         $message[]= msgPool::required(_("MAC address"));
633       }elseif(!tests::is_mac($this->macAddress)){
634         $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
635       }
636     }
638     /* only perfrom this checks if this is a valid DNS account */
639     if($this->DNS_is_account){
641       $checkArray = array();
642       $onlyOnce   = array();
644       //  $onlyOnce['cNAMERecord'] = 0;
645        $tmp = array_flip($this->Zones);
646        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
647        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
648          $tmp2 = preg_replace("/^.*\//","",$tmp2);
649          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
650        }
652       /* Walk through all entries and detect duplicates or mismatches
653        */  
654       foreach($this->dnsEntry['RECORDS'] as $name => $values){
656         /* Count record values, to detect duplicate entries for a specific record
657          */
658         if(!isset($checkArray[$values['type']][$values['value']])){
659           $checkArray[$values['type']][$values['value']] = 0;
660         }else{
661           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
662         }
664         /* Check if given entries in $onlyOnce are used more than once
665          */
666         if(isset($onlyOnce[$values['type']])){
667           $onlyOnce[$values['type']] ++;
668           if($onlyOnce[$values['type']] > 1){
669             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
670           }
671         }
673         /* Skip txt record ... 
674          */
675         if($values['type'] == "tXTRecord") continue;
677         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
678          */
679         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
680           #TODO: Where's the problem here?
681           $message[]=sprintf(_("The IP address '%s' will be added as 'A Record', this will be done automatically, please remove the record."), 
682                $this->ipHostNumber);
683         }
685         /* only lower-case is allowed in record entries ... 
686          */
687         if($values['value'] != strtolower($values['value'])){
688           #TODO: What's in values['value']? Something for a propper message?
689           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
690         }
691       }
692     }
693     return ($message);
694   }
697   /* Save to LDAP */
698   function save()
699   {
700     $ldap= $this->config->get_ldap_link();
701   
702     $dn = $this->parent->dn;
703  
704     /*******************/ 
705     /* IP-MAC HANDLING */
706     /*******************/ 
708     /* $dn was posted as parameter */
709     $this->dn = $dn;
710     
711     /* Save DNS setting & ip/Mac*/
712     plugin::save();
714     /* Add all additional ipHostNumbers now 
715      */
716     if(!empty($this->ipHostNumber)){
717       $this->attrs['ipHostNumber'] = array($this->ipHostNumber);
718     }
719     foreach($this->additionalHostNumbers as $value){
720       $this->attrs['ipHostNumber'][] = $value;
721     }
723     /* Do not add the objectClass ipHost if no ip address is given */
724     if(!isset($this->attrs['ipHostNumber'])){
725       $this->attrs['objectClass'] = array_remove_entries(array("ipHost"),$this->attrs['objectClass']);
726     }
728     /* Write back to ldap */
729     $ldap->cd($this->dn);
730     $this->cleanup();
731     $ldap->modify ($this->attrs); 
733     /****************/ 
734     /* DHCP HANDLING */
735     /****************/ 
736   
737     /* New entry */
738     if($this->dhcpEnabled && $this->acl_is_writeable("dhcpSetup")) {
740       if(count($this->dhcpHostEntry) == 0){
741         $this->dialog = new dhcpHost($this->parent,$this->dhcpParentNode,TRUE);
742         $this->dialog->cn = $this->cn;
743         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
744         if(!empty($this->ipHostNumber)){
745           $this->dialog->statements->set('fixed-address', $this->ipHostNumber);
746         }
747         $this->dialog->execute();
748         $this->dialog->save_object(); 
749         $this->dhcpHostEntry = $this->dialog->save();
750         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
751           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
752         }
753       }
755       /* Write mac address to dhcp settings */
756       if($this->dhcp_is_Account){
757         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
758             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
759           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
760           $this->dhcpHostEntry['MODIFIED'] = TRUE;
761         }
762       }
764       /* Updated IP host number */
765       if($this->dhcp_is_Account && $this->dhcpHostEntry['dhcpStatements']){
766         foreach($this->dhcpHostEntry['dhcpStatements'] as $id => $value){
767           if(preg_match("/^fixed-address/",$value)){
768             $this->dhcpHostEntry['dhcpStatements'][$id] = "fixed-address ".$this->ipHostNumber; 
769             $this->dhcpHostEntry['MODIFIED'] = TRUE;
770           }
771         }
772       }
774       /* Unset dhcpStatements if this attribute is empty  */
775       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
776           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
777         unset($this->dhcpHostEntry['dhcpStatements']);
778       }
779   
780       /* DHCP removed */
781       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
782         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
783         if (!$ldap->success()){
784           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
785         }
787         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
788         $tmp->handle_post_events("remove");
789       }
791       /* DHCP Added */
792       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
793         $attrs = $this->dhcpHostEntry;
794         unset($attrs['MODIFIED']);
795         unset($attrs['dn']);
796         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
797         $res = $ldap->add($attrs);
799         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
800         $tmp->handle_post_events("add");
802         if (!$ldap->success()){
803           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
804         }
805       }
807       /* DHCP still activated */
808       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
810         /* DHCP node changed */
811         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
812            ($this->cn != $this->OrigCn)){
813           $attrs = $this->dhcpHostEntry;
814           $attrs[$this->namingAttr] = $this->cn;
815           unset($attrs['dn']);
816           unset($attrs['MODIFIED']);
817           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
818           $res = $ldap->add($attrs);
820           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
821           $tmp->handle_post_events("modify");
823           if (!$ldap->success()){
824             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
825           }
826           if($res){
827             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
828             if (!$ldap->success()){
829               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
830             }
831           }
832         }
833          
834         /* SAME node but modified */ 
835         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
836             $this->initial_dhcpParentNode == $this->dhcpParentNode){
837           $attrs = $this->dhcpHostEntry;
838           unset($attrs['dn']);
839           unset($attrs['MODIFIED']);
840           $ldap->cd($this->dhcpHostEntry['dn']);
841           $ldap->modify($attrs);
842           
843           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
844           $tmp->handle_post_events("modify");
846           if (!$ldap->success()){
847             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
848           }
849         }    
850       }
851     }
852     $this->dialog = FALSE; 
854     /****************/ 
855     /* DNS HANDLING */
856     /****************/ 
858     /* If isn't DNS account but initially was DNS account 
859        remove all DNS entries 
860      */ 
861     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
862       return;
863     }elseif($this->acl_is_writeable("dnsSetup")){
865       /* Add ipHostNumber to aRecords
866        */
867       $backup_dnsEntry = $this->dnsEntry;
868       if(!empty($this->ipHostNumber)){
869         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
870         $ptr = $this->get_pTRRecord();
871         if(!empty($ptr)){
872           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
873         } 
874       }
876       /* Create diff and follow instructions 
877        * If Account was disabled, remove account by setting exists to false
878        */
879       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
880         $this->dnsEntry['exists'] = false;
881         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
882       }else{
883         $this->dnsEntry['exists'] = $this->DNS_is_account;
884         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
885       }   
887       /* move follwoing entries 
888        */
889       foreach($tmp['move'] as $src => $dst){
890         $this->recursive_move($src,$dst);
891       }
893       /* Delete dns */
894       foreach($tmp['del'] as $dn => $del){
895         $ldap->cd($dn);
896         $ldap->rmdir_recursive($dn);
897         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
898       }
900       /* Add || Update new DNS entries 
901        */
902       foreach($tmp['add'] as $dn => $attrs){
903         $ldap->cd($dn);
904         $ldap->cat($dn, array('dn'));
905         if(count($ldap->fetch())){
906           $ldap->cd($dn);
907           $ldap->modify ($attrs); 
908         }else{
909           $ldap->cd($dn);
910           $ldap->add($attrs);
911         }
912         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
913       }
916       /* Display errors 
917        */
918       if (!$ldap->success()){
919         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
920       }
922       $tmp2 = new servdns($this->config,$this->dn);
923       $tmp2->handle_post_events("modify");
925       $this->dnsEntry =  $backup_dnsEntry;
926     }
927   }
929   /*  Create html table with all used record types
930    */
931   function generateRecordsList()
932   {
933     $changeStateForRecords = "";
934     
935     if(!$this->DNS_is_account) {
936       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
937       return(array("str" => $str, "changeStateForRecords"=> ""));
938     }
939  
940     $str = "<table summary='' width='100%'>";
941     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
943         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
944         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
945         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
947         $str.=" <tr>".
948           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
949           "   <td><input type='text' value=\"".htmlentities($entry['value'])."\" name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
950           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
951           "</tr>";
952     }
954     $str.= "  <tr>".
955            "    <td colspan=2 width='50%'></td><td>".
956            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
957            "    </td>".
958            "  </tr>".
959            "</table>";
960      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
961   
962     return($ret);
963   }
966   /* Create a html select box which allows us to select different types of records 
967    */
968   function generateRecordListBox($selected,$name)
969   {
970     $str = "<select name='".$name."' id='".$name."'>";
971     foreach($this->RecordTypes as $type => $value){
972       $use = "";
973       if($type == $selected){
974         $use = " selected ";
975       }
976       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
977     }
978     $str.="</select>";
979     return($str); 
980   }
983   /* Return plugin informations for acl handling  */ 
984   static function plInfo()
985   {
986     $tmp =  array(
987         "plShortName"   => _("DNS"),
988         "plDescription" => _("DNS settings"),
989         "plSelfModify"  => FALSE,
990         "plDepends"     => array(),
991         "plPriority"    => 5,
992         "plSection"     => array("administration"),
993         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
995         "plProvidedAcls"=> array(
996           "ipHostNumber"  => _("IP address"),
997           "macAddress"    => _("MAC address"))
998         );
1000     /* Hide all dns/dhcp configurations if not available
1001      */
1002     if(class_available("servdns")){
1003       $tmp['plProvidedAcls']["dnsSetup"]    = _("DNS configuration");
1004     }
1005     if(class_available("servdhcp")){
1006       $tmp['plProvidedAcls']["dhcpSetup"]   = _("DHCP configuration");
1007     }
1008     return($tmp);
1009   }
1011   
1012   function get_dhcp_host_entry()
1013   {
1014     $attrs = array();
1015     $dn = $this->get_dhcp_host_entry_dn();
1016     if($dn){
1017       $ldap = $this->config->get_ldap_link();
1018       $ldap->cd($this->config->current['BASE']);
1019       $ldap->cat($dn,array("*"));
1020       if($ldap->count()){
1021         $attrs = $ldap->fetch();
1022         foreach($attrs as $key => $value){
1023           if(is_numeric($key) || ($key == "count")){
1024             unset($attrs[$key]);
1025           }
1026           if(is_array($value) && isset($value['count'])){
1027             unset($attrs[$key]['count']);
1028           }
1029         }
1030       }
1031     }
1032     return($attrs);
1033   }
1036   function get_dhcp_host_entry_dn()
1037   {
1038     $ldap = $this->config->get_ldap_link();
1039     $ldap->cd($this->config->current['BASE']);
1040     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("uid","cn","dn"));
1042     if($ldap->count()){
1043       $attr = $ldap->fetch();
1044       return($attr['dn']);
1045     }else{
1046       return("");
1047     }
1048   }  
1051   function get_dhcp_parent_node()
1052   {
1053     return(preg_replace("/^cn=".preg_quote($this->cn, '/').",/","",$this->get_dhcp_host_entry_dn()));
1054   }
1057   function get_dhcp_parent_nodes()
1058   {
1059     $ldap = $this->config->get_ldap_link();
1060     $ldap->cd($this->config->current['BASE']);
1061     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
1062     
1063     $dhcp_dns = array();
1064     while($attr = $ldap->fetch()){
1065       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
1066     }
1067  
1068     foreach($dhcp_dns as $key => $pri_dns){
1069       $ldap->cat($pri_dns,array("cn"));
1070       $tmp = $ldap->fetch();
1071       if(isset($tmp['cn'][0])){
1072         $dhcp_dns[$key] = $tmp['cn'][0];
1073       }else{
1074         unset($dhcp_dns[$key]);
1075       }
1076     }
1078     $tmp = $tmp2 = array();
1079     foreach($dhcp_dns as $dn => $cn){
1080       $ldap->cd($dn);
1081       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
1082                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
1083       while($attr = $ldap->fetch()){
1084         $tmp[$attr['dn']] = $attr['cn'][0];
1085       }
1086       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
1087     }
1088     return($tmp2);
1089   }
1091   
1092   /* this function returns the default ptr record entry */
1093   function get_pTRRecord()
1094   {
1095     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
1096       $ldap = $this->config->get_ldap_link();
1097       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
1098       $attrs = $ldap->fetch();
1099       $tmp = array_flip($this->Zones);
1100       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
1101       $tmp = trim(preg_replace("/\.in-addr.arpa$/","",$tmp));
1102       $ptr = preg_replace("/^".preg_quote(DNS::FlipIp($tmp), '/')."\./","",$this->ipHostNumber);
1103       return($ptr);
1104     }else{
1105       return(FALSE);
1106     }
1107   }
1109   
1110   function generateRandomIP($net = "")
1111   {
1112     $str = $net;
1113     $cnt = 4;
1115     // first gather all IPs 
1116     $ldap = $this->config->get_ldap_link();
1117     $ocs = 
1118       "(objectClass=goFonHardware)".
1119       "(objectClass=goServer)".
1120       "(objectClass=GOhard)".
1121       "(objectClass=gotoTerminal)".
1122       "(objectClass=gotoWorkstation)".
1123       "(objectClass=gotoPrinter)".
1124       "(objectClass=ipHost)";
1125     $list = array();
1126     $ldap->search("(&(|{$ocs})(ipHostNumber=*))",array("ipHostNumber"));
1127     while($attrs = $ldap->fetch()){
1128       if (preg_match("/^$net\./", $attrs['ipHostNumber'][0])) {
1129         $list[] = $attrs['ipHostNumber'][0];
1130       }
1131     }
1133     // Set starting ip.
1134     $ip_data = preg_split("/\./",$net);
1135     for($i=0;$i<4;$i++){
1136       if(!isset($ip_data[$i])) $ip_data[$i] = 0;
1137     }
1139     // Search the next free and valid ip.
1140     while(in_array(implode(".",$ip_data),$list) || $ip_data[3] <= 1){
1141       $ip_data[3] ++ ;
1142       if($ip_data[3] > 255){
1143         $ip_data[3] = 1 ;
1144         $ip_data[2] ++ ;
1145       }
1146       if($ip_data[2] > 255){
1147         $ip_data[2] = 1 ;
1148         $ip_data[1] ++ ;
1149       }
1150       if($ip_data[1] > 255){
1151         $ip_data[1] = 1 ;
1152         $ip_data[0] ++ ;
1153       }
1154       if($ip_data[0] > 255) break;
1155     }
1157     return(implode(".",$ip_data));
1158   }
1160   
1161   function create_tree($arr,$base,$current = "")
1162   {
1163     $ret = array();
1164     foreach($arr as $r => $name){
1165       $base_part = str_replace($base,"",$r);
1166       if(preg_match("/^[a-z]*=".preg_quote($name, '/')."(|,)$/i",$base_part)){
1167         $ret[$r] = $current.$name;
1168         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1169         foreach($tmp as $sub_key => $sub_name){
1170           $ret[$sub_key] = $sub_name;
1171         }
1172       } 
1173     }
1174     return($ret);
1175   }
1177   function force_dns()
1178   {
1179     if($this->DNSenabled){
1181       /* Only force DNS account, if we have at least on dns Zone */
1182       if(count($this->Zones)){
1183         $this->DNS_is_account  = TRUE;
1184         $this->hide_dns_check_box = TRUE;
1185       }
1186     }
1187   }
1190 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1191 ?>