Code

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