Code

f73fe741fe1c18baf372227799c0242752687330
[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 $initially_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']['SERVERSERVICE'] 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     /* Store initally account settings 
101      */
102     $this->initially_was_account = $this->DNS_is_account;
103   }
106   function getVarsForSaving($attrs) 
107   {
108     foreach($this->attributes as $attr){
109       if(!empty($this->$attr)){
110         $attrs[$attr] = $this->$attr;
111       }
112     }
113     return($attrs); 
114   }
116   function execute()
117   {
118           /* Call parent execute */
119     $smarty= get_smarty();
121     $tmp = $this->plInfo();
122     foreach($tmp['plProvidedAcls'] as $name => $translation){
123       $smarty->assign($name."ACL",$this->getacl($name));
124     }
126     $display= "";
128     $smarty->assign("staticAddress", ""); 
129     $smarty->assign("autonet", "");
130  
131     /* Check for autonet button */
132     if ($this->autonet && isset($_POST['autonet'])){
133       $cmd= $this->config->data['MAIN']['AUTO_NETWORK_HOOK'];
134       if(!empty($cmd) && $this->cn != ""){
135         $res = shell_exec($cmd." ".$this->cn);
136         if(!$res){
137           print_red(sprintf(_("Can't execute specified AUTO_NETWORK_HOOK '%s'. Please check your gosa.conf."),$cmd));
138         } else {
139           $res= split(';', trim($res));
140           if (isset($res[0]) && $res[0] != ""){
141             $this->ipHostNumber= $res[0];
142           }
143           if (isset($res[1]) && $res[1] != ""){
144             $this->macAddress= $res[1];
145           }
146         }
147       }
148     }
150     /* There is no dns available 
151      */
152     if($this->DNSenabled == false){
153        
154       /* Is IP address must ? */ 
155       $smarty->assign("DNS_enabled",false);  
156       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
157     
158       /* Assign smarty all non DNs attributes */
159       foreach($this->attributes as $attr){
160         $smarty->assign($attr,$this->$attr);
161       }
162       $smarty->assign("staticAddress","<font class=\"must\">*</font>");
164       if ($this->autonet){
165         $smarty->assign("autonet", "true");
166       } else {
167         $smarty->assign("autonet", "");
168       }
169       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
170       return($display);
171     }else{
172       $smarty->assign("DNS_enabled",true); 
173     }
175     $accountACL = false; 
176     if($this->DNS_is_account && $this->acl_is_removeable()){
177       $accountACL = true;
178     }elseif(!$this->DNS_is_account && $this->acl_is_createable()){
179       $accountACL = true;
180     }
181     $smarty->assign("accountACL",$accountACL);
183     /* Add new empty array to our record list */
184     if(isset($_POST['AddNewRecord'])){
185       $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
186     }
187    
188     /* Handle all posts */ 
189     $only_once =true;
190     foreach($_POST as $name => $value){
192       /* Check if we have to delete a record entry */
193       if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
194       
195         /* Avoid performing this once again */
196         $only_once = false;
198         /* Extract id for specified entry */
199         $id = preg_replace("/RemoveRecord_/","",$name);
200         $id = preg_replace("/_.*$/","",$id);
201     
202         /* Delete this record, mark edited entries to be able to delete them */
203         if(isset($this->dnsEntry['RECORDS'][$id])){
204           unset($this->dnsEntry['RECORDS'][$id]);
205         }
206       }
207     }
209     /* Assign smarty all non DNs attributes */
210     foreach($this->attributes as $attr){
211       $smarty->assign($attr,$this->$attr);
212     }
214     /* Assign smarty all DNS attributes */
215     foreach($this->DNSattributes as $attr){
216       $smarty->assign($attr,$this->dnsEntry[$attr]);
217     }
218     
219     /* Assign all needed vars */
220     $smarty->assign("DNS_is_account",$this->DNS_is_account);
221     $smarty->assign("Zones",$this->Zones);
222     $smarty->assign("ZoneKeys",($this->Zones));
223     $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
224   
225     $tmp = $this->generateRecordsList();
226     
227     $changeStateForRecords = $tmp['changeStateForRecords'];
229     $smarty->assign("records",$tmp['str']);
230     $smarty->assign("changeStateForRecords",$changeStateForRecords);
231     $smarty->assign("staticAddress","<font class=\"must\">*</font>");
233     $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
234     return($display);
235   }
237   function remove_from_parent()
238   {
239     /*
240     $ldap = $this->config->get_ldap_link();
241     $ldap->cd($this->orig_dn);
242     $ldap->search("(&(objectClass=dNSZone)(zoneName=*)(!(relativeDomainName=@)))",array("relativeDomainName","zoneName"));
243     while($attr = $ldap->fetch()){  
244     $ldap->cd($attr['dn']);
245     $ldap->rmDir($attr['dn']);
246     show_ldap_error($ldap->get_error(), sprintf(_("Removing of terminal/dns acoount with dn '%s' failed."),$this->dn));
247     }
248      */
249   }
251   /* Save data to object */
252   function save_object()
253   {
254     /* Save all posted vars */
255     plugin::save_object();
257     if(isset($_POST['network_tpl_posted'])){
259       /* Ge all non dns attributes (IP/MAC)*/
260       foreach($this->attributes as $attr){
261         if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
262           $this->$attr = $_POST[$attr];
263         }
264       }
266       /* Check if DNS should be enabled / disabled */
267       if($this->DNS_is_account && $this->acl_is_removeable() && !isset($_POST['DNS_is_account'])){
268         $this->DNS_is_account = false;
269       }elseif(!$this->DNS_is_account && $this->acl_is_createable() && isset($_POST['DNS_is_account'])){
270         $this->DNS_is_account = true;
271       }
273       /* Get dns attributes */
274       if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
276         /* Check for posted record changes */
277         if(is_array($this->dnsEntry['RECORDS']) && $this->acl_is_writeable("Records")){
278           foreach($this->dnsEntry['RECORDS'] as $key => $value){
280             /* Check if type has changed */
281             if(isset($_POST['RecordTypeSelectedFor_'.$key])){
282               $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
283             }
284             /* Check if value has changed */
285             if(isset($_POST['RecordValue_'.$key])){
286               $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
287             }
288           }
289         }
290         /* Get all basic DNS attributes (TTL, Clas ..)*/
291         foreach($this->DNSattributes as $attr){
292           if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
293             $this->dnsEntry[$attr] = $_POST[$attr];
294           }
295         }
298       }
299     }
300   }
303   /* Check supplied data */
304   function check()
305   {
306     /* Call common method to give check the hook */
307     $message= plugin::check();
309     /* Check if ip must be given
310      */  
311     if(($this->IPisMust)||($this->DNS_is_account)){
312       if (empty($this->ipHostNumber)){
313         $message[]= _("The required field 'IP-address' is not set.");
314       }
316       if (!is_ip($this->ipHostNumber)){
317         $message[]= _("Wrong IP format in field IP-address.");
318       }
319     }
321     /* Check if mac is empty 
322      */
323     if ($this->macAddress == "" ){
324       $message[]= _("The required field 'MAC-address' is not set.");
325     }
326     if(!is_mac($this->macAddress)){
327       $message[]=(_("The given macaddress is invalid. There must be 6 2byte segments seperated by ':'."));
328     }
330     /* only perfrom this checks if this is a valid DNS account */
331     if($this->DNS_is_account){
333       $checkArray = array();
334       $onlyOnce   = array();
336       //  $onlyOnce['cNAMERecord'] = 0;
338       /* Walk through all entries and detect duplicates or mismatches
339        */  
340       foreach($this->dnsEntry['RECORDS'] as $name => $values){
342         /* Count record values, to detect duplicate entries for a specific record
343          */
344         if(!isset($checkArray[$values['type']][$values['value']])){
345           $checkArray[$values['type']][$values['value']] = 0;
346         }else{
347           $message[] = sprintf(_("Found duplicate value for record type '%s'."),$values['type']);
348         }
350         /* Check if given entries in $onlyOnce are used more than once
351          */
352         if(isset($onlyOnce[$values['type']])){
353           $onlyOnce[$values['type']] ++;
354           if($onlyOnce[$values['type']] > 1){
355             $message[] = sprintf(_("Found more than one entry for the uniqe record type '%s'."),$values['type']);
356           }
357         }
359         /* Skip txt record ... 
360          */
361         if($values['type'] == "tXTRecord") continue;
363         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
364          */
365         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
366           $message[]=sprintf(_("The device IP '%s' is added as 'A Record', this will be done automatically, please remove the record."), 
367                $this->ipHostNumber);
368         }
370         /* only lower-case is allowed in record entries ... 
371          */
372         if($values['value'] != strtolower($values['value'])){
373           $message[] = sprintf(_("Only lowercase is allowed, please check your '%ss'."),$values['type']);
374         }
375       }
376     }
377     return ($message);
378   }
381   /* Save to LDAP */
382   function save($dn)
383   {
384     $ldap= $this->config->get_ldap_link();
385    
386     /*******************/ 
387     /* IP-MAC HANDLING */
388     /*******************/ 
390     /* $dn was posted as parameter */
391     $this->dn = $dn;
392     
393     /* Save DNS setting & ip/Mac*/
394     plugin::save();
396     /* Write back to ldap */
397     $ldap->cd($this->dn);
398     $this->cleanup();
399     $ldap->modify ($this->attrs); 
401     /****************/ 
402     /* DNS HANDLING */
403     /****************/ 
405     /* If isn't DNS account but initially was DNS account 
406        remove all DNS entries 
407      */ 
408     if((!$this->DNSenabled) || ((!$this->DNS_is_account)&&(!$this->initially_was_account))){
409       return;
410     }else{
412       /* Add ipHostNumber to aRecords
413        */
414       $backup_dnsEntry = $this->dnsEntry;
415       $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
417       /* Create diff and follow instructions 
418        * If Account was disabled, remove account by setting exists to false
419        */
420       if((!$this->DNS_is_account)&&($this->initially_was_account)){  
421         $this->dnsEntry['exists'] = false;
422         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
423       }else{
424         $this->dnsEntry['exists'] = $this->DNS_is_account;
425         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
426       }   
428       /* move follwoing entries 
429        */
430       foreach($tmp['move'] as $src => $dst){
431         $this->recursive_move($src,$dst);
432       }
434       /* Delete dns */
435       foreach($tmp['del'] as $dn => $del){
436         $ldap->cd($dn);
437         $ldap->rmdir_recursive($dn);
438       }
440       /* Add || Update new DNS entries 
441        */
442       foreach($tmp['add'] as $dn => $attrs){
443         $ldap->cd($dn);
444         $ldap->cat($dn, array('dn'));
445         if(count($ldap->fetch())){
446           $ldap->cd($dn);
447           $ldap->modify ($attrs); 
448         }else{
449           $ldap->cd($dn);
450           $ldap->add($attrs);
451         }
452       }
454       /* Display errors 
455        */
456       if($ldap->get_error() != "Success"){
457         show_ldap_error($ldap->get_error(), sprintf(_("Saving of terminal/dns account with dn '%s' failed."),$this->dn));
458       }
460       $this->dnsEntry =  $backup_dnsEntry;
461     }
462   }
464   /*  Create html table with all used record types
465    */
466   function generateRecordsList()
467   {
468     $changeStateForRecords = "";
469     
470     if(!$this->DNS_is_account) {
471       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
472       return $str;
473     }
474  
475     $str = "<table summary='' width='100%'>";
476     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
478         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
479         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
480         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
482         $str.=" <tr>".
483           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
484           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
485           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
486           "</tr>";
487     }
489     $str.= "  <tr>".
490            "    <td colspan=2 width='50%'></td><td>".
491            "      <input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord'>".
492            "    </td>".
493            "  </tr>".
494            "</table>";
495      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
496     return($ret);
497   }
500   /* Create a html select box which allows us to select different types of records 
501    */
502   function generateRecordListBox($selected,$name)
503   {
504     $str = "<select name='".$name."' id='".$name."'>";
505     foreach($this->RecordTypes as $type => $value){
506       $use = "";
507       if($type == $selected){
508         $use = " selected ";
509       }
510       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
511     }
512     $str.="</select>";
513     return($str); 
514   }
517   /* Return plugin informations for acl handling  */ 
518   function plInfo()
519   {
520     $tmp =  array(
521         "plShortName"   => _("DNS"),
522         "plDescription" => _("DNS settings"),
523         "plSelfModify"  => FALSE,
524         "plDepends"     => array(),
525         "plPriority"    => 5,
526         "plSection"     => array("administration"),
527         "plCategory"    => array("workstation","terminal","phone","server","component","printer","winworkstation"),
529         "plProvidedAcls"=> array(
530           "ipHostNumber"  => _("IP address"),
531           "macAddress"    => _("MAC address"))
532         );
534     /* Hide all dns specific code, if dns is not available
535      */
536     $DNSenabled = false;
537     foreach($_SESSION['config']->data['TABS']['SERVERSERVICE'] as $tab){
538       if(preg_match("/^servdns$/",$tab['CLASS'])){
539         $tmp['plProvidedAcls']["Records"]        = _("DNS records");
540         $tmp['plProvidedAcls']["zoneName"]       = _("Zone name");
541         $tmp['plProvidedAcls']["dNSTTL"]         = _("TTL");
542       }
543     }
544     return($tmp);
545   }
548 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
549 ?>