Code

3c2f020b46bd2adf75f3783dfe6df2f6117dccce
[gosa.git] / plugins / gofon / phoneaccount / class_phoneAccount.inc
1 <?php
3 class phoneAccount extends plugin
4 {
5   /* Definitions */
6   var $plHeadline= "Phone";
7   var $plDescription= "This does something";
8   var $has_mailAccount= FALSE;
10   /* Attributes */
11   var $telephoneNumber        = "";
12   var $goFonHardware          = "";
13   var $goFonForwarding        = "";
14   var $goFonFormat            = "";
15   var $goFonPIN               = "";
16   var $goFonDeliveryMode      = "";
17   var $phoneNumbers           = array();
18   var $forwarders             = array();
19   var $mail                   = "";
20   var $hardware_list          = array();
21   var $used_hardware          = array();
22   var $goFonMacro             = "";
23   var $macro                  = 0;              // Selected Macor
24   var $macros                 = array();        // List of macros for smarty select box
25   var $macroarray             = array();        // All needed macro informations
26   var $macrostillavailable    = false;
27   var $generate_error         = "";
28   var $a_old_telenums           = array();
30   /* CLI vars */
31   var $cli_summary            = "Manage users phone account";
32   var $cli_description        = "Some longer text\nfor help";
33   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
35   /* attribute list for save action */
36   var $attributes             = array("goFonDeliveryMode", "goFonForwarding", "goFonFormat",
37       "goFonHardware", "goFonPIN", "telephoneNumber", "goFonMacro","macro");
38   var $objectclasses= array("goFonAccount");
40   function phoneAccount ($config, $dn= NULL)
41   {
42     plugin::plugin ($config, $dn);
44     /* Set phone hardware */
45     if (!isset($this->attrs['goFonHardware'])){
46       $this->goFonHardware= "automatic";
47     }
49     /* Preset voice format */
50     if (!isset($this->attrs['goFonFormat'])){
51       $this->goFonFormat= "wav";
52     }
54     /* Assemble phone numbers */
55     if (isset($this->attrs['telephoneNumber'])){
56       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
57         $number= $this->attrs['telephoneNumber'][$i];
58         $this->phoneNumbers[$number]= $number;
59       }
60     }
62     /* Assemble forwarders */
63     if (isset($this->attrs['goFonForwarding'])){
64       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
65         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
66         $this->forwarders[$num]= "$v1;$v2";
67       }
68     } else {
69       $this->forwarders= array("");
70     }
72     /* Set up has_mailAccount */
73     if (isset($this->attrs['objectClass'])){
74       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
75         $this->has_mailAccount= TRUE;
76       }
77     }
79     /* Load hardware list */
80     $ldap= $this->config->get_ldap_link();
81     $ldap->cd($this->config->current['BASE']);
82     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
83     while ($attrs= $ldap->fetch()){
84       $cn= $attrs['cn'][0];
85       if (isset($attrs['description'])){
86         $description= " - ".$attrs['description'][0];
87       } else {
88         $description= "";
89       }
90       $this->hardware_list[$cn]= "$cn$description";
92     }
94     /* Prepare templating */
95     $smarty= get_smarty();
98     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
99     $ldap->search("(objectClass=goFonMacro)", array("*"));
101     /* Add none for no macro*/
102     $this->macros['none']=_("no macro");    
103     $this->macro ="none";
106     /* Fetch all Macros*/
107     while ($attrs= $ldap->fetch()){
109       /* Only visisble */
110       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
112         /* unset Count, we don't need that here */
113         unset($attrs['displayName']['count']);
115         /* fill Selectfield variable with Macros */
116         if(isset($attrs['displayName'][0])){
117           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
118         }else{
119           $this->macros[$attrs['dn']] = _("undefined");
120         }
122         /* Parse macro data, unset count for parameterarrays  */
123         unset($attrs['goFonMacroParameter']['count']);
125         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
126         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
128           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
130             /* Split Data in readable values, by delimiter !  */
131             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
133             /* Set all attrs */
134             $id = $data[0];
135             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
136             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
137             $this->macroarray[$attrs['dn']][$id]['id']     = $id;
138             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
139             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
140             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
141           }//foreach
142         }//is_array
143       }//visible = 1
144     }//while
146     /* Go through already saved values, for a parameter */
147     $tmp = split("!",$this->goFonMacro);
149     /* it is possible that nothing has been saved yet */
150     if(is_array($tmp)){
152       /* First value is the macroname */
153       $this->macro = $tmp[0];
155       /* Macroname saved, delete that index */
156       unset($tmp[0]);
158       /* Check if makro has been removed */
159       if(!isset($this->macroarray[$this->macro])){
160         $this->macrostillavailable = false;
161       }else{
162         $this->macrostillavailable = true;
163       }
165       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
166       foreach($tmp as $var){
168         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
169         $varar = split("#",$var);
171         /* Only insert if the parameter still exists */
172         if(isset($this->macroarray[$this->macro][$varar[0]])){
174           /* Assign value */
175           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
176         }
177       }
178     }
180     /* Eventually colorize phones */
181     $ldap->cd($this->config->current['BASE']);
182     foreach ($this->hardware_list as $cn => $desc){
183       $ldap->search("(goFonHardware=$cn)", array('cn'));
184       if ($ldap->count() > 0){
185         $ldap->fetch();
186         if ($ldap->getDN() != $this->dn){
187           $this->used_hardware[$cn]= $ldap->getDN();
188         }
189       }
190     }
192     $this->hardware_list["automatic"]= _("automatic");
193     ksort($this->hardware_list);
194     $this->a_old_telenums = $this->phoneNumbers;
195   }
200   // Generate MySQL Syntax
201   function generate_mysql_entension_entries($save = false){
203     // Get Configuration for Mysql database Server
204     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
205     $s_parameter  ="";
207     // Connect to DB server
208     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
210     // Check if we are  connected correctly
211     if(!$r_con){
212       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
213           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
214       gosa_log(mysql_error());
215       return false;
216     }
218     // Select database for Extensions
219     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
221     // Test if we have the database selected correctly
222     if(!$db){
223       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
224       gosa_log(mysql_error());
225       return false;
226     }
228     // Save data 
229     if($save == true){
231       // Get phonehardware to setup sip entry
232       $ldap= $this->config->get_ldap_link();
233       $res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
234       $attrs = $ldap->fetch();
236       // Attribute GoFonDefaultIP set ?
237       if(((isset($attrs['goFonDefaultIP'][0]))&&($attrs['goFonDefaultIP'][0] != "dynamic"))){
238         $ip = $attrs['goFonDefaultIP'][0];
239         $host = $ip;
240       }else{
241         $ip = NULL;
242         $host = "dynamic";
243       }
245       // Attribute GoFonQualify set ?
246       if(!isset($attrs['goFonQualify'])){
247         $qualify = NULL;
248       }else{
249         $qualify = $attrs['goFonQualify'][0];
250       }
252       // Attribute GoFonPIN set ?
253       if(!isset($this->goFonPIN)){
254         $pin = NULL;
255       }else{
256         $pin = $this->goFonPIN;
257       }
259       // Attribute GoFonType set ?
260       if(!isset($attrs['goFonType'])){
261         $type = NULL;
262       }else{
263         $type = $attrs['goFonType'][0];
264       }
266       // generate SIP entry
267       $sip_data_array['id']           = "";
268       $sip_data_array['name']         = $this->uid;
269       $sip_data_array['accountcode']  = NULL;          
270       $sip_data_array['amaflags']     = NULL;
271       $sip_data_array['callgroup']    = NULL;
272       $sip_data_array['callerid']     = "";
273       $sip_data_array['canreinvite']  = "yes";
274     
275       // Must be default and the name of an entry that already exists
276       $sip_data_array['context']      = "default";
277       $sip_data_array['defaultip']    = NULL;
278       
279       if(isset($attrs['goFonDmtfMode'][0])){
280         $sip_data_array['dtmfmode']     = $attrs['goFonDmtfMode'][0];
281       }else{
282         $sip_data_array['dtmfmode']     ="rfc2833";
283       }
284       $sip_data_array['fromuser']     = NULL;
285       $sip_data_array['fromdomain']   = NULL;
286       $sip_data_array['host']         = $host;
287       $sip_data_array['insecure']     = NULL;
288       $sip_data_array['language']     = NULL;
289       $sip_data_array['mailbox']      = "asterisk";
290       $sip_data_array['md5secret']    = NULL;
291       $sip_data_array['nat']          = "no";
292       $sip_data_array['permit']       = NULL;
293       $sip_data_array['deny']         = NULL;
294       $sip_data_array['mask']         = NULL;
295       $sip_data_array['pickupgroup']  = NULL;
296       $sip_data_array['port']         = NULL;
297       $sip_data_array['qualify']      = $qualify;
298       $sip_data_array['restrictcid']  = "n";
299       $sip_data_array['rtptimeout']   = NULL;
300       $sip_data_array['rtpholdtimeout']=NULL;
301       $sip_data_array['secret']       = $pin;
302       $sip_data_array['type']         = $type ;
303       $sip_data_array['username']     = $this->uid;
304       $sip_data_array['disallow']     = NULL;
305       $sip_data_array['allow']        = NULL;
306       $sip_data_array['musiconhold']  = NULL;
307       $sip_data_array['regseconds']   = NULL;
308       $sip_data_array['ipaddr']       = $ip;
309       $sip_data_array['regexten']     = NULL;
310       $sip_data_array['cancallforward']=NULL;
312       // Get selected Macro Parameter and create parameter entry 
313       if(isset($this->macroarray[$this->macro])){
314         foreach($this->macroarray[$this->macro] as $key => $val ){
315           $s_parameter .= $val['choosen']."|";
316         }
317         $s_parameter = preg_replace("/\|$/","",$s_parameter);
318       }
320       // $SQL contains all queries
321       $SQL = array();
322       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
323       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
325       // Create new SIP entry ...
326       $sip_entry = $sip_data_array;
327     
328       reset($this->phoneNumbers);
329   
330       $key = key($this->phoneNumbers);
331       $sip_entry['callerid']  =$this->phoneNumbers[$key];
332      
333       if(isset($this->parent->by_object['mailAccount']->mail)){
334         $mail = $this->parent->by_object['mailAccount']->mail;
335       }else{
336         $mail = "";
337       }
340       $SQL[]= "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$this->phoneNumbers[$key]."';"; 
341       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." 
342                   (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`) 
343                VALUES 
344                   ('".$this->phoneNumbers[$key]."','default','".$this->phoneNumbers[$key]."','".$this->goFonPIN."','".$this->sn."','".$mail."','');";
346       // Generate Strings with keys and values 
347       $values = "";
348       $keys   = "";
349       foreach($sip_entry as $key=>$val){
350         if($val == NULL) continue;
351         $values.="'".$val."',";
352         $keys  .="`".$key."`,";
353       }
354       // Remove last ,
355       $values =  preg_replace("/,$/","",$values);
356       $keys   =  preg_replace("/,$/","",$keys);
358       // Append SIP Entry 
359       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$keys.") VALUES (".$values.");";
361       // Delete old entries
362       foreach($this->a_old_telenums as $s_telenums){
363         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
364       }
366       $i_is_accounted=false;
368       // Entension entries  Hint / Dial / Goto
369       foreach($this->phoneNumbers as $s_telenums){
370         // Entry  to call by name
371         $s_entry_name['context']  = 'GOsa';
372         $s_entry_name['exten']    = $this->uid;
373         $s_entry_name['priority'] = 1;
374         $s_entry_name['app']      = 'Goto';
375         $s_entry_name['appdata']  = $s_telenums."|1";
376         
377         // hint
378         $s_entry_hint['context']  = 'GOsa';
379         $s_entry_hint['exten']    = $s_telenums;
380         $s_entry_hint['app']      = 'hint';
381         $s_entry_hint['appdata']  = 'SIP/'.$this->uid;
383         // If no macro is selected use Dial
384         if($this->macro!="none"){ 
385           $macroname = preg_replace("/,.*$/","",$this->macro);        
386           $macroname = preg_replace("/^.*=/","",$macroname);        
387           $s_app = "Macro";$macroname;
388           $s_par = $macroname."|".$s_parameter; 
389         }else{
390           $s_app = "Dial";
391           $s_par = 'SIP/'.$this->uid;
392         }
394         // Entry  to call by number
395         $s_entry_phone['context']  = 'GOsa';
396         $s_entry_phone['exten']    = $s_telenums;
397         $s_entry_phone['priority'] = 1;
398         $s_entry_phone['app']      = $s_app;
399         $s_entry_phone['appdata']  = $s_par;
401         // append name entry only once
402         if(!$i_is_accounted){ 
403           $i_is_accounted = true;
404           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
405         }else{
406           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
407         }
408       }
410       // Append all these Entries 
411       foreach($entries as $num => $val){
412         foreach($val as $entr){
413           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
414           foreach($entr as $key2 => $val2){
415             $SQL_syn.= "`".$key2."`,";
416           }
417           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
418           $SQL_syn .= ") VALUES ("; 
419           foreach($entr as $key2 => $val2){
420             $SQL_syn .= "'".$val2."',";
421           }
422           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
423           $SQL_syn .=");\n";
424           $SQL[] =$SQL_syn;
425           $SQL_syn ="";
426         }
427       }
429       // Perform queries ...
430       foreach($SQL as $query){
431         if(!mysql_query($query,$r_con)){
432           print_red(_("Error while performing query ".mysql_error()));
433           return false;
434         }
435       }
436     }
437   return true;
438   }
453   function execute()
454   {
455     /* Do we need to flip is_account state? */
456     if (isset($_POST['modify_state'])){
457       $this->is_account= !$this->is_account;
458     }
460     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
461     if(empty($this->macro)){
462       $this->macro ="none";
463     }
465     /* tell user that the pluging selected is no longer available*/
466     if((!$this->macrostillavailable)&&($this->macro!="none")){
467       print_red(_("The macro you selected in the past, is no longer available for you, please choose another one."));
468     }
470     /* Prepare templating */
471     $smarty= get_smarty();
473     /* Assing macroselectbox values  */
474     $smarty->assign("macros",$this->macros);   
475     $smarty->assign("macro", $this->macro);   
477     /* Create parameter table, skip if no parameters given */
478     if(!isset($this->macroarray[$this->macro])){
479       $macrotab="";
480     }else{
482       $macrotab ="<table summary=\""._("Parameter")."\">";
483       /* for every single parameter-> display textfile,combo, or true false switch*/
484       foreach($this->macroarray[$this->macro] as $paras){
486         /* get al vars */
487         $var        = $paras['var'];           
488         $name       = $paras['name'];           
489         $default    = $paras['default'];
490         $type       = $paras['type'];
491         $choosen    = $paras['choosen'] ; 
492         $str        = $default;
494         /* in case of a combo box display a combobox with selected attr */
495         $macrotab.= "<tr>";
496         switch ($type){
498           case "combo":
499             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
500           foreach(split(":",$default) as $choice){
501             if($choosen==$choice){
502               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
503             }else{
504               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
505             }
506           }
507           $str.="</select>";
508           $macrotab.= "<td>$name</td><td>$str";
509           break;
511           case "bool":
512             if(!$choosen){
513               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
514             }else{
515               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
516             }
517           $macrotab.= "<td colspan='2'>$str&nbsp;$name";
518           break;
520           case "string":
521             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro").">";
522           $macrotab.= "<td>$name</td><td>$str";
523           break;
525         }
526         $macrotab.= "</td</tr>";
528       }
529       $macrotab.="</table>";
530     }//is_array()
532     /* Give smarty the table */
533     $smarty->assign("macrotab",$macrotab);
535     /* Do we represent a valid account? */
536     if (!$this->is_account && $this->parent == NULL){
537       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
538         _("This account has no phone extensions.")."</b>";
539       $display.= back_to_main();
540       return($display);
541     }
543     $display= "";
545     /* Show tab dialog headers */
546     if ($this->parent != NULL){
547       if ($this->is_account){
548         $display= $this->show_header(_("Remove phone account"),
549             _("This account has phone features enabled. You can disable them by clicking below."));
550       } else {
551         $display= $this->show_header(_("Create phone account"),
552             _("This account has phone features disabled. You can enable them by clicking below."));
553         return ($display);
554       }
555     }
557     /* Add phone number */
558     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
559       if (is_phone_nr($_POST['phonenumber'])){
560         $number= $_POST["phonenumber"];
561         $this->phoneNumbers[$number]= $number;
562         $this->is_modified= TRUE;
563       } else {
564         print_red(_("Please enter a valid phone number!"));
565       }
566     }
568     /* Remove phone number */
569     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
570       foreach ($_POST['phonenumber_list'] as $number){
571         unset($this->phoneNumbers[$number]);
572         $this->is_modified= TRUE;
573       }
574     }
576     /* Check for forwarding action */
577     foreach ($this->forwarders as $nr => $fw){
579       /* Buttons pressed? */
580       if (isset($_POST["add_fw$nr"])){
581         $this->forwarders= $this->insert_after("", $nr, $this->forwarders);
582       }
583       if (isset($_POST["remove_fw$nr"])){
584         unset($this->forwarders[$nr]);
585       }
586     }
588     /* Transfer ACL's */
589     foreach($this->attributes as $val){
590       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
591       $smarty->assign($val,$this->$val);
592     }
594     /* Fill arrays */
595     $smarty->assign ("goFonHardware", $this->goFonHardware);
596     if (!count($this->phoneNumbers)){
597       $smarty->assign ("phoneNumbers", array(""));
598     } else {
599       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
600     }
601     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
602       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
603     foreach ($this->hardware_list as $cn => $description){
604       if ($cn == $this->goFonHardware){
605         $selected= "selected";
606       } else {
607         $selected= "";
608       }
609       if (isset($this->used_hardware[$cn])){
610         $color= "style=\"color:#A0A0A0\"";
611       } else {
612         $color= "";
613       }
614       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
615     }
616     $hl.= "</select>\n";
617     $smarty->assign ("hardware_list", $hl);
619     /* Generate forwarder view */
620     $forwarder_list="";
621     $acl= chkacl($this->acl, "goFonForwaring");
622     foreach ($this->forwarders as $nr => $fw){
623       if ($fw == ""){
624         $number= ""; $timeout= "";
625       } else {
626         list($number, $timeout)= split(";", $fw);
627       }
628       $forwarder_list.= "<tr><td>";
629       $forwarder_list.= "<input name=\"fwn$nr\" size=25 align=\"middle\" maxlength=60 value=\"$number\" $acl>";
630       $forwarder_list.= "</td><td>";
631       $forwarder_list.= "<input name=\"fwt$nr\" size=5 align=\"middle\" maxlength=5 value=\"$timeout\" $acl>";
632       $forwarder_list.= "</td><td>";
633       $forwarder_list.= "<input type=\"submit\" value=\""._("Add")."\" name=\"add_fw$nr\" $acl>";
634       if (count($this->forwarders) > 1){
635         $forwarder_list.= "<input type=\"submit\" value=\""._("Remove")."\" name=\"remove_fw$nr\" $acl>";
636       }
637       $forwarder_list.= "</td></tr>";
638     }
639     $smarty->assign("forwarder_list", $forwarder_list);
641     /* Show main page */
642     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
643     return($display);
644   }
647   function save_object()
648   {
649     if (isset($_POST["phoneTab"])){
650       plugin::save_object();
652       /* Save checkbox */
653       if (isset($_POST['fon_to_mail'])){
654         $tmp= "[M]";
655       } else {
656         $tmp= "[]";
657       }
658       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
659         if ($this->goFonDeliveryMode != $tmp){
660           $this->is_modified= TRUE;
661         }
662         $this->goFonDeliveryMode= $tmp;
663       }
665       /* Save forwarding numbers and timeouts */
666       if (chkacl ($this->acl, "goFonForwarder") == ""){
667         foreach ($this->forwarders as $nr => $fw){
668           $tmp= $_POST["fwn$nr"].";".$_POST["fwt$nr"];
669           if ($this->forwarders[$nr] != $tmp){
670             $this->is_modified= TRUE;
671           }
672           $this->forwarders[$nr]= $tmp;
673         }
674       }
676       /* Every macro in the select box are available */
677       if((isset($_POST['macro']))){
678         $this->macrostillavailable=true;
679       }
681       /* get all Postvars */
682       if(isset($this->macroarray[$this->macro])){ 
683         foreach($this->macroarray[$this->macro] as $key => $paras){
684           if(isset($_POST[$paras['var']])){
685             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']]; 
686           }
688           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
689              We need this code below to read and save checkboxes correct
690            */
691           if($this->macroarray[$this->macro][$key]['type']=="bool"){
692             if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
693               $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
694             }else{
695               $this->macroarray[$this->macro][$key]['choosen']=false;
696             }
697           }
698         }
699       }
700     }
703   }
705   function check()
706   {
707     /* Reset message array */
708     $message= array();
710     if(!$this->generate_mysql_entension_entries()){
711       $message[] = $this->generate_error;
712     }
714     /* We need at least one phone number */
715     if (count($this->phoneNumbers) == 0){
716       $message[]= sprintf(_("You need to specify at least one phone number!"));
717     }
719     if(($this->goFonPIN)==""){
720       $this->goFonPIN = array();
721     }else{
722       if(strcmp ((int)($this->goFonPIN),($this->goFonPIN))){
723         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
724       }elseif(strlen($this->goFonPIN) < 4){
725         $message[] = sprintf(_("The given PIN is too short"));
726       }
728     }
729     /* Check timestamps and phonenumbers */
730     foreach ($this->forwarders as $fw){
732       /* Skip empty values */
733       if ($fw == ";"){
734         continue;
735       }         
737       /* Check */
738       list($number, $timeout)= split(";", $fw);
739       if (!is_phone_nr($number)){
740         $message[]= sprintf(_("The number '%s' is no valid phone number!"), $number);
741       }
742       if (!is_id($timeout)){
743         $message[]= sprintf(_("The timeout '%s' contains invalid characters!"), $timeout);
744       }
745     }
747     /* check for ! in any parameter setting*/
748     if(isset($this->macroarray[$this->macro])){
749       foreach($this->macroarray[$this->macro] as $val){
750         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
751           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
752         }
753       }
754     }
755     return ($message);
756   }
760   function save()
761   {
762     plugin::save();
764     /* Save arrays */
765     $this->attrs['telephoneNumber']= array();
766     foreach ($this->phoneNumbers as $number){
767       $this->attrs['telephoneNumber'][]= $number;
768     }
769     $this->attrs['goFonForwarding']= array();
770     foreach ($this->forwarders as $index => $number){
771       $this->attrs['goFonForwarding'][]= "$index;$number";
772     }
774     /* Save settings, or remove goFonMacro attribute*/
775     if($this->macro!="none"){    
776       $this->attrs['goFonMacro']=$this->macro;
777       if(isset($this->macroarray[$this->macro])){
778         foreach($this->macroarray[$this->macro] as $paras)  {
779           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
780         }
781       }
782     }else{
783       $this->attrs['goFonMacro']=array();
784     }
785     unset($this->attrs['macro'])  ;
787     if($this->attrs['goFonMacro']==""){
788       $this->attrs['goFonMacro']=array();
789     }
790     /* Write back to ldap */
791     $ldap= $this->config->get_ldap_link();
792     $ldap->cd($this->dn);
793     $ldap->modify($this->attrs);
794     show_ldap_error($ldap->get_error());
796     $this->generate_mysql_entension_entries(true);
799     /* Optionally execute a command after we're done */
800     if ($this->initially_was_account == $this->is_account){
801       if ($this->is_modified){
802         $this->handle_post_events("modify");
803       }
804     } else {
805       $this->handle_post_events("add");
806     }
808   }
811   function insert_after($entry, $nr, $list)
812   {
813     /* Is the entry free? No? Make it free... */
814     if (isset($list[$nr])) {
815       $dest= array();
816       $newidx= 0;
818       foreach ($list as $idx => $contents){
819         $dest[$newidx++]= $contents;
820         if ($idx == $nr){
821           $dest[$newidx++]= $entry;
822         }
823       }
824     } else {
825       $dest= $list;
826       $dest[$nr]= $entry;
827     }
829     return ($dest);
830   }
833   function adapt_from_template($dn)
834   {
835     plugin::adapt_from_template($dn);
837     /* Assemble phone numbers */
838     if (isset($this->attrs['telephoneNumber'])){
839       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
840         $number= $this->attrs['telephoneNumber'][$i];
841         $this->phoneNumbers[$number]= $number;
842       }
843     }
845     /* Assemble forwarders */
846     if (isset($this->attrs['goFonForwarding'])){
847       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
848         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
849         $this->forwarders[$num]= "$v1;$v2";
850       }
851     } else {
852       $this->forwarders= array("");
853     }
854   }
857   function remove_from_parent()
858   {
859     // Get Configuration for Mysql database Server
860     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
861     $s_parameter  ="";
863     // Connect to DB server
864     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
866     // Check if we are  connected correctly
867     if(!$r_con){
868       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
869           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
870       gosa_log(mysql_error());
871       return false;
872     }
874     // Select database for Extensions
875     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
877     // Test if we have the database selected correctly
878     if(!$db){
879       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
880       gosa_log(mysql_error());
881       return false;
882     }
884     $SQL="";
886     $first_num = false;
887     // Delete old entries
888       foreach($this->a_old_telenums as $s_telenums){
889         if(!$first_num){
890           $first_num = $s_telenums;
891         }
892         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
893       }
895       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
896       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
897       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
900       foreach($SQL as $query){
901         if(!mysql_query($query,$r_con)){
902           print_red(_("Stop".mysql_error()));
903           return false;
904         }
905       }
909     /* unset macro attr, it will cause an error */
910     $tmp = array_flip($this->attributes);
911     unset($tmp['macro']);
912     $this->attributes=array_flip($tmp);
914     /* Cancel if there's nothing to do here */
915     if (!$this->initially_was_account){
916       return;
917     }
919     plugin::remove_from_parent();
921     /* Just keep one phone number */
922     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
923       $this->attrs['telephoneNumber']= $this->telephoneNumber[0];
924     } else {
925       $this->attrs['telephoneNumber']= array();
926     }
928     $ldap= $this->config->get_ldap_link();
929     $ldap->cd($this->dn);
930     $ldap->modify($this->attrs);
931     show_ldap_error($ldap->get_error());
933     /* Optionally execute a command after we're done */
934     $this->handle_post_events('remove');
935   }
940 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
941 ?>