Code

Merged dns edit fixes from zeph
[gosa.git] / plugins / admin / systems / class_termDNS.inc
1 <?php
3 class termDNS extends plugin
4 {
5   /* CLI vars */
6   var $cli_summary      = "Manage server basic objects";
7   var $cli_description  = "Some longer text\nfor help";
8   var $cli_parameters   = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
10   /* attribute list for save action */
11   var $ignore_account = true;
12   var $autonet        = false;
14   /* Basic informations 
15    */
16   var $attributes     = array("ipHostNumber","macAddress");
17   var $objectclasses  = array("whatever");
19   var $ipHostNumber   = "";    // IP address 
20   var $macAddress     = "";    // Mac address 
21   var $cn             = "";    // CN of currently edited device 
22   var $OrigCn         = "";    // Initial cn
23   var $IPisMust       = false;
24   var $MACisMust      = false;
26   /* DNS attributes  
27    */
28   var $DNSattributes            = array("dNSClass","zoneName","dNSTTL");
29   var $DNS_is_Account           = false;
30   var $DNSinitially_was_account = false;
31   var $dnsEntry                 = array();
32   var $DNSenabled               = false;
34   /*  Terminal dns 
35    */
36   function termDNS ($config, $dn,$objectClasses,$IPisMust = false)
37   {
38     /* We need to know which objectClasses are used, to store the ip/mac
39      * Because of different type of devices   
40      */
41     $this->objectclasses  =  $objectClasses;
42     $this->IPisMust       = $IPisMust;
44     plugin::plugin ($config, $dn);
46     if(isset($this->attrs['cn'][0])){
47       $this->OrigCn = $this->attrs['cn'][0];
48       $this->cn = $this->attrs['cn'][0];
49     }
51     /* Do we have autonet support? */
52     if (isset($this->config->data['MAIN']['AUTO_NETWORK_HOOK'])){
53       $this->autonet= true;
54     }
56     /* Hide all dns specific code, if dns is not available 
57      */
58     $DNSenabled = false;
59     foreach($this->config->data['TABS']['SERVTABS'] as $tab){
60       if(preg_match("/^servdns$/",$tab['CLASS'])){
61         $this->DNSenabled = true;
62       }
63     }
64     if(!$this->DNSenabled){
65       $this->DNS_is_account = false;
66       return;
67     }
69     if($this->DNSenabled){
71       /* Get Zones  
72        */
73       $this->Zones        = getAvailableZones($config);
75       /* Get Entry 
76        */
77       $this->dnsEntry     = getDNSHostEntries($config,$this->OrigCn);
79       /* Remove A record which equals $this->ipHostNumber
80        */
81       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
82         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
83           unset($this->dnsEntry['RECORDS'][$key]);
84         }
85       }
87       /* Get Record types 
88        */
89       $this->RecordTypes  = getDnsRecordTypes();
91       /* If there is at least one entry in this -> types, we have DNS enabled 
92        */
93       if($this->dnsEntry['exists']){
94         $this->DNS_is_account = true;
95       }else{
96         $this->DNS_is_account = false;
97       }
98    
99     }
100  
101     /* Store initally account settings 
102      */
103     $this->DNSinitially_was_account = $this->DNS_is_account;
104   }
107   function getVarsForSaving($attrs) 
108   {
109     foreach($this->attributes as $attr){
110       if(!empty($this->$attr)){
111         $attrs[$attr] = $this->$attr;
112       }
113     }
114     return($attrs); 
115   }
117   function execute()
118   {
119           /* Call parent execute */
120     $smarty= get_smarty();
121     $display= "";
123     $smarty->assign("staticAddress", ""); 
124     $smarty->assign("autonet", "");
125  
126     /* Check for autonet button */
127     if ($this->autonet && isset($_POST['autonet'])){
128       $cmd= $this->config->data['MAIN']['AUTO_NETWORK_HOOK'];
129       if(!empty($cmd) && $this->cn != ""){
130         $res = shell_exec($cmd." ".$this->cn);
131         if(!$res){
132           print_red(sprintf(_("Can't execute specified AUTO_NETWORK_HOOK '%s'. Please check your gosa.conf."),$cmd));
133         } else {
134           $res= split(';', trim($res));
135           if (isset($res[0]) && $res[0] != ""){
136             $this->ipHostNumber= $res[0];
137           }
138           if (isset($res[1]) && $res[1] != ""){
139             $this->macAddress= $res[1];
140           }
141         }
142       }
143     }
145     /* There is no dns available 
146      */
147     if($this->DNSenabled == false){
148        
149       /* Is IP address must ? */ 
150       $smarty->assign("DNS_is_account",false);  
151       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
152     
153       /* Assign smarty all non DNs attributes */
154       foreach($this->attributes as $attr){
155         $smarty->assign($attr,$this->$attr);
156       }
157       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
159       if ($this->autonet){
160         $smarty->assign("autonet", "true");
161       } else {
162         $smarty->assign("autonet", "");
163       }
164       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
165       return($display);
166     }else{
167       $smarty->assign("DNS_is_account",true); 
168     }
169  
170     /* Add new empty array to our record list */
171     if(isset($_POST['AddNewRecord'])){
172       $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
173     }
174    
175     /* Handle all posts */ 
176     $only_once =true;
177     foreach($_POST as $name => $value){
179       /* Check if we have to delete a record entry */
180       if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
181       
182         /* Avoid performing this once again */
183         $only_once = false;
185         /* Extract id for specified entry */
186         $id = preg_replace("/RemoveRecord_/","",$name);
187         $id = preg_replace("/_.*$/","",$id);
188     
189         /* Delete this record, mark edited entries to be able to delete them */
190         if(isset($this->dnsEntry['RECORDS'][$id])){
191           unset($this->dnsEntry['RECORDS'][$id]);
192         }
193       }
194     }
196     /* Assign smarty all non DNs attributes */
197     foreach($this->attributes as $attr){
198       $smarty->assign($attr,$this->$attr);
199     }
201     /* Assign smarty all DNS attributes */
202     foreach($this->DNSattributes as $attr){
203       $smarty->assign($attr,$this->dnsEntry[$attr]);
204     }
205     
206     /* Assign all needed vars */
207     $smarty->assign("DNSAccount",$this->DNS_is_account);
208     $smarty->assign("Zones",$this->Zones);
209     $smarty->assign("ZoneKeys",($this->Zones));
210     $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
211   
212     $tmp = $this->generateRecordsList();
213     
214     $changeStateForRecords = $tmp['changeStateForRecords'];
216     $smarty->assign("records",$tmp['str']);
217     $smarty->assign("changeStateForRecords",$changeStateForRecords);
218     $smarty->assign("staticAddress","<font class=\"must\">*</font>");
220     $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
221     return($display);
222   }
224   function remove_from_parent()
225   {
226     /*
227     $ldap = $this->config->get_ldap_link();
228     $ldap->cd($this->orig_dn);
229     $ldap->search("(&(objectClass=dNSZone)(zoneName=*)(!(relativeDomainName=@)))",array("relativeDomainName","zoneName"));
230     while($attr = $ldap->fetch()){  
231       $ldap->cd($attr['dn']);
232       $ldap->rmDir($attr['dn']);
233       show_ldap_error("Record:".$ldap->get_error(), _("Removing terminal from DNS object failed")); 
234     }
235     */
236   }
238   /* Save data to object */
239   function save_object()
240   {
241     /* Save all posted vars */
242     plugin::save_object();
243     
244     /* Ge all non dns attributes (IP/MAC)*/
245     foreach($this->attributes as $attr){
246       if(isset($_POST[$attr])){
247         $this->$attr = $_POST[$attr];
248       }
249     }
251     /* Get dns attributes */
252     if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
254       /* Check for posted record changes */
255       if(is_array($this->dnsEntry['RECORDS'])){
256         foreach($this->dnsEntry['RECORDS'] as $key => $value){
258           /* Check if type has changed */
259           if(isset($_POST['RecordTypeSelectedFor_'.$key])){
260             $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
261           }
262           /* Check if value has changed */
263           if(isset($_POST['RecordValue_'.$key])){
264             $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
265           }
266         }
267       }
268       /* Get all basic DNS attributes (TTL, Clas ..)*/
269       foreach($this->DNSattributes as $attr){
270         if(isset($_POST[$attr])){
271           $this->dnsEntry[$attr] = $_POST[$attr];
272         }
273       }
275       /* Enable diable DNS */
276       if(isset($_POST['enableDNS'])){
277         $this->DNS_is_account = true;
278       }else{
279         $this->DNS_is_account = false;
280       }
281     }
282   }
285   /* Check supplied data */
286   function check()
287   {
288     /* Call common method to give check the hook */
289     $message= plugin::check();
291     /* Check if ip must be given
292      */  
293     if(($this->IPisMust)||($this->DNS_is_account)){
294   
295       /* Check if ip is empty 
296        */
297       if ($this->ipHostNumber == "" && chkacl ($this->acl, "ipHostNumber") == ""){
298         $message[]= _("The required field 'IP-address' is not set.");
299       }
301     }
303     /* check if given ip is valid ip */
304     if ($this->ipHostNumber != "" && !is_ip($this->ipHostNumber)){
305       $message[]= _("Wrong IP format in field IP-address.");
306     }
308     /* Check if mac is empty 
309      */
310     if ($this->macAddress == "" && chkacl ($this->acl, "macAddress") == ""){
311       $message[]= _("The required field 'MAC-address' is not set.");
312     }
314     /* Check if given mac is valid mac 
315      */
316     if(!is_mac($this->macAddress)){
317       $message[]=(_("The given macaddress is invalid. There must be 6 2byte segments seperated by ':'."));
318     }
320     /* only perfrom this checks if this is a valid DNS account */
321     if($this->DNS_is_account){
323       $checkArray = array();
324       $onlyOnce   = array();
326                         // There can be many CNAME records
327       //$onlyOnce['cNAMERecord'] = 0;
329       /* Walk through all entries and detect duplicates or mismatches
330        */  
331       foreach($this->dnsEntry['RECORDS'] as $name => $values){
333         /* Count record values, to detect duplicate entries for a specific record
334          */
335         if(!isset($checkArray[$values['type']][$values['value']])){
336           $checkArray[$values['type']][$values['value']] = 0;
337         }else{
338           $message[] = sprintf(_("Found duplicate value for record type '%s'."),$values['type']);
339         }
341         /* Check if given entries in $onlyOnce are used more than once
342          */
343         if(isset($onlyOnce[$values['type']])){
344           $onlyOnce[$values['type']] ++;
345           if($onlyOnce[$values['type']] > 1){
346             $message[] = sprintf(_("Found more than one entry for the uniqe record type '%s'."),$values['type']);
347           }
348         }
350         /* Skip txt record ... 
351          */
352         if($values['type'] == "tXTRecord") continue;
354         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
355          */
356         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
357           $message[]=sprintf(_("The device IP '%s' is added as 'A Record', this will be done automatically, please remove the record."), 
358                $this->ipHostNumber);
359         }
361         /* only lower-case is allowed in record entries ... 
362          */
363         if($values['value'] != strtolower($values['value'])){
364           $message[] = sprintf(_("Only lowercase is allowed, please check your '%ss'."),$values['type']);
365         }
366       }
367     }
368     return ($message);
369   }
372   /* Save to LDAP */
373   function save($dn)
374   {
375     $ldap= $this->config->get_ldap_link();
376    
377     /*******************/ 
378     /* IP-MAC HANDLING */
379     /*******************/ 
381     /* $dn was posted as parameter */
382     $this->dn = $dn;
383     
384     /* Save DNS setting & ip/Mac*/
385     plugin::save();
387     /* Write back to ldap */
388     $ldap->cd($this->dn);
389     $this->cleanup();
390     $ldap->modify ($this->attrs); 
392     /****************/ 
393     /* DNS HANDLING */
394     /****************/ 
396     /* If isn't DNS account but initially was DNS account 
397        remove all DNS entries 
398      */ 
399     if(!$this->DNSenabled){
400       return;
401     }else{
403       /* Add ipHostNumber to aRecords
404        */
405       $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
407       /* Create diff and follow instructions 
408        * If Account was disabled, remove account by setting exists to false
409        */
410       if((!$this->DNS_is_account)&&($this->DNSinitially_was_account)){  
411         $this->dnsEntry['exists'] = false;
412         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
413       }else{
414         $this->dnsEntry['exists'] = $this->DNS_is_account;
415         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
416       }   
418       /* move follwoing entries 
419        */
420       foreach($tmp['move'] as $src => $dst){
421         $this->recursive_move($src,$dst);
422       }
424       /* Delete dns */
425       foreach($tmp['del'] as $dn => $del){
426         $ldap->cd($dn);
427         $ldap->rmdir_recursive($dn);
428       }
430       /* Add || Update new DNS entries 
431        */
432       foreach($tmp['add'] as $dn => $attrs){
433         $ldap->cd($dn);
434         $ldap->cat($dn, array('dn'));
435         if(count($ldap->fetch())){
436           $ldap->cd($dn);
437           $ldap->modify ($attrs); 
438         }else{
439           $ldap->cd($dn);
440           $ldap->add($attrs);
441         }
442       }
444       /* Display errors 
445        */
446       if($ldap->get_error() != "Success"){
447         show_ldap_error("Record:".$ldap->get_error(), _("Saving terminal to DNS object failed")); 
448       }
449     }
450   }
452   /*  Create html table with all used record types
453    */
454   function generateRecordsList()
455   {
456     $changeStateForRecords = "";
457     
458     if(!$this->DNS_is_account) {
459       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
460       return $str;
461     }
462  
463     $str = "<table summary='' width='100%'>";
464     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
466         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
467         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
468         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
470         $str.=" <tr>".
471           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
472           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
473           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
474           "</tr>";
475     }
477     $str.= "  <tr>".
478            "    <td colspan=2 width='50%'></td><td>".
479            "      <input type='submit' value='"._("Add")."' name='AddNewRecord'>".
480            "    </td>".
481            "  </tr>".
482            "</table>";
483      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
484     return($ret);
485   }
488   /* Create a html select box which allows us to select different types of records 
489    */
490   function generateRecordListBox($selected,$name)
491   {
492     $str = "<select name='".$name."' id='".$name."'>";
493     foreach($this->RecordTypes as $type => $value){
494       $use = "";
495       if($type == $selected){
496         $use = " selected ";
497       }
498       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
499     }
500     $str.="</select>";
501     return($str); 
502   }
505 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
506 ?>