Code

7de9e5aab0a309d1f004a44464bfa98ac4d275b9
[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 
230       // Get phonehardware to setup sip entry
231       $ldap= $this->config->get_ldap_link();
232       $res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
233       $attrs = $ldap->fetch();
235       // Attribute GoFonDefaultIP set ?
236       if(((isset($attrs['goFonDefaultIP'][0]))&&($attrs['goFonDefaultIP'][0] != "dynamic"))){
237         $ip = $attrs['goFonDefaultIP'][0];
238         $host = $ip;
239       }else{
240         $ip = NULL;
241         $host = "dynamic";
242       }
244       // Attribute GoFonQualify set ?
245       if(!isset($attrs['goFonQualify'])){
246         $qualify = NULL;
247       }else{
248         $qualify = $attrs['goFonQualify'][0];
249       }
251       // Attribute GoFonPIN set ?
252       if(!isset($this->goFonPIN)){
253         $pin = NULL;
254       }else{
255         $pin = $this->goFonPIN;
256       }
258       // Attribute GoFonType set ?
259       if(!isset($attrs['goFonType'])){
260         $type = NULL;
261       }else{
262         $type = $attrs['goFonType'][0];
263       }
265       // generate SIP entry
266       $sip_data_array['id']           = "";
267       $sip_data_array['name']         = $this->uid;
268       $sip_data_array['accountcode']  = NULL;          
269       $sip_data_array['amaflags']     = NULL;
270       $sip_data_array['callgroup']    = NULL;
271       $sip_data_array['callerid']     = "";
272       $sip_data_array['canreinvite']  = "yes";
273     
274       // Must be default and the name of an entry that already exists
275       $sip_data_array['context']      = "default";
276       $sip_data_array['defaultip']    = NULL;
277       
278       if(isset($attrs['goFonDmtfMode'][0])){
279         $sip_data_array['dtmfmode']     = $attrs['goFonDmtfMode'][0];
280       }else{
281         $sip_data_array['dtmfmode']     ="rfc2833";
282       }
283       $sip_data_array['fromuser']     = NULL;
284       $sip_data_array['fromdomain']   = NULL;
285       $sip_data_array['host']         = $host;
286       $sip_data_array['insecure']     = NULL;
287       $sip_data_array['language']     = NULL;
288       $sip_data_array['mailbox']      = "asterisk";
289       $sip_data_array['md5secret']    = NULL;
290       $sip_data_array['nat']          = "no";
291       $sip_data_array['permit']       = NULL;
292       $sip_data_array['deny']         = NULL;
293       $sip_data_array['mask']         = NULL;
294       $sip_data_array['pickupgroup']  = NULL;
295       $sip_data_array['port']         = NULL;
296       $sip_data_array['qualify']      = $qualify;
297       $sip_data_array['restrictcid']  = "n";
298       $sip_data_array['rtptimeout']   = NULL;
299       $sip_data_array['rtpholdtimeout']=NULL;
300       $sip_data_array['secret']       = $pin;
301       $sip_data_array['type']         = $type ;
302       $sip_data_array['username']     = $this->uid;
303       $sip_data_array['disallow']     = NULL;
304       $sip_data_array['allow']        = NULL;
305       $sip_data_array['musiconhold']  = NULL;
306       $sip_data_array['regseconds']   = NULL;
307       $sip_data_array['ipaddr']       = $ip;
308       $sip_data_array['regexten']     = NULL;
309       $sip_data_array['cancallforward']=NULL;
311       // Get selected Macro Parameter and create parameter entry 
312       if(isset($this->macroarray[$this->macro])){
313         foreach($this->macroarray[$this->macro] as $key => $val ){
314           $s_parameter .= $val['choosen']."|";
315         }
316         $s_parameter = preg_replace("/\|$/","",$s_parameter);
317       }
318       
325       // $SQL contains all queries
326       $SQL = array();
327       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
328       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
330       // Create new SIP entry ...
331       $sip_entry = $sip_data_array;
332     
333       reset($this->phoneNumbers);
334   
335       $key = key($this->phoneNumbers);
336       $sip_entry['callerid']  =$this->phoneNumbers[$key];
337       $sip_entry['mailbox']   =$this->phoneNumbers[$key];
341       foreach($this->phoneNumbers as $phonekey => $val){
342         $ress = mysql_query( "SELECT * FROM ".$a_SETUP['EXT_TABLE']." WHERE   ((exten='".$this->phoneNumbers[$phonekey]."') AND (app='hint')) 
343                                                                       OR      ((exten='".$this->phoneNumbers[$phonekey]."') AND (priority='hint'));");
344         while($atr = mysql_fetch_row($ress)){
345           $uid = preg_replace("/^.*\//","",$atr[5]);
346           if($uid != $this->uid){
347             $this->generate_error = sprintf(_("This telephone number '%s' is already assigned to userID '%s'"),$this->phoneNumbers[$key],$uid);
348             gosa_log(mysql_error());
349             return false;
350           }
351         }
352       }
354      
355     if($save == true){
356       if(isset($this->parent->by_object['mailAccount']->mail)){
357         $mail = $this->parent->by_object['mailAccount']->mail;
358       }else{
359         $mail = "";
360       }
363       $SQL[]= "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$this->phoneNumbers[$key]."';"; 
364       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." 
365                   (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`) 
366                VALUES 
367                   ('".$this->phoneNumbers[$key]."','default','".$this->phoneNumbers[$key]."','".$this->goFonPIN."','".$this->sn."','".$mail."','');";
369       // Generate Strings with keys and values 
370       $values = "";
371       $keys   = "";
372       foreach($sip_entry as $key=>$val){
373         if($val == NULL) continue;
374         $values.="'".$val."',";
375         $keys  .="`".$key."`,";
376       }
377       // Remove last ,
378       $values =  preg_replace("/,$/","",$values);
379       $keys   =  preg_replace("/,$/","",$keys);
381       // Append SIP Entry 
382       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$keys.") VALUES (".$values.");";
384       // Delete old entries
385       foreach($this->a_old_telenums as $s_telenums){
386         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
387       }
389       $i_is_accounted=false;
391       // Entension entries  Hint / Dial / Goto
392       foreach($this->phoneNumbers as $s_telenums){
393         // Entry  to call by name
394         $s_entry_name['context']  = 'GOsa';
395         $s_entry_name['exten']    = $this->uid;
396         $s_entry_name['priority'] = 1;
397         $s_entry_name['app']      = 'Goto';
398         $s_entry_name['appdata']  = $s_telenums."|1";
399         
400         // hint
401         $s_entry_hint['context']  = 'GOsa';
402         $s_entry_hint['exten']    = $s_telenums;
403         $s_entry_hint['app']      = 'hint';
404         $s_entry_hint['appdata']  = 'SIP/'.$this->uid;
406         // If no macro is selected use Dial
407         if($this->macro!="none"){ 
408           $macroname = preg_replace("/,.*$/","",$this->macro);        
409           $macroname = preg_replace("/^.*=/","",$macroname);        
410           $s_app = "Macro";$macroname;
411           $s_par = $macroname."|".$s_parameter; 
412         }else{
413           $s_app = "Dial";
414           $s_par = 'SIP/'.$this->uid;
415         }
417         // Entry  to call by number
418         $s_entry_phone['context']  = 'GOsa';
419         $s_entry_phone['exten']    = $s_telenums;
420         $s_entry_phone['priority'] = 1;
421         $s_entry_phone['app']      = $s_app;
422         $s_entry_phone['appdata']  = $s_par;
424         // append name entry only once
425         if(!$i_is_accounted){ 
426           $i_is_accounted = true;
427           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
428         }else{
429           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
430         }
431       }
433       // Append all these Entries 
434       foreach($entries as $num => $val){
435         foreach($val as $entr){
436           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
437           foreach($entr as $key2 => $val2){
438             $SQL_syn.= "`".$key2."`,";
439           }
440           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
441           $SQL_syn .= ") VALUES ("; 
442           foreach($entr as $key2 => $val2){
443             $SQL_syn .= "'".$val2."',";
444           }
445           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
446           $SQL_syn .=");\n";
447           $SQL[] =$SQL_syn;
448           $SQL_syn ="";
449         }
450       }
452       // Perform queries ...
453       foreach($SQL as $query){
454         if(!mysql_query($query,$r_con)){
455           print_red(_("Error while performing query ".mysql_error()));
456           return false;
457         }
458       }
459     }
460   return true;
461   }
476   function execute()
477   {
478     /* Do we need to flip is_account state? */
479     if (isset($_POST['modify_state'])){
480       $this->is_account= !$this->is_account;
481     }
483     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
484     if(empty($this->macro)){
485       $this->macro ="none";
486     }
488     /* tell user that the pluging selected is no longer available*/
489     if((!$this->macrostillavailable)&&($this->macro!="none")){
490       print_red(_("The macro you selected in the past, is no longer available for you, please choose another one."));
491     }
493     /* Prepare templating */
494     $smarty= get_smarty();
496     /* Assing macroselectbox values  */
497     $smarty->assign("macros",$this->macros);   
498     $smarty->assign("macro", $this->macro);   
500     /* Create parameter table, skip if no parameters given */
501     if(!isset($this->macroarray[$this->macro])){
502       $macrotab="";
503     }else{
505       $macrotab ="<table summary=\""._("Parameter")."\">";
506       /* for every single parameter-> display textfile,combo, or true false switch*/
507       foreach($this->macroarray[$this->macro] as $paras){
509         /* get al vars */
510         $var        = $paras['var'];           
511         $name       = $paras['name'];           
512         $default    = $paras['default'];
513         $type       = $paras['type'];
514         $choosen    = $paras['choosen'] ; 
515         $str        = $default;
517         /* in case of a combo box display a combobox with selected attr */
518         $macrotab.= "<tr>";
519         switch ($type){
521           case "combo":
522             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
523           foreach(split(":",$default) as $choice){
524             if($choosen==$choice){
525               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
526             }else{
527               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
528             }
529           }
530           $str.="</select>";
531           $macrotab.= "<td>$name</td><td>$str";
532           break;
534           case "bool":
535             if(!$choosen){
536               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
537             }else{
538               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
539             }
540           $macrotab.= "<td colspan='2'>$str&nbsp;$name";
541           break;
543           case "string":
544             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro").">";
545           $macrotab.= "<td>$name</td><td>$str";
546           break;
548         }
549         $macrotab.= "</td</tr>";
551       }
552       $macrotab.="</table>";
553     }//is_array()
555     /* Give smarty the table */
556     $smarty->assign("macrotab",$macrotab);
558     /* Do we represent a valid account? */
559     if (!$this->is_account && $this->parent == NULL){
560       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
561         _("This account has no phone extensions.")."</b>";
562       $display.= back_to_main();
563       return($display);
564     }
566     $display= "";
568     /* Show tab dialog headers */
569     if ($this->parent != NULL){
570       if ($this->is_account){
571         $display= $this->show_header(_("Remove phone account"),
572             _("This account has phone features enabled. You can disable them by clicking below."));
573       } else {
574         $display= $this->show_header(_("Create phone account"),
575             _("This account has phone features disabled. You can enable them by clicking below."));
576         return ($display);
577       }
578     }
580     /* Add phone number */
581     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
582       if (is_phone_nr($_POST['phonenumber'])){
583         $number= $_POST["phonenumber"];
584         $this->phoneNumbers[$number]= $number;
585         $this->is_modified= TRUE;
586       } else {
587         print_red(_("Please enter a valid phone number!"));
588       }
589     }
591     /* Remove phone number */
592     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
593       foreach ($_POST['phonenumber_list'] as $number){
594         unset($this->phoneNumbers[$number]);
595         $this->is_modified= TRUE;
596       }
597     }
599     /* Check for forwarding action */
600     foreach ($this->forwarders as $nr => $fw){
602       /* Buttons pressed? */
603       if (isset($_POST["add_fw$nr"])){
604         $this->forwarders= $this->insert_after("", $nr, $this->forwarders);
605       }
606       if (isset($_POST["remove_fw$nr"])){
607         unset($this->forwarders[$nr]);
608       }
609     }
611     /* Transfer ACL's */
612     foreach($this->attributes as $val){
613       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
614       $smarty->assign($val,$this->$val);
615     }
617     /* Fill arrays */
618     $smarty->assign ("goFonHardware", $this->goFonHardware);
619     if (!count($this->phoneNumbers)){
620       $smarty->assign ("phoneNumbers", array(""));
621     } else {
622       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
623     }
624     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
625       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
626     foreach ($this->hardware_list as $cn => $description){
627       if ($cn == $this->goFonHardware){
628         $selected= "selected";
629       } else {
630         $selected= "";
631       }
632       if (isset($this->used_hardware[$cn])){
633         $color= "style=\"color:#A0A0A0\"";
634       } else {
635         $color= "";
636       }
637       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
638     }
639     $hl.= "</select>\n";
640     $smarty->assign ("hardware_list", $hl);
642     /* Generate forwarder view */
643     $forwarder_list="";
644     $acl= chkacl($this->acl, "goFonForwaring");
645     foreach ($this->forwarders as $nr => $fw){
646       if ($fw == ""){
647         $number= ""; $timeout= "";
648       } else {
649         list($number, $timeout)= split(";", $fw);
650       }
651       $forwarder_list.= "<tr><td>";
652       $forwarder_list.= "<input name=\"fwn$nr\" size=25 align=\"middle\" maxlength=60 value=\"$number\" $acl>";
653       $forwarder_list.= "</td><td>";
654       $forwarder_list.= "<input name=\"fwt$nr\" size=5 align=\"middle\" maxlength=5 value=\"$timeout\" $acl>";
655       $forwarder_list.= "</td><td>";
656       $forwarder_list.= "<input type=\"submit\" value=\""._("Add")."\" name=\"add_fw$nr\" $acl>";
657       if (count($this->forwarders) > 1){
658         $forwarder_list.= "<input type=\"submit\" value=\""._("Remove")."\" name=\"remove_fw$nr\" $acl>";
659       }
660       $forwarder_list.= "</td></tr>";
661     }
662     $smarty->assign("forwarder_list", $forwarder_list);
664     /* Show main page */
665     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
666     return($display);
667   }
670   function save_object()
671   {
672     if (isset($_POST["phoneTab"])){
673       plugin::save_object();
675       /* Save checkbox */
676       if (isset($_POST['fon_to_mail'])){
677         $tmp= "[M]";
678       } else {
679         $tmp= "[]";
680       }
681       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
682         if ($this->goFonDeliveryMode != $tmp){
683           $this->is_modified= TRUE;
684         }
685         $this->goFonDeliveryMode= $tmp;
686       }
688       /* Save forwarding numbers and timeouts */
689       if (chkacl ($this->acl, "goFonForwarder") == ""){
690         foreach ($this->forwarders as $nr => $fw){
691           $tmp= $_POST["fwn$nr"].";".$_POST["fwt$nr"];
692           if ($this->forwarders[$nr] != $tmp){
693             $this->is_modified= TRUE;
694           }
695           $this->forwarders[$nr]= $tmp;
696         }
697       }
699       /* Every macro in the select box are available */
700       if((isset($_POST['macro']))){
701         $this->macrostillavailable=true;
702       }
704       /* get all Postvars */
705       if(isset($this->macroarray[$this->macro])){ 
706         foreach($this->macroarray[$this->macro] as $key => $paras){
707           if(isset($_POST[$paras['var']])){
708             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']]; 
709           }
711           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
712              We need this code below to read and save checkboxes correct
713            */
714           if($this->macroarray[$this->macro][$key]['type']=="bool"){
715             if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
716               $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
717             }else{
718               $this->macroarray[$this->macro][$key]['choosen']=false;
719             }
720           }
721         }
722       }
723     }
726   }
728   function check()
729   {
730     /* Reset message array */
731     $message= array();
733     if(!$this->generate_mysql_entension_entries()){
734       $message[] = $this->generate_error;
735     }
737     /* We need at least one phone number */
738     if (count($this->phoneNumbers) == 0){
739       $message[]= sprintf(_("You need to specify at least one phone number!"));
740     }
742     if(($this->goFonPIN)==""){
743       $this->goFonPIN = array();
744     }else{
745       if(strcmp ((int)($this->goFonPIN),($this->goFonPIN))){
746         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
747       }elseif(strlen($this->goFonPIN) < 4){
748         $message[] = sprintf(_("The given PIN is too short"));
749       }
751     }
752     /* Check timestamps and phonenumbers */
753     foreach ($this->forwarders as $fw){
755       /* Skip empty values */
756       if ($fw == ";"){
757         continue;
758       }         
760       /* Check */
761       list($number, $timeout)= split(";", $fw);
762       if (!is_phone_nr($number)){
763         $message[]= sprintf(_("The number '%s' is no valid phone number!"), $number);
764       }
765       if (!is_id($timeout)){
766         $message[]= sprintf(_("The timeout '%s' contains invalid characters!"), $timeout);
767       }
768     }
770     /* check for ! in any parameter setting*/
771     if(isset($this->macroarray[$this->macro])){
772       foreach($this->macroarray[$this->macro] as $val){
773         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
774           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
775         }
776       }
777     }
778     return ($message);
779   }
783   function save()
784   {
785     plugin::save();
787     /* Save arrays */
788     $this->attrs['telephoneNumber']= array();
789     foreach ($this->phoneNumbers as $number){
790       $this->attrs['telephoneNumber'][]= $number;
791     }
792     $this->attrs['goFonForwarding']= array();
793     foreach ($this->forwarders as $index => $number){
794       $this->attrs['goFonForwarding'][]= "$index;$number";
795     }
797     /* Save settings, or remove goFonMacro attribute*/
798     if($this->macro!="none"){    
799       $this->attrs['goFonMacro']=$this->macro;
800       if(isset($this->macroarray[$this->macro])){
801         foreach($this->macroarray[$this->macro] as $paras)  {
802           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
803         }
804       }
805     }else{
806       $this->attrs['goFonMacro']=array();
807     }
808     unset($this->attrs['macro'])  ;
810     if($this->attrs['goFonMacro']==""){
811       $this->attrs['goFonMacro']=array();
812     }
813     /* Write back to ldap */
814     $ldap= $this->config->get_ldap_link();
815     $ldap->cd($this->dn);
816     $ldap->modify($this->attrs);
817     show_ldap_error($ldap->get_error());
819     $this->generate_mysql_entension_entries(true);
822     /* Optionally execute a command after we're done */
823     if ($this->initially_was_account == $this->is_account){
824       if ($this->is_modified){
825         $this->handle_post_events("modify");
826       }
827     } else {
828       $this->handle_post_events("add");
829     }
831   }
834   function insert_after($entry, $nr, $list)
835   {
836     /* Is the entry free? No? Make it free... */
837     if (isset($list[$nr])) {
838       $dest= array();
839       $newidx= 0;
841       foreach ($list as $idx => $contents){
842         $dest[$newidx++]= $contents;
843         if ($idx == $nr){
844           $dest[$newidx++]= $entry;
845         }
846       }
847     } else {
848       $dest= $list;
849       $dest[$nr]= $entry;
850     }
852     return ($dest);
853   }
856   function adapt_from_template($dn)
857   {
858     plugin::adapt_from_template($dn);
860     /* Assemble phone numbers */
861     if (isset($this->attrs['telephoneNumber'])){
862       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
863         $number= $this->attrs['telephoneNumber'][$i];
864         $this->phoneNumbers[$number]= $number;
865       }
866     }
868     /* Assemble forwarders */
869     if (isset($this->attrs['goFonForwarding'])){
870       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
871         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
872         $this->forwarders[$num]= "$v1;$v2";
873       }
874     } else {
875       $this->forwarders= array("");
876     }
877   }
880   function remove_from_parent()
881   {
882     // Get Configuration for Mysql database Server
883     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
884     $s_parameter  ="";
886     // Connect to DB server
887     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
889     // Check if we are  connected correctly
890     if(!$r_con){
891       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
892           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
893       gosa_log(mysql_error());
894       return false;
895     }
897     // Select database for Extensions
898     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
900     // Test if we have the database selected correctly
901     if(!$db){
902       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
903       gosa_log(mysql_error());
904       return false;
905     }
907     $SQL="";
909     $first_num = false;
910     // Delete old entries
911       foreach($this->a_old_telenums as $s_telenums){
912         if(!$first_num){
913           $first_num = $s_telenums;
914         }
915         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
916       }
918       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
919       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
920       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
923       foreach($SQL as $query){
924         if(!mysql_query($query,$r_con)){
925           print_red(_("Stop".mysql_error()));
926           return false;
927         }
928       }
932     /* unset macro attr, it will cause an error */
933     $tmp = array_flip($this->attributes);
934     unset($tmp['macro']);
935     $this->attributes=array_flip($tmp);
937     /* Cancel if there's nothing to do here */
938     if (!$this->initially_was_account){
939       return;
940     }
942     plugin::remove_from_parent();
944     /* Just keep one phone number */
945     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
946       $this->attrs['telephoneNumber']= $this->telephoneNumber[0];
947     } else {
948       $this->attrs['telephoneNumber']= array();
949     }
951     $ldap= $this->config->get_ldap_link();
952     $ldap->cd($this->dn);
953     $ldap->modify($this->attrs);
954     show_ldap_error($ldap->get_error());
956     /* Optionally execute a command after we're done */
957     $this->handle_post_events('remove');
958   }
963 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
964 ?>