Code

913684baddab5a06bdec8bbff84899c8b04dc2d5
[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;
13   /* Basic informations 
14    */
15   var $attributes     = array("ipHostNumber","macAddress");
16   var $objectclasses  = array("whatever");
18   var $ipHostNumber   = "";    // IP address 
19   var $macAddress     = "";    // Mac address 
20   var $cn             = "";    // CN of currently edited device 
21   var $OrigCn         = "";    // Initial cn
22   var $IPisMust       = false;
23   var $MACisMust      = false;
25   /* DNS attributes  
26    */
27   var $DNSattributes            = array("dNSClass","zoneName","dNSTTL");
28   var $DNS_is_Account           = false;
29   var $DNSinitially_was_account = false;
30   var $dnsEntry                 = array();
31   var $DNSenabled               = false;
33   /*  Terminal dns 
34    */
35   function termDNS ($config, $dn,$objectClasses,$IPisMust = false)
36   {
37     /* We need to know which objectClasses are used, to store the ip/mac
38      * Because of different type of devices   
39      */
40     $this->objectclasses  =  $objectClasses;
41     $this->IPisMust       = $IPisMust;
43     plugin::plugin ($config, $dn);
45     if(isset($this->attrs['cn'][0])){
46       $this->OrigCn = $this->attrs['cn'][0];
47     }
49     /* Hide all dns specific code, if dns is not available 
50      */
51     $DNSenabled = false;
52     foreach($this->config->data['TABS']['SERVTABS'] as $tab){
53       if(preg_match("/^servdns$/",$tab['CLASS'])){
54         $this->DNSenabled = true;
55       }
56     }
57     if(!$this->DNSenabled){
58       $this->DNS_is_account = false;
59       return;
60     }
62     if($this->DNSenabled){
64       /* Get Zones  
65        */
66       $this->Zones        = getAvailableZones($config);
68       /* Get Entry 
69        */
70       $this->dnsEntry     = getDNSHostEntries($config,$this->OrigCn);
72       /* Remove A record which equals $this->ipHostNumber
73        */
74       foreach($this->dnsEntry['RECORDS'] as $key => $rec){
75         if(($rec['type'] == "aRecord") && ($rec['value'] == $this->ipHostNumber)){
76           unset($this->dnsEntry['RECORDS'][$key]);
77         }
78       }
80       /* Get Record types 
81        */
82       $this->RecordTypes  = getDnsRecordTypes();
84       /* If there is at least one entry in this -> types, we have DNS enabled 
85        */
86       if($this->dnsEntry['exists']){
87         $this->DNS_is_account = true;
88       }else{
89         $this->DNS_is_account = false;
90       }
91    
92     }
93  
94     /* Store initally account settings 
95      */
96     $this->DNSinitially_was_account = $this->DNS_is_account;
97   }
100   function getVarsForSaving($attrs) 
101   {
102     foreach($this->attributes as $attr){
103       if(!empty($this->$attr)){
104         $attrs[$attr] = $this->$attr;
105       }
106     }
107     return($attrs); 
108   }
110   function execute()
111   {
112           /* Call parent execute */
113     $smarty= get_smarty();
114     $display= "";
116     $smarty->assign("staticAddress", ""); 
117  
118     /* There is no dns available 
119      */
120     if($this->DNSenabled == false){
121        
122       /* Is IP address must ? */ 
123       $smarty->assign("DNS_is_account",false);  
124       $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
125     
126       /* Assign smarty all non DNs attributes */
127       foreach($this->attributes as $attr){
128         $smarty->assign($attr,$this->$attr);
129       }
130       $smarty->assign("staticAddress", "");
131       $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
132       return($display);
133     }else{
134       $smarty->assign("DNS_is_account",true); 
135     }
136  
137     /* Add new empty array to our record list */
138     if(isset($_POST['AddNewRecord'])){
139       $this->dnsEntry['RECORDS'][]  =array("type"=>"aRecord","value"=>"");
140     }
141    
142     /* Handle all posts */ 
143     $only_once =true;
144     foreach($_POST as $name => $value){
146       /* Check if we have to delete a record entry */
147       if((preg_match("/RemoveRecord_/",$name))&&($only_once)) {
148       
149         /* Avoid performing this once again */
150         $only_once = false;
152         /* Extract id for specified entry */
153         $id = preg_replace("/RemoveRecord_/","",$name);
154         $id = preg_replace("/_.*$/","",$id);
155     
156         /* Delete this record, mark edited entries to be able to delete them */
157         if(isset($this->dnsEntry['RECORDS'][$id])){
158           unset($this->dnsEntry['RECORDS'][$id]);
159         }
160       }
161     }
163     /* Assign smarty all non DNs attributes */
164     foreach($this->attributes as $attr){
165       $smarty->assign($attr,$this->$attr);
166     }
168     /* Assign smarty all DNS attributes */
169     foreach($this->DNSattributes as $attr){
170       $smarty->assign($attr,$this->dnsEntry[$attr]);
171     }
172     
173     /* Assign all needed vars */
174     $smarty->assign("DNSAccount",$this->DNS_is_account);
175     $smarty->assign("Zones",$this->Zones);
176     $smarty->assign("ZoneKeys",($this->Zones));
177     $smarty->assign("IPisMust",(($this->IPisMust)||($this->DNS_is_account)));
178   
179     $tmp = $this->generateRecordsList();
180     
181     $changeStateForRecords = $tmp['changeStateForRecords'];
183     $smarty->assign("records",$tmp['str']);
184     $smarty->assign("changeStateForRecords",$changeStateForRecords);
185     $smarty->assign("staticAddress","<font class=\"must\">*</font>");
187     $display.= $smarty->fetch(get_template_path('network.tpl', TRUE));
188     return($display);
189   }
191   function remove_from_parent()
192   {
193     /*
194     $ldap = $this->config->get_ldap_link();
195     $ldap->cd($this->orig_dn);
196     $ldap->search("(&(objectClass=dNSZone)(zoneName=*)(!(relativeDomainName=@)))",array("relativeDomainName","zoneName"));
197     while($attr = $ldap->fetch()){  
198       $ldap->cd($attr['dn']);
199       $ldap->rmDir($attr['dn']);
200     }
201     */
202   }
204   /* Save data to object */
205   function save_object()
206   {
207     /* Save all posted vars */
208     plugin::save_object();
209     
210     /* Ge all non dns attributes (IP/MAC)*/
211     foreach($this->attributes as $attr){
212       if(isset($_POST[$attr])){
213         $this->$attr = $_POST[$attr];
214       }
215     }
217     /* Get dns attributes */
218     if(($this->DNSenabled) && (isset($_POST['network_tpl_posted']))){
220       /* Check for posted record changes */
221       if(is_array($this->dnsEntry['RECORDS'])){
222         foreach($this->dnsEntry['RECORDS'] as $key => $value){
224           /* Check if type has changed */
225           if(isset($_POST['RecordTypeSelectedFor_'.$key])){
226             $this->dnsEntry['RECORDS'][$key]['type'] = $_POST['RecordTypeSelectedFor_'.$key];
227           }
228           /* Check if value has changed */
229           if(isset($_POST['RecordValue_'.$key])){
230             $this->dnsEntry['RECORDS'][$key]['value'] = $_POST['RecordValue_'.$key];
231           }
232         }
233       }
234       /* Get all basic DNS attributes (TTL, Clas ..)*/
235       foreach($this->DNSattributes as $attr){
236         if(isset($_POST[$attr])){
237           $this->dnsEntry[$attr] = $_POST[$attr];
238         }
239       }
241       /* Enable diable DNS */
242       if(isset($_POST['enableDNS'])){
243         $this->DNS_is_account = true;
244       }else{
245         $this->DNS_is_account = false;
246       }
247     }
248   }
251   /* Check supplied data */
252   function check()
253   {
254     /* Call common method to give check the hook */
255     $message= plugin::check();
257     /* Check if ip must be given
258      */  
259     if(($this->IPisMust)||($this->DNS_is_account)){
260   
261       /* Check if ip is empty 
262        */
263       if ($this->ipHostNumber == "" && chkacl ($this->acl, "ipHostNumber") == ""){
264         $message[]= _("The required field 'IP-address' is not set.");
265       }
267       /* check if given ip is valid ipi
268        */
269       $num="(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])";
270       if (!preg_match("/^$num\\.$num\\.$num\\.$num$/", $this->ipHostNumber)){
271         $message[]= _("Wrong IP format in field IP-address.");
272       }
273     }
275     /* Check if mac is empty 
276      */
277     if ($this->macAddress == "" && chkacl ($this->acl, "macAddress") == ""){
278       $message[]= _("The required field 'MAC-address' is not set.");
279     }
281     /* Check if given mac is valid mac 
282      */
283     $tr = count(split(":",$this->macAddress));
284     if($tr!=6){
285       $message[]=(_("The given macaddress is invalid. There must be 6 1byte segments seperated by ':'."));
286     }
288     /* only perfrom this checks if this is a valid DNS account */
289     if($this->DNS_is_account){
291       $checkArray = array();
292       $onlyOnce   = array();
294       $onlyOnce['cNAMERecord'] = 0;
296       /* Walk through all entries and detect duplicates or mismatches
297        */  
298       foreach($this->dnsEntry['RECORDS'] as $name => $values){
300         /* Count record values, to detect duplicate entries for a specific record
301          */
302         if(!isset($checkArray[$values['type']][$values['value']])){
303           $checkArray[$values['type']][$values['value']] = 0;
304         }else{
305           $message[] = sprintf(_("Found duplicate value for record type '%s'."),$values['type']);
306         }
308         /* Check if given entries in $onlyOnce are used more than once
309          */
310         if(isset($onlyOnce[$values['type']])){
311           $onlyOnce[$values['type']] ++;
312           if($onlyOnce[$values['type']] > 1){
313             $message[] = sprintf(_("Found more than one entry for the uniqe record type '%s'."),$values['type']);
314           }
315         }
317         /* Skip txt record ... 
318          */
319         if($values['type'] == "tXTRecord") continue;
321         /* Check if there is an aRecord defined which uses the same IP as used in IPhostAddress 
322          */
323         if(($values['type'] == "aRecord")&&($values['value'] == $this->ipHostNumber)){
324           $message[]=sprintf(_("The device IP '%s' is added as 'A Record', this will be done automatically, please remove the record."), 
325                $this->ipHostNumber);
326         }
328         /* only lower-case is allowed in record entries ... 
329          */
330         if($values['value'] != strtolower($values['value'])){
331           $message[] = sprintf(_("Only lowercase is allowed, please check your '%ss'."),$values['type']);
332         }
333       }
334     }
335     return ($message);
336   }
339   /* Save to LDAP */
340   function save($dn)
341   {
342     $ldap= $this->config->get_ldap_link();
343    
344     /*******************/ 
345     /* IP-MAC HANDLING */
346     /*******************/ 
348     /* $dn was posted as parameter */
349     $this->dn = $dn;
350     
351     /* Save DNS setting & ip/Mac*/
352     plugin::save();
354     /* Write back to ldap */
355     $ldap->cd($this->dn);
356     $this->cleanup();
357     $ldap->modify ($this->attrs); 
359     /****************/ 
360     /* DNS HANDLING */
361     /****************/ 
363     /* If isn't DNS account but initially was DNS account 
364        remove all DNS entries 
365      */ 
366     if(!$this->DNSenabled){
367       return;
368     }else{
370       /* Add ipHostNumber to aRecords
371        */
372       $this->dnsEntry['RECORDS'][] = array("type"=>"aRecord","value"=>$this->ipHostNumber);
374       /* Create diff and follow instructions 
375        * If Account was disabled, remove account by setting exists to false
376        */
377       if((!$this->DNS_is_account)&&($this->DNSinitially_was_account)){  
378         $this->dnsEntry['exists'] = false;
379         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
380       }else{
381         $this->dnsEntry['exists'] = $this->DNS_is_account;
382         $tmp = getDNSHostEntriesDiff($this->config,$this->OrigCn,$this->dnsEntry,$this->cn);
383       }   
385       /* move follwoing entries 
386        */
387       foreach($tmp['move'] as $src => $dst){
388         $this->recursive_move($src,$dst);
389       }
391       /* Delete dns */
392       foreach($tmp['del'] as $dn => $del){
393         $ldap->cd($dn);
394         $ldap->rmdir_recursive($dn);
395       }
397       /* Add || Update new DNS entries 
398        */
399       foreach($tmp['add'] as $dn => $attrs){
400         $ldap->cd($dn);
401         $ldap->cat($dn);
402         if(count($ldap->fetch())){
403           $ldap->cd($dn);
404           $ldap->modify ($attrs); 
405         }else{
406           $ldap->cd($dn);
407           $ldap->add($attrs);
408         }
409       }
411       /* Display errors 
412        */
413       if($ldap->get_error() != "Success"){
414         show_ldap_error("Record:".$ldap->get_error()); 
415       }
416     }
417   }
419   /*  Create html table with all used record types
420    */
421   function generateRecordsList()
422   {
423     $changeStateForRecords = "";
424     
425     if(!$this->DNS_is_account) {
426       $str = "<input type='submit' value='"._("Add")."' name='AddNewRecord' id='AddNewRecord' disabled>";
427       return $str;
428     }
429  
430     $str = "<table summary='' width='100%'>";
431     foreach($this->dnsEntry['RECORDS'] as $key => $entry){
433         $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
434         $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
435         $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
437         $str.=" <tr>".
438           "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
439           "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
440           "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
441           "</tr>";
442     }
444     $str.= "  <tr>".
445            "    <td colspan=2 width='50%'></td><td>".
446            "      <input type='submit' value='"._("Add")."' name='AddNewRecord'>".
447            "    </td>".
448            "  </tr>".
449            "</table>";
450      $ret =  array("str" => $str, "changeStateForRecords" => $changeStateForRecords);
451     return($ret);
452   }
455   /* Create a html select box which allows us to select different types of records 
456    */
457   function generateRecordListBox($selected,$name)
458   {
459     $str = "<select name='".$name."' id='".$name."'>";
460     foreach($this->RecordTypes as $type => $value){
461       $use = "";
462       if($type == $selected){
463         $use = " selected ";
464       }
465       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
466     }
467     $str.="</select>";
468     return($str); 
469   }
472 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
473 ?>