Code

Corrected FAQ
[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       $smarty->assign("autonet", $this->autonet);
160       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
161       return($display);
162     }else{
163       $smarty->assign("DNS_is_account",true); 
164     }
165  
166     /* Add new empty array to our record list */
167     if(isset($_POST['AddNewRecord'])){
168       $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
169     }
170    
171     /* Handle all posts */ 
172     $only_once =true;
173     foreach($_POST as $name => $value){
175       /* Check if we have to delete a record entry */
176       if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
177       
178         /* Avoid performing this once again */
179         $only_once = false;
181         /* Extract id for specified entry */
182         $id = preg_replace("/RemoveRecord_/","",$name);
183         $id = preg_replace("/_.*$/","",$id);
184     
185         /* Delete this record, mark edited entries to be able to delete them */
186         if(isset($this->dnsEntry['RECORDS'][$id])){
187           unset($this->dnsEntry['RECORDS'][$id]);
188         }
189       }
190     }
192     /* Assign smarty all non DNs attributes */
193     foreach($this->attributes as $attr){
194       $smarty->assign($attr,$this->$attr);
195     }
197     /* Assign smarty all DNS attributes */
198     foreach($this->DNSattributes as $attr){
199       $smarty->assign($attr,$this->dnsEntry[$attr]);
200     }
201     
202     /* Assign all needed vars */
203     $smarty->assign("DNSAccount",$this->DNS_is_account);
204     $smarty->assign("Zones",$this->Zones);
205     $smarty->assign("ZoneKeys",($this->Zones));
206     $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
207   
208     $tmp = $this->generateRecordsList();
209     
210     $changeStateForRecords = $tmp['changeStateForRecords'];
212     $smarty->assign("records",$tmp['str']);
213     $smarty->assign("changeStateForRecords",$changeStateForRecords);
214     $smarty->assign("staticAddress","<font class=\"must\">*</font>");
216     $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
217     return($display);
218   }
220   function remove_from_parent()
221   {
222     /*
223     $ldap = $this->config->get_ldap_link();
224     $ldap->cd($this->orig_dn);
225     $ldap->search("(&(objectClass=dNSZone)(zoneName=*)(!(relativeDomainName=@)))",array("relativeDomainName","zoneName"));
226     while($attr = $ldap->fetch()){  
227       $ldap->cd($attr['dn']);
228       $ldap->rmDir($attr['dn']);
229       show_ldap_error("Record:".$ldap->get_error(), _("Removing terminal from DNS object failed")); 
230     }
231     */
232   }
234   /* Save data to object */
235   function save_object()
236   {
237     /* Save all posted vars */
238     plugin::save_object();
239     
240     /* Ge all non dns attributes (IP/MAC)*/
241     foreach($this->attributes as $attr){
242       if(isset($_POST[$attr])){
243         $this->$attr = $_POST[$attr];
244       }
245     }
247     /* Get dns attributes */
248     if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
250       /* Check for posted record changes */
251       if(is_array($this->dnsEntry['RECORDS'])){
252         foreach($this->dnsEntry['RECORDS'] as $key => $value){
254           /* Check if type has changed */
255           if(isset($_POST['RecordTypeSelectedFor_'.$key])){
256             $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
257           }
258           /* Check if value has changed */
259           if(isset($_POST['RecordValue_'.$key])){
260             $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
261           }
262         }
263       }
264       /* Get all basic DNS attributes (TTL, Clas ..)*/
265       foreach($this->DNSattributes as $attr){
266         if(isset($_POST[$attr])){
267           $this->dnsEntry[$attr] = $_POST[$attr];
268         }
269       }
271       /* Enable diable DNS */
272       if(isset($_POST['enableDNS'])){
273         $this->DNS_is_account = true;
274       }else{
275         $this->DNS_is_account = false;
276       }
277     }
278   }
281   /* Check supplied data */
282   function check()
283   {
284     /* Call common method to give check the hook */
285     $message= plugin::check();
287     /* Check if ip must be given
288      */  
289     if(($this->IPisMust)||($this->DNS_is_account)){
290   
291       /* Check if ip is empty 
292        */
293       if ($this->ipHostNumber == "" && chkacl ($this->acl, "ipHostNumber") == ""){
294         $message[]= _("The required field 'IP-address' is not set.");
295       }
297     }
299     /* check if given ip is valid ip */
300     if ($this->ipHostNumber != "" && !is_ip($this->ipHostNumber)){
301       $message[]= _("Wrong IP format in field IP-address.");
302     }
304     /* Check if mac is empty 
305      */
306     if ($this->macAddress == "" && chkacl ($this->acl, "macAddress") == ""){
307       $message[]= _("The required field 'MAC-address' is not set.");
308     }
310     /* Check if given mac is valid mac 
311      */
312     if(!is_mac($this->macAddress)){
313       $message[]=(_("The given macaddress is invalid. There must be 6 2byte segments seperated by ':'."));
314     }
316     /* only perfrom this checks if this is a valid DNS account */
317     if($this->DNS_is_account){
319       $checkArray = array();
320       $onlyOnce   = array();
322                         // There can be many CNAME records
323       //$onlyOnce['cNAMERecord'] = 0;
325       /* Walk through all entries and detect duplicates or mismatches
326        */  
327       foreach($this->dnsEntry['RECORDS'] as $name => $values){
329         /* Count record values, to detect duplicate entries for a specific record
330          */
331         if(!isset($checkArray[$values['type']][$values['value']])){
332           $checkArray[$values['type']][$values['value']] = 0;
333         }else{
334           $message[] = sprintf(_("Found duplicate value for record type '%s'."),$values['type']);
335         }
337         /* Check if given entries in $onlyOnce are used more than once
338          */
339         if(isset($onlyOnce[$values['type']])){
340           $onlyOnce[$values['type']] ++;
341           if($onlyOnce[$values['type']] > 1){
342             $message[] = sprintf(_("Found more than one entry for the uniqe record type '%s'."),$values['type']);
343           }
344         }
346         /* Skip txt record ... 
347          */
348         if($values['type'] == "tXTRecord") continue;
350         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
351          */
352         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
353           $message[]=sprintf(_("The device IP '%s' is added as 'A Record', this will be done automatically, please remove the record."), 
354                $this->ipHostNumber);
355         }
357         /* only lower-case is allowed in record entries ... 
358          */
359         if($values['value'] != strtolower($values['value'])){
360           $message[] = sprintf(_("Only lowercase is allowed, please check your '%ss'."),$values['type']);
361         }
362       }
363     }
364     return ($message);
365   }
368   /* Save to LDAP */
369   function save($dn)
370   {
371     $ldap= $this->config->get_ldap_link();
372    
373     /*******************/ 
374     /* IP-MAC HANDLING */
375     /*******************/ 
377     /* $dn was posted as parameter */
378     $this->dn = $dn;
379     
380     /* Save DNS setting & ip/Mac*/
381     plugin::save();
383     /* Write back to ldap */
384     $ldap->cd($this->dn);
385     $this->cleanup();
386     $ldap->modify ($this->attrs); 
388     /****************/ 
389     /* DNS HANDLING */
390     /****************/ 
392     /* If isn't DNS account but initially was DNS account 
393        remove all DNS entries 
394      */ 
395     if(!$this->DNSenabled){
396       return;
397     }else{
399       /* Add ipHostNumber to aRecords
400        */
401       $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
403       /* Create diff and follow instructions 
404        * If Account was disabled, remove account by setting exists to false
405        */
406       if((!$this->DNS_is_account)&&($this->DNSinitially_was_account)){  
407         $this->dnsEntry['exists'] = false;
408         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
409       }else{
410         $this->dnsEntry['exists'] = $this->DNS_is_account;
411         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
412       }   
414       /* move follwoing entries 
415        */
416       foreach($tmp['move'] as $src => $dst){
417         $this->recursive_move($src,$dst);
418       }
420       /* Delete dns */
421       foreach($tmp['del'] as $dn => $del){
422         $ldap->cd($dn);
423         $ldap->rmdir_recursive($dn);
424       }
426       /* Add || Update new DNS entries 
427        */
428       foreach($tmp['add'] as $dn => $attrs){
429         $ldap->cd($dn);
430         $ldap->cat($dn, array('dn'));
431         if(count($ldap->fetch())){
432           $ldap->cd($dn);
433           $ldap->modify ($attrs); 
434         }else{
435           $ldap->cd($dn);
436           $ldap->add($attrs);
437         }
438       }
440       /* Display errors 
441        */
442       if($ldap->get_error() != "Success"){
443         show_ldap_error("Record:".$ldap->get_error(), _("Saving terminal to DNS object failed")); 
444       }
445     }
446   }
448   /*  Create html table with all used record types
449    */
450   function generateRecordsList()
451   {
452     $changeStateForRecords = "";
453     
454     if(!$this->DNS_is_account) {
455       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled='disabled'>";
456       return $str;
457     }
458  
459     $str = "<table summary='' width='100%'>";
460     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
462         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
463         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
464         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
466         $str.=" <tr>".
467           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
468           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
469           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
470           "</tr>";
471     }
473     $str.= "  <tr>".
474            "    <td colspan=2 width='50%'></td><td>".
475            "      <input type='submit' value='"._("Add")."' name='AddNewRecord'>".
476            "    </td>".
477            "  </tr>".
478            "</table>";
479      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
480     return($ret);
481   }
484   /* Create a html select box which allows us to select different types of records 
485    */
486   function generateRecordListBox($selected,$name)
487   {
488     $str = "<select name='".$name."' id='".$name."'>";
489     foreach($this->RecordTypes as $type => $value){
490       $use = "";
491       if($type == $selected){
492         $use = " selected ";
493       }
494       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
495     }
496     $str.="</select>";
497     return($str); 
498   }
501 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
502 ?>