Code

some fixes
[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       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']."
410         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
411         VALUES
412         ('".$this->phoneNumbers[$i_new_key]."','default','".$this->phoneNumbers[$i_new_key]."','".$this->goFonPINVoice."','".$this->cn."','".$s_mail."','');";
414       $i_is_accounted=false;
415     
416       $i = 0; 
417   
418       // Entension entries  Hint / Dial / Goto
419       foreach($this->phoneNumbers as $s_telenums){
421         /* Mapping : Name TO Number*/
422         $EXT[$i]['context'] = 'GOsa';
423         $EXT[$i]['exten']   = $this->uid;
424         $EXT[$i]['priority']= 1;
425         $EXT[$i]['app']     = "Goto";
426         $EXT[$i]['appdata'] = $s_telenums."|1";
427         $i ++;  
428         /* Hint Entry */
429         $EXT[$i]['context'] = 'GOsa';
430         $EXT[$i]['exten']   = $s_telenums;
431         $EXT[$i]['priority']= "Hint";
432         $EXT[$i]['app']     = 'SIP/'.$this->uid;
433         $i ++;  
434         /* SetCID */
435         $EXT[$i]['context'] = 'GOsa';
436         $EXT[$i]['exten']   = $s_telenums;
437         $EXT[$i]['priority']= 1;
438         $EXT[$i]['app']     = "SetCIDName";
439         $EXT[$i]['appdata'] = $this->cn;
440         $i ++;  
442         // If no macro is selected use Dial
443         if($this->macro!="none"){ 
444           $macroname = preg_replace("/,.*$/","",$this->macro);        
445           $macroname = preg_replace("/^.*=/","",$macroname);        
446           $s_app = "Macro";$macroname;
447           $s_par = $macroname."|".$s_parameter; 
448         }else{
449           $s_app = "Dial";
450           $s_par = 'SIP/'.$this->uid;
451         }
453         $EXT[$i]['context'] = 'GOsa';
454         $EXT[$i]['exten']   = $s_telenums;
455         $EXT[$i]['priority']= 2;
456         $EXT[$i]['app']     = $s_app;
457         $EXT[$i]['appdata'] = $s_par;
458         $i ++;
460       }
462       // Append all these Entries 
463       foreach($EXT as $entr){
464         $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
465         foreach($entr as $key2 => $val2){
466           $SQL_syn.= "`".$key2."`,";
467         }
468         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
469         $SQL_syn .= ") VALUES ("; 
470         foreach($entr as $key2 => $val2){
471           $SQL_syn .= "'".$val2."',";
472         }
473         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
474         $SQL_syn .=");\n";
475         $SQL[] =$SQL_syn;
476         $SQL_syn ="";
477       }
479       // Perform queries ...
480       foreach($SQL as $query){
481         if(!mysql_query($query,$r_con)){
482           print_red(_("Error while performing query ".mysql_error()));
483           return false;
484         }
485       }
486     }
487     return true;
488   }
491   function execute()
492   {
493     /* Do we represent a valid account? */
494     if (!$this->is_account && $this->parent == NULL){
495       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
496         _("This account has no phone extensions.")."</b>";
497       $display.= back_to_main();
498       return ($display);
499     }
501     /* Do we need to flip is_account state? */
502     if (isset($_POST['modify_state'])){
503       $this->is_account= !$this->is_account;
504     }
506     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
507     if(empty($this->macro)){
508       $this->macro ="none";
509     }
511     /* Set new Voicemail password */
512     if(isset($_POST['goFonPINVoiceSet'])){
513       $this->goFonPINVoice = $_POST['goFonPIN'];
514     }
516     /* tell user that the pluging selected is no longer available*/
517     if((!$this->macrostillavailable)&&($this->macro!="none")){
518       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
519     }
521     /* Prepare templating */
522     $smarty= get_smarty();
524     /* Assing macroselectbox values  */
525     $smarty->assign("macros",$this->macros);   
526     $smarty->assign("macro", $this->macro);   
528     /* Create parameter table, skip if no parameters given */
529     if(!isset($this->macroarray[$this->macro])){
530       $macrotab="";
531     }else{
533       $macrotab ="<table summary=\""._("Parameter")."\">";
534       /* for every single parameter-> display textfile,combo, or true false switch*/
537       /* Automatic fill out */
538       if(isset($_POST['fillout'])){
540         foreach($this->phoneNumbers as $phonenum){
541           $tmp[] = $phonenum;
542         }
544         /* Go through all params */
545         foreach($this->macroarray[$this->macro] as $key => $paras){
547           $string = $paras['default'];
549           $string=preg_replace("/%uid/i",$this->uid,$string);
550           $string=preg_replace("/%cn/i",$this->cn,$string);
552           for($i = 0 ; $i < 10; $i++){
553             if(isset($tmp[$i])){
554               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
555             }
556           }
558           $this->macroarray[$this->macro][$key]['choosen']=$string;
559         }
560       }
562       foreach($this->macroarray[$this->macro] as $paras){
564         /* get al vars */
565         $var        = $paras['var'];           
566         $name       = $paras['name'];           
567         $default    = $paras['default'];
568         $type       = $paras['type'];
569         $choosen    = $paras['choosen'] ; 
570         $str        = $default;
572         /* in case of a combo box display a combobox with selected attr */
573         $macrotab.= "<tr>";
574         switch ($type){
576           case "combo":
577             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
578           foreach(split(":",$default) as $choice){
579             if($choosen==$choice){
580               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
581             }else{
582               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
583             }
584           }
585           $str.="</select>";
586           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
587           break;
589           case "bool":
590             if(!$choosen){
591               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
592             }else{
593               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
594             }
595           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
596           break;
598           case "string":
599             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
600           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
601           break;
603         }
604         $macrotab.= "</td></tr>";
606       }
607       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
608     }//is_array()
610     /* Give smarty the table */
611     $smarty->assign("macrotab",$macrotab);
613     /* Do we represent a valid account? */
614     if (!$this->is_account && $this->parent == NULL){
615       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
616         _("This account has no phone extensions.")."</b>";
617       $display.= back_to_main();
618       return($display);
619     }
621     $display= "";
623     /* Show tab dialog headers */
624     if ($this->parent != NULL){
625       if ($this->is_account){
626         $display= $this->show_header(_("Remove phone account"),
627             _("This account has phone features enabled. You can disable them by clicking below."));
628       } else {
629         if(empty($this->uid)){
630           $display= $this->show_header(_("Create phone account"),
631               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
632         }else{
633           $display= $this->show_header(_("Create phone account"),
634               _("This account has phone features disabled. You can enable them by clicking below."));
635         }
636         return ($display);
637       }
638     }
640     /* Add phone number */
641     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
642       if (is_phone_nr($_POST['phonenumber'])){
643         $number= $_POST["phonenumber"];
644         $this->phoneNumbers[$number]= $number;
645         $this->is_modified= TRUE;
646       } else {
647         print_red(_("Please enter a valid phone number!"));
648       }
649     }
651     /* Remove phone number */
652     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
653       foreach ($_POST['phonenumber_list'] as $number){
654         unset($this->phoneNumbers[$number]);
655         $this->is_modified= TRUE;
656       }
657     }
659     /* Transfer ACL's */
660     foreach($this->attributes as $val){
661       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
662       $smarty->assign($val,$this->$val);
663     }
665     /* Fill arrays */
666     $smarty->assign ("goFonHardware", $this->goFonHardware);
667     if (!count($this->phoneNumbers)){
668       $smarty->assign ("phoneNumbers", array(""));
669     } else {
670       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
671     }
672     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
673       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
674     foreach ($this->hardware_list as $cn => $description){
675       if ($cn == $this->goFonHardware){
676         $selected= "selected";
677       } else {
678         $selected= "";
679       }
680       if (isset($this->used_hardware[$cn])){
681         $color= "style=\"color:#A0A0A0\"";
682       } else {
683         $color= "";
684       }
685       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
686     }
687     $hl.= "</select>\n";
688     $smarty->assign ("hardware_list", $hl);
690     /* Show main page */
691     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
692     return($display);
693   }
696   function save_object()
697   {
698     if (isset($_POST["phoneTab"])){
699       plugin::save_object();
701       /* Save checkbox */
702       if (isset($_POST['fon_to_mail'])){
703         $tmp= "[M]";
704       } else {
705         $tmp= "[]";
706       }
707       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
708         if ($this->goFonDeliveryMode != $tmp){
709           $this->is_modified= TRUE;
710         }
711         $this->goFonDeliveryMode= $tmp;
712       }
714       /* Every macro in the select box are available */
715       if((isset($_POST['macro']))){
716         $this->macrostillavailable=true;
717       }
719       if(is_array($this->phoneNumbers)){
720         foreach($this->phoneNumbers as $telenumms) {
721           $nummsinorder[]=$telenumms; 
722         }
723       }else{
724         $nummsinorder=array("");
725       }
727       /* get all Postvars */
728       if(isset($this->macroarray[$this->macro])){ 
729         foreach($this->macroarray[$this->macro] as $key => $paras){
730           if(isset($_POST[$paras['var']])){
731             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
732           }
734           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
735              We need this code below to read and save checkboxes correct
736            */
738           if(isset($_POST['post_success'])){
739             if($this->macroarray[$this->macro][$key]['type']=="bool"){
740               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
741                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
742               }else{
743                 $this->macroarray[$this->macro][$key]['choosen']=false;
744               }
745             }
746           }
747         }
748       }
749     }
750   }
752   function check()
753   {
754     /* Reset message array */
755     $message= array();
757     if(!$this->generate_mysql_entension_entries()){
758       $message[] = $this->generate_error;
759     }
761     /* We need at least one phone number */
762     if (count($this->phoneNumbers) == 0){
763       $message[]= sprintf(_("You need to specify at least one phone number!"));
764     }
766     if(($this->goFonPIN)==""){
767       $message[]= sprintf(_("You need to specify a Phone PIN."));
768     }else{
769       if(!is_id($this->goFonPIN)){
770         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
771       }elseif(strlen($this->goFonPIN) < 4){
772         $message[] = sprintf(_("The given PIN is too short"));
773       }
775     }
777     /* check for ! in any parameter setting*/
778     if(isset($this->macroarray[$this->macro])){
779       foreach($this->macroarray[$this->macro] as $val){
780         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
781           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
782         }
783       }
784     }
785     return ($message);
786   }
790   function save()
791   {
792     plugin::save();
794     /* Save arrays */
795     $this->attrs['telephoneNumber']= array();
796     foreach ($this->phoneNumbers as $number){
797       $this->attrs['telephoneNumber'][]= $number;
798     }
800     /* Save settings, or remove goFonMacro attribute*/
801     if($this->macro!="none"){    
802       $this->attrs['goFonMacro']=$this->macro;
803       if(isset($this->macroarray[$this->macro])){
804         foreach($this->macroarray[$this->macro] as $paras)  {
805           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
806         }
807       }
808     }else{
809       $this->attrs['goFonMacro']=array();
810     }
811     unset($this->attrs['macro'])  ;
813     $this->attrs['goFonForwarding']=array();
815     $this->generate_mysql_entension_entries(true);
817     if($this->attrs['goFonMacro']==""){
818       $this->attrs['goFonMacro']=array();
819     }
821     /* Write back to ldap */
822     $ldap= $this->config->get_ldap_link();
823     $ldap->cd($this->dn);
824     $ldap->modify($this->attrs);
825     show_ldap_error($ldap->get_error());
827     /* Optionally execute a command after we're done */
829     if ($this->initially_was_account == $this->is_account){
830       if ($this->is_modified){
831         $this->handle_post_events("modify");
832       }
833     } else {
834       $this->handle_post_events("add");
835     }
837   }
840   function insert_after($entry, $nr, $list)
841   {
842     /* Is the entry free? No? Make it free... */
843     if (isset($list[$nr])) {
844       $dest= array();
845       $newidx= 0;
847       foreach ($list as $idx => $contents){
848         $dest[$newidx++]= $contents;
849         if ($idx == $nr){
850           $dest[$newidx++]= $entry;
851         }
852       }
853     } else {
854       $dest= $list;
855       $dest[$nr]= $entry;
856     }
858     return ($dest);
859   }
862   function adapt_from_template($dn)
863   {
864     plugin::adapt_from_template($dn);
866     /* Assemble phone numbers */
867     if (isset($this->attrs['telephoneNumber'])){
868       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
869         $number= $this->attrs['telephoneNumber'][$i];
870         $this->phoneNumbers[$number]= $number;
871       }
872     }
873   }
876   function remove_from_parent()
877   {
878   
879     foreach($this->attributes as $key=>$val){
881       if(in_array($val,array("uid","cn","mail"))){
882         unset($this->attributes[$key]);
883         unset($this->$val);
884       }
885     
886     }
888     // Get Configuration for Mysql database Server
889     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
890     $s_parameter  ="";
892     // Connect to DB server
893     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
895     // Check if we are  connected correctly
896     if(!$r_con){
897       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
898           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
899       gosa_log(mysql_error());
900       return false;
901     }
903     // Select database for Extensions
904     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
906     // Test if we have the database selected correctly
907     if(!$db){
908       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
909       gosa_log(mysql_error());
910       return false;
911     }
913     $SQL="";
915     /* If deletion starts from userslist, cn uid are not set */
916     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
917       $this->uid = $this->parent->by_object['user']->uid;
918     }
920     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
921       $this->cn  = $this->parent->by_object['user']->cn;
922     }
924     $first_num = false;
925     // Delete old entries
926     foreach($this->a_old_telenums as $s_telenums){
927       if(!$first_num){
928         $first_num = $s_telenums;
929       }
930       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
931     }
933     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
934     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
935     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
938     foreach($SQL as $query){
939       if(!mysql_query($query,$r_con)){
940         print_red(_("Stop".mysql_error()));
941         return false;
942       }
943     }
947     /* unset macro attr, it will cause an error */
948     $tmp = array_flip($this->attributes);
949     unset($tmp['macro']);
950     $this->attributes=array_flip($tmp);
952     /* Cancel if there's nothing to do here */
953     if (!$this->initially_was_account){
954       return;
955     }
957     plugin::remove_from_parent();
959     /* Just keep one phone number */
960     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
961       $this->attrs['telephoneNumber']= $this->telephoneNumber;
962     } else {
963       $this->attrs['telephoneNumber']= array();
964     }
966     $ldap= $this->config->get_ldap_link();
967     $ldap->cd($this->config->current['BASE']);
968     $ldap->search("(objectClass=goFonQueue)", array("member"));
969     while($attr = $ldap->fetch()){
970       if(in_array($this->dn,$attr['member'])){
971         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
972         unset($new->by_object['ogroup']->memberList[$this->dn]);
973         unset($new->by_object['ogroup']->member[$this->dn]);
974         $new->save();
975         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
976       }
977     }
978     $ldap->cd($this->dn);
979     $ldap->modify($this->attrs);
980     show_ldap_error($ldap->get_error());
982     /* Optionally execute a command after we're done */
983     $this->handle_post_events('remove');
984   }
988   /* This function checks if the given phonenumbers are available or already in use*/
989   function is_number_used()
990   {
991     $ldap= $this->config->get_ldap_link();
992     $ldap->cd($this->config->current['BASE']);
993     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
994     while($attrs = $ldap->fetch()) {
995       unset($attrs['telephoneNumber']['count']);
996       foreach($attrs['telephoneNumber'] as $tele){
997         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
998         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
999         $numbers[$tele]=$attrs;
1000       }
1001     }
1003     foreach($this->phoneNumbers as $num){
1004       if(!isset($this->cn)) $this->cn = "";
1006       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1007         if(isset($numbers[$num]['uid'][0])){
1008           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1009         }else{
1010           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1011         }
1012       }
1013     }
1014   }
1017 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1018 ?>