Code

73b6d9db229f3fcbdf2304b077474d37d3a2355c
[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 $goFonVoicemailPIN      = "";
16   var $goFonDeliveryMode      = "";
17   var $phoneNumbers           = array();
18   var $mail                   = "";
19   var $hardware_list          = array();
20   var $used_hardware          = array();
21   var $goFonMacro             = "";
22   var $macro                  = 0;              // Selected Macro
23   var $macros                 = array();        // List of macros for smarty select box
24   var $macroarray             = array();        // All needed macro informations
25   var $macrostillavailable    = false;
26   var $generate_error         = "";
27   var $a_old_telenums         = array();
28   var $goFonPINVoice          = "";
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", "goFonFormat","uid","cn","mail",
37       "goFonHardware","goFonPIN","goFonVoicemailPIN","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     /* Set up has_mailAccount */
63     if (isset($this->attrs['objectClass'])){
64       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
65         $this->has_mailAccount= TRUE;
66       }
67     }
69     $a_SETUP= array();
70     if(array_key_exists('config',$_SESSION) &&
71        array_key_exists('SERVERS',$_SESSION['config']->data) &&
72        array_key_exists('FON',$_SESSION['config']->data['SERVERS'])) {
73       $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
74       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
75       if(!$r_con){
76         $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
77           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
78         gosa_log(mysql_error());
79         return false;
80       }
81       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
82       if(!$db){
83         $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
84         gosa_log(mysql_error());
85         return false;
86       }
87  
88       $first = false; 
89       foreach($this->phoneNumbers as $key => $val){
90         if(!$first){
91           $first = $key;
92         }
93       }
94     }
96     /* Load hardware list */
97     $ldap= $this->config->get_ldap_link();
98     $ldap->cd($this->config->current['BASE']);
99     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
100     while ($attrs= $ldap->fetch()){
101       $cn= $attrs['cn'][0];
102       if (isset($attrs['description'])){
103         $description= " - ".$attrs['description'][0];
104       } else {
105         $description= "";
106       }
107       $this->hardware_list[$cn]= "$cn$description";
109     }
111     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
112     $ldap->search("(objectClass=goFonMacro)", array("*"));
114     /* Add none for no macro*/
115     $this->macros['none']=_("no macro");    
116     $this->macro ="none";
119     /* Fetch all Macros*/
120     while ($attrs= $ldap->fetch()){
122       /* Only visisble */
123       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
125         /* unset Count, we don't need that here */
126         unset($attrs['displayName']['count']);
128         /* fill Selectfield variable with Macros */
129         if(isset($attrs['displayName'][0])){
130           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
131         }else{
132           $this->macros[$attrs['dn']] = _("undefined");
133         }
135         /* Parse macro data, unset count for parameterarrays  */
136         unset($attrs['goFonMacroParameter']['count']);
138         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
139         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
141           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
142             /* Split Data in readable values, by delimiter !  */
143             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
145             /* Set all attrs */
146             $id = $data[0];
147             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
148             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
149             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
150             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
151             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
152             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
153             if($data[2] == "bool"){
154               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
155             }
156           }//foreach
157         }//is_array
158       }//visible = 1
159     }//while
161     /* Go through already saved values, for a parameter */
162     $tmp = split("!",$this->goFonMacro);
164     /* it is possible that nothing has been saved yet */
165     if(is_array($tmp)){
167       /* First value is the macroname */
168       $this->macro = $tmp[0];
170       /* Macroname saved, delete that index */
171       unset($tmp[0]);
173       /* Check if makro has been removed */
174       if(!isset($this->macroarray[$this->macro])){
175         $this->macrostillavailable = false;
176       }else{
177         $this->macrostillavailable = true;
178       }
180       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
181       foreach($tmp as $var){
183         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
184         $varar = split("#",$var);
186         /* Only insert if the parameter still exists */
187         if(isset($this->macroarray[$this->macro][$varar[0]])){
188           /* Assign value */
189           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
190         }
191       }
192     }
195     /* Eventually colorize phones */
196     $ldap->cd($this->config->current['BASE']);
197     foreach ($this->hardware_list as $cn => $desc){
198       $ldap->search("(goFonHardware=$cn)", array('cn'));
199       if ($ldap->count() > 0){
200         $ldap->fetch();
201         if ($ldap->getDN() != $this->dn){
202           $this->used_hardware[$cn]= $ldap->getDN();
203         }
204       }
205     }
206     $this->hardware_list["automatic"]= _("automatic");
207     ksort($this->hardware_list);
208     $this->a_old_telenums = $this->phoneNumbers;
210     if($this->is_account){
211       $this->is_modified = true;
212     }
215   /* Get voicemail PIN from MySQL DB 
216    * Because every user can change his PIN directly from the phone
217    *  without any update to the ldap
218    * This means, the PIN in the DB is up to date
219    */
220     // Connect to DB server
221     if((isset($a_SETUP))&&(isset($a_SETUP['SERVER']))&&(isset($a_SETUP['LOGIN']))&&(isset($a_SETUP['PASSWORD']))){
222       $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
223       if($r_con){
224         $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
225         $vp = mysql_fetch_row(mysql_query("SELECT ".$a_SETUP['VOICE_TABLE'].".password FROM  ".$a_SETUP['VOICE_TABLE'].", ".$a_SETUP['SIP_TABLE']."  WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'"));
227         if((isset($vp[0]))&&(!empty($vp[0]))){
228           $this->goFonPINVoice = $vp[0];
229         }
230       }
231     }
232   }
235   // Generate MySQL Syntax
236   function generate_mysql_entension_entries($save = false){
238     // Get Configuration for Mysql database Server
239     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
240     $s_parameter    = "";                                           // Contains paramter for selected Macro 
241     $r_con          = false;                                        // DB connection
242     $r_db           = false;                                        // Selected DB
243     $r_res          = false;                                        // Result resource
244     $a_ldap_attrs   = array();                                      //  
246     $s_ip           = NULL;                   // Contains ip for Sip entry
247     $s_host         = NULL;                   // Contains host for Sip entry
248     $s_qualify      = NULL;                   // Qualify entry
249     $s_pin          = NULL;                   // Entry for secret
250     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
252     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
253     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
254     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
256     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
257     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
259     $s_sip_key      = "";     // Key for SIP entry index      
260     $s_sip_val      = "";     // Value for SIP entry index      
262     $b_first_deleted= false;  // Only delete first entry, 
263     $s_telenums     = "";     // for each value variable
265     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
268     // Connect to DB server
269     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
271     // Check if we are  connected correctly
272     if(!$r_con){
273       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
274           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
275       gosa_log(mysql_error());
276       return false;
277     }
279     // Select database for Extensions
280     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
282     // Test if we have the database selected correctly
283     if(!$r_db){
284       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
285       gosa_log(mysql_error());
286       return false;
287     }
289     // Get phonehardware to setup sip entry
290     $ldap         = $this->config->get_ldap_link();
291     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
292     $a_ldap_attrs = $ldap->fetch();
294     if($this->is_number_used()){
295       $this->generate_error = $this->is_number_used(); 
296       return false;
297     }
299     /* If Save == true, we should save something.
300      * Generate SQL, for drop of old entries
301      * Generate SQL, for insert new entries
302      */ 
303     if($save == true){
305       // Attribute GoFonDefaultIP set ?
306       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
307         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
308         $s_host     = $s_ip;
309       }else{
310         $s_ip       = NULL;
311         $s_host     = "dynamic";
312       }
314       // Attribute GoFonQualify set ?
315       if(isset($a_ldap_attrs['goFonQualify'])){
316         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
317       }
319       // Attribute GoFonPIN set ?
320       if(isset($this->goFonPIN)){
321         $s_pin      = $this->goFonPIN;
322       }
324       // Attribute GoFonType set ?
325       if(isset($a_ldap_attrs['goFonType'])){
326         $s_type = $a_ldap_attrs['goFonType'][0];
327       }
329       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
330         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
331       }else{
332         $sip_data_array['dtmfmode']     ="rfc2833";
333       }
335       // generate SIP entry
336       $sip_data_array['id']           = "";
337       $sip_data_array['name']         = $this->uid;
338       $sip_data_array['accountcode']  = NULL;          
339       $sip_data_array['amaflags']     = NULL;
340       $sip_data_array['callgroup']    = NULL;
341       $sip_data_array['callerid']     = "";
342       $sip_data_array['canreinvite']  = "no";
343       $sip_data_array['context']      = "default";
344       $sip_data_array['defaultip']    = NULL;
345       $sip_data_array['fromuser']     = NULL;
346       $sip_data_array['fromdomain']   = NULL;
347       $sip_data_array['host']         = $s_host;
348       $sip_data_array['insecure']     = NULL;
349       $sip_data_array['language']     = NULL;
350       $sip_data_array['mailbox']      = "asterisk";
351       $sip_data_array['md5secret']    = NULL;
352       $sip_data_array['nat']          = "no";
353       $sip_data_array['permit']       = NULL;
354       $sip_data_array['deny']         = NULL;
355       $sip_data_array['mask']         = NULL;
356       $sip_data_array['pickupgroup']  = NULL;
357       $sip_data_array['port']         = NULL;
358       $sip_data_array['qualify']      = $s_qualify;
359       $sip_data_array['restrictcid']  = "n";
360       $sip_data_array['rtptimeout']   = NULL;
361       $sip_data_array['rtpholdtimeout']=NULL;
362       $sip_data_array['secret']       = $this->goFonPIN;
363       $sip_data_array['type']         = $s_type ;
364       $sip_data_array['username']     = $this->uid;
365       $sip_data_array['disallow']     = NULL;
366       $sip_data_array['allow']        = NULL;
367       $sip_data_array['musiconhold']  = NULL;
368       $sip_data_array['regseconds']   = NULL;
369       $sip_data_array['ipaddr']       = $s_ip;
370       $sip_data_array['regexten']     = NULL;
371       $sip_data_array['cancallforward']=NULL;
373       // Get selected Macro Parameter and create parameter entry 
374       if(isset($this->macroarray[$this->macro])){
375         foreach($this->macroarray[$this->macro] as $key => $val ){
376           $s_parameter .= $val['choosen']."|";
377         }
378         $s_parameter = preg_replace("/\|$/","",$s_parameter);
379       }
381       if($this->is_number_used()){
382         $this->generate_error = $this->is_number_used(); 
383         return false;
384       }
386       // Create new SIP entry ...
387       $sip_entry = $sip_data_array;
388       reset($this->phoneNumbers);
389       $i_new_key = key($this->phoneNumbers);
390       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
391       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
393       if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
394         $s_mail = $this->parent->by_object['mailAccount']->mail;
395       }else{
396         $s_mail = "";
397       }
400       // $SQL contains all queries
401       $SQL   = array();
402       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
403       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
404       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
406       // Generate Strings with keys and values 
407       foreach($sip_entry as $s_sip_key=>$s_sip_val){
408         if($s_sip_val == NULL) continue;
409         $s_sip_values.="'".$s_sip_val."',";
410         $s_sip_keys  .="`".$s_sip_key."`,";
411       }
412       // Remove last ,
413       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
414       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
416       // Append SIP Entry 
417       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
419       // Delete old entries
420       $b_first_deleted  =false;
421       foreach($this->a_old_telenums as $s_telenums){
422         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
423         if(!$b_first_deleted){
424           $b_first_deleted=true;
425           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
426         }
427       }
429       /* If deletion starts from userslist, cn uid are not set */
430       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
431         $this->uid = $this->parent->by_object['user']->uid;
432       }
434       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
435         $this->cn  = $this->parent->by_object['user']->cn;
436       }
438       if((!isset($this->cn))||(empty($this->cn))){
439         $CNname= $this->uid;
440       }else{
441         $CNname= $this->cn;
442       }
444       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
445           VALUES   ('".$this->phoneNumbers[$i_new_key]."',
446                     'default',
447                     '".$this->phoneNumbers[$i_new_key]."',
448                     '".$this->goFonVoicemailPIN."',
449                     '".$CNname."',
450                     '".$s_mail."',
451                     '');";
452       $i_is_accounted=false;
453     
454       $i = 0; 
455   
456       // Entension entries  Hint / Dial / Goto
457       foreach($this->phoneNumbers as $s_telenums){
459         /* Mapping : Name TO Number*/
460         $EXT[$i]['context'] = 'GOsa';
461         $EXT[$i]['exten']   = $this->uid;
462         $EXT[$i]['priority']= 1;
463         $EXT[$i]['app']     = "Goto";
464         $EXT[$i]['appdata'] = $s_telenums."|1";
465         $i ++;  
466         /* Hint Entry */
467         $EXT[$i]['context'] = 'GOsa';
468         $EXT[$i]['exten']   = $s_telenums;
469         $EXT[$i]['priority']= "Hint";
470         $EXT[$i]['app']     = 'SIP/'.$this->uid;
471         $i ++;  
472         /* SetCID */
473         $EXT[$i]['context'] = 'GOsa';
474         $EXT[$i]['exten']   = $s_telenums;
475         $EXT[$i]['priority']= 1;
476         $EXT[$i]['app']     = "SetCIDName";
477         $EXT[$i]['appdata'] = $CNname;
478         $i ++;  
480         // If no macro is selected use Dial
481         if($this->macro!="none"){ 
482           $macroname = preg_replace("/,.*$/","",$this->macro);        
483           $macroname = preg_replace("/^.*=/","",$macroname);        
484           $s_app = "Macro";$macroname;
485           $s_par = $macroname."|".$s_parameter; 
486         }else{
487           $s_app = "Dial";
488           $s_par = 'SIP/'.$this->uid;
489         }
491         $EXT[$i]['context'] = 'GOsa';
492         $EXT[$i]['exten']   = $s_telenums;
493         $EXT[$i]['priority']= 2;
494         $EXT[$i]['app']     = $s_app;
495         $EXT[$i]['appdata'] = $s_par;
496         $i ++;
498       }
500       // Append all these Entries 
501       foreach($EXT as $entr){
502         $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
503         foreach($entr as $key2 => $val2){
504           $SQL_syn.= "`".$key2."`,";
505         }
506         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
507         $SQL_syn .= ") VALUES ("; 
508         foreach($entr as $key2 => $val2){
509           $SQL_syn .= "'".$val2."',";
510         }
511         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
512         $SQL_syn .=");\n";
513         $SQL[] =$SQL_syn;
514         $SQL_syn ="";
515       }
517       // Perform queries ...
518       foreach($SQL as $query){
519         if(!@mysql_query($query,$r_con)){
520           print_red(_("Error while performing query ".mysql_error()));
521           return false;
522         }
523       }
524     }
525     return true;
526   }
529   function execute()
530   {
531     /* Do we represent a valid account? */
532     if (!$this->is_account && $this->parent == NULL){
533       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
534         _("This account has no phone extensions.")."</b>";
535       $display.= back_to_main();
536       return ($display);
537     }
539     /* Do we need to flip is_account state? */
540     if (isset($_POST['modify_state'])){
541       $this->is_account= !$this->is_account;
542     }
544     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
545     if(empty($this->macro)){
546       $this->macro ="none";
547     }
549     /* tell user that the pluging selected is no longer available*/
550     if((!$this->macrostillavailable)&&($this->macro!="none")){
551       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
552     }
554     /* Prepare templating */
555     $smarty= get_smarty();
557     /* Assing macroselectbox values  */
558     $smarty->assign("macros",$this->macros);   
559     $smarty->assign("macro", $this->macro);   
561     /* Create parameter table, skip if no parameters given */
562     if(!isset($this->macroarray[$this->macro])){
563       $macrotab="";
564     }else{
566       $macrotab ="<table summary=\""._("Parameter")."\">";
567       /* for every single parameter-> display textfile,combo, or true false switch*/
570       /* Automatic fill out */
571       if(isset($_POST['fillout'])){
573         foreach($this->phoneNumbers as $phonenum){
574           $tmp[] = $phonenum;
575         }
577         /* Go through all params */
578         foreach($this->macroarray[$this->macro] as $key => $paras){
580           $string = $paras['default'];
582           $string=preg_replace("/%uid/i",$this->uid,$string);
583           
584           if(isset($this->cn)){
585             $string=preg_replace("/%cn/i",$this->cn,$string);
586           }
588           for($i = 0 ; $i < 10; $i++){
589             if(isset($tmp[$i])){
590               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
591             }
592           }
594           $this->macroarray[$this->macro][$key]['choosen']=$string;
595         }
596       }
598       foreach($this->macroarray[$this->macro] as $paras){
600         /* get al vars */
601         $var        = $paras['var'];           
602         $name       = $paras['name'];           
603         $default    = $paras['default'];
604         $type       = $paras['type'];
605         $choosen    = $paras['choosen'] ; 
606         $str        = $default;
608         /* in case of a combo box display a combobox with selected attr */
609         $macrotab.= "<tr>";
610         switch ($type){
612           case "combo":
613             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
614           foreach(split(":",$default) as $choice){
615             if($choosen==$choice){
616               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
617             }else{
618               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
619             }
620           }
621           $str.="</select>";
622           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
623           break;
625           case "bool":
626             if(!$choosen){
627               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
628             }else{
629               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
630             }
631           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
632           break;
634           case "string":
635             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
636           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
637           break;
639         }
640         $macrotab.= "</td></tr>";
642       }
643       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
644     }//is_array()
646     /* Give smarty the table */
647     $smarty->assign("macrotab",$macrotab);
649     /* Do we represent a valid account? */
650     if (!$this->is_account && $this->parent == NULL){
651       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
652         _("This account has no phone extensions.")."</b>";
653       $display.= back_to_main();
654       return($display);
655     }
657     $display= "";
659     /* Show tab dialog headers */
660     if ($this->parent != NULL){
661       if ($this->is_account){
662         $display= $this->show_header(_("Remove phone account"),
663             _("This account has phone features enabled. You can disable them by clicking below."));
664       } else {
665         if(empty($this->uid)){
666           $display= $this->show_header(_("Create phone account"),
667               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
668         }else{
669           $display= $this->show_header(_("Create phone account"),
670               _("This account has phone features disabled. You can enable them by clicking below."));
671         }
672         return ($display);
673       }
674     }
676     /* Add phone number */
677     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
678       if (is_phone_nr($_POST['phonenumber'])){
679         $number= $_POST["phonenumber"];
680         $this->phoneNumbers[$number]= $number;
681         $this->is_modified= TRUE;
682       } else {
683         print_red(_("Please enter a valid phone number!"));
684       }
685     }
687     /* Remove phone number */
688     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
689       foreach ($_POST['phonenumber_list'] as $number){
690         unset($this->phoneNumbers[$number]);
691         $this->is_modified= TRUE;
692       }
693     }
695     /* Transfer ACL's */
696     foreach($this->attributes as $val){
697       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
698       if(isset($this->$val)){
699         $smarty->assign($val,$this->$val);
700       }else{
701         $smarty->assign($val,"");
702       }
703     }
705     /* Fill arrays */
706     $smarty->assign ("goFonHardware", $this->goFonHardware);
707     if (!count($this->phoneNumbers)){
708       $smarty->assign ("phoneNumbers", array(""));
709     } else {
710       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
711     }
712     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
713       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
714     foreach ($this->hardware_list as $cn => $description){
715       if ($cn == $this->goFonHardware){
716         $selected= "selected";
717       } else {
718         $selected= "";
719       }
720       if (isset($this->used_hardware[$cn])){
721         $color= "style=\"color:#A0A0A0\"";
722       } else {
723         $color= "";
724       }
725       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
726     }
727     $hl.= "</select>\n";
728     $smarty->assign ("hardware_list", $hl);
730     /* Show main page */
732     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
733     return($display);
734   }
737   function save_object()
738   {
739     if (isset($_POST["phoneTab"])){
740       plugin::save_object();
742       /* Save checkbox */
743       if (isset($_POST['fon_to_mail'])){
744         $tmp= "[M]";
745       } else {
746         $tmp= "[]";
747       }
748       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
749         if ($this->goFonDeliveryMode != $tmp){
750           $this->is_modified= TRUE;
751         }
752         $this->goFonDeliveryMode= $tmp;
753       }
755       /* Every macro in the select box are available */
756       if((isset($_POST['macro']))){
757         $this->macrostillavailable=true;
758       }
760       if(is_array($this->phoneNumbers)){
761         foreach($this->phoneNumbers as $telenumms) {
762           $nummsinorder[]=$telenumms; 
763         }
764       }else{
765         $nummsinorder=array("");
766       }
768       /* get all Postvars */
769       if(isset($this->macroarray[$this->macro])){ 
770         foreach($this->macroarray[$this->macro] as $key => $paras){
771           if(isset($_POST[$paras['var']])){
772             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
773           }
775           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
776              We need this code below to read and save checkboxes correct
777            */
779           if(isset($_POST['post_success'])){
780             if($this->macroarray[$this->macro][$key]['type']=="bool"){
781               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
782                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
783               }else{
784                 $this->macroarray[$this->macro][$key]['choosen']=false;
785               }
786             }
787           }
788         }
789       }
790     }
791   }
793   function check()
794   {
795     /* Reset message array */
796     $message= array();
798     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
799       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
800     }else{
801       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
802         $message[]=(_("The specified oicemail PIN contains invalid characters, only numeric values are allowed here."));
803       }
804     }
807     if((strlen($this->goFonPIN)!=4)){
808       $message[]=(_("Phone PIN must be 4 characters long."));
809     }else{
810       if(preg_match("/[^0-9]/",$this->goFonPIN)){
811         $message[]=(_("The specified phone PIN contains invalid characters, only numeric values are allowed here."));
812       }
813     }
815     if(!$this->generate_mysql_entension_entries()){
816       $message[] = $this->generate_error;
817     }
819     /* We need at least one phone number */
820     if (count($this->phoneNumbers) == 0){
821       $message[]= sprintf(_("You need to specify at least one phone number!"));
822     }
824     /* check for ! in any parameter setting*/
825     if(isset($this->macroarray[$this->macro])){
826       foreach($this->macroarray[$this->macro] as $val){
827         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
828           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
829         }
830       }
831     }
832     return ($message);
833   }
837   function save()
838   {
839     plugin::save();
841     /* Save arrays */
842     $this->attrs['telephoneNumber']= array();
843     foreach ($this->phoneNumbers as $number){
844       $this->attrs['telephoneNumber'][]= $number;
845     }
847     /* Save settings, or remove goFonMacro attribute*/
848     if($this->macro!="none"){    
849       $this->attrs['goFonMacro']=$this->macro;
850       if(isset($this->macroarray[$this->macro])){
851         foreach($this->macroarray[$this->macro] as $paras)  {
852           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
853         }
854       }
855     }else{
856       $this->attrs['goFonMacro']=array();
857     }
858     unset($this->attrs['macro'])  ;
860     $this->attrs['goFonForwarding']=array();
862     $this->generate_mysql_entension_entries(true);
864     if($this->attrs['goFonMacro']==""){
865       $this->attrs['goFonMacro']=array();
866     }
868     unset($this->attrs['cn']);
870     /* Write back to ldap */
871     $ldap= $this->config->get_ldap_link();
872     $ldap->cd($this->dn);
873     $ldap->modify($this->attrs);
874     show_ldap_error($ldap->get_error());
876     /* Optionally execute a command after we're done */
878     if ($this->initially_was_account == $this->is_account){
879       if ($this->is_modified){
880         $this->handle_post_events("modify");
881       }
882     } else {
883       $this->handle_post_events("add");
884     }
886   }
889   function insert_after($entry, $nr, $list)
890   {
891     /* Is the entry free? No? Make it free... */
892     if (isset($list[$nr])) {
893       $dest= array();
894       $newidx= 0;
896       foreach ($list as $idx => $contents){
897         $dest[$newidx++]= $contents;
898         if ($idx == $nr){
899           $dest[$newidx++]= $entry;
900         }
901       }
902     } else {
903       $dest= $list;
904       $dest[$nr]= $entry;
905     }
907     return ($dest);
908   }
911   function adapt_from_template($dn)
912   {
913     plugin::adapt_from_template($dn);
915     /* Assemble phone numbers */
916     if (isset($this->attrs['telephoneNumber'])){
917       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
918         $number= $this->attrs['telephoneNumber'][$i];
919         $this->phoneNumbers[$number]= $number;
920       }
921     }
922   }
925   function remove_from_parent()
926   {
927   
928     foreach($this->attributes as $key=>$val){
929       if(in_array($val,array("uid","cn","mail"))){
930         unset($this->attributes[$key]);
931         unset($this->$val);
932       }
933     }
935     if(array_key_exists('config', $_SESSION) &&
936        array_key_exists('SERVERS', $_SESSION['config']->data) &&
937        array_key_exists('FON', $_SESSION['config']->data['SERVERS'])) {
938       // Get Configuration for Mysql database Server
939       $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
940       $s_parameter  ="";
942       // Connect to DB server
943       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
945       // Check if we are  connected correctly
946       if(!$r_con){
947         $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
948             $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
949         gosa_log(@mysql_error());
950         return false;
951       }
953       // Select database for Extensions
954       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
956       // Test if we have the database selected correctly
957       if(!$db){
958         $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
959         gosa_log(@mysql_error());
960         return false;
961       }
963       $SQL="";
965       /* If deletion starts from userslist, cn uid are not set */
966       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
967         $this->uid = $this->parent->by_object['user']->uid;
968       }
970       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
971         $this->cn  = $this->parent->by_object['user']->cn;
972       }
974       $first_num = false;
975       // Delete old entries
976       foreach($this->a_old_telenums as $s_telenums){
977         if(!$first_num){
978           $first_num = $s_telenums;
979         }
980         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
981       }
983       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
984       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
985       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
988       foreach($SQL as $query){
989         if(!@mysql_query($query,$r_con)){
990           print_red(_("Stop".mysql_error()));
991           return false;
992         }
993       }
994     }
997     /* unset macro attr, it will cause an error */
998     $tmp = array_flip($this->attributes);
999     unset($tmp['macro']);
1000     $this->attributes=array_flip($tmp);
1002     /* Cancel if there's nothing to do here */
1003     if (!$this->initially_was_account){
1004       return;
1005     }
1007     plugin::remove_from_parent();
1009     /* Just keep one phone number */
1010     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1011       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1012     } else {
1013       $this->attrs['telephoneNumber']= array();
1014     }
1016     $ldap= $this->config->get_ldap_link();
1017     $ldap->cd($this->config->current['BASE']);
1018     $ldap->search("(objectClass=goFonQueue)", array("member"));
1019     while($attr = $ldap->fetch()){
1020       if(in_array($this->dn,$attr['member'])){
1021         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1022         unset($new->by_object['ogroup']->memberList[$this->dn]);
1023         unset($new->by_object['ogroup']->member[$this->dn]);
1024         $new->save();
1025         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1026       }
1027     }
1028     $ldap->cd($this->dn);
1029     $ldap->modify($this->attrs);
1030     show_ldap_error($ldap->get_error());
1032     /* Optionally execute a command after we're done */
1033     $this->handle_post_events('remove');
1034   }
1038   /* This function checks if the given phonenumbers are available or already in use*/
1039   function is_number_used()
1040   {
1041     $ldap= $this->config->get_ldap_link();
1042     $ldap->cd($this->config->current['BASE']);
1043     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1044     while($attrs = $ldap->fetch()) {
1045       unset($attrs['telephoneNumber']['count']);
1046       foreach($attrs['telephoneNumber'] as $tele){
1047         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1048         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1049         $numbers[$tele]=$attrs;
1050       }
1051     }
1053     foreach($this->phoneNumbers as $num){
1054       if(!isset($this->cn)) $this->cn = "";
1056       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1057         if(isset($numbers[$num]['uid'][0])){
1058           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1059         }else{
1060           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1061         }
1062       }
1063     }
1064   }
1067 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1068 ?>