Code

Added check for duplicate use of Phonenumbers
[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];
340       foreach($this->phoneNumbers as $phonekey => $val){
341         $ress = mysql_query( "SELECT * FROM ".$a_SETUP['EXT_TABLE']." WHERE   ((exten='".$this->phoneNumbers[$phonekey]."') AND (app='hint')) 
342                                                                       OR      ((exten='".$this->phoneNumbers[$phonekey]."') AND (priority='hint'));");
343         while($atr = mysql_fetch_row($ress)){
344           $uid = preg_replace("/^.*\//","",$atr[5]);
345           if($uid != $this->uid){
346             $this->generate_error = sprintf(_("This telephone number '%s' is already assigned to userID '%s'"),$this->phoneNumbers[$key],$uid);
347             gosa_log(mysql_error());
348             return false;
349           }
350         }
351       }
353      
354     if($save == true){
355       if(isset($this->parent->by_object['mailAccount']->mail)){
356         $mail = $this->parent->by_object['mailAccount']->mail;
357       }else{
358         $mail = "";
359       }
362       $SQL[]= "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$this->phoneNumbers[$key]."';"; 
363       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." 
364                   (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`) 
365                VALUES 
366                   ('".$this->phoneNumbers[$key]."','default','".$this->phoneNumbers[$key]."','".$this->goFonPIN."','".$this->sn."','".$mail."','');";
368       // Generate Strings with keys and values 
369       $values = "";
370       $keys   = "";
371       foreach($sip_entry as $key=>$val){
372         if($val == NULL) continue;
373         $values.="'".$val."',";
374         $keys  .="`".$key."`,";
375       }
376       // Remove last ,
377       $values =  preg_replace("/,$/","",$values);
378       $keys   =  preg_replace("/,$/","",$keys);
380       // Append SIP Entry 
381       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$keys.") VALUES (".$values.");";
383       // Delete old entries
384       foreach($this->a_old_telenums as $s_telenums){
385         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
386       }
388       $i_is_accounted=false;
390       // Entension entries  Hint / Dial / Goto
391       foreach($this->phoneNumbers as $s_telenums){
392         // Entry  to call by name
393         $s_entry_name['context']  = 'GOsa';
394         $s_entry_name['exten']    = $this->uid;
395         $s_entry_name['priority'] = 1;
396         $s_entry_name['app']      = 'Goto';
397         $s_entry_name['appdata']  = $s_telenums."|1";
398         
399         // hint
400         $s_entry_hint['context']  = 'GOsa';
401         $s_entry_hint['exten']    = $s_telenums;
402         $s_entry_hint['app']      = 'hint';
403         $s_entry_hint['appdata']  = 'SIP/'.$this->uid;
405         // If no macro is selected use Dial
406         if($this->macro!="none"){ 
407           $macroname = preg_replace("/,.*$/","",$this->macro);        
408           $macroname = preg_replace("/^.*=/","",$macroname);        
409           $s_app = "Macro";$macroname;
410           $s_par = $macroname."|".$s_parameter; 
411         }else{
412           $s_app = "Dial";
413           $s_par = 'SIP/'.$this->uid;
414         }
416         // Entry  to call by number
417         $s_entry_phone['context']  = 'GOsa';
418         $s_entry_phone['exten']    = $s_telenums;
419         $s_entry_phone['priority'] = 1;
420         $s_entry_phone['app']      = $s_app;
421         $s_entry_phone['appdata']  = $s_par;
423         // append name entry only once
424         if(!$i_is_accounted){ 
425           $i_is_accounted = true;
426           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
427         }else{
428           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
429         }
430       }
432       // Append all these Entries 
433       foreach($entries as $num => $val){
434         foreach($val as $entr){
435           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
436           foreach($entr as $key2 => $val2){
437             $SQL_syn.= "`".$key2."`,";
438           }
439           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
440           $SQL_syn .= ") VALUES ("; 
441           foreach($entr as $key2 => $val2){
442             $SQL_syn .= "'".$val2."',";
443           }
444           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
445           $SQL_syn .=");\n";
446           $SQL[] =$SQL_syn;
447           $SQL_syn ="";
448         }
449       }
451       // Perform queries ...
452       foreach($SQL as $query){
453         if(!mysql_query($query,$r_con)){
454           print_red(_("Error while performing query ".mysql_error()));
455           return false;
456         }
457       }
458     }
459   return true;
460   }
475   function execute()
476   {
477     /* Do we need to flip is_account state? */
478     if (isset($_POST['modify_state'])){
479       $this->is_account= !$this->is_account;
480     }
482     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
483     if(empty($this->macro)){
484       $this->macro ="none";
485     }
487     /* tell user that the pluging selected is no longer available*/
488     if((!$this->macrostillavailable)&&($this->macro!="none")){
489       print_red(_("The macro you selected in the past, is no longer available for you, please choose another one."));
490     }
492     /* Prepare templating */
493     $smarty= get_smarty();
495     /* Assing macroselectbox values  */
496     $smarty->assign("macros",$this->macros);   
497     $smarty->assign("macro", $this->macro);   
499     /* Create parameter table, skip if no parameters given */
500     if(!isset($this->macroarray[$this->macro])){
501       $macrotab="";
502     }else{
504       $macrotab ="<table summary=\""._("Parameter")."\">";
505       /* 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>";
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       }
703       /* get all Postvars */
704       if(isset($this->macroarray[$this->macro])){ 
705         foreach($this->macroarray[$this->macro] as $key => $paras){
706           if(isset($_POST[$paras['var']])){
707             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']]; 
708           }
710           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
711              We need this code below to read and save checkboxes correct
712            */
713           if($this->macroarray[$this->macro][$key]['type']=="bool"){
714             if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
715               $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
716             }else{
717               $this->macroarray[$this->macro][$key]['choosen']=false;
718             }
719           }
720         }
721       }
722     }
725   }
727   function check()
728   {
729     /* Reset message array */
730     $message= array();
732     if(!$this->generate_mysql_entension_entries()){
733       $message[] = $this->generate_error;
734     }
736     /* We need at least one phone number */
737     if (count($this->phoneNumbers) == 0){
738       $message[]= sprintf(_("You need to specify at least one phone number!"));
739     }
741     if(($this->goFonPIN)==""){
742       $this->goFonPIN = array();
743     }else{
744       if(strcmp ((int)($this->goFonPIN),($this->goFonPIN))){
745         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
746       }elseif(strlen($this->goFonPIN) < 4){
747         $message[] = sprintf(_("The given PIN is too short"));
748       }
750     }
751     /* Check timestamps and phonenumbers */
752     foreach ($this->forwarders as $fw){
754       /* Skip empty values */
755       if ($fw == ";"){
756         continue;
757       }         
759       /* Check */
760       list($number, $timeout)= split(";", $fw);
761       if (!is_phone_nr($number)){
762         $message[]= sprintf(_("The number '%s' is no valid phone number!"), $number);
763       }
764       if (!is_id($timeout)){
765         $message[]= sprintf(_("The timeout '%s' contains invalid characters!"), $timeout);
766       }
767     }
769     /* check for ! in any parameter setting*/
770     if(isset($this->macroarray[$this->macro])){
771       foreach($this->macroarray[$this->macro] as $val){
772         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
773           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
774         }
775       }
776     }
777     return ($message);
778   }
782   function save()
783   {
784     plugin::save();
786     /* Save arrays */
787     $this->attrs['telephoneNumber']= array();
788     foreach ($this->phoneNumbers as $number){
789       $this->attrs['telephoneNumber'][]= $number;
790     }
791     $this->attrs['goFonForwarding']= array();
792     foreach ($this->forwarders as $index => $number){
793       $this->attrs['goFonForwarding'][]= "$index;$number";
794     }
796     /* Save settings, or remove goFonMacro attribute*/
797     if($this->macro!="none"){    
798       $this->attrs['goFonMacro']=$this->macro;
799       if(isset($this->macroarray[$this->macro])){
800         foreach($this->macroarray[$this->macro] as $paras)  {
801           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
802         }
803       }
804     }else{
805       $this->attrs['goFonMacro']=array();
806     }
807     unset($this->attrs['macro'])  ;
809     if($this->attrs['goFonMacro']==""){
810       $this->attrs['goFonMacro']=array();
811     }
812     /* Write back to ldap */
813     $ldap= $this->config->get_ldap_link();
814     $ldap->cd($this->dn);
815     $ldap->modify($this->attrs);
816     show_ldap_error($ldap->get_error());
818     $this->generate_mysql_entension_entries(true);
821     /* Optionally execute a command after we're done */
822     if ($this->initially_was_account == $this->is_account){
823       if ($this->is_modified){
824         $this->handle_post_events("modify");
825       }
826     } else {
827       $this->handle_post_events("add");
828     }
830   }
833   function insert_after($entry, $nr, $list)
834   {
835     /* Is the entry free? No? Make it free... */
836     if (isset($list[$nr])) {
837       $dest= array();
838       $newidx= 0;
840       foreach ($list as $idx => $contents){
841         $dest[$newidx++]= $contents;
842         if ($idx == $nr){
843           $dest[$newidx++]= $entry;
844         }
845       }
846     } else {
847       $dest= $list;
848       $dest[$nr]= $entry;
849     }
851     return ($dest);
852   }
855   function adapt_from_template($dn)
856   {
857     plugin::adapt_from_template($dn);
859     /* Assemble phone numbers */
860     if (isset($this->attrs['telephoneNumber'])){
861       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
862         $number= $this->attrs['telephoneNumber'][$i];
863         $this->phoneNumbers[$number]= $number;
864       }
865     }
867     /* Assemble forwarders */
868     if (isset($this->attrs['goFonForwarding'])){
869       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
870         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
871         $this->forwarders[$num]= "$v1;$v2";
872       }
873     } else {
874       $this->forwarders= array("");
875     }
876   }
879   function remove_from_parent()
880   {
881     // Get Configuration for Mysql database Server
882     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
883     $s_parameter  ="";
885     // Connect to DB server
886     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
888     // Check if we are  connected correctly
889     if(!$r_con){
890       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
891           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
892       gosa_log(mysql_error());
893       return false;
894     }
896     // Select database for Extensions
897     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
899     // Test if we have the database selected correctly
900     if(!$db){
901       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
902       gosa_log(mysql_error());
903       return false;
904     }
906     $SQL="";
908     $first_num = false;
909     // Delete old entries
910       foreach($this->a_old_telenums as $s_telenums){
911         if(!$first_num){
912           $first_num = $s_telenums;
913         }
914         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
915       }
917       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
918       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
919       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
922       foreach($SQL as $query){
923         if(!mysql_query($query,$r_con)){
924           print_red(_("Stop".mysql_error()));
925           return false;
926         }
927       }
931     /* unset macro attr, it will cause an error */
932     $tmp = array_flip($this->attributes);
933     unset($tmp['macro']);
934     $this->attributes=array_flip($tmp);
936     /* Cancel if there's nothing to do here */
937     if (!$this->initially_was_account){
938       return;
939     }
941     plugin::remove_from_parent();
943     /* Just keep one phone number */
944     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
945       $this->attrs['telephoneNumber']= $this->telephoneNumber[0];
946     } else {
947       $this->attrs['telephoneNumber']= array();
948     }
950     $ldap= $this->config->get_ldap_link();
951     $ldap->cd($this->dn);
952     $ldap->modify($this->attrs);
953     show_ldap_error($ldap->get_error());
955     /* Optionally execute a command after we're done */
956     $this->handle_post_events('remove');
957   }
962 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
963 ?>