Code

Updated must dectection for macAddress
[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":"");
263     $smarty->assign("MACisMust",$this->MACisMust);
265     $tmp = $this->plInfo();
266     foreach($tmp['plProvidedAcls'] as $name => $translation){
267       $smarty->assign($name."ACL",$this->getacl($name));
268     }
270     $display= "";
272     /**********
273      * Additional ipHostNumber handling 
274      **********/
275       
276     /* Add a new one */
277     if($this->acl_is_writeable("ipHostNumber")){
278       foreach($_POST as $name => $value){
279         if(preg_match("/^additionalHostNumbers_add/",$name)){
280           $this->additionalHostNumbers[] = "";
281           break;
282         }
284         /* Delete given entry */
285         if(preg_match("/^additionalHostNumbers_del_/",$name)){
286           $id = preg_replace("/^^additionalHostNumbers_del_([0-9]*)_.*/","\\1",$name);
287           if(isset($this->additionalHostNumbers[$id])){
288             unset($this->additionalHostNumbers[$id]);
289             $this->additionalHostNumbers = array_values($this->additionalHostNumbers);
290           }
291           break;
292         } 
293       }
294     }
295  
296     $smarty->assign("additionalHostNumbers",$this->additionalHostNumbers);
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       }
384       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
385     }else{
386  #     $smarty->assign("DNS_is_account",true);
388       /* Add new empty array to our record list */
389       if(isset($_POST['AddNewRecord']) && $this->acl_is_writeable("dnsSetup")){
390         $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
391       }
393       /* propose_ip */
394       if(isset($_POST['propose_ip']) && $this->acl_is_writeable("ipHostNumber")){
395         foreach($this->Zones as $key => $name){
396           if($name == $this->dnsEntry['zoneName']){
397             $net = DNS::FlipIp(str_replace(".in-addr.arpa.","",DNS::getNameFromMix($key)));
398             $this->ipHostNumber = $this->generateRandomIP($net);
399           }
400         }
401       }
403       /* Handle all posts */
404       $only_once =true;
405       if($this->acl_is_writeable("dnsSetup")){
406         foreach($_POST as $name => $value){
408           /* Check if we have to delete a record entry */
409           if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
411             /* Avoid performing this once again */
412             $only_once = false;
414             /* Extract id for specified entry */
415             $id = preg_replace("/RemoveRecord_/","",$name);
416             $id = preg_replace("/_.*$/","",$id);
418             /* Delete this record, mark edited entries to be able to delete them */
419             if(isset($this->dnsEntry['RECORDS'][$id])){
420               unset($this->dnsEntry['RECORDS'][$id]);
421             }
422           }
423         }
424       }
425       /* Assign smarty all non DNs attributes */
426       foreach($this->attributes as $attr){
427         $smarty->assign($attr,$this->$attr);
428       }
430       /* Assign smarty all DNS attributes */
431       foreach($this->DNSattributes as $attr){
432         $smarty->assign($attr,htmlentities($this->dnsEntry[$attr]));
433       }
435       /* Assign all needed vars */
436  #     $smarty->assign("DNSAccount",$this->DNS_is_account);
437       $smarty->assign("hide_dns_check_box",$this->hide_dns_check_box);
438   
439       $smarty->assign("Zones",$this->Zones);
440       $smarty->assign("ZoneCnt",count($this->Zones));
441       $smarty->assign("ZoneKeys",($this->Zones));
442       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
444       /* Create zone array */
445       $idZones = array();
446       foreach($this->Zones as $id => $zone){
447         if($this->netmaskIsCoherent($id)) {
448           $idZones[$id] = $zone;
449         }else{
450           $idZones[$id] = $zone."&nbsp;("._("Not matching").")";
451         }
452       }
453       $smarty->assign("Zones",$idZones);
454       $smarty->assign("ZoneKeys", $this->Zones);
456       $tmp = $this->generateRecordsList();
458       $changeStateForRecords = $tmp['changeStateForRecords'];
460       $smarty->assign("records",$tmp['str']);
461       $smarty->assign("changeStateForRecords",$changeStateForRecords);
463       $smarty->assign("autonetACL",$this->acl_is_writeable("macAddress") && $this->acl_is_writeable("ipHostNumber")?"rw":"");
465       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
466     }
468     return($display);
469   }
472   function remove_from_parent()
473   {
474     if($this->DNS_is_account){
476       $ldap = $this->config->get_ldap_link();
478       $tmp = array();
479       $this->dnsEntry['exists'] = false;
480       $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
481   
482       /* Delete dns */
483       foreach($tmp['del'] as $dn => $del){
484         $ldap->cd($dn);
485         $ldap->rmdir_recursive($dn);
486         new log("remove","unknown/".get_class($this),$dn);
487         if (!$ldap->success()){
488           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_DEL, get_class()));
489         }
490       }
491     }
492   }
495   /* Save data to object */
496   function save_object()
497   {
499     if(isset($_POST['network_tpl_posted'])){
501       /* Save all posted vars */
502       plugin::save_object();
504       /******
505         Additional IP Host Numbers 
506        ******/
508       /* Get posts for all additionally added ipHostNumbers */
509       if($this->acl_is_writeable("ipHostNumber")){
510         foreach($this->additionalHostNumbers as $id => $value){
511           if(isset($_POST['additionalHostNumbers_'.$id])){
512             $this->additionalHostNumbers[$id] = get_post('additionalHostNumbers_'.$id);
513           }
514         } 
515       } 
518       /******
519         DHCP posts
520        ******/
522       if($this->acl_is_writeable("dhcpSetup") && $this->dhcpEnabled && isset($_POST['network_tpl_posted'])){
523         foreach($this->dhcpAttributes as $attr){
524           if(isset($_POST[$attr])){
525             $this->$attr = $_POST[$attr];
526           }
527         }
528         if(isset($_POST['dhcp_is_Account'])){
529           $this->dhcp_is_Account = TRUE;
530         }else{
531           $this->dhcp_is_Account = FALSE;
532         }
533       }
535       /* Ge all non dns attributes (IP/MAC)*/
536       foreach($this->attributes as $attr){
537         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
538           $this->$attr = $_POST[$attr];
539         }
540       }
543       /******
544         DNS posts
545        ******/
547       /* Check if DNS should be enabled / disabled 
548        *  -skip this, if the dns account is enforced.
549        */
550       if(!$this->hide_dns_check_box){
551         if($this->DNS_is_account && $this->acl_is_writeable("dnsSetup") && !isset($_POST['DNS_is_account'])){
552           $this->DNS_is_account = false;
553         }elseif(!$this->DNS_is_account && $this->acl_is_writeable("dnsSetup") && isset($_POST['DNS_is_account'])){
554           $this->DNS_is_account = true;
555         }
556       }
558       /* Get dns attributes */
559       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted'])) && $this->acl_is_writeable("dnsSetup")){
561         /* Check for posted record changes */
562         if(is_array($this->dnsEntry['RECORDS'])){
563           foreach($this->dnsEntry['RECORDS'] as $key => $value){
565             /* Check if type has changed */
566             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
567               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
568             }
569             /* Check if value has changed */
570             if(isset($_POST['RecordValue_'.$key])){
571               $this->dnsEntry['RECORDS'][$key]['value'] = get_post('RecordValue_'.$key);
572             }
573           }
574         }
576         /* Get all basic DNS attributes (TTL, Clas ..)*/
577         foreach($this->DNSattributes as $attr){
578           if(isset($_POST[$attr])){
579             $this->dnsEntry[$attr] = get_post($attr);
580           }
581         }
582       }
583       if($this->hide_dns_check_box){
584         $this->DNS_is_account = true;
585       }
586     }
587   }
590   /* Check supplied data */
591   function check()
592   {
593     /* Call common method to give check the hook */
594     $message= plugin::check();
596     /******
597       check additional IP Host Numbers 
598      ******/
600     foreach($this->additionalHostNumbers as $id => $value){
601       if(!tests::is_ip($value)){
602         $message[]= msgPool::invalid(sprintf(_("IP address %s"),($id +2)), "", "", "192.168.1.10");
603       }
604     }
607     /* Check if mac and ip are already used */
608     if(!empty($this->ipHostNumber) && $this->DNS_is_account && 
609         $this->ipHostNumber != $this->orig_ipHostNumber && 
610         in_array("ip:".$this->ipHostNumber,$this->used_ip_mac)){
611       $message[]= msgPool::duplicated(_("IP address"));
612     }
613     if(!empty($this->macAddress) && $this->dhcp_is_Account && 
614         $this->macAddress != $this->orig_macAddress && 
615         in_array("mac:".$this->macAddress,$this->used_ip_mac)){
616       $message[]= msgPool::duplicated(_("MAC address"));
617     }
619     /* Check if ip must be given
620      */  
621     if(($this->IPisMust)||($this->DNS_is_account)){
622       if (empty($this->ipHostNumber)){
623         $message[]= msgPool::required(_("IP address"));
624       }elseif (!tests::is_ip($this->ipHostNumber)){
625         $message[]= msgPool::invalid(_("IP address"), "", "", "192.168.1.10");
626       }
627     }
629     /* Check if mac is empty 
630      */
631     if($this->MACisMust || $this->dhcp_is_Account){
632       if ($this->macAddress == "" ){
633         $message[]= msgPool::required(_("MAC address"));
634       }elseif(!tests::is_mac($this->macAddress)){
635         $message[]= msgPool::invalid(_("MAC address"), "", "", "00:0C:7F:31:33:F1");
636       }
637     }
639     /* only perfrom this checks if this is a valid DNS account */
640     if($this->DNS_is_account){
642       $checkArray = array();
643       $onlyOnce   = array();
645       //  $onlyOnce['cNAMERecord'] = 0;
646        $tmp = array_flip($this->Zones);
647        $tmp2 = $tmp[$this->dnsEntry['zoneName']];
648        if(!$this->netmaskIsCoherent($tmp2)){ //this->dnsEntry['zoneName'])){
649          $tmp2 = preg_replace("/^.*\//","",$tmp2);
650          $message[] =sprintf(_("The IP address '%s' is not part of the selected reverse zone '%s'!"),$this->ipHostNumber,$tmp2);
651        }
653       /* Walk through all entries and detect duplicates or mismatches
654        */  
655       foreach($this->dnsEntry['RECORDS'] as $name => $values){
657         /* Count record values, to detect duplicate entries for a specific record
658          */
659         if(!isset($checkArray[$values['type']][$values['value']])){
660           $checkArray[$values['type']][$values['value']] = 0;
661         }else{
662           $message[] = sprintf(_("Record type '%s' is duplicated!"),$values['type']);
663         }
665         /* Check if given entries in $onlyOnce are used more than once
666          */
667         if(isset($onlyOnce[$values['type']])){
668           $onlyOnce[$values['type']] ++;
669           if($onlyOnce[$values['type']] > 1){
670             $message[] = sprintf(_("Uniq record type '%s' is duplicated!"),$values['type']);
671           }
672         }
674         /* Skip txt record ... 
675          */
676         if($values['type'] == "tXTRecord") continue;
678         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
679          */
680         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
681           #TODO: Where's the problem here?
682           $message[]=sprintf(_("The IP address '%s' will be added as 'A Record', this will be done automatically, please remove the record."), 
683                $this->ipHostNumber);
684         }
686         /* only lower-case is allowed in record entries ... 
687          */
688         if($values['value'] != strtolower($values['value'])){
689           #TODO: What's in values['value']? Something for a propper message?
690           $message[] = sprintf(_("Only lowercase records are allowed, please check your '%ss'."),$values['type']);
691         }
692       }
693     }
694     return ($message);
695   }
698   /* Save to LDAP */
699   function save()
700   {
701     $ldap= $this->config->get_ldap_link();
702   
703     $dn = $this->parent->dn;
704  
705     /*******************/ 
706     /* IP-MAC HANDLING */
707     /*******************/ 
709     /* $dn was posted as parameter */
710     $this->dn = $dn;
711     
712     /* Save DNS setting & ip/Mac*/
713     plugin::save();
715     /* Add all additional ipHostNumbers now 
716      */
717     if(!empty($this->ipHostNumber)){
718       $this->attrs['ipHostNumber'] = array($this->ipHostNumber);
719     }
720     foreach($this->additionalHostNumbers as $value){
721       $this->attrs['ipHostNumber'][] = $value;
722     }
724     /* Do not add the objectClass ipHost if no ip address is given */
725     if(!isset($this->attrs['ipHostNumber'])){
726       $this->attrs['objectClass'] = array_remove_entries(array("ipHost"),$this->attrs['objectClass']);
727     }
729     /* Write back to ldap */
730     $ldap->cd($this->dn);
731     $this->cleanup();
732     $ldap->modify ($this->attrs); 
734     /****************/ 
735     /* DHCP HANDLING */
736     /****************/ 
737   
738     /* New entry */
739     if($this->dhcpEnabled && $this->acl_is_writeable("dhcpSetup")) {
741       if(count($this->dhcpHostEntry) == 0){
742         $this->dialog = new dhcpHost($this->parent,$this->dhcpParentNode,TRUE);
743         $this->dialog->cn = $this->cn;
744         $this->dialog->dhcpHWAddress = "ethernet ".$this->macAddress;
745         if(!empty($this->ipHostNumber)){
746           $this->dialog->statements->set('fixed-address', $this->ipHostNumber);
747         }
748         $this->dialog->execute();
749         $this->dialog->save_object(); 
750         $this->dhcpHostEntry = $this->dialog->save();
751         if(count($this->dhcpHostEntry['dhcpOption']) == 0){
752           $this->dhcpHostEntry['dhcpOption']= array("host-name ".$this->cn);
753         }
754       }else{
756         // Updated Host-Name entry 
757         foreach($this->dhcpHostEntry['dhcpOption'] as $key => $entry){
758           if(preg_match("/^host-name/", $entry)){
759             $this->dhcpHostEntry['dhcpOption'][$key] = "host-name ".$this->cn;
760             break;
761           }
762         }
763       }
765       /* Write mac address to dhcp settings */
766       if($this->dhcp_is_Account){
767         if(!isset($this->dhcpHostEntry['dhcpHWAddress'][0]) || 
768             !preg_match("/ethernet ".$this->macAddress."/",$this->dhcpHostEntry['dhcpHWAddress'][0])){
769           $this->dhcpHostEntry['dhcpHWAddress'] = array("ethernet ".$this->macAddress);
770           $this->dhcpHostEntry['MODIFIED'] = TRUE;
771         }
772       }
774       /* Updated IP host number */
775       if($this->dhcp_is_Account && $this->dhcpHostEntry['dhcpStatements']){
776         foreach($this->dhcpHostEntry['dhcpStatements'] as $id => $value){
777           if(preg_match("/^fixed-address/",$value)){
778             $this->dhcpHostEntry['dhcpStatements'][$id] = "fixed-address ".$this->ipHostNumber; 
779             $this->dhcpHostEntry['MODIFIED'] = TRUE;
780           }
781         }
782       }
784       /* Unset dhcpStatements if this attribute is empty  */
785       if(isset($this->dhcpHostEntry['dhcpStatements']) && 
786           ($this->dhcpHostEntry['dhcpStatements'] == "" || count($this->dhcpHostEntry['dhcpStatements']) == 0) ){
787         unset($this->dhcpHostEntry['dhcpStatements']);
788       }
789   
790       /* DHCP removed */
791       if($this->initial_dhcp_is_Account && !$this->dhcp_is_Account){
792         $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
793         if (!$ldap->success()){
794           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
795         }
797         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
798         $tmp->handle_post_events("remove");
799       }
801       /* DHCP Added */
802       if(!$this->initial_dhcp_is_Account && $this->dhcp_is_Account){
803         $attrs = $this->dhcpHostEntry;
804         unset($attrs['MODIFIED']);
805         unset($attrs['dn']);
806         $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
807         $res = $ldap->add($attrs);
809         $tmp = new servdhcp($this->config,$this->dhcpParentNode);
810         $tmp->handle_post_events("add");
812         if (!$ldap->success()){
813           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
814         }
815       }
817       /* DHCP still activated */
818       if($this->initial_dhcp_is_Account && $this->dhcp_is_Account){
820         /* DHCP node changed */
821         if(($this->initial_dhcpParentNode != $this->dhcpParentNode) || 
822            ($this->cn != $this->OrigCn)){
823           $attrs = $this->dhcpHostEntry;
824           $attrs[$this->namingAttr] = $this->cn;
825           unset($attrs['dn']);
826           unset($attrs['MODIFIED']);
827           $ldap->cd("cn=".$this->cn.",".$this->dhcpParentNode);
828           $res = $ldap->add($attrs);
830           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
831           $tmp->handle_post_events("modify");
833           if (!$ldap->success()){
834             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), "cn=".$this->cn.",".$this->dhcpParentNode, LDAP_ADD, get_class()));
835           }
836           if($res){
837             $ldap->rmdir_recursive($this->dhcpHostEntry['dn']);
838             if (!$ldap->success()){
839               msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_DEL, get_class()));
840             }
841           }
842         }
843          
844         /* SAME node but modified */ 
845         if(isset($this->dhcpHostEntry['MODIFIED']) && $this->dhcpHostEntry['MODIFIED'] == 1  && 
846             $this->initial_dhcpParentNode == $this->dhcpParentNode){
847           $attrs = $this->dhcpHostEntry;
848           unset($attrs['dn']);
849           unset($attrs['MODIFIED']);
850           $ldap->cd($this->dhcpHostEntry['dn']);
851           $ldap->modify($attrs);
852           
853           $tmp = new servdhcp($this->config,$this->dhcpParentNode);
854           $tmp->handle_post_events("modify");
856           if (!$ldap->success()){
857             msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dhcpHostEntry['dn'], LDAP_MOD, get_class()));
858           }
859         }    
860       }
861     }
862     $this->dialog = FALSE; 
864     /****************/ 
865     /* DNS HANDLING */
866     /****************/ 
868     /* If isn't DNS account but initially was DNS account 
869        remove all DNS entries 
870      */ 
871     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
872       return;
873     }elseif($this->acl_is_writeable("dnsSetup")){
875       /* Add ipHostNumber to aRecords
876        */
877       $backup_dnsEntry = $this->dnsEntry;
878       if(!empty($this->ipHostNumber)){
879         $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
880         $ptr = $this->get_pTRRecord();
881         if(!empty($ptr)){
882           $this->dnsEntry['RECORDS'][] = array("type"=>"pTRRecord","value"=>$ptr);
883         } 
884       }
886       /* Create diff and follow instructions 
887        * If Account was disabled, remove account by setting exists to false
888        */
889       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
890         $this->dnsEntry['exists'] = false;
891         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
892       }else{
893         $this->dnsEntry['exists'] = $this->DNS_is_account;
894         $tmp = DNS::getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
895       }   
896     
897       /* Update SOA record if needed
898        */
899       $this->updateSOARecord();
901       /* move follwoing entries 
902        */
903       foreach($tmp['move'] as $src => $dst){
904         $this->recursive_move($src,$dst);
905       }
907       /* Delete dns */
908       foreach($tmp['del'] as $dn => $del){
909         $ldap->cd($dn);
910         $ldap->rmdir_recursive($dn);
911         new log("modify","unknown/".get_class($this),$dn,array("*"),$ldap->get_error());
912       }
914       /* Add || Update new DNS entries 
915        */
916       foreach($tmp['add'] as $dn => $attrs){
917         $ldap->cd($dn);
918         $ldap->cat($dn, array('dn'));
919         if(count($ldap->fetch())){
920           $ldap->cd($dn);
921           $ldap->modify ($attrs); 
922         }else{
923           $ldap->cd($dn);
924           $ldap->add($attrs);
925         }
926         new log("modify","unknown/".get_class($this),$dn,array_keys($attrs),$ldap->get_error());
927       }
930       /* Display errors 
931        */
932       if (!$ldap->success()){
933         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
934       }
936       $tmp2 = new servdns($this->config,$this->dn);
937       $tmp2->handle_post_events("modify");
939       $this->dnsEntry =  $backup_dnsEntry;
940     }
941   }
943   /*  Create html table with all used record types
944    */
945   function generateRecordsList()
946   {
947     $changeStateForRecords = "";
948     $str = "<table summary='' width='100%'>";
949     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
951         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
952         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
953         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
955         $str.=" <tr>".
956           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
957           "   <td><input type='text' value=\"".htmlentities($entry['value'])."\" name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
958           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
959           "</tr>";
960     }
962     $str.= "  <tr>".
963            "    <td colspan=2 width='50%'></td><td>".
964            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
965            "    </td>".
966            "  </tr>".
967            "</table>";
968      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
969   
970     return($ret);
971   }
974   /* Create a html select box which allows us to select different types of records 
975    */
976   function generateRecordListBox($selected,$name)
977   {
978     $str = "<select name='".$name."' id='".$name."'>";
979     foreach($this->RecordTypes as $type => $value){
980       $use = "";
981       if($type == $selected){
982         $use = " selected ";
983       }
984       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
985     }
986     $str.="</select>";
987     return($str); 
988   }
991   /* Return plugin informations for acl handling  */ 
992   static function plInfo()
993   {
994     $tmp =  array(
995         "plShortName"   => _("DNS"),
996         "plDescription" => _("DNS settings"),
997         "plSelfModify"  => FALSE,
998         "plDepends"     => array(),
999         "plPriority"    => 5,
1000         "plSection"     => array("administration"),
1001         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
1003         "plProvidedAcls"=> array(
1004           "ipHostNumber"  => _("IP address"),
1005           "macAddress"    => _("MAC address"))
1006         );
1008     /* Hide all dns/dhcp configurations if not available
1009      */
1010     if(class_available("servdns")){
1011       $tmp['plProvidedAcls']["dnsSetup"]    = _("DNS configuration");
1012     }
1013     if(class_available("servdhcp")){
1014       $tmp['plProvidedAcls']["dhcpSetup"]   = _("DHCP configuration");
1015     }
1016     return($tmp);
1017   }
1019   
1020   function get_dhcp_host_entry()
1021   {
1022     $attrs = array();
1023     $dn = $this->get_dhcp_host_entry_dn();
1024     if($dn){
1025       $ldap = $this->config->get_ldap_link();
1026       $ldap->cd($this->config->current['BASE']);
1027       $ldap->cat($dn,array("*"));
1028       if($ldap->count()){
1029         $attrs = $ldap->fetch();
1030         foreach($attrs as $key => $value){
1031           if(is_numeric($key) || ($key == "count")){
1032             unset($attrs[$key]);
1033           }
1034           if(is_array($value) && isset($value['count'])){
1035             unset($attrs[$key]['count']);
1036           }
1037         }
1038       }
1039     }
1040     return($attrs);
1041   }
1044   function get_dhcp_host_entry_dn()
1045   {
1046     $ldap = $this->config->get_ldap_link();
1047     $ldap->cd($this->config->current['BASE']);
1048     $ldap->search ("(&(objectClass=dhcpHost)(cn=".$this->cn."))",array("uid","cn","dn"));
1050     if($ldap->count()){
1051       $attr = $ldap->fetch();
1052       return($attr['dn']);
1053     }else{
1054       return("");
1055     }
1056   }  
1059   function get_dhcp_parent_node()
1060   {
1061     return(preg_replace("/^cn=".preg_quote($this->cn, '/').",/","",$this->get_dhcp_host_entry_dn()));
1062   }
1065   function get_dhcp_parent_nodes()
1066   {
1067     $ldap = $this->config->get_ldap_link();
1068     $ldap->cd($this->config->current['BASE']);
1069     $ldap->search("(objectClass=dhcpService)",array("dhcpPrimaryDN"));
1070     
1071     $dhcp_dns = array();
1072     while($attr = $ldap->fetch()){
1073       $dhcp_dns[$attr['dn']] = $attr['dhcpPrimaryDN'][0];
1074     }
1075  
1076     foreach($dhcp_dns as $key => $pri_dns){
1077       $ldap->cat($pri_dns,array("cn"));
1078       $tmp = $ldap->fetch();
1079       if(isset($tmp['cn'][0])){
1080         $dhcp_dns[$key] = $tmp['cn'][0];
1081       }else{
1082         unset($dhcp_dns[$key]);
1083       }
1084     }
1086     $tmp = $tmp2 = array();
1087     foreach($dhcp_dns as $dn => $cn){
1088       $ldap->cd($dn);
1089       $ldap->search("(|(objectClass=dhcpService)(objectClass=dhcpGroup)".
1090                     "(objectClass=dhcpSubnet)(objectClass=dhcpSharedNetwork))",array("cn"));
1091       while($attr = $ldap->fetch()){
1092         $tmp[$attr['dn']] = $attr['cn'][0];
1093       }
1094       $tmp2 = array_merge($tmp2,$this->create_tree($tmp,preg_replace("/^[^,]+,/i","",$dn),"(".$cn.")&nbsp;"));
1095     }
1096     return($tmp2);
1097   }
1099   
1100   /* this function returns the default ptr record entry */
1101   function get_pTRRecord()
1102   {
1103     if(!empty($this->ipHostNumber) && isset($this->dnsEntry['zoneName']) && !empty($this->dnsEntry['zoneName'])){
1104       $ldap = $this->config->get_ldap_link();
1105       $ldap->cat(DNS::getDNSZoneDN($this->config,$this->dnsEntry['zoneName']));
1106       $attrs = $ldap->fetch();
1107       $tmp = array_flip($this->Zones);
1108       $tmp = preg_replace("/^[^\/]*+\//","",$tmp[$this->dnsEntry['zoneName']]);
1109       $tmp = trim(preg_replace("/\.in-addr.arpa\.$/","",$tmp));
1110       $ptr = preg_replace("/^".preg_quote(DNS::FlipIp($tmp), '/')."\./","",$this->ipHostNumber);
1111       return($ptr);
1112     }else{
1113       return(FALSE);
1114     }
1115   }
1117   
1118   function generateRandomIP($net = "")
1119   {
1120     $str = $net;
1121     $cnt = 4;
1123     // first gather all IPs 
1124     $ldap = $this->config->get_ldap_link();
1125     $ocs = 
1126       "(objectClass=goFonHardware)".
1127       "(objectClass=goServer)".
1128       "(objectClass=GOhard)".
1129       "(objectClass=gotoTerminal)".
1130       "(objectClass=gotoWorkstation)".
1131       "(objectClass=gotoPrinter)".
1132       "(objectClass=ipHost)";
1133     $list = array();
1134     $ldap->search("(&(|{$ocs})(ipHostNumber=*))",array("ipHostNumber"));
1135     while($attrs = $ldap->fetch()){
1136       if (preg_match("/^$net\./", $attrs['ipHostNumber'][0])) {
1137         $list[] = $attrs['ipHostNumber'][0];
1138       }
1139     }
1141     // Set starting ip.
1142     $ip_data = preg_split("/\./",$net);
1143     for($i=0;$i<4;$i++){
1144       if(!isset($ip_data[$i])) $ip_data[$i] = 0;
1145     }
1147     // Search the next free and valid ip.
1148     while(in_array(implode(".",$ip_data),$list) || $ip_data[3] <= 1){
1149       $ip_data[3] ++ ;
1150       if($ip_data[3] > 255){
1151         $ip_data[3] = 1 ;
1152         $ip_data[2] ++ ;
1153       }
1154       if($ip_data[2] > 255){
1155         $ip_data[2] = 1 ;
1156         $ip_data[1] ++ ;
1157       }
1158       if($ip_data[1] > 255){
1159         $ip_data[1] = 1 ;
1160         $ip_data[0] ++ ;
1161       }
1162       if($ip_data[0] > 255) break;
1163     }
1165     return(implode(".",$ip_data));
1166   }
1168   
1169   function create_tree($arr,$base,$current = "")
1170   {
1171     $ret = array();
1172     foreach($arr as $r => $name){
1173       $base_part = str_replace($base,"",$r);
1174       if(preg_match("/^[a-z]*=".preg_quote($name, '/')."(|,)$/i",$base_part)){
1175         $ret[$r] = $current.$name;
1176         $tmp = $this->create_tree($arr,$r,$current.".&nbsp;");
1177         foreach($tmp as $sub_key => $sub_name){
1178           $ret[$sub_key] = $sub_name;
1179         }
1180       } 
1181     }
1182     return($ret);
1183   }
1185   function force_dns()
1186   {
1187     if($this->DNSenabled){
1189       /* Only force DNS account, if we have at least on dns Zone */
1190       if(count($this->Zones)){
1191         $this->DNS_is_account  = TRUE;
1192         $this->hide_dns_check_box = TRUE;
1193       }
1194     }
1195   }
1197   function updateSOARecord()
1198   {
1199     $oldEntries = DNS::getDNSHostEntries($this->config,$this->OrigCn);
1200     $newEntries = $this->dnsEntry;
1201     if(array_differs($newEntries['RECORDS'],$oldEntries['RECORDS'])){
1202       DNS::touchDNSZone($this->config,$this->dnsEntry['zoneName']);
1203     }
1204   }
1207 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1208 ?>