Code

ab1a47101623df0414da6dd87f5d53120f49ce21
[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 Macroi
23   var $lastmacro              = "";
24   var $macros                 = array();        // List of macros for smarty select box
25   var $macroarray             = array();        // All needed macro informations
26   var $macrostillavailable    = false;
27   var $generate_error         = "";
28   var $a_old_telenums         = array();
29   var $goFonPINVoice          = "";
31   /* CLI vars */
32   var $cli_summary            = "Manage users phone account";
33   var $cli_description        = "Some longer text\nfor help";
34   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
36   /* attribute list for save action */
37   var $attributes             = array("goFonDeliveryMode", "goFonFormat","uid","cn","mail",
38       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
39   var $objectclasses= array("goFonAccount");
41   function phoneAccount ($config, $dn= NULL)
42   {
43     plugin::plugin ($config, $dn);
45     /* Set phone hardware */
46     if (!isset($this->attrs['goFonHardware'])){
47       $this->goFonHardware= "automatic";
48     }
50     /* Preset voice format */
51     if (!isset($this->attrs['goFonFormat'])){
52       $this->goFonFormat= "wav";
53     }
55     /* Assemble phone numbers */
56     if (isset($this->attrs['telephoneNumber'])){
57       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
58         $number= $this->attrs['telephoneNumber'][$i];
59         $this->phoneNumbers[$number]= $number;
60       }
61     }
63     /* Set up has_mailAccount */
64     if (isset($this->attrs['objectClass'])){
65       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
66         $this->has_mailAccount= TRUE;
67       }
68     }
70     $a_SETUP= array();
71     if(array_key_exists('config',$_SESSION) &&
72        array_key_exists('SERVERS',$_SESSION['config']->data) &&
73        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
74        is_callable("mysql_connect")
75        ) {
76       $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
77       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
78       if(!$r_con){
79         $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
80           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
81         gosa_log(mysql_error());
82         return false;
83       }
84       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
85       if(!$db){
86         $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
87         gosa_log(mysql_error());
88         return false;
89       }
90  
91       $first = false; 
92       foreach($this->phoneNumbers as $key => $val){
93         if(!$first){
94           $first = $key;
95         }
96       }
97     }
99     /* Load hardware list */
100     $ldap= $this->config->get_ldap_link();
101     $ldap->cd($this->config->current['BASE']);
102     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
103     while ($attrs= $ldap->fetch()){
104       $cn= $attrs['cn'][0];
105       if (isset($attrs['description'])){
106         $description= " - ".$attrs['description'][0];
107       } else {
108         $description= "";
109       }
110       $this->hardware_list[$cn]= "$cn$description";
112     }
114     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
115     $ldap->search("(objectClass=goFonMacro)", array("*"));
117     /* Add none for no macro*/
118     $this->macros['none']=_("no macro");    
119     $this->macro ="none";
122     /* Fetch all Macros*/
123     while ($attrs= $ldap->fetch()){
125       /* Only visisble */
126       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
128         /* unset Count, we don't need that here */
129         unset($attrs['displayName']['count']);
131         /* fill Selectfield variable with Macros */
132         if(isset($attrs['displayName'][0])){
133           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
134         }else{
135           $this->macros[$attrs['dn']] = _("undefined");
136         }
138         /* Parse macro data, unset count for parameterarrays  */
139         if (isset($attrs['goFonMacroParameter']['count'])){
140           unset($attrs['goFonMacroParameter']['count']);
141         }
143         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
144         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
146           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
147             /* Split Data in readable values, by delimiter !  */
148             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
150             /* Set all attrs */
151             $id = $data[0];
152             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
153             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
154             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
155             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
156             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
157             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
158             if($data[2] == "bool"){
159               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
160             }
161           }//foreach
162         }//is_array
163       }//visible = 1
164     }//while
166     /* Go through already saved values, for a parameter */
167     $tmp = split("!",$this->goFonMacro);
169     /* it is possible that nothing has been saved yet */
170     if(is_array($tmp)){
172       /* First value is the macroname */
173       $this->macro = $tmp[0];
175       /* Macroname saved, delete that index */
176       unset($tmp[0]);
178       /* Check if makro has been removed */
179       if(!isset($this->macroarray[$this->macro])){
180         $this->macrostillavailable = false;
181       }else{
182         $this->macrostillavailable = true;
183       }
185       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
186       foreach($tmp as $var){
188         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
189         $varar = split("#",$var);
191         /* Only insert if the parameter still exists */
192         if(isset($this->macroarray[$this->macro][$varar[0]])){
193           /* Assign value */
194           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
195         }
196       }
197     }
200     /* Eventually colorize phones */
201     $ldap->cd($this->config->current['BASE']);
202     foreach ($this->hardware_list as $cn => $desc){
203       $ldap->search("(goFonHardware=$cn)", array('cn'));
204       if ($ldap->count() > 0){
205         $ldap->fetch();
206         if ($ldap->getDN() != $this->dn){
207           $this->used_hardware[$cn]= $ldap->getDN();
208         }
209       }
210     }
211     $this->hardware_list["automatic"]= _("automatic");
212     ksort($this->hardware_list);
213     $this->a_old_telenums = $this->phoneNumbers;
215     if($this->is_account){
216       $this->is_modified = true;
217     }
220     /* Get voicemail PIN from MySQL DB 
221      * Because every user can change his PIN directly from the phone
222      *  without any update to the ldap
223      * This means, the PIN in the DB is up to date
224      */
225     // Connect to DB server
226     if((is_callable("mysql_pconnect"))&&(isset($a_SETUP))&&(isset($a_SETUP['SERVER']))&&(isset($a_SETUP['LOGIN']))&&(isset($a_SETUP['PASSWORD']))){
227       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
228       if($r_con){
229         $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
230         $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."'"));
232         if((isset($vp[0]))&&(!empty($vp[0]))){
233           $this->goFonPINVoice = $vp[0];
234         }
235       }
236     }
237     $this->lastmacro=$this->macro;
239     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
240       @mysql_close($r_con) ;
241     }
242   }
245   // Generate MySQL Syntax
246   function generate_mysql_entension_entries($save = false){
248     if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
249       if($save)
250       print_red(_("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer). Your settings can't be saved to asterisk database."));
251       return(true);
252     }
254     if(!is_callable("mysql_pconnect")){
255       if($save)
256       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
257       return(true);
258     }
259   
260     // Get Configuration for Mysql database Server
261     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
262     $s_parameter    = "";                                           // Contains paramter for selected Macro 
263     $r_con          = false;                                        // DB connection
264     $r_db           = false;                                        // Selected DB
265     $r_res          = false;                                        // Result resource
266     $a_ldap_attrs   = array();                                      //  
268     $s_ip           = NULL;                   // Contains ip for Sip entry
269     $s_host         = NULL;                   // Contains host for Sip entry
270     $s_qualify      = NULL;                   // Qualify entry
271     $s_pin          = NULL;                   // Entry for secret
272     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
274     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
275     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
276     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
278     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
279     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
281     $s_sip_key      = "";     // Key for SIP entry index      
282     $s_sip_val      = "";     // Value for SIP entry index      
284     $b_first_deleted= false;  // Only delete first entry, 
285     $s_telenums     = "";     // for each value variable
287     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
290     // Connect to DB server
291     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
293     // Check if we are  connected correctly
294     if(!$r_con){
295       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
296           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
297       gosa_log(mysql_error());
298       return false;
299     }
301     // Select database for Extensions
302     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
304     // Test if we have the database selected correctly
305     if(!$r_db){
306       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
307       gosa_log(mysql_error());
308       return false;
309     }
311     // Get phonehardware to setup sip entry
312     $ldap         = $this->config->get_ldap_link();
313     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
314     $a_ldap_attrs = $ldap->fetch();
316     if($this->is_number_used()){
317       $this->generate_error = $this->is_number_used(); 
318       return false;
319     }
321     /* If Save == true, we should save something.
322      * Generate SQL, for drop of old entries
323      * Generate SQL, for insert new entries
324      */ 
325     if($save == true){
326       
327       foreach($this->a_old_telenums as $tele){
328         $oldnums[]= preg_replace("/[^0-9]/","",$tele);
329       }
331       foreach($this->phoneNumbers as $tele){
332         $newnums[]= preg_replace("/[^0-9]/","",$tele);
333       }
335       // Attribute GoFonDefaultIP set ?
336       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
337         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
338         $s_host     = $s_ip;
339       }else{
340         $s_ip       = NULL;
341         $s_host     = "dynamic";
342       }
344       // Attribute GoFonQualify set ?
345       if(isset($a_ldap_attrs['goFonQualify'])){
346         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
347       }
349       // Attribute GoFonPIN set ?
350       if(isset($this->goFonPIN)){
351         $s_pin      = $this->goFonPIN;
352       }
354       // Attribute GoFonType set ?
355       if(isset($a_ldap_attrs['goFonType'])){
356         $s_type = $a_ldap_attrs['goFonType'][0];
357       }
359       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
360         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
361       }else{
362         $sip_data_array['dtmfmode']     ="rfc2833";
363       }
365       // generate SIP entry
366       $sip_data_array['id']           = "";
367       $sip_data_array['name']         = $this->uid;
368       $sip_data_array['accountcode']  = NULL;          
369       $sip_data_array['amaflags']     = NULL;
370       $sip_data_array['callgroup']    = NULL;
371       $sip_data_array['callerid']     = "";
372       $sip_data_array['canreinvite']  = "no";
373       $sip_data_array['context']      = "default";
374       $sip_data_array['defaultip']    = NULL;
375       $sip_data_array['fromuser']     = NULL;
376       $sip_data_array['fromdomain']   = NULL;
377       $sip_data_array['host']         = $s_host;
378       $sip_data_array['insecure']     = NULL;
379       $sip_data_array['language']     = NULL;
380       $sip_data_array['mailbox']      = "asterisk";
381       $sip_data_array['md5secret']    = NULL;
382       $sip_data_array['nat']          = "no";
383       $sip_data_array['permit']       = NULL;
384       $sip_data_array['deny']         = NULL;
385       $sip_data_array['mask']         = NULL;
386       $sip_data_array['pickupgroup']  = NULL;
387       $sip_data_array['port']         = NULL;
388       $sip_data_array['qualify']      = $s_qualify;
389       $sip_data_array['restrictcid']  = "n";
390       $sip_data_array['rtptimeout']   = NULL;
391       $sip_data_array['rtpholdtimeout']=NULL;
392       $sip_data_array['secret']       = $this->goFonPIN;
393       $sip_data_array['type']         = $s_type ;
394       $sip_data_array['username']     = $this->uid;
395       $sip_data_array['disallow']     = NULL;
396       $sip_data_array['allow']        = NULL;
397       $sip_data_array['musiconhold']  = NULL;
398       $sip_data_array['regseconds']   = NULL;
399       $sip_data_array['ipaddr']       = $s_ip;
400       $sip_data_array['regexten']     = NULL;
401       $sip_data_array['cancallforward']=NULL;
403       // Get selected Macro Parameter and create parameter entry 
404       if(isset($this->macroarray[$this->macro])){
405         foreach($this->macroarray[$this->macro] as $key => $val ){
406           $s_parameter .= $val['choosen']."|";
407         }
408         $s_parameter = preg_replace("/\|$/","",$s_parameter);
409       }
411       if($this->is_number_used()){
412         $this->generate_error = $this->is_number_used(); 
413         return false;
414       }
416       // Create new SIP entry ...
417       $sip_entry = $sip_data_array;
418       reset($newnums);
419       $i_new_key = key($newnums);
420       $sip_entry['callerid']  =$newnums[$i_new_key];
421       $sip_entry['mailbox']   =$newnums[$i_new_key];
423       if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
424         $s_mail = $this->parent->by_object['mailAccount']->mail;
425       }else{
426         $s_mail = "";
427       }
429       // $SQL contains all queries
430       $SQL   = array();
431       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
432       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
433       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$newnums[$i_new_key].";"; 
434       // Delete old entries
435       $b_first_deleted  =false;
436       foreach($oldnums as $s_telenums){
437         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
438         if(!$b_first_deleted){
439           $b_first_deleted=true;
440           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
441         }
442       }
444       if($this->goFonHardware=="automatic"){
445         foreach($SQL as $query ){
446           mysql_query($query) ;
447         }
448         return;
449       }
451       // Generate Strings with keys and values 
452       foreach($sip_entry as $s_sip_key=>$s_sip_val){
453         if($s_sip_val == NULL) continue;
454         $s_sip_values.="'".$s_sip_val."',";
455         $s_sip_keys  .="`".$s_sip_key."`,";
456       }
457       // Remove last ,
458       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
459       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
461       // Append SIP Entry 
462       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
464       /* If deletion starts from userslist, cn uid are not set */
465       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
466         $this->uid = $this->parent->by_object['user']->uid;
467       }
469       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
470         $this->cn  = $this->parent->by_object['user']->cn;
471       }
473       if((!isset($this->cn))||(empty($this->cn))){
474         $CNname= $this->uid;
475       }else{
476         $CNname= $this->cn;
477       }
479       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
480           VALUES   ('".$newnums[$i_new_key]."',
481                     'default',
482                     '".$newnums[$i_new_key]."',
483                     '".$this->goFonVoicemailPIN."',
484                     '".$CNname."',
485                     '".$s_mail."',
486                     '');";
487       $i_is_accounted=false;
488     
489       $i = 0; 
490  
491       $is_inserted_once = false;
492  
493       // Entension entries  Hint / Dial / Goto
494       foreach($newnums as $s_telenums){
496         if(!$is_inserted_once){
497           $is_inserted_once = true;
498           $EXT[$i]['context'] = 'GOsa';
499           $EXT[$i]['exten']   = $this->uid;
500           $EXT[$i]['priority']= 1;
501           $EXT[$i]['app']     = "Goto";
502           $EXT[$i]['appdata'] = $s_telenums."|1";
503           $i ++;
504         }
505         /* Hint Entry */
506         $EXT[$i]['context'] = 'GOsa';
507         $EXT[$i]['exten']   = $s_telenums;
508         $EXT[$i]['priority']= "Hint";
509         $EXT[$i]['app']     = 'SIP/'.$this->uid;
510         $i ++;  
511         /* SetCID */
512         //$EXT[$i]['context'] = 'GOsa';
513         //$EXT[$i]['exten']   = $s_telenums;
514         //$EXT[$i]['priority']= 1;
515         //$EXT[$i]['app']     = "SetCIDName";
516         //$EXT[$i]['appdata'] = $CNname;
517         //$i ++;  
519         // If no macro is selected use Dial
520         if($this->macro!="none"){ 
521           $macroname = preg_replace("/,.*$/","",$this->macro);        
522           $macroname = preg_replace("/^.*=/","",$macroname);        
523           $s_app = "Macro";$macroname;
524           $s_par = $macroname."|".$s_parameter; 
525         }else{
526           $s_app = "Dial";
527           $s_par = 'SIP/'.$this->uid."|20|r";
528         }
530         $EXT[$i]['context'] = 'GOsa';
531         $EXT[$i]['exten']   = $s_telenums;
532         $EXT[$i]['priority']= 1;
533         $EXT[$i]['app']     = $s_app;
534         $EXT[$i]['appdata'] = $s_par;
535         $i ++;
537       }
539       // Append all these Entries 
540       foreach($EXT as $entr){
541         $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
542         foreach($entr as $key2 => $val2){
543           $SQL_syn.= "`".$key2."`,";
544         }
545         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
546         $SQL_syn .= ") VALUES ("; 
547         foreach($entr as $key2 => $val2){
548           $SQL_syn .= "'".$val2."',";
549         }
550         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
551         $SQL_syn .=");\n";
552         $SQL[] =$SQL_syn;
553         $SQL_syn ="";
554       }
556       // Perform queries ...
557       foreach($SQL as $query){
558         if(!@mysql_query($query,$r_con)){
559           print_red(_("Error while performing query:")." ".mysql_error());
560           return false;
561         }
562       }
563     }
564     @mysql_close($r_con);
565     return true;
566   }
569   function execute()
570   {
571         /* Call parent execute */
572         plugin::execute();
574     $display = "";
576     if(empty($this->macro)&&(!empty($this->goFonMacro))){
578       /* Go through already saved values, for a parameter */
579       $tmp = split("!",$this->goFonMacro);
581       /* it is possible that nothing has been saved yet */
582       if(is_array($tmp)){
584         /* First value is the macroname */
585         $this->macro = $tmp[0];
587         /* Macroname saved, delete that index */
588         unset($tmp[0]);
590         /* Check if makro has been removed */
591         if(!isset($this->macroarray[$this->macro])){
592           $this->macrostillavailable = false;
593         }else{
594           $this->macrostillavailable = true;
595         }
597         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
598         foreach($tmp as $var){
600           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
601           $varar = split("#",$var);
603           /* Only insert if the parameter still exists */
604           if(isset($this->macroarray[$this->macro][$varar[0]])){
605             /* Assign value */
606             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
607           }
608         }
609       }
610     }
611     
612     /* Do we represent a valid account? */
613     if (!$this->is_account && $this->parent == NULL){
614       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
615         _("This account has no phone extensions.")."</b>";
616       $display.= back_to_main();
617       return ($display);
618     }
620     /* Do we need to flip is_account state? */
621     if (isset($_POST['modify_state'])){
622       $this->is_account= !$this->is_account;
623     }
625     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
626     if(empty($this->macro)){
627       $this->macro ="none";
628     }
630     /* Prepare templating */
631     $smarty= get_smarty();
633     /* tell user that the pluging selected is no longer available*/
634     if((!$this->macrostillavailable)&&($this->macro!="none")){
635       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
636     }
638     /* Assing macroselectbox values  */
639     $smarty->assign("macros",$this->macros);   
640     $smarty->assign("macro", $this->macro);   
642     /* check if there is a FON server created */
643     if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
644       print_red(_("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer). Your settings can't be saved to asterisk database."));
645     }
647     /* Create parameter table, skip if no parameters given */
648     if(!isset($this->macroarray[$this->macro])){
649       $macrotab="";
650     }else{
652       $macrotab ="<table summary=\""._("Parameter")."\">";
653       /* for every single parameter-> display textfile,combo, or true false switch*/
655       foreach($this->phoneNumbers as $phonenum){
656         $tmp[] = $phonenum;
657       }
659       
660     
661       if($this->macro != $this->lastmacro){
662         /* Go through all params */
663         foreach($this->macroarray[$this->macro] as $key => $paras){
665           $string = $paras['default'];
667           $string=preg_replace("/%uid/i",$this->uid,$string);
669           if(isset($this->cn)){
670             $string=preg_replace("/%cn/i",$this->cn,$string);
671           }
673           for($i = 0 ; $i < 10; $i++){
674             if(isset($tmp[$i])){
675               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
676             }
677           }
678           if(isset($tmp[0])){
679             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
680           }
681           $this->macroarray[$this->macro][$key]['choosen']=$string;
682         }
683       }
685       foreach($this->macroarray[$this->macro] as $paras){
687         /* get al vars */
688         $var        = $paras['var'];           
689         $name       = $paras['name'];           
690         $default    = $paras['default'];
691         $type       = $paras['type'];
692         $choosen    = $paras['choosen'] ; 
693         $str        = $default;
695         /* in case of a combo box display a combobox with selected attr */
696         $macrotab.= "<tr>";
697         switch ($type){
699           case "combo":
700             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
701           foreach(split(":",$default) as $choice){
702             if($choosen==$choice){
703               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
704             }else{
705               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
706             }
707           }
708           $str.="</select>";
709           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
710           break;
712           case "bool":
713             if(!$choosen){
714               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
715             }else{
716               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
717             }
718           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
719           break;
721           case "string":
722             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
723           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
724           break;
726         }
727         $macrotab.= "</td></tr>";
729       }
730       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
731     }//is_array()
733     /* Give smarty the table */
734     $smarty->assign("macrotab",$macrotab);
736     /* Do we represent a valid account? */
737     if (!$this->is_account && $this->parent == NULL){
738       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
739         _("This account has no phone extensions.")."</b>";
740       $display.= back_to_main();
741       return($display);
742     }
744     $display= "";
746     /* Show tab dialog headers */
747     if ($this->parent != NULL){
748       if ($this->is_account){
749         $display= $this->show_header(_("Remove phone account"),
750             _("This account has phone features enabled. You can disable them by clicking below."));
751       } else {
752         if(empty($this->uid)){
753           $display= $this->show_header(_("Create phone account"),
754               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
755         }else{
756           $display= $this->show_header(_("Create phone account"),
757               _("This account has phone features disabled. You can enable them by clicking below."));
758         }
759         return ($display);
760       }
761     }
763     /* Add phone number */
764     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
765       if (is_phone_nr($_POST['phonenumber'])){
766         $number= $_POST["phonenumber"];
767         $this->phoneNumbers[$number]= $number;
768         $this->is_modified= TRUE;
769       } else {
770         print_red(_("Please enter a valid phone number!"));
771       }
772     }
774     /* Remove phone number */
775     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
776       foreach ($_POST['phonenumber_list'] as $number){
777         unset($this->phoneNumbers[$number]);
778         $this->is_modified= TRUE;
779       }
780     }
782     /* Transfer ACL's */
783     foreach($this->attributes as $val){
784       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
785       if(isset($this->$val)){
786         $smarty->assign($val,$this->$val);
787       }else{
788         $smarty->assign($val,"");
789       }
790     }
792     /* Fill arrays */
793     $smarty->assign ("goFonHardware", $this->goFonHardware);
794     if (!count($this->phoneNumbers)){
795       $smarty->assign ("phoneNumbers", array(""));
796     } else {
797       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
798     }
799     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
800       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
801     foreach ($this->hardware_list as $cn => $description){
802       if ($cn == $this->goFonHardware){
803         $selected= "selected";
804       } else {
805         $selected= "";
806       }
807       if (isset($this->used_hardware[$cn])){
808         $color= "style=\"color:#A0A0A0\"";
809       } else {
810         $color= "";
811       }
812       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
813     }
814     $hl.= "</select>\n";
815     $smarty->assign ("hardware_list", $hl);
817     /* Show main page */
818     $this->lastmacro = $this->macro;
819     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
820     return($display);
821   }
824   function save_object()
825   {
826     if (isset($_POST["phoneTab"])){
827       plugin::save_object();
829       /* Save checkbox */
830       if (isset($_POST['fon_to_mail'])){
831         $tmp= "[M]";
832       } else {
833         $tmp= "[]";
834       }
835       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
836         if ($this->goFonDeliveryMode != $tmp){
837           $this->is_modified= TRUE;
838         }
839         $this->goFonDeliveryMode= $tmp;
840       }
842       /* Every macro in the select box are available */
843       if((isset($_POST['macro']))){
844         $this->macrostillavailable=true;
845       }
847       if(is_array($this->phoneNumbers)){
848         foreach($this->phoneNumbers as $telenumms) {
849           $nummsinorder[]=$telenumms; 
850         }
851       }else{
852         $nummsinorder=array("");
853       }
855       /* get all Postvars */
856       if(isset($this->macroarray[$this->macro])){ 
857         foreach($this->macroarray[$this->macro] as $key => $paras){
858           if(isset($_POST[$paras['var']])){
859             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
860           }
862           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
863              We need this code below to read and save checkboxes correct
864            */
866           if(isset($_POST['post_success'])){
867             if($this->macroarray[$this->macro][$key]['type']=="bool"){
868               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
869                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
870               }else{
871                 $this->macroarray[$this->macro][$key]['choosen']=false;
872               }
873             }
874           }
875         }
876       }
877     }
878   }
880   function check()
881   {
882     /* Reset message array */
883     $message= array();
885     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
886       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
887     }else{
888       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
889         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
890       }
891     }
894     if((strlen($this->goFonPIN)!=4)){
895       $message[]=(_("Phone PIN must be 4 characters long."));
896     }else{
897       if(preg_match("/[^0-9]/",$this->goFonPIN)){
898         $message[]=(_("The specified phone PIN contains invalid characters, only numeric values are allowed here."));
899       }
900     }
902     if(!$this->generate_mysql_entension_entries()){
903       $message[] = $this->generate_error;
904     }
906     /* We need at least one phone number */
907     if (count($this->phoneNumbers) == 0){
908       $message[]= sprintf(_("You need to specify at least one phone number!"));
909     }
911     /* check for ! in any parameter setting*/
912     if(isset($this->macroarray[$this->macro])){
913       foreach($this->macroarray[$this->macro] as $val){
914         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
915           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
916         }
917       }
918     }
919     return ($message);
920   }
924   function save()
925   {
926     plugin::save();
928     /* Save arrays */
929     $this->attrs['telephoneNumber']= array();
930     foreach ($this->phoneNumbers as $number){
931       $this->attrs['telephoneNumber'][]= $number;
932     }
934     /* Save settings, or remove goFonMacro attribute*/
935     if($this->macro!="none"){    
936       $this->attrs['goFonMacro']=$this->macro;
937       if(isset($this->macroarray[$this->macro])){
938         foreach($this->macroarray[$this->macro] as $paras)  {
939           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
940         }
941       }
942     }else{
943       $this->attrs['goFonMacro']=array();
944     }
945     unset($this->attrs['macro'])  ;
947     $this->attrs['goFonForwarding']=array();
949     $this->generate_mysql_entension_entries(true);
951     if($this->attrs['goFonMacro']==""){
952       $this->attrs['goFonMacro']=array();
953     }
955     unset($this->attrs['cn']);
957     /* Write back to ldap */
958     $ldap= $this->config->get_ldap_link();
959     $ldap->cd($this->dn);
960     $ldap->modify($this->attrs);
961     show_ldap_error($ldap->get_error());
963     /* Optionally execute a command after we're done */
965     if ($this->initially_was_account == $this->is_account){
966       if ($this->is_modified){
967         $this->handle_post_events("modify");
968       }
969     } else {
970       $this->handle_post_events("add");
971     }
973   }
976   function insert_after($entry, $nr, $list)
977   {
978     /* Is the entry free? No? Make it free... */
979     if (isset($list[$nr])) {
980       $dest= array();
981       $newidx= 0;
983       foreach ($list as $idx => $contents){
984         $dest[$newidx++]= $contents;
985         if ($idx == $nr){
986           $dest[$newidx++]= $entry;
987         }
988       }
989     } else {
990       $dest= $list;
991       $dest[$nr]= $entry;
992     }
994     return ($dest);
995   }
998   function adapt_from_template($dn)
999   {
1000     plugin::adapt_from_template($dn);
1002     /* Assemble phone numbers */
1003     if (isset($this->attrs['telephoneNumber'])){
1004       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1005         $number= $this->attrs['telephoneNumber'][$i];
1006         $this->phoneNumbers[$number]= $number;
1007       }
1008     }
1009   }
1012   function remove_from_parent()
1013   {
1014   
1015     foreach($this->attributes as $key=>$val){
1016       if(in_array($val,array("uid","cn","mail"))){
1017         unset($this->attributes[$key]);
1018         unset($this->$val);
1019       }
1020     }
1022     if(array_key_exists('config', $_SESSION) &&
1023        array_key_exists('SERVERS', $_SESSION['config']->data) &&
1024        array_key_exists('FON', $_SESSION['config']->data['SERVERS'])) {
1025       // Get Configuration for Mysql database Server
1026       $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
1027       $s_parameter  ="";
1029       // Connect to DB server
1030       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1032       // Check if we are  connected correctly
1033       if(!$r_con){
1034         $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1035             $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
1036         gosa_log(@mysql_error());
1037         return false;
1038       }
1040       // Select database for Extensions
1041       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1043       // Test if we have the database selected correctly
1044       if(!$db){
1045         $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
1046         gosa_log(@mysql_error());
1047         return false;
1048       }
1050       $SQL="";
1052       /* If deletion starts from userslist, cn uid are not set */
1053       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1054         $this->uid = $this->parent->by_object['user']->uid;
1055       }
1057       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1058         $this->cn  = $this->parent->by_object['user']->cn;
1059       }
1061       $first_num = false;
1062       // Delete old entries
1063       foreach($this->a_old_telenums as $s_telenums){
1064         if(!$first_num){
1065           $first_num = $s_telenums;
1066         }
1067         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1068       }
1070       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1071       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1072       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1075       foreach($SQL as $query){
1076         if(!@mysql_query($query,$r_con)){
1077           print_red(_("Stop".mysql_error()));
1078           return false;
1079         }
1080       }
1081     }
1084     /* unset macro attr, it will cause an error */
1085     $tmp = array_flip($this->attributes);
1086     unset($tmp['macro']);
1087     $this->attributes=array_flip($tmp);
1089     /* Cancel if there's nothing to do here */
1090     if (!$this->initially_was_account){
1091       return;
1092     }
1094     plugin::remove_from_parent();
1096     /* Just keep one phone number */
1097     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1098       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1099     } else {
1100       $this->attrs['telephoneNumber']= array();
1101     }
1103     $ldap= $this->config->get_ldap_link();
1104     $ldap->cd($this->config->current['BASE']);
1105     $ldap->search("(objectClass=goFonQueue)", array("member"));
1106     while($attr = $ldap->fetch()){
1107       if(in_array($this->dn,$attr['member'])){
1108         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1109         unset($new->by_object['ogroup']->memberList[$this->dn]);
1110         unset($new->by_object['ogroup']->member[$this->dn]);
1111         $new->save();
1112         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1113       }
1114     }
1115     $ldap->cd($this->dn);
1116     $ldap->modify($this->attrs);
1117     show_ldap_error($ldap->get_error());
1119     /* Optionally execute a command after we're done */
1120     @mysql_close($r_con);
1121     $this->handle_post_events('remove');
1122   }
1126   /* This function checks if the given phonenumbers are available or already in use*/
1127   function is_number_used()
1128   {
1129     $ldap= $this->config->get_ldap_link();
1130     $ldap->cd($this->config->current['BASE']);
1131     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1132     while($attrs = $ldap->fetch()) {
1133       unset($attrs['telephoneNumber']['count']);
1134       foreach($attrs['telephoneNumber'] as $tele){
1135         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1136         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1137         $numbers[$tele]=$attrs;
1138       }
1139     }
1141     foreach($this->phoneNumbers as $num){
1142       if(!isset($this->cn)) $this->cn = "";
1144       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1145         if(isset($numbers[$num]['uid'][0])){
1146           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1147         }else{
1148           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1149         }
1150       }
1151     }
1152   }
1155 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1156 ?>