Code

3965507f6092b87b8c201ac731312e9c24a9a51f
[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     }
61     /* Assemble forwarders */
62     if (isset($this->attrs['goFonForwarding'])){
63       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
64         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
65         $this->forwarders[$num]= "$v1;$v2";
66       }
67     } else {
68       $this->forwarders= array("");
69     }
71     /* Set up has_mailAccount */
72     if (isset($this->attrs['objectClass'])){
73       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
74         $this->has_mailAccount= TRUE;
75       }
76     }
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){
129             /* Split Data in readable values, by delimiter !  */
130             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
132             /* Set all attrs */
133             $id = $data[0];
134             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
135             $string = preg_replace("/%uid/",$this->attrs['uid'][0],$data[3]);
136             $string = preg_replace("/%telephoneNumber/",$this->attrs['telephoneNumber'][0],$string);
137             $string = preg_replace("/%cn/",$this->attrs['cn'][0],$string);
138             $this->macroarray[$attrs['dn']][$id]['choosen']= $string; 
140             $this->macroarray[$attrs['dn']][$id]['id']     = $id;
141             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
142             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
143             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
144             if($data[2] == "bool"){
145               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
146             }
147           }//foreach
148         }//is_array
149       }//visible = 1
150     }//while
152     /* Go through already saved values, for a parameter */
153     $tmp = split("!",$this->goFonMacro);
155     /* it is possible that nothing has been saved yet */
156     if(is_array($tmp)){
158       /* First value is the macroname */
159       $this->macro = $tmp[0];
161       /* Macroname saved, delete that index */
162       unset($tmp[0]);
164       /* Check if makro has been removed */
165       if(!isset($this->macroarray[$this->macro])){
166         $this->macrostillavailable = false;
167       }else{
168         $this->macrostillavailable = true;
169       }
171       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
172       foreach($tmp as $var){
174         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
175         $varar = split("#",$var);
177         /* Only insert if the parameter still exists */
178         if(isset($this->macroarray[$this->macro][$varar[0]])){
179           /* Assign value */
180           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
181         }
182       }
183     }
186     /* Eventually colorize phones */
187     $ldap->cd($this->config->current['BASE']);
188     foreach ($this->hardware_list as $cn => $desc){
189       $ldap->search("(goFonHardware=$cn)", array('cn'));
190       if ($ldap->count() > 0){
191         $ldap->fetch();
192         if ($ldap->getDN() != $this->dn){
193           $this->used_hardware[$cn]= $ldap->getDN();
194         }
195       }
196     }
197     $this->hardware_list["automatic"]= _("automatic");
198     ksort($this->hardware_list);
199     $this->a_old_telenums = $this->phoneNumbers;
200   }
205   // Generate MySQL Syntax
206   function generate_mysql_entension_entries($save = false){
208     // Get Configuration for Mysql database Server
209     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
210     $s_parameter  ="";
212     // Connect to DB server
213     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
215     // Check if we are  connected correctly
216     if(!$r_con){
217       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
218           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
219       gosa_log(mysql_error());
220       return false;
221     }
223     // Select database for Extensions
224     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
226     // Test if we have the database selected correctly
227     if(!$db){
228       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
229       gosa_log(mysql_error());
230       return false;
231     }
233     // Get phonehardware to setup sip entry
234     $ldap= $this->config->get_ldap_link();
235     $res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
236     $attrs = $ldap->fetch();
238     // Attribute GoFonDefaultIP set ?
239     if(((isset($attrs['goFonDefaultIP'][0]))&&($attrs['goFonDefaultIP'][0] != "dynamic"))){
240       $ip = $attrs['goFonDefaultIP'][0];
241       $host = $ip;
242     }else{
243       $ip = NULL;
244       $host = "dynamic";
245     }
247     // Attribute GoFonQualify set ?
248     if(!isset($attrs['goFonQualify'])){
249       $qualify = NULL;
250     }else{
251       $qualify = $attrs['goFonQualify'][0];
252     }
254     // Attribute GoFonPIN set ?
255     if(!isset($this->goFonPIN)){
256       $pin = NULL;
257     }else{
258       $pin = $this->goFonPIN;
259     }
261     // Attribute GoFonType set ?
262     if(!isset($attrs['goFonType'])){
263       $type = NULL;
264     }else{
265       $type = $attrs['goFonType'][0];
266     }
268     // generate SIP entry
269     $sip_data_array['id']           = "";
270     $sip_data_array['name']         = $this->uid;
271     $sip_data_array['accountcode']  = NULL;          
272     $sip_data_array['amaflags']     = NULL;
273     $sip_data_array['callgroup']    = NULL;
274     $sip_data_array['callerid']     = "";
275     $sip_data_array['canreinvite']  = "yes";
277     // Must be default and the name of an entry that already exists
278     $sip_data_array['context']      = "default";
279     $sip_data_array['defaultip']    = NULL;
281     if(isset($attrs['goFonDmtfMode'][0])){
282       $sip_data_array['dtmfmode']     = $attrs['goFonDmtfMode'][0];
283     }else{
284       $sip_data_array['dtmfmode']     ="rfc2833";
285     }
286     $sip_data_array['fromuser']     = NULL;
287     $sip_data_array['fromdomain']   = NULL;
288     $sip_data_array['host']         = $host;
289     $sip_data_array['insecure']     = NULL;
290     $sip_data_array['language']     = NULL;
291     $sip_data_array['mailbox']      = "asterisk";
292     $sip_data_array['md5secret']    = NULL;
293     $sip_data_array['nat']          = "no";
294     $sip_data_array['permit']       = NULL;
295     $sip_data_array['deny']         = NULL;
296     $sip_data_array['mask']         = NULL;
297     $sip_data_array['pickupgroup']  = NULL;
298     $sip_data_array['port']         = NULL;
299     $sip_data_array['qualify']      = $qualify;
300     $sip_data_array['restrictcid']  = "n";
301     $sip_data_array['rtptimeout']   = NULL;
302     $sip_data_array['rtpholdtimeout']=NULL;
303     $sip_data_array['secret']       = $pin;
304     $sip_data_array['type']         = $type ;
305     $sip_data_array['username']     = $this->uid;
306     $sip_data_array['disallow']     = NULL;
307     $sip_data_array['allow']        = NULL;
308     $sip_data_array['musiconhold']  = NULL;
309     $sip_data_array['regseconds']   = NULL;
310     $sip_data_array['ipaddr']       = $ip;
311     $sip_data_array['regexten']     = NULL;
312     $sip_data_array['cancallforward']=NULL;
314     // Get selected Macro Parameter and create parameter entry 
315     if(isset($this->macroarray[$this->macro])){
316       foreach($this->macroarray[$this->macro] as $key => $val ){
317         $s_parameter .= $val['choosen']."|";
318       }
319       $s_parameter = preg_replace("/\|$/","",$s_parameter);
320     }
328     // $SQL contains all queries
329     $SQL = array();
330     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
331     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
333     // Create new SIP entry ...
334     $sip_entry = $sip_data_array;
336     reset($this->phoneNumbers);
338     $key = key($this->phoneNumbers);
339     $sip_entry['callerid']  =$this->phoneNumbers[$key];
340     $sip_entry['mailbox']   =$this->phoneNumbers[$key];
342     if($this->is_number_used()){
343       $this->generate_error = $this->is_number_used(); 
344       return false;
345     }
347     if($save == true){
348       if(isset($this->parent->by_object['mailAccount']->mail)){
349         $mail = $this->parent->by_object['mailAccount']->mail;
350       }else{
351         $mail = "";
352       }
355       $SQL[]= "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$this->phoneNumbers[$key]."';"; 
356       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." 
357         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`) 
358         VALUES 
359         ('".$this->phoneNumbers[$key]."','default','".$this->phoneNumbers[$key]."','".$this->goFonPIN."','".$this->sn."','".$mail."','');";
361       // Generate Strings with keys and values 
362       $values = "";
363       $keys   = "";
364       foreach($sip_entry as $key=>$val){
365         if($val == NULL) continue;
366         $values.="'".$val."',";
367         $keys  .="`".$key."`,";
368       }
369       // Remove last ,
370       $values =  preg_replace("/,$/","",$values);
371       $keys   =  preg_replace("/,$/","",$keys);
373       // Append SIP Entry 
374       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$keys.") VALUES (".$values.");";
376       // Delete old entries
377       foreach($this->a_old_telenums as $s_telenums){
378         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
379       }
381       $i_is_accounted=false;
383       // Entension entries  Hint / Dial / Goto
384       foreach($this->phoneNumbers as $s_telenums){
385         // Entry  to call by name
386         $s_entry_name['context']  = 'GOsa';
387         $s_entry_name['exten']    = $this->uid;
388         $s_entry_name['priority'] = 1;
389         $s_entry_name['app']      = 'Goto';
390         $s_entry_name['appdata']  = $s_telenums."|1";
392         // hint
393         $s_entry_hint['context']  = 'GOsa';
394         $s_entry_hint['exten']    = $s_telenums;
395         $s_entry_hint['app']      = 'hint';
396         $s_entry_hint['appdata']  = 'SIP/'.$this->uid;
398         // If no macro is selected use Dial
399         if($this->macro!="none"){ 
400           $macroname = preg_replace("/,.*$/","",$this->macro);        
401           $macroname = preg_replace("/^.*=/","",$macroname);        
402           $s_app = "Macro";$macroname;
403           $s_par = $macroname."|".$s_parameter; 
404         }else{
405           $s_app = "Dial";
406           $s_par = 'SIP/'.$this->uid;
407         }
409         // Entry  to call by number
410         $s_entry_phone['context']  = 'GOsa';
411         $s_entry_phone['exten']    = $s_telenums;
412         $s_entry_phone['priority'] = 1;
413         $s_entry_phone['app']      = $s_app;
414         $s_entry_phone['appdata']  = $s_par;
416         // append name entry only once
417         if(!$i_is_accounted){ 
418           $i_is_accounted = true;
419           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
420         }else{
421           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
422         }
423       }
425       // Append all these Entries 
426       foreach($entries as $num => $val){
427         foreach($val as $entr){
428           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
429           foreach($entr as $key2 => $val2){
430             $SQL_syn.= "`".$key2."`,";
431           }
432           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
433           $SQL_syn .= ") VALUES ("; 
434           foreach($entr as $key2 => $val2){
435             $SQL_syn .= "'".$val2."',";
436           }
437           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
438           $SQL_syn .=");\n";
439           $SQL[] =$SQL_syn;
440           $SQL_syn ="";
441         }
442       }
444       // Perform queries ...
445       foreach($SQL as $query){
446         if(!mysql_query($query,$r_con)){
447           print_red(_("Error while performing query ".mysql_error()));
448           return false;
449         }
450       }
451     }
452     return true;
453   }
468   function execute()
469   {
470     /* force postmodify event, to restart phones */
471     
472     $this->parent->by_object['user']->is_modified=TRUE;
473     $this->is_modified=TRUE; 
475     /* Do we need to flip is_account state? */
476     if (isset($_POST['modify_state'])){
477       $this->is_account= !$this->is_account;
478     }
480     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
481     if(empty($this->macro)){
482       $this->macro ="none";
483     }
485     /* tell user that the pluging selected is no longer available*/
486     if((!$this->macrostillavailable)&&($this->macro!="none")){
487       print_red(_("The macro you selected in the past, is no longer available for you, please choose another one."));
488     }
490     /* Prepare templating */
491     $smarty= get_smarty();
493     /* Assing macroselectbox values  */
494     $smarty->assign("macros",$this->macros);   
495     $smarty->assign("macro", $this->macro);   
497     /* Create parameter table, skip if no parameters given */
498     if(!isset($this->macroarray[$this->macro])){
499       $macrotab="";
500     }else{
502       $macrotab ="<table summary=\""._("Parameter")."\">";
503       /* for every single parameter-> display textfile,combo, or true false switch*/
506       foreach($this->macroarray[$this->macro] as $paras){
508         /* get al vars */
509         $var        = $paras['var'];           
510         $name       = $paras['name'];           
511         $default    = $paras['default'];
512         $type       = $paras['type'];
513         $choosen    = $paras['choosen'] ; 
514         $str        = $default;
516         /* in case of a combo box display a combobox with selected attr */
517         $macrotab.= "<tr>";
518         switch ($type){
520           case "combo":
521             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
522           foreach(split(":",$default) as $choice){
523             if($choosen==$choice){
524               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
525             }else{
526               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
527             }
528           }
529           $str.="</select>";
530           $macrotab.= "<td>$name</td><td>$str";
531           break;
533           case "bool":
534             if(!$choosen){
535               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
536             }else{
537               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
538             }
539           $macrotab.= "<td colspan='2'>$str&nbsp;$name";
540           break;
542           case "string":
543             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro").">";
544           $macrotab.= "<td>$name</td><td>$str";
545           break;
547         }
548         $macrotab.= "</td></tr>";
550       }
551       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
552     }//is_array()
554     /* Give smarty the table */
555     $smarty->assign("macrotab",$macrotab);
557     /* Do we represent a valid account? */
558     if (!$this->is_account && $this->parent == NULL){
559       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
560         _("This account has no phone extensions.")."</b>";
561       $display.= back_to_main();
562       return($display);
563     }
565     $display= "";
567     /* Show tab dialog headers */
568     if ($this->parent != NULL){
569       if ($this->is_account){
570         $display= $this->show_header(_("Remove phone account"),
571             _("This account has phone features enabled. You can disable them by clicking below."));
572       } else {
573         $display= $this->show_header(_("Create phone account"),
574             _("This account has phone features disabled. You can enable them by clicking below."));
575         return ($display);
576       }
577     }
579     /* Add phone number */
580     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
581       if (is_phone_nr($_POST['phonenumber'])){
582         $number= $_POST["phonenumber"];
583         $this->phoneNumbers[$number]= $number;
584         $this->is_modified= TRUE;
585       } else {
586         print_red(_("Please enter a valid phone number!"));
587       }
588     }
590     /* Remove phone number */
591     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
592       foreach ($_POST['phonenumber_list'] as $number){
593         unset($this->phoneNumbers[$number]);
594         $this->is_modified= TRUE;
595       }
596     }
598     /* Check for forwarding action */
599     foreach ($this->forwarders as $nr => $fw){
601       /* Buttons pressed? */
602       if (isset($_POST["add_fw$nr"])){
603         $this->forwarders= $this->insert_after("", $nr, $this->forwarders);
604       }
605       if (isset($_POST["remove_fw$nr"])){
606         unset($this->forwarders[$nr]);
607       }
608     }
610     /* Transfer ACL's */
611     foreach($this->attributes as $val){
612       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
613       $smarty->assign($val,$this->$val);
614     }
616     /* Fill arrays */
617     $smarty->assign ("goFonHardware", $this->goFonHardware);
618     if (!count($this->phoneNumbers)){
619       $smarty->assign ("phoneNumbers", array(""));
620     } else {
621       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
622     }
623     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
624       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
625     foreach ($this->hardware_list as $cn => $description){
626       if ($cn == $this->goFonHardware){
627         $selected= "selected";
628       } else {
629         $selected= "";
630       }
631       if (isset($this->used_hardware[$cn])){
632         $color= "style=\"color:#A0A0A0\"";
633       } else {
634         $color= "";
635       }
636       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
637     }
638     $hl.= "</select>\n";
639     $smarty->assign ("hardware_list", $hl);
641     /* Generate forwarder view */
642     $forwarder_list="";
643     $acl= chkacl($this->acl, "goFonForwaring");
644     foreach ($this->forwarders as $nr => $fw){
645       if ($fw == ""){
646         $number= ""; $timeout= "";
647       } else {
648         list($number, $timeout)= split(";", $fw);
649       }
650       $forwarder_list.= "<tr><td>";
651       $forwarder_list.= "<input name=\"fwn$nr\" size=25 align=\"middle\" maxlength=60 value=\"$number\" $acl>";
652       $forwarder_list.= "</td><td>";
653       $forwarder_list.= "<input name=\"fwt$nr\" size=5 align=\"middle\" maxlength=5 value=\"$timeout\" $acl>";
654       $forwarder_list.= "</td><td>";
655       $forwarder_list.= "<input type=\"submit\" value=\""._("Add")."\" name=\"add_fw$nr\" $acl>";
656       if (count($this->forwarders) > 1){
657         $forwarder_list.= "<input type=\"submit\" value=\""._("Remove")."\" name=\"remove_fw$nr\" $acl>";
658       }
659       $forwarder_list.= "</td></tr>";
660     }
661     $smarty->assign("forwarder_list", $forwarder_list);
663     /* Show main page */
664     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
665     return($display);
666   }
669   function save_object()
670   {
671     if (isset($_POST["phoneTab"])){
672       plugin::save_object();
674       /* Save checkbox */
675       if (isset($_POST['fon_to_mail'])){
676         $tmp= "[M]";
677       } else {
678         $tmp= "[]";
679       }
680       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
681         if ($this->goFonDeliveryMode != $tmp){
682           $this->is_modified= TRUE;
683         }
684         $this->goFonDeliveryMode= $tmp;
685       }
687       /* Save forwarding numbers and timeouts */
688       if (chkacl ($this->acl, "goFonForwarder") == ""){
689         foreach ($this->forwarders as $nr => $fw){
690           $tmp= $_POST["fwn$nr"].";".$_POST["fwt$nr"];
691           if ($this->forwarders[$nr] != $tmp){
692             $this->is_modified= TRUE;
693           }
694           $this->forwarders[$nr]= $tmp;
695         }
696       }
698       /* Every macro in the select box are available */
699       if((isset($_POST['macro']))){
700         $this->macrostillavailable=true;
701       }
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   
715           if(isset($_POST['post_success'])){
716             if($this->macroarray[$this->macro][$key]['type']=="bool"){
717               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
718                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
719               }else{
720                 $this->macroarray[$this->macro][$key]['choosen']=false;
721               }
722             }
723           }
724         }
725       }
726     }
727   }
729   function check()
730   {
731     /* Reset message array */
732     $message= array();
734     if(!$this->generate_mysql_entension_entries()){
735       $message[] = $this->generate_error;
736     }
738     /* We need at least one phone number */
739     if (count($this->phoneNumbers) == 0){
740       $message[]= sprintf(_("You need to specify at least one phone number!"));
741     }
743     if(($this->goFonPIN)==""){
744       $message[]= sprintf(_("You need to specify a Phone PIN."));
745     }else{
746       if(strcmp ((int)($this->goFonPIN),($this->goFonPIN))){
747         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
748       }elseif(strlen($this->goFonPIN) < 4){
749         $message[] = sprintf(_("The given PIN is too short"));
750       }
752     }
753     /* Check timestamps and phonenumbers */
754     foreach ($this->forwarders as $fw){
756       /* Skip empty values */
757       if ($fw == ";"){
758         continue;
759       }         
761       /* Check */
762       list($number, $timeout)= split(";", $fw);
763       if (!is_phone_nr($number)){
764         $message[]= sprintf(_("The number '%s' is no valid phone number!"), $number);
765       }
766       if (!is_id($timeout)){
767         $message[]= sprintf(_("The timeout '%s' contains invalid characters!"), $timeout);
768       }
769     }
771     /* check for ! in any parameter setting*/
772     if(isset($this->macroarray[$this->macro])){
773       foreach($this->macroarray[$this->macro] as $val){
774         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
775           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
776         }
777       }
778     }
779     return ($message);
780   }
784   function save()
785   {
786     plugin::save();
788     /* Save arrays */
789     $this->attrs['telephoneNumber']= array();
790     foreach ($this->phoneNumbers as $number){
791       $this->attrs['telephoneNumber'][]= $number;
792     }
793     $this->attrs['goFonForwarding']= array();
794     foreach ($this->forwarders as $index => $number){
795       $this->attrs['goFonForwarding'][]= "$index;$number";
796     }
798     /* Save settings, or remove goFonMacro attribute*/
799     if($this->macro!="none"){    
800       $this->attrs['goFonMacro']=$this->macro;
801       if(isset($this->macroarray[$this->macro])){
802         foreach($this->macroarray[$this->macro] as $paras)  {
803           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
804         }
805       }
806     }else{
807       $this->attrs['goFonMacro']=array();
808     }
809     unset($this->attrs['macro'])  ;
811     $this->generate_mysql_entension_entries(true);
813     if($this->attrs['goFonMacro']==""){
814       $this->attrs['goFonMacro']=array();
815     }
816     /* Write back to ldap */
817     $ldap= $this->config->get_ldap_link();
818     $ldap->cd($this->dn);
819     $ldap->modify($this->attrs);
820     show_ldap_error($ldap->get_error());
822     /* Optionally execute a command after we're done */
823     
824     if ($this->initially_was_account == $this->is_account){
825       if ($this->is_modified){
826         $this->handle_post_events("modify");
827       }
828     } else {
829       $this->handle_post_events("add");
830     }
832   }
835   function insert_after($entry, $nr, $list)
836   {
837     /* Is the entry free? No? Make it free... */
838     if (isset($list[$nr])) {
839       $dest= array();
840       $newidx= 0;
842       foreach ($list as $idx => $contents){
843         $dest[$newidx++]= $contents;
844         if ($idx == $nr){
845           $dest[$newidx++]= $entry;
846         }
847       }
848     } else {
849       $dest= $list;
850       $dest[$nr]= $entry;
851     }
853     return ($dest);
854   }
857   function adapt_from_template($dn)
858   {
859     plugin::adapt_from_template($dn);
861     /* Assemble phone numbers */
862     if (isset($this->attrs['telephoneNumber'])){
863       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
864         $number= $this->attrs['telephoneNumber'][$i];
865         $this->phoneNumbers[$number]= $number;
866       }
867     }
869     /* Assemble forwarders */
870     if (isset($this->attrs['goFonForwarding'])){
871       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
872         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
873         $this->forwarders[$num]= "$v1;$v2";
874       }
875     } else {
876       $this->forwarders= array("");
877     }
878   }
881   function remove_from_parent()
882   {
883     // Get Configuration for Mysql database Server
884     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
885     $s_parameter  ="";
887     // Connect to DB server
888     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
890     // Check if we are  connected correctly
891     if(!$r_con){
892       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
893           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
894       gosa_log(mysql_error());
895       return false;
896     }
898     // Select database for Extensions
899     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
901     // Test if we have the database selected correctly
902     if(!$db){
903       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
904       gosa_log(mysql_error());
905       return false;
906     }
908     $SQL="";
910     $first_num = false;
911     // Delete old entries
912     foreach($this->a_old_telenums as $s_telenums){
913       if(!$first_num){
914         $first_num = $s_telenums;
915       }
916       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
917     }
919     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
920     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
921     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
924     foreach($SQL as $query){
925       if(!mysql_query($query,$r_con)){
926         print_red(_("Stop".mysql_error()));
927         return false;
928       }
929     }
933     /* unset macro attr, it will cause an error */
934     $tmp = array_flip($this->attributes);
935     unset($tmp['macro']);
936     $this->attributes=array_flip($tmp);
938     /* Cancel if there's nothing to do here */
939     if (!$this->initially_was_account){
940       return;
941     }
943     plugin::remove_from_parent();
945     /* Just keep one phone number */
946     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
947       $this->attrs['telephoneNumber']= $this->telephoneNumber[0];
948     } else {
949       $this->attrs['telephoneNumber']= array();
950     }
952     $ldap= $this->config->get_ldap_link();
953     $ldap->cd($this->dn);
954     $ldap->modify($this->attrs);
955     show_ldap_error($ldap->get_error());
957     /* Optionally execute a command after we're done */
958     $this->handle_post_events('remove');
959   }
963   /* This function checks if the given phonenumbers are available or already in use*/
964   function is_number_used()
965   {
966     $ldap= $this->config->get_ldap_link();
967     $ldap->cd($this->config->current['BASE']);
968     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue))", array("telephoneNumber","cn","uid"));
969     while($attrs = $ldap->fetch()) {
970       unset($attrs['telephoneNumber']['count']);
971       foreach($attrs['telephoneNumber'] as $tele){
972         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
973         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
974         $numbers[$tele]=$attrs;
975       }
976     }
978     foreach($this->phoneNumbers as $num){
979       if(!isset($this->cn)) $this->cn = "";
981       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
982         if(isset($numbers[$num]['uid'][0])){
983           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
984         }else{
985           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
986         }
987       }
988     }
989   }
994 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
995 ?>