Code

dde34df58f5d077ba39a2da6e836dd36c39cfcec
[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 $goFonFormat            = "";
14   var $goFonPIN               = "";
15   var $goFonDeliveryMode      = "";
16   var $phoneNumbers           = array();
17   var $mail                   = "";
18   var $hardware_list          = array();
19   var $used_hardware          = array();
20   var $goFonMacro             = "";
21   var $macro                  = 0;              // Selected Macro
22   var $macros                 = array();        // List of macros for smarty select box
23   var $macroarray             = array();        // All needed macro informations
24   var $macrostillavailable    = false;
25   var $generate_error         = "";
26   var $a_old_telenums         = array();
27   var $goFonPINVoice          = "";
29   /* CLI vars */
30   var $cli_summary            = "Manage users phone account";
31   var $cli_description        = "Some longer text\nfor help";
32   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
34   /* attribute list for save action */
35   var $attributes             = array("goFonDeliveryMode", "goFonFormat","uid","cn","mail",
36       "goFonHardware", "goFonPIN", "telephoneNumber", "goFonMacro","macro");
37   var $objectclasses= array("goFonAccount");
39   function phoneAccount ($config, $dn= NULL)
40   {
41     plugin::plugin ($config, $dn);
43     /* Set phone hardware */
44     if (!isset($this->attrs['goFonHardware'])){
45       $this->goFonHardware= "automatic";
46     }
48     /* Preset voice format */
49     if (!isset($this->attrs['goFonFormat'])){
50       $this->goFonFormat= "wav";
51     }
53     /* Assemble phone numbers */
54     if (isset($this->attrs['telephoneNumber'])){
55       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
56         $number= $this->attrs['telephoneNumber'][$i];
57         $this->phoneNumbers[$number]= $number;
58       }
59     }
61     /* Set up has_mailAccount */
62     if (isset($this->attrs['objectClass'])){
63       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
64         $this->has_mailAccount= TRUE;
65       }
66     }
68     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
69     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
70     if(!$r_con){
71       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
72           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
73       gosa_log(mysql_error());
74       return false;
75     }
76     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
77     if(!$db){
78       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
79       gosa_log(mysql_error());
80       return false;
81     }
82  
83     $first = false; 
84     foreach($this->phoneNumbers as $key => $val){
85       if(!$first){
86         $first = $key;
87       }
88     }
90     $attrs = @mysql_fetch_row(@mysql_query("SELECT *  FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$first].";"));
91     if($attrs){
92       $this->goFonPINVoice = $attrs[4];
93     }else{
94       $this->goFonPINVoice = false;
95     }
97     /* Load hardware list */
98     $ldap= $this->config->get_ldap_link();
99     $ldap->cd($this->config->current['BASE']);
100     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
101     while ($attrs= $ldap->fetch()){
102       $cn= $attrs['cn'][0];
103       if (isset($attrs['description'])){
104         $description= " - ".$attrs['description'][0];
105       } else {
106         $description= "";
107       }
108       $this->hardware_list[$cn]= "$cn$description";
110     }
112     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
113     $ldap->search("(objectClass=goFonMacro)", array("*"));
115     /* Add none for no macro*/
116     $this->macros['none']=_("no macro");    
117     $this->macro ="none";
120     /* Fetch all Macros*/
121     while ($attrs= $ldap->fetch()){
123       /* Only visisble */
124       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
126         /* unset Count, we don't need that here */
127         unset($attrs['displayName']['count']);
129         /* fill Selectfield variable with Macros */
130         if(isset($attrs['displayName'][0])){
131           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
132         }else{
133           $this->macros[$attrs['dn']] = _("undefined");
134         }
136         /* Parse macro data, unset count for parameterarrays  */
137         unset($attrs['goFonMacroParameter']['count']);
139         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
140         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
142           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
143             /* Split Data in readable values, by delimiter !  */
144             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
146             /* Set all attrs */
147             $id = $data[0];
148             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
149             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
150             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
151             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
152             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
153             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
154             if($data[2] == "bool"){
155               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
156             }
157           }//foreach
158         }//is_array
159       }//visible = 1
160     }//while
162     /* Go through already saved values, for a parameter */
163     $tmp = split("!",$this->goFonMacro);
165     /* it is possible that nothing has been saved yet */
166     if(is_array($tmp)){
168       /* First value is the macroname */
169       $this->macro = $tmp[0];
171       /* Macroname saved, delete that index */
172       unset($tmp[0]);
174       /* Check if makro has been removed */
175       if(!isset($this->macroarray[$this->macro])){
176         $this->macrostillavailable = false;
177       }else{
178         $this->macrostillavailable = true;
179       }
181       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
182       foreach($tmp as $var){
184         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
185         $varar = split("#",$var);
187         /* Only insert if the parameter still exists */
188         if(isset($this->macroarray[$this->macro][$varar[0]])){
189           /* Assign value */
190           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
191         }
192       }
193     }
196     /* Eventually colorize phones */
197     $ldap->cd($this->config->current['BASE']);
198     foreach ($this->hardware_list as $cn => $desc){
199       $ldap->search("(goFonHardware=$cn)", array('cn'));
200       if ($ldap->count() > 0){
201         $ldap->fetch();
202         if ($ldap->getDN() != $this->dn){
203           $this->used_hardware[$cn]= $ldap->getDN();
204         }
205       }
206     }
207     $this->hardware_list["automatic"]= _("automatic");
208     ksort($this->hardware_list);
209     $this->a_old_telenums = $this->phoneNumbers;
210   }
213   // Generate MySQL Syntax
214   function generate_mysql_entension_entries($save = false){
216     // Get Configuration for Mysql database Server
217     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
218     $s_parameter    = "";                                           // Contains paramter for selected Macro 
219     $r_con          = false;                                        // DB connection
220     $r_db           = false;                                        // Selected DB
221     $r_res          = false;                                        // Result resource
222     $a_ldap_attrs   = array();                                      //  
224     $s_ip           = NULL;                   // Contains ip for Sip entry
225     $s_host         = NULL;                   // Contains host for Sip entry
226     $s_qualify      = NULL;                   // Qualify entry
227     $s_pin          = NULL;                   // Entry for secret
228     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
230     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
231     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
232     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
234     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
235     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
237     $s_sip_key      = "";     // Key for SIP entry index      
238     $s_sip_val      = "";     // Value for SIP entry index      
240     $b_first_deleted= false;  // Only delete first entry, 
241     $s_telenums     = "";     // for each value variable
243     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
246     // Connect to DB server
247     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
249     // Check if we are  connected correctly
250     if(!$r_con){
251       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
252           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
253       gosa_log(mysql_error());
254       return false;
255     }
257     // Select database for Extensions
258     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
260     // Test if we have the database selected correctly
261     if(!$r_db){
262       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
263       gosa_log(mysql_error());
264       return false;
265     }
267     // Get phonehardware to setup sip entry
268     $ldap         = $this->config->get_ldap_link();
269     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
270     $a_ldap_attrs = $ldap->fetch();
272     if($this->is_number_used()){
273       $this->generate_error = $this->is_number_used(); 
274       return false;
275     }
277     /* If Save == true, we should save something.
278      * Generate SQL, for drop of old entries
279      * Generate SQL, for insert new entries
280      */ 
281     if($save == true){
282       // Attribute GoFonDefaultIP set ?
283       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
284         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
285         $s_host     = $s_ip;
286       }else{
287         $s_ip       = NULL;
288         $s_host     = "dynamic";
289       }
291       // Attribute GoFonQualify set ?
292       if(isset($a_ldap_attrs['goFonQualify'])){
293         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
294       }
296       // Attribute GoFonPIN set ?
297       if(isset($this->goFonPIN)){
298         $s_pin      = $this->goFonPIN;
299       }
301       // Attribute GoFonType set ?
302       if(isset($a_ldap_attrs['goFonType'])){
303         $s_type = $a_ldap_attrs['goFonType'][0];
304       }
306       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
307         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
308       }else{
309         $sip_data_array['dtmfmode']     ="rfc2833";
310       }
312       // generate SIP entry
313       $sip_data_array['id']           = "";
314       $sip_data_array['name']         = $this->uid;
315       $sip_data_array['accountcode']  = NULL;          
316       $sip_data_array['amaflags']     = NULL;
317       $sip_data_array['callgroup']    = NULL;
318       $sip_data_array['callerid']     = "";
319       $sip_data_array['canreinvite']  = "yes";
320       $sip_data_array['context']      = "default";
321       $sip_data_array['defaultip']    = NULL;
322       $sip_data_array['fromuser']     = NULL;
323       $sip_data_array['fromdomain']   = NULL;
324       $sip_data_array['host']         = $s_host;
325       $sip_data_array['insecure']     = NULL;
326       $sip_data_array['language']     = NULL;
327       $sip_data_array['mailbox']      = "asterisk";
328       $sip_data_array['md5secret']    = NULL;
329       $sip_data_array['nat']          = "no";
330       $sip_data_array['permit']       = NULL;
331       $sip_data_array['deny']         = NULL;
332       $sip_data_array['mask']         = NULL;
333       $sip_data_array['pickupgroup']  = NULL;
334       $sip_data_array['port']         = NULL;
335       $sip_data_array['qualify']      = $s_qualify;
336       $sip_data_array['restrictcid']  = "n";
337       $sip_data_array['rtptimeout']   = NULL;
338       $sip_data_array['rtpholdtimeout']=NULL;
339       $sip_data_array['secret']       = $s_pin;
340       $sip_data_array['type']         = $s_type ;
341       $sip_data_array['username']     = $this->uid;
342       $sip_data_array['disallow']     = NULL;
343       $sip_data_array['allow']        = NULL;
344       $sip_data_array['musiconhold']  = NULL;
345       $sip_data_array['regseconds']   = NULL;
346       $sip_data_array['ipaddr']       = $s_ip;
347       $sip_data_array['regexten']     = NULL;
348       $sip_data_array['cancallforward']=NULL;
350       // Get selected Macro Parameter and create parameter entry 
351       if(isset($this->macroarray[$this->macro])){
352         foreach($this->macroarray[$this->macro] as $key => $val ){
353           $s_parameter .= $val['choosen']."|";
354         }
355         $s_parameter = preg_replace("/\|$/","",$s_parameter);
356       }
358       if($this->is_number_used()){
359         $this->generate_error = $this->is_number_used(); 
360         return false;
361       }
363       // Create new SIP entry ...
364       $sip_entry = $sip_data_array;
365       reset($this->phoneNumbers);
366       $i_new_key = key($this->phoneNumbers);
367       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
368       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
370       if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
371         $s_mail = $this->parent->by_object['mailAccount']->mail;
372       }else{
373         $s_mail = "";
374       }
376       // $SQL contains all queries
377       $SQL   = array();
378       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
379       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
380       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
382       // Generate Strings with keys and values 
383       foreach($sip_entry as $s_sip_key=>$s_sip_val){
384         if($s_sip_val == NULL) continue;
385         $s_sip_values.="'".$s_sip_val."',";
386         $s_sip_keys  .="`".$s_sip_key."`,";
387       }
388       // Remove last ,
389       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
390       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
392       // Append SIP Entry 
393       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
395       // Delete old entries
396       $b_first_deleted  =false;
397       foreach($this->a_old_telenums as $s_telenums){
398         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
399         if(!$b_first_deleted){
400           $b_first_deleted=true;
401           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
402         }
403       }
405       if(empty($this->goFonPINVoice)){
406         $this->goFonPINVoice = $this->goFonPIN;
407       } 
409       if((!isset($this->cn))||(empty($this->cn))){
410         $CNname= $this->uid;
411       }else{
412         $CNname= $this->cn;
413       }
415       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']."
416         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
417         VALUES
418         ('".$this->phoneNumbers[$i_new_key]."','default','".$this->phoneNumbers[$i_new_key]."','".$this->goFonPINVoice."','".$CNname."','".$s_mail."','');";
420       $i_is_accounted=false;
421     
422       $i = 0; 
423   
424       // Entension entries  Hint / Dial / Goto
425       foreach($this->phoneNumbers as $s_telenums){
427         /* Mapping : Name TO Number*/
428         $EXT[$i]['context'] = 'GOsa';
429         $EXT[$i]['exten']   = $this->uid;
430         $EXT[$i]['priority']= 1;
431         $EXT[$i]['app']     = "Goto";
432         $EXT[$i]['appdata'] = $s_telenums."|1";
433         $i ++;  
434         /* Hint Entry */
435         $EXT[$i]['context'] = 'GOsa';
436         $EXT[$i]['exten']   = $s_telenums;
437         $EXT[$i]['priority']= "Hint";
438         $EXT[$i]['app']     = 'SIP/'.$this->uid;
439         $i ++;  
440         /* SetCID */
441         $EXT[$i]['context'] = 'GOsa';
442         $EXT[$i]['exten']   = $s_telenums;
443         $EXT[$i]['priority']= 1;
444         $EXT[$i]['app']     = "SetCIDName";
445         $EXT[$i]['appdata'] = $CNname;
446         $i ++;  
448         // If no macro is selected use Dial
449         if($this->macro!="none"){ 
450           $macroname = preg_replace("/,.*$/","",$this->macro);        
451           $macroname = preg_replace("/^.*=/","",$macroname);        
452           $s_app = "Macro";$macroname;
453           $s_par = $macroname."|".$s_parameter; 
454         }else{
455           $s_app = "Dial";
456           $s_par = 'SIP/'.$this->uid;
457         }
459         $EXT[$i]['context'] = 'GOsa';
460         $EXT[$i]['exten']   = $s_telenums;
461         $EXT[$i]['priority']= 2;
462         $EXT[$i]['app']     = $s_app;
463         $EXT[$i]['appdata'] = $s_par;
464         $i ++;
466       }
468       // Append all these Entries 
469       foreach($EXT as $entr){
470         $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
471         foreach($entr as $key2 => $val2){
472           $SQL_syn.= "`".$key2."`,";
473         }
474         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
475         $SQL_syn .= ") VALUES ("; 
476         foreach($entr as $key2 => $val2){
477           $SQL_syn .= "'".$val2."',";
478         }
479         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
480         $SQL_syn .=");\n";
481         $SQL[] =$SQL_syn;
482         $SQL_syn ="";
483       }
485       // Perform queries ...
486       foreach($SQL as $query){
487         if(!mysql_query($query,$r_con)){
488           print_red(_("Error while performing query ".mysql_error()));
489           return false;
490         }
491       }
492     }
493     return true;
494   }
497   function execute()
498   {
499     /* Do we represent a valid account? */
500     if (!$this->is_account && $this->parent == NULL){
501       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
502         _("This account has no phone extensions.")."</b>";
503       $display.= back_to_main();
504       return ($display);
505     }
507     /* Do we need to flip is_account state? */
508     if (isset($_POST['modify_state'])){
509       $this->is_account= !$this->is_account;
510     }
512     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
513     if(empty($this->macro)){
514       $this->macro ="none";
515     }
517     /* Set new Voicemail password */
518     if(isset($_POST['goFonPINVoiceSet'])){
519       $this->goFonPINVoice = $_POST['goFonPIN'];
520     }
522     /* tell user that the pluging selected is no longer available*/
523     if((!$this->macrostillavailable)&&($this->macro!="none")){
524       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
525     }
527     /* Prepare templating */
528     $smarty= get_smarty();
530     /* Assing macroselectbox values  */
531     $smarty->assign("macros",$this->macros);   
532     $smarty->assign("macro", $this->macro);   
534     /* Create parameter table, skip if no parameters given */
535     if(!isset($this->macroarray[$this->macro])){
536       $macrotab="";
537     }else{
539       $macrotab ="<table summary=\""._("Parameter")."\">";
540       /* for every single parameter-> display textfile,combo, or true false switch*/
543       /* Automatic fill out */
544       if(isset($_POST['fillout'])){
546         foreach($this->phoneNumbers as $phonenum){
547           $tmp[] = $phonenum;
548         }
550         /* Go through all params */
551         foreach($this->macroarray[$this->macro] as $key => $paras){
553           $string = $paras['default'];
555           $string=preg_replace("/%uid/i",$this->uid,$string);
556           $string=preg_replace("/%cn/i",$this->cn,$string);
558           for($i = 0 ; $i < 10; $i++){
559             if(isset($tmp[$i])){
560               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
561             }
562           }
564           $this->macroarray[$this->macro][$key]['choosen']=$string;
565         }
566       }
568       foreach($this->macroarray[$this->macro] as $paras){
570         /* get al vars */
571         $var        = $paras['var'];           
572         $name       = $paras['name'];           
573         $default    = $paras['default'];
574         $type       = $paras['type'];
575         $choosen    = $paras['choosen'] ; 
576         $str        = $default;
578         /* in case of a combo box display a combobox with selected attr */
579         $macrotab.= "<tr>";
580         switch ($type){
582           case "combo":
583             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
584           foreach(split(":",$default) as $choice){
585             if($choosen==$choice){
586               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
587             }else{
588               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
589             }
590           }
591           $str.="</select>";
592           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
593           break;
595           case "bool":
596             if(!$choosen){
597               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
598             }else{
599               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
600             }
601           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
602           break;
604           case "string":
605             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
606           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
607           break;
609         }
610         $macrotab.= "</td></tr>";
612       }
613       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
614     }//is_array()
616     /* Give smarty the table */
617     $smarty->assign("macrotab",$macrotab);
619     /* Do we represent a valid account? */
620     if (!$this->is_account && $this->parent == NULL){
621       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
622         _("This account has no phone extensions.")."</b>";
623       $display.= back_to_main();
624       return($display);
625     }
627     $display= "";
629     /* Show tab dialog headers */
630     if ($this->parent != NULL){
631       if ($this->is_account){
632         $display= $this->show_header(_("Remove phone account"),
633             _("This account has phone features enabled. You can disable them by clicking below."));
634       } else {
635         if(empty($this->uid)){
636           $display= $this->show_header(_("Create phone account"),
637               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
638         }else{
639           $display= $this->show_header(_("Create phone account"),
640               _("This account has phone features disabled. You can enable them by clicking below."));
641         }
642         return ($display);
643       }
644     }
646     /* Add phone number */
647     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
648       if (is_phone_nr($_POST['phonenumber'])){
649         $number= $_POST["phonenumber"];
650         $this->phoneNumbers[$number]= $number;
651         $this->is_modified= TRUE;
652       } else {
653         print_red(_("Please enter a valid phone number!"));
654       }
655     }
657     /* Remove phone number */
658     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
659       foreach ($_POST['phonenumber_list'] as $number){
660         unset($this->phoneNumbers[$number]);
661         $this->is_modified= TRUE;
662       }
663     }
665     /* Transfer ACL's */
666     foreach($this->attributes as $val){
667       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
668       if(isset($this->$val)){
669         $smarty->assign($val,$this->$val);
670       }else{
671         $smarty->assign($val,"");
672       }
673     }
675     /* Fill arrays */
676     $smarty->assign ("goFonHardware", $this->goFonHardware);
677     if (!count($this->phoneNumbers)){
678       $smarty->assign ("phoneNumbers", array(""));
679     } else {
680       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
681     }
682     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
683       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
684     foreach ($this->hardware_list as $cn => $description){
685       if ($cn == $this->goFonHardware){
686         $selected= "selected";
687       } else {
688         $selected= "";
689       }
690       if (isset($this->used_hardware[$cn])){
691         $color= "style=\"color:#A0A0A0\"";
692       } else {
693         $color= "";
694       }
695       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
696     }
697     $hl.= "</select>\n";
698     $smarty->assign ("hardware_list", $hl);
700     /* Show main page */
701     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
702     return($display);
703   }
706   function save_object()
707   {
708     if (isset($_POST["phoneTab"])){
709       plugin::save_object();
711       /* Save checkbox */
712       if (isset($_POST['fon_to_mail'])){
713         $tmp= "[M]";
714       } else {
715         $tmp= "[]";
716       }
717       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
718         if ($this->goFonDeliveryMode != $tmp){
719           $this->is_modified= TRUE;
720         }
721         $this->goFonDeliveryMode= $tmp;
722       }
724       /* Every macro in the select box are available */
725       if((isset($_POST['macro']))){
726         $this->macrostillavailable=true;
727       }
729       if(is_array($this->phoneNumbers)){
730         foreach($this->phoneNumbers as $telenumms) {
731           $nummsinorder[]=$telenumms; 
732         }
733       }else{
734         $nummsinorder=array("");
735       }
737       /* get all Postvars */
738       if(isset($this->macroarray[$this->macro])){ 
739         foreach($this->macroarray[$this->macro] as $key => $paras){
740           if(isset($_POST[$paras['var']])){
741             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
742           }
744           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
745              We need this code below to read and save checkboxes correct
746            */
748           if(isset($_POST['post_success'])){
749             if($this->macroarray[$this->macro][$key]['type']=="bool"){
750               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
751                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
752               }else{
753                 $this->macroarray[$this->macro][$key]['choosen']=false;
754               }
755             }
756           }
757         }
758       }
759     }
760   }
762   function check()
763   {
764     /* Reset message array */
765     $message= array();
767     if(!$this->generate_mysql_entension_entries()){
768       $message[] = $this->generate_error;
769     }
771     /* We need at least one phone number */
772     if (count($this->phoneNumbers) == 0){
773       $message[]= sprintf(_("You need to specify at least one phone number!"));
774     }
776     if(($this->goFonPIN)==""){
777       $message[]= sprintf(_("You need to specify a Phone PIN."));
778     }else{
779       if(!is_id($this->goFonPIN)){
780         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
781       }elseif(strlen($this->goFonPIN) < 4){
782         $message[] = sprintf(_("The given PIN is too short"));
783       }
785     }
787     /* check for ! in any parameter setting*/
788     if(isset($this->macroarray[$this->macro])){
789       foreach($this->macroarray[$this->macro] as $val){
790         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
791           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
792         }
793       }
794     }
795     return ($message);
796   }
800   function save()
801   {
802     plugin::save();
804     /* Save arrays */
805     $this->attrs['telephoneNumber']= array();
806     foreach ($this->phoneNumbers as $number){
807       $this->attrs['telephoneNumber'][]= $number;
808     }
810     /* Save settings, or remove goFonMacro attribute*/
811     if($this->macro!="none"){    
812       $this->attrs['goFonMacro']=$this->macro;
813       if(isset($this->macroarray[$this->macro])){
814         foreach($this->macroarray[$this->macro] as $paras)  {
815           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
816         }
817       }
818     }else{
819       $this->attrs['goFonMacro']=array();
820     }
821     unset($this->attrs['macro'])  ;
823     $this->attrs['goFonForwarding']=array();
825     $this->generate_mysql_entension_entries(true);
827     if($this->attrs['goFonMacro']==""){
828       $this->attrs['goFonMacro']=array();
829     }
831     unset($this->attrs['cn']);
833     /* Write back to ldap */
834     $ldap= $this->config->get_ldap_link();
835     $ldap->cd($this->dn);
836     $ldap->modify($this->attrs);
837     show_ldap_error($ldap->get_error());
839     /* Optionally execute a command after we're done */
841     if ($this->initially_was_account == $this->is_account){
842       if ($this->is_modified){
843         $this->handle_post_events("modify");
844       }
845     } else {
846       $this->handle_post_events("add");
847     }
849   }
852   function insert_after($entry, $nr, $list)
853   {
854     /* Is the entry free? No? Make it free... */
855     if (isset($list[$nr])) {
856       $dest= array();
857       $newidx= 0;
859       foreach ($list as $idx => $contents){
860         $dest[$newidx++]= $contents;
861         if ($idx == $nr){
862           $dest[$newidx++]= $entry;
863         }
864       }
865     } else {
866       $dest= $list;
867       $dest[$nr]= $entry;
868     }
870     return ($dest);
871   }
874   function adapt_from_template($dn)
875   {
876     plugin::adapt_from_template($dn);
878     /* Assemble phone numbers */
879     if (isset($this->attrs['telephoneNumber'])){
880       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
881         $number= $this->attrs['telephoneNumber'][$i];
882         $this->phoneNumbers[$number]= $number;
883       }
884     }
885   }
888   function remove_from_parent()
889   {
890   
891     foreach($this->attributes as $key=>$val){
893       if(in_array($val,array("uid","cn","mail"))){
894         unset($this->attributes[$key]);
895         unset($this->$val);
896       }
897     
898     }
900     // Get Configuration for Mysql database Server
901     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
902     $s_parameter  ="";
904     // Connect to DB server
905     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
907     // Check if we are  connected correctly
908     if(!$r_con){
909       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
910           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
911       gosa_log(mysql_error());
912       return false;
913     }
915     // Select database for Extensions
916     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
918     // Test if we have the database selected correctly
919     if(!$db){
920       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
921       gosa_log(mysql_error());
922       return false;
923     }
925     $SQL="";
927     /* If deletion starts from userslist, cn uid are not set */
928     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
929       $this->uid = $this->parent->by_object['user']->uid;
930     }
932     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
933       $this->cn  = $this->parent->by_object['user']->cn;
934     }
936     $first_num = false;
937     // Delete old entries
938     foreach($this->a_old_telenums as $s_telenums){
939       if(!$first_num){
940         $first_num = $s_telenums;
941       }
942       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
943     }
945     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
946     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
947     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
950     foreach($SQL as $query){
951       if(!mysql_query($query,$r_con)){
952         print_red(_("Stop".mysql_error()));
953         return false;
954       }
955     }
959     /* unset macro attr, it will cause an error */
960     $tmp = array_flip($this->attributes);
961     unset($tmp['macro']);
962     $this->attributes=array_flip($tmp);
964     /* Cancel if there's nothing to do here */
965     if (!$this->initially_was_account){
966       return;
967     }
969     plugin::remove_from_parent();
971     /* Just keep one phone number */
972     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
973       $this->attrs['telephoneNumber']= $this->telephoneNumber;
974     } else {
975       $this->attrs['telephoneNumber']= array();
976     }
978     $ldap= $this->config->get_ldap_link();
979     $ldap->cd($this->config->current['BASE']);
980     $ldap->search("(objectClass=goFonQueue)", array("member"));
981     while($attr = $ldap->fetch()){
982       if(in_array($this->dn,$attr['member'])){
983         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
984         unset($new->by_object['ogroup']->memberList[$this->dn]);
985         unset($new->by_object['ogroup']->member[$this->dn]);
986         $new->save();
987         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
988       }
989     }
990     $ldap->cd($this->dn);
991     $ldap->modify($this->attrs);
992     show_ldap_error($ldap->get_error());
994     /* Optionally execute a command after we're done */
995     $this->handle_post_events('remove');
996   }
1000   /* This function checks if the given phonenumbers are available or already in use*/
1001   function is_number_used()
1002   {
1003     $ldap= $this->config->get_ldap_link();
1004     $ldap->cd($this->config->current['BASE']);
1005     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1006     while($attrs = $ldap->fetch()) {
1007       unset($attrs['telephoneNumber']['count']);
1008       foreach($attrs['telephoneNumber'] as $tele){
1009         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1010         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1011         $numbers[$tele]=$attrs;
1012       }
1013     }
1015     foreach($this->phoneNumbers as $num){
1016       if(!isset($this->cn)) $this->cn = "";
1018       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1019         if(isset($numbers[$num]['uid'][0])){
1020           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1021         }else{
1022           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1023         }
1024       }
1025     }
1026   }
1029 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1030 ?>