Code

Updated trunk dns plugins.
[gosa.git] / plugins / admin / systems / class_servDNSeditZone.inc
1 <?php
3 class servdnseditZone 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 $attributes     = array("zoneName","ReverseZone","dNSClass",
13       "sOAprimary","sOAmail","sOAserial","sOArefresh","sOAretry","sOAexpire","sOAttl"); 
14   var $objectclasses  = array("whatever");
16   var $RecordTypes              = array();
18   var $ReverseZone              = "";
19   var $zoneName                 = "";
20   var $dNSClass                 = "IN";
22   var $sOAprimary               = "";
23   var $sOAmail                  = "";
24   var $sOAserial                = "";
25   var $sOArefresh               = "3600";
26   var $sOAretry                 = "1800";
27   var $sOAexpire                = "720000";
28   var $sOAttl                   = "6400";
30   var $Records                  = array();
31   var $mXRecords                = array();
33   var $OldZoneName              = ""; // To detect changes made with this edit
34   var $OldReverseZone           = "";
36   var $InitialReverseZone       = "";
37   var $InitialzoneName          = "";
38   var $NetworkClass                = "A" ; // One out of A,B,C
40   var $dialog                   = false;
42   var $isNew                    = true;
44   var $ZoneObject               = array();
46   function servdnseditZone ($config, $dn= NULL,$attrs = array())
47   {
48     plugin::plugin ($config, $dn);
50     /* All types with required attrs */
51     $this->RecordTypes = getDnsRecordTypes(true); 
53     if(!count($attrs)){
54       $this->OldZoneName        = "";
55       $this->OldReverseZone     = "";
56       $this->isNew              = true;
57       $this->sOAserial          = date("Ymd")."1";
58       
59       $this->InitialzoneName    = "";//$attrs['InitialzoneName'];
60       $this->InitialReverseZone = "";//$attrs['InitialReverseZone'];
61     }else{
62       $this->ZoneObject         = $attrs;
65       $this->OldZoneName        = $attrs['zoneName'];
66       $this->OldReverseZone     = $attrs['ReverseZone'];
68       $this->InitialzoneName    = $attrs['InitialzoneName'];
69       $this->InitialReverseZone = $attrs['InitialReverseZone'];
71       $this->isNew                  = false;
73       foreach($this->attributes as $value){
74         $this->$value = $attrs[$value];
75       }
77       $this->sOAmail            = preg_replace("/\./","@",$this->sOAmail,1);
78       $this->sOAmail            = preg_replace("/\.$/","",$this->sOAmail);
79       $this->sOAprimary         = preg_replace("/\.$/","",$this->sOAprimary);
80       $this->zoneName           = preg_replace("/\.$/","",$this->zoneName);
82       if(isset($attrs['RECORDS'])){
83         $this->Records = $attrs['RECORDS']; 
85         $tmp2 = array();
86         $usedPrio = array();
87         foreach($this->Records as $key => $rec){
88           if($rec['type'] == "mXRecord"){
89             $tmp = split(" ",$rec['value']);
90             $rec['value'] = $tmp[1];
91             $tmp2[$tmp[0]] = $rec;
92             unset($this->Records[$key]);
93           }
94           if($rec['type'] == "nSRecord"){
95             unset($this->Records[$key]);
96           }
97         }
98         if(count($tmp2) != 0){
99           reset($tmp2);
100           ksort($tmp2);
101         }
102         $this->mXRecords = $tmp2;
103       }else{
104         $this->mXRecords  = array();
105         $this->Records    = array();
106       }
108       $str = date("Ymd");
109       if(preg_match("/^".$str."/",$this->sOAserial)){
110         $this->sOAserial = $this->sOAserial + 1;
111       }else{
112         $this->sOAserial = date("Ymd")."01";
113       }
114     }
116     /* Detect Network class */
117     if(!empty($this->ReverseZone)){
119       $dots = count(split(".",$this->ReverseZone));
120       if($dots == 0){
121         $this->NetworkClass = "A";  
122         $this->ReverseZone .= ".0.0.0"; 
123       }elseif($dots == 1){
124         $this->NetworkClass = "B";  
125         $this->ReverseZone .= ".0.0"; 
126       }else{
127         $this->NetworkClass = "C";  
128         $this->ReverseZone .= ".0"; 
129       }
130     }
131   }
133   /* TRansports the geiven Arraykey one position up*/
134   function ArrayUp($atr,$attrs)
135   {
136     $ret = $attrs;
137     $pos = $atr ;
138     $cn = count($attrs);
139     if(!(($pos == -1)||($pos == 1)||($pos >$cn))){
140       $before = array_slice($attrs,0,($pos-2));
141       $mitte  = array_reverse(array_slice($attrs,($pos-2),2));
142       $unten  = array_slice($attrs,$pos);
143       $ret = array();
144       $ret = $this->combineArrays($before,$mitte,$unten);
145     }
146     return($ret);
147   }
150   /* TRansports the geiven Arraykey one position up*/
151   function ArrayDown($atr,$attrs)
152   {
153     $ret = $attrs;
154     $pos = $atr ;
155     $cn = count($attrs);
156     if(!(($pos == -1)||($pos == $cn))){
157       $before = array_slice($attrs,0,($pos-1));
158       $mitte  = array_reverse(array_slice($attrs,($pos-1),2));
159       $unten  = array_slice($attrs,($pos+1));
160       $ret = array();
161       $ret = $this->combineArrays($before,$mitte,$unten);
162     }
163     return($ret);
164   }
166   /* Combine new array */
167   function combineArrays($ar0,$ar1,$ar2)
168   {
169     $ret = array();
170     if(is_array($ar0))
171     foreach($ar0 as $ar => $a){
172         $ret[]=$a;
173     }
174     if(is_array($ar1))
175     foreach($ar1 as $ar => $a){
176         $ret[]=$a;
177     }
178     if(is_array($ar2))
179     foreach($ar2 as $ar => $a){
180         $ret[]=$a;
181     }
182     return($ret);
183   }
184   
185   function getpos($atr,$attrs)
186   {
187     $i = 0;
188     foreach($attrs as $attr => $name)    {
189       $i++;
190       if($attr == $atr){
191         return($i);
192       }
193     }
194     return(-1);
195   }
198   function execute()
199   {
200     /* Call parent execute */
201     plugin::execute();
204     /* Fill templating stuff */
205     $smarty= get_smarty();
206     $display= "";
208     /* Open Zone Entry Edit Dialog
209      */
210     if(!count($this->ZoneObject)){
211       $smarty->assign("AllowZoneEdit" , false);
212     }else{
213       $smarty->assign("AllowZoneEdit" , true);
214       if(isset($_POST['EditZoneEntries'])){
215         $this->dialog= new servDNSeditZoneEntries($this->config,$this->dn,$this->ZoneObject);
216       }
217     }
219     /* Save Zone Entry Edit Dialog
220      */
221     if(isset($_POST['SaveZoneEntryChanges'])){
222       $this->dialog->save_object();
223       if(count($this->dialog->check())){
224         $msgs = $this->dialog->check();
225         foreach($msgs as $msg){
226           print_red($msg);
227         }
228       }else{
229         $this->dialog->save();
230         $this->dialog = false;
231       }
232     }
234     /* Cancel Zone Entrie Edit Dialog
235     */
236     if(isset($_POST['CancelZoneEntryChanges'])){
237       $this->dialog = false;
238     }
240     /* Display any type of open dialogs 
241      */
242     if($this->dialog){
243       $this->dialog->save_object();
244       return($this->dialog->execute());
245     }
247     $once =true;
248     foreach($_POST as $name => $value){
249       if((preg_match("/^MXup_/",$name)) && ($once)){
250         $once = false;
252         $id = preg_replace("/^MXup_/","",$name);
253         $id = preg_replace("/_.*$/","",$id);
254         $id = base64_decode($id);
255     
256         $this->mXRecords = $this->ArrayUp(($id+1),$this->mXRecords);
257       }
258       if((preg_match("/^MXdown_/",$name)) && ($once)){
259         $once = false;
260         
261         $id = preg_replace("/^MXdown_/","",$name);
262         $id = preg_replace("/_.*$/","",$id);
263         $id = base64_decode($id);
264   
265         $this->mXRecords = $this->ArrayDown(($id+1),$this->mXRecords);
266       }
267       if((preg_match("/^MXdel_/",$name)) && ($once)){
268         $once = false;
269         
270         $id = preg_replace("/^MXdel_/","",$name);
271         $id = preg_replace("/_.*$/","",$id);
272         $id = base64_decode($id);
273         
274         unset($this->mXRecords[$id]);
276         $tmp  =array();
277         foreach($this->mXRecords as $entry){
278           $tmp[] = $entry;
279         }
280  
281         $this->mXRecords = $tmp; 
282       }
283     }
285     if((isset($_POST['AddMXRecord'])) && (!empty($_POST['StrMXRecord']))){
286       $this->mXRecords[] = array("type"=>"mXRecord","value"=>trim($_POST['StrMXRecord']));      
287     }
289     /* Handle Post events */
290     $once = true;
291     foreach($_POST as $name => $value){
293       /* Delete record if requested */
294       if((preg_match("/RemoveRecord_/",$name))&&($once)){
295         $once = false;
296         $id= preg_replace("/RemoveRecord_/","",$name);
297         unset($this->Records[$id]);
298       }
299     }
301     /* Add new Zonerecord */
302     if(isset($_POST['AddNewRecord'])){
303       $this->Records[] = array("type"=>"aRecord","value"=>"");
304     }
306     /* Fill in values */
307     foreach($this->attributes as $name){
308       $smarty->assign($name,$this->$name);
309     }
312     $div = new DivSelectBox("MxRecords");
313     $div->setHeight(120);
314     $recs = $this->mXRecords;
316     $oneup    = "<input name='MXup_%s'    type='image' src='images/sort_up.png'    title='"._("Up")."'      class='center'>&nbsp;"; 
317     $onedown  = "<input name='MXdown_%s'  type='image' src='images/sort_down.png'  title='"._("Down")."'    class='center'>&nbsp;"; 
318     $onedel   = "<img src='images/empty.png' width='20' class='center'>
319                  <input name='MXdel_%s'   type='image' src='images/edittrash.png'  title='"._("Delete")."'  class='center'>"; 
321     foreach($recs as $key => $rec){
322       $div ->AddEntry(array(
323             array("string"=>$rec['value']),
324 /*            array("string"=>$key,
325                   "attach"=>"style='width:20px;'"),*/
326             array("string"=>str_replace("%s",base64_encode($key),$oneup.$onedown.$onedel),
327                   "attach"=>"style='width:70px;border-right:0px;'")
328             ));
329     }
331     /* Assign records list */
332     $smarty->assign("NotNew", false);
333     $smarty->assign("Mxrecords",  $div->DrawList());
334     $smarty->assign("records"  ,  $this->generateRecordsList());
335     $smarty->assign("NetworkClass",  $this->NetworkClass);
336     $smarty->assign("NetworkClasses",  array("A"=>"255.0.0.0 (Class A)","B"=>"255.255.0.0 (Class B)","C"=>"255.255.255.0 (Class C)"));
338     /* Display tempalte */
339     $display.= $smarty->fetch(get_template_path('servdnseditzone.tpl', TRUE));
340     return($display);
341   }
343   function remove_from_parent()
344   {
345   }
347   /* Save data to object */
348   function save_object()
349   {
350     //plugin::save_object();
351     foreach($this->attributes as $attr){
352       if(isset($_POST[$attr])){
353         $this->$attr = $_POST[$attr];
354       }
355     }
357     foreach($this->Records as $id => $value){  
358       if(isset($_POST['RecordTypeSelectedFor_'.$id])){
359         $this->Records[$id]['type'] = $_POST['RecordTypeSelectedFor_'.$id];
360       }
361       if(isset($_POST['RecordValue_'.$id])){
362         $this->Records[$id]['value'] = $_POST['RecordValue_'.$id];
363       }
364     }
366      if(isset($_POST['NetworkClass'])){
367        $this->NetworkClass = $_POST['NetworkClass'];
368      }
370   }
373   /* Check supplied data */
374   function check()
375   {
376     /* Call common method to give check the hook */
377     $message= plugin::check();
378         
379     /* Check if zoneName is already in use */
380     $usedZones = $this->getUsedZoneNames();
381     if(($this->isNew == true)||($this->zoneName  != $this->InitialzoneName)||($this->ReverseZone != $this->InitialReverseZone)){
382     /*  if((isset($usedZones[$this->zoneName]))&&($this->zoneName  != $this->InitialzoneName)){
383         $message[] =_("This zoneName is already in use");
384       }
385       if((in_array($this->ReverseZone,$usedZones))&&($this->ReverseZone != $this->InitialReverseZone)){
386         $message[] =_("This reverse zone is already in use");
387       }*/
388     }
390     if(empty($this->zoneName)){
391       $message[] =sprintf(_("Please choose a valid zone name."));
392     }
394     if(empty($this->ReverseZone)){
395       $message[] =sprintf(_("Please choose a valid reverse zone name."));
396     }
398     if($this->zoneName != strtolower($this->zoneName)){
399       $message[] = _("Only lowercase strings are allowed as zone name.");
400     }
402     if(!is_numeric($this->sOAserial)){
403       $message[] = _("Please specify a numeric value for serial number.");
404     }
406     if(!is_numeric($this->sOArefresh)){
407       $message[] = _("Please specify a numeric value for refresh.");
408     }
410     if(!is_numeric($this->sOAttl)){
411       $message[] = _("Please specify a numeric value for ttl.");
412     }
414     if(!is_numeric($this->sOAexpire)){
415       $message[] = _("Please specify a numeric value for expire.");
416     }
418     if(!is_numeric($this->sOAretry)){
419       $message[] = _("Please specify a numeric value for retry.");
420     }
422     foreach($this->Records as $name => $values){
423       /* only lower-case is allowed in record entries ... */
424       if($values['value'] != strtolower($values['value'])){
425         $message[] = sprintf(_("Only lowercase is allowed, please check your '%ss'."),$values['type']);
426       }
427     }
429     /* Check class for given Zone Address */
430     $addr = preg_replace("/^[^\/]*+\//","",$this->ReverseZone);
431   
432     /* Check for valid&complete IP address */
433     if(!is_ip($addr)){
434       $message[] = _("The given network address is not a valid, please specify a valid IP address.");
435     }
436  
437     /* Check if given address matches selected network class */
438     switch($this->NetworkClass){
439       case 'A': { 
440                   if(!preg_match("/^[0-9]*\.0\.0\.0$/",$addr)){
441                     $message[] = sprintf(_("The specified network address is not matching with the specified zone class, try it this way x.0.0.0"));
442                   }
443                 }
444                 break;
445       case 'B': {
446                   if(!preg_match("/^[0-9]*\.[0-9]*\.0\.0$/",$addr)){
447                     $message[] = sprintf(_("The specified network address is not matching with the specified zone class, try it this way x.x.0.0"));
448                   }
449                 }
450                 break;
451       case 'C': {
452                   if(!preg_match("/^[0-9]*\.[0-9]*\.[0-9]*\.0$/",$addr)){
453                     $message[] = sprintf(_("The specified network address is not matching with the specified zone class, try it this way x.x.x.0"));
454                   }
455                 }
456                 break;
457       default : $message[] =sprintf(_("The given network class '%s' is not valid."),$this->NetworkClass);
458     }
460     return ($message);
461   }
463   /* This funtion returns all used Zonenames */
464   function getUsedZoneNames()
465   {
466     $ret = array();
467     $ldap = $this->config->get_ldap_link();
468     $ldap->cd($this->config->current['BASE']);
469     $ldap->search("(&(objectClass=dNSZone)(relativeDomainName=@)(zoneName=*))",array("zoneName","tXTRecord"));
470     while($attr = $ldap->fetch()){
471       if(preg_match("/in-addr\.arpa/",$attr['zoneName'][0])){
472         if(isset($attr['tXTRecord'][0])){
473           $zn = preg_replace("/zoneName\=/","",$attr['tXTRecord'][0]);
474           $ret[$zn] =FlipIp(preg_replace("/\.in-addr\.arpa/","",$attr['zoneName'][0]));
475         }
476       }else{
477         $ret[$attr['zoneName'][0]]="";
478       }
479     }
480     return($ret);
481   }
483   /* Save to LDAP */
484   function save()
485   {
486     $ret =array();
487     foreach($this->attributes as $name){
488       $ret[$name] = $this->$name;
489     }
491     /* Create mx records 
492      */
493     foreach($this->mXRecords as $key => $rec){
494       $rec['value']= $key." ".$rec['value'];
495       $this->Records [] = $rec;
496     }
498   
499     $ret['RECORDS'] = $this->Records; 
500  
501     switch($this->NetworkClass){
502       case 'C' : $ret['ReverseZone']= preg_replace("/\.[0-9]*$/","",$this->ReverseZone);break;
503       case 'B' : $ret['ReverseZone']= preg_replace("/\.[0-9]*\.[0-9]*$/","",$this->ReverseZone);break;
504       case 'A' : $ret['ReverseZone']= preg_replace("/\.[0-9]*\.[0-9]*\.[0-9]*$/","",$this->ReverseZone);break;
505       default : trigger_error("Invalid network class given '".$this->NetworkClass."'");
506     }
508     $ret['InitialReverseZone']=  $this->InitialReverseZone;
509     $ret['InitialzoneName']   =  $this->InitialzoneName;
511     $ret['sOAmail']            = preg_replace("/\@/",".",$this->sOAmail);
513     foreach(array("sOAprimary","zoneName","sOAmail") as $attr){
514       if(!preg_match("/\.$/",$ret[$attr])){
515         if(!is_ip($ret[$attr])){
516           $ret[$attr] = $ret[$attr].".";
517         }
518       }
519     }
521     $ret['RECORDS'][] = array("type" => "nSRecord","value" => $ret['sOAprimary']) ;
522     return($ret);
523   }
525   
526   /* This function generate a table row for each used record.
527      This table row displays the recordtype in a select box
528       and the specified value for the record, and a remove button.
529      The last element of the table also got an 'add' button.
530    */
531   function generateRecordsList($changeStateForRecords="")
532   {
533     $changeStateForRecords = "";
535     $str = "<table summary=''>";
536     foreach($this->Records as $key => $entry){
538       if($entry['type'] == "mXRecord") continue;
539       
540       $changeStateForRecords.= "changeState('RecordTypeSelectedFor_".$key."');\n";
541       $changeStateForRecords.= "changeState('RecordValue_".$key."');\n";
542       $changeStateForRecords.= "changeState('RemoveRecord_".$key."');\n";
544       $str.=" <tr>".
545         "   <td>".$this->generateRecordListBox($entry['type'],"RecordTypeSelectedFor_".$key)."</td>".
546         "   <td><input type='text' value='".$entry['value']."' name='RecordValue_".$key."' id='RecordValue_".$key."'></td>".
547         "   <td><input type='submit' name='RemoveRecord_".$key."' value='"._("Delete")."' id='RemoveRecord_".$key."'></td>".
548         "</tr>";
549     }
551     $str.= "  <tr>".
552       "    <td colspan=2></td><td>".
553       "      <input type='submit' value='"._("Add")."' name='AddNewRecord'>".
554       "    </td>".
555       "  </tr>".
556       "</table>";
557     return($str);
558   }
560   /* This function generates a select box out of $this->RecordTypes options.
561      The Parameter $selected is used to predefine an attribute.
562      $name is used to specify a post name
563    */
564   function generateRecordListBox($selected,$name)
565   {
566     $str = "<select name='".$name."' id='".$name."'>";
567     foreach($this->RecordTypes as $type => $value){
569       if(preg_match("/^mXRecord$/i",$value)) continue;
571       $use = "";
572       if($type == $selected){
573         $use = " selected ";
574       }
575       $str.="\n <option value='".$type."' ".$use.">".strtoupper(preg_replace("/record/i","",$type))."</option>";
576     }
577     $str.="</select>";
578     return($str);
579   }
582 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
583 ?>