Code

0cf7ac03a6684df4a90025ec05e5a1f02382b3cc
[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        = array();
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 $CopyPasteVars          = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
38                                       "hardware_list","used_hardware");
40   var $attributes             = array("goFonDeliveryMode", "goFonFormat","uid","cn",
41       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
42   var $objectclasses= array("goFonAccount");
44   var $uid;
46   function phoneAccount ($config, $dn= NULL, $parent= NULL)
47   {
48     plugin::plugin ($config, $dn, $parent);
50     /* Set phone hardware */
51     if (!isset($this->attrs['goFonHardware'])){
52       $this->goFonHardware= "automatic";
53     }
55     /* Preset voice format */
56     if (!isset($this->attrs['goFonFormat'])){
57       $this->goFonFormat= "wav";
58     }
60     /* Assemble phone numbers */
61     if (isset($this->attrs['telephoneNumber'])){
62       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
63         $number= $this->attrs['telephoneNumber'][$i];
64         $this->phoneNumbers[$number]= $number;
65       }
66     }
68     /* Set up has_mailAccount */
69     if (isset($this->attrs['objectClass'])){
70       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
71         $this->has_mailAccount= TRUE;
72       }
73     }
75     $a_SETUP= array();
76     if(array_key_exists('config',$_SESSION) &&
77        array_key_exists('SERVERS',$_SESSION['config']->data) &&
78        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
79        is_callable("mysql_connect")
80        ) {
81       $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
82       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
83       if(!$r_con){
84         $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
85           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
86         gosa_log(mysql_error());
87         return false;
88       }
89       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
90       if(!$db){
91         $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
92         gosa_log(mysql_error());
93         return false;
94       }
95  
96       $first = false; 
97       foreach($this->phoneNumbers as $key => $val){
98         if(!$first){
99           $first = $key;
100         }
101       }
102     }
104     /* Load hardware list */
105     $ldap= $this->config->get_ldap_link();
106     $ldap->cd($this->config->current['BASE']);
107     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
108     while ($attrs= $ldap->fetch()){
109       $cn= $attrs['cn'][0];
110       if (isset($attrs['description'])){
111         $description= " - ".$attrs['description'][0];
112       } else {
113         $description= "";
114       }
115       $this->hardware_list[$cn]= "$cn$description";
117     }
119     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
120     $ldap->search("(objectClass=goFonMacro)", array("*"));
122     /* Add none for no macro*/
123     $this->macros['none']=_("no macro");    
124     $this->macro ="none";
127     /* Fetch all Macros*/
128     while ($attrs= $ldap->fetch()){
130       /* Only visisble */
131       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
133         /* unset Count, we don't need that here */
134         unset($attrs['displayName']['count']);
136         /* fill Selectfield variable with Macros */
137         if(isset($attrs['displayName'][0])){
138           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
139         }else{
140           $this->macros[$attrs['dn']] = _("undefined");
141         }
143         /* Parse macro data, unset count for parameterarrays  */
144         if (isset($attrs['goFonMacroParameter']['count'])){
145           unset($attrs['goFonMacroParameter']['count']);
146         }
148         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
149         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
151           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
152             /* Split Data in readable values, by delimiter !  */
153             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
155             /* Set all attrs */
156             $id = $data[0];
157             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
158             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
159             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
160             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
161             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
162             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
163             if($data[2] == "bool"){
164               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
165             }
166           }//foreach
167         }//is_array
168       }//visible = 1
169     }//while
171     /* Go through already saved values, for a parameter */
172     $tmp = split("!",$this->goFonMacro);
174     /* it is possible that nothing has been saved yet */
175     if(is_array($tmp)){
177       /* First value is the macroname */
178       $this->macro = $tmp[0];
180       /* Macroname saved, delete that index */
181       unset($tmp[0]);
183       /* Check if makro has been removed */
184       if(!isset($this->macroarray[$this->macro])){
185         $this->macrostillavailable = false;
186       }else{
187         $this->macrostillavailable = true;
188       }
190       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
191       foreach($tmp as $var){
193         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
194         $varar = split("#",$var);
196         /* Only insert if the parameter still exists */
197         if(isset($this->macroarray[$this->macro][$varar[0]])){
198           /* Assign value */
199           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
200         }
201       }
202     }
205     /* Eventually colorize phones */
206     $ldap->cd($this->config->current['BASE']);
207     foreach ($this->hardware_list as $cn => $desc){
208       $ldap->search("(goFonHardware=$cn)", array('cn'));
209       if ($ldap->count() > 0){
210         $ldap->fetch();
211         if ($ldap->getDN() != $this->dn){
212           $this->used_hardware[$cn]= $ldap->getDN();
213         }
214       }
215     }
216     $this->hardware_list["automatic"]= _("automatic");
217     ksort($this->hardware_list);
218     $this->a_old_telenums = $this->phoneNumbers;
220     if($this->is_account){
221       $this->is_modified = true;
222     }
225     /* Get voicemail PIN from MySQL DB 
226      * Because every user can change his PIN directly from the phone
227      *  without any update to the ldap
228      * This means, the PIN in the DB is up to date
229      */
230     // Connect to DB server
231     if((is_callable("mysql_pconnect"))&&(isset($a_SETUP))&&(isset($a_SETUP['SERVER']))&&(isset($a_SETUP['LOGIN']))&&(isset($a_SETUP['PASSWORD']))){
232       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
233       if($r_con){
234         $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
235         $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."'"));
237         if((isset($vp[0]))&&(!empty($vp[0]))){
238           $this->goFonPINVoice = $vp[0];
239         }
240       }
241     }
242     $this->lastmacro=$this->macro;
244     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
245       @mysql_close($r_con) ;
246     }
247   }
250   // Generate MySQL Syntax
251   function generate_mysql_entension_entries($save = false){
253     if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
254       if($save)
255       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."));
256       return(true);
257     }
259     if(!is_callable("mysql_pconnect")){
260       if($save)
261       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
262       return(true);
263     }
264   
265     // Get Configuration for Mysql database Server
266     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
267     $s_parameter    = "";                                           // Contains paramter for selected Macro 
268     $r_con          = false;                                        // DB connection
269     $r_db           = false;                                        // Selected DB
270     $r_res          = false;                                        // Result resource
271     $a_ldap_attrs   = array();                                      //  
273     $s_ip           = NULL;                   // Contains ip for Sip entry
274     $s_host         = NULL;                   // Contains host for Sip entry
275     $s_qualify      = "yes";                  // Qualify entry
276     $s_pin          = NULL;                   // Entry for secret
277     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
279     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
280     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
281     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
283     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
284     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
286     $s_sip_key      = "";     // Key for SIP entry index      
287     $s_sip_val      = "";     // Value for SIP entry index      
289     $b_first_deleted= false;  // Only delete first entry, 
290     $s_telenums     = "";     // for each value variable
292     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
295     // Connect to DB server
296     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
298     // Check if we are  connected correctly
299     if(!$r_con){
300       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
301           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
302       gosa_log(mysql_error());
303       return false;
304     }
306     // Select database for Extensions
307     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
309     // Test if we have the database selected correctly
310     if(!$r_db){
311       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
312       gosa_log(mysql_error());
313       return false;
314     }
316     // Get phonehardware to setup sip entry
317     $ldap         = $this->config->get_ldap_link();
318     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
319     $a_ldap_attrs = $ldap->fetch();
321     if($this->is_number_used()){
322       $this->generate_error = $this->is_number_used(); 
323       return false;
324     }
326     /* If Save == true, we should save something.
327      * Generate SQL, for drop of old entries
328      * Generate SQL, for insert new entries
329      */ 
330     if($save == true){
331       
332       foreach($this->a_old_telenums as $tele){
333         $oldnums[]= preg_replace("/[^0-9]/","",$tele);
334       }
336       foreach($this->phoneNumbers as $tele){
337         $newnums[]= preg_replace("/[^0-9]/","",$tele);
338       }
340       // Attribute GoFonDefaultIP set ?
341       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
342         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
343         $s_host     = $s_ip;
344       }else{
345         $s_ip       = NULL;
346         $s_host     = "dynamic";
347       }
349       // Attribute GoFonQualify set ?
350       if(isset($a_ldap_attrs['goFonQualify'])){
351         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
352       }
354       // Attribute GoFonPIN set ?
355       if(isset($this->goFonPIN)){
356         $s_pin      = $this->goFonPIN;
357       }
359       // Attribute GoFonType set ?
360       if(isset($a_ldap_attrs['goFonType'])){
361         $s_type = $a_ldap_attrs['goFonType'][0];
362       }
364       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
365         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
366       }else{
367         $sip_data_array['dtmfmode']     ="rfc2833";
368       }
370       // generate SIP entry
371       $sip_data_array['id']           = "";
372       $sip_data_array['name']         = $this->uid;
373       $sip_data_array['accountcode']  = NULL;          
374       $sip_data_array['amaflags']     = NULL;
375       $sip_data_array['callgroup']    = NULL;
376       $sip_data_array['callerid']     = "";
377       $sip_data_array['canreinvite']  = "no";
378       $sip_data_array['context']      = "default";
379       $sip_data_array['defaultip']    = NULL;
380       $sip_data_array['fromuser']     = NULL;
381       $sip_data_array['fromdomain']   = NULL;
382       $sip_data_array['host']         = $s_host;
383       $sip_data_array['insecure']     = NULL;
384       $sip_data_array['language']     = NULL;
385       $sip_data_array['mailbox']      = "asterisk";
386       $sip_data_array['md5secret']    = NULL;
387       $sip_data_array['nat']          = "no";
388       $sip_data_array['permit']       = NULL;
389       $sip_data_array['deny']         = NULL;
390       $sip_data_array['mask']         = NULL;
391       $sip_data_array['pickupgroup']  = NULL;
392       $sip_data_array['port']         = NULL;
393       $sip_data_array['qualify']      = $s_qualify;
394       $sip_data_array['restrictcid']  = "n";
395       $sip_data_array['rtptimeout']   = NULL;
396       $sip_data_array['rtpholdtimeout']=NULL;
397       $sip_data_array['secret']       = $this->goFonPIN;
398       $sip_data_array['type']         = $s_type ;
399       $sip_data_array['username']     = $this->uid;
400       $sip_data_array['disallow']     = NULL;
401       $sip_data_array['allow']        = NULL;
402       $sip_data_array['musiconhold']  = NULL;
403       $sip_data_array['regseconds']   = NULL;
404       $sip_data_array['ipaddr']       = $s_ip;
405       $sip_data_array['regexten']     = NULL;
406       $sip_data_array['cancallforward']=NULL;
408       // Get selected Macro Parameter and create parameter entry 
409       if(isset($this->macroarray[$this->macro])){
410         foreach($this->macroarray[$this->macro] as $key => $val ){
411           $s_parameter .= $val['choosen']."|";
412         }
413         $s_parameter = preg_replace("/\|$/","",$s_parameter);
414       }
416       if($this->is_number_used()){
417         $this->generate_error = $this->is_number_used(); 
418         return false;
419       }
421       // Create new SIP entry ...
422       $sip_entry = $sip_data_array;
423       reset($newnums);
424       $i_new_key = key($newnums);
425       $sip_entry['callerid']  =$newnums[$i_new_key];
426       $sip_entry['mailbox']   =$newnums[$i_new_key];
428       if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
429         $s_mail = $this->parent->by_object['mailAccount']->mail;
430       }else{
431         $s_mail = "";
432       }
434       // $SQL contains all queries
435       $SQL   = array();
436       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
437       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
438       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$newnums[$i_new_key].";"; 
439       // Delete old entries
440       $b_first_deleted  =false;
441       if(isset($oldnums) && is_array($oldnums)){
442         foreach($oldnums as $s_telenums){
443           $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
444           if(!$b_first_deleted){
445             $b_first_deleted=true;
446             $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
447           }
448         }
449       }
450       if($this->goFonHardware=="automatic"){
451         foreach($SQL as $query ){
452           mysql_query($query) ;
453         }
454         return;
455       }
457       // Generate Strings with keys and values 
458       foreach($sip_entry as $s_sip_key=>$s_sip_val){
459         if($s_sip_val == NULL) continue;
460         $s_sip_values.="'".$s_sip_val."',";
461         $s_sip_keys  .="`".$s_sip_key."`,";
462       }
463       // Remove last ,
464       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
465       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
467       // Append SIP Entry 
468       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
470       /* If deletion starts from userslist, cn uid are not set */
471       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
472         $this->uid = $this->parent->by_object['user']->uid;
473       }
475       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
476         $this->cn  = $this->parent->by_object['user']->cn;
477       }
479       if((!isset($this->cn))||(empty($this->cn))){
480         $CNname= $this->uid;
481       }else{
482         $CNname= $this->cn;
483       }
485       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
486           VALUES   ('".$newnums[$i_new_key]."',
487                     'default',
488                     '".$newnums[$i_new_key]."',
489                     '".$this->goFonVoicemailPIN."',
490                     '".$CNname."',
491                     '".$s_mail."',
492                     '');";
493       $i_is_accounted=false;
494     
495       $i = 0; 
496  
497       $is_inserted_once = false;
498  
499       // Entension entries  Hint / Dial / Goto
500       foreach($newnums as $s_telenums){
502         if(!$is_inserted_once){
503           $is_inserted_once = true;
504           $EXT[$i]['context'] = 'GOsa';
505           $EXT[$i]['exten']   = $this->uid;
506           $EXT[$i]['priority']= 1;
507           $EXT[$i]['app']     = "Goto";
508           $EXT[$i]['appdata'] = $s_telenums."|1";
509           $i ++;
510         }
511         /* Hint Entry */
512         $EXT[$i]['context'] = 'GOsa';
513         $EXT[$i]['exten']   = $s_telenums;
514         $EXT[$i]['priority']= "Hint";
515         $EXT[$i]['app']     = 'SIP/'.$this->uid;
516         $i ++;  
517         /* SetCID */
518         //$EXT[$i]['context'] = 'GOsa';
519         //$EXT[$i]['exten']   = $s_telenums;
520         //$EXT[$i]['priority']= 1;
521         //$EXT[$i]['app']     = "SetCIDName";
522         //$EXT[$i]['appdata'] = $CNname;
523         //$i ++;  
525         // If no macro is selected use Dial
526         if($this->macro!="none"){ 
527           $macroname = preg_replace("/,.*$/","",$this->macro);        
528           $macroname = preg_replace("/^.*=/","",$macroname);        
529           $s_app = "Macro";$macroname;
530           $s_par = $macroname."|".$s_parameter; 
531         }else{
532           $s_app = "Dial";
533           $s_par = 'SIP/'.$this->uid."|20|r";
534         }
536         $EXT[$i]['context'] = 'GOsa';
537         $EXT[$i]['exten']   = $s_telenums;
538         $EXT[$i]['priority']= 1;
539         $EXT[$i]['app']     = $s_app;
540         $EXT[$i]['appdata'] = $s_par;
541         $i ++;
543       }
545       // Append all these Entries 
546       foreach($EXT as $entr){
547         $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
548         foreach($entr as $key2 => $val2){
549           $SQL_syn.= "`".$key2."`,";
550         }
551         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
552         $SQL_syn .= ") VALUES ("; 
553         foreach($entr as $key2 => $val2){
554           $SQL_syn .= "'".$val2."',";
555         }
556         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
557         $SQL_syn .=");\n";
558         $SQL[] =$SQL_syn;
559         $SQL_syn ="";
560       }
562       // Perform queries ...
563       foreach($SQL as $query){
564         if(!@mysql_query($query,$r_con)){
565           print_red(_("Error while performing query:")." ".mysql_error());
566           return false;
567         }
568       }
569     }
570     @mysql_close($r_con);
571     return true;
572   }
575   function execute()
576   {
577         /* Call parent execute */
578         plugin::execute();
580     $display = "";
582     if(empty($this->macro)&&(!empty($this->goFonMacro))){
584       /* Go through already saved values, for a parameter */
585       $tmp = split("!",$this->goFonMacro);
587       /* it is possible that nothing has been saved yet */
588       if(is_array($tmp)){
590         /* First value is the macroname */
591         $this->macro = $tmp[0];
593         /* Macroname saved, delete that index */
594         unset($tmp[0]);
596         /* Check if makro has been removed */
597         if(!isset($this->macroarray[$this->macro])){
598           $this->macrostillavailable = false;
599         }else{
600           $this->macrostillavailable = true;
601         }
603         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
604         foreach($tmp as $var){
606           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
607           $varar = split("#",$var);
609           /* Only insert if the parameter still exists */
610           if(isset($this->macroarray[$this->macro][$varar[0]])){
611             /* Assign value */
612             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
613           }
614         }
615       }
616     }
617     
618     /* Do we represent a valid account? */
619     if (!$this->is_account && $this->parent == NULL){
620       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
621         _("This account has no phone extensions.")."</b>";
622       $display.= back_to_main();
623       return ($display);
624     }
626     /* Do we need to flip is_account state? */
627     if (isset($_POST['modify_state'])){
628       $this->is_account= !$this->is_account;
629     }
631     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
632     if(empty($this->macro)){
633       $this->macro ="none";
634     }
636     /* Prepare templating */
637     $smarty= get_smarty();
639     /* tell user that the pluging selected is no longer available*/
640     if((!$this->macrostillavailable)&&($this->macro!="none")){
641       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
642     }
644     /* Assing macroselectbox values  */
645     $smarty->assign("macros",$this->macros);   
646     $smarty->assign("macro", $this->macro);   
648     /* check if there is a FON server created */
649     if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
650       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."));
651     }
653     /* Create parameter table, skip if no parameters given */
654     if(!isset($this->macroarray[$this->macro])){
655       $macrotab="";
656     }else{
658       $macrotab ="<table summary=\""._("Parameter")."\">";
659       /* for every single parameter-> display textfile,combo, or true false switch*/
661       foreach($this->phoneNumbers as $phonenum){
662         $tmp[] = $phonenum;
663       }
665       
666     
667       if($this->macro != $this->lastmacro){
668         /* Go through all params */
669         foreach($this->macroarray[$this->macro] as $key => $paras){
671           $string = $paras['default'];
673           $string=preg_replace("/%uid/i",$this->uid,$string);
675           if(isset($this->cn)){
676             $string=preg_replace("/%cn/i",$this->cn,$string);
677           }
679           for($i = 0 ; $i < 10; $i++){
680             if(isset($tmp[$i])){
681               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
682             }
683           }
684           if(isset($tmp[0])){
685             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
686           }
687           $this->macroarray[$this->macro][$key]['choosen']=$string;
688         }
689       }
691       foreach($this->macroarray[$this->macro] as $paras){
693         /* get al vars */
694         $var        = $paras['var'];           
695         $name       = $paras['name'];           
696         $default    = $paras['default'];
697         $type       = $paras['type'];
698         $choosen    = $paras['choosen'] ; 
699         $str        = $default;
701         /* in case of a combo box display a combobox with selected attr */
702         $macrotab.= "<tr>";
703         switch ($type){
705           case "combo":
706             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
707           foreach(split(":",$default) as $choice){
708             if($choosen==$choice){
709               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
710             }else{
711               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
712             }
713           }
714           $str.="</select>";
715           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
716           break;
718           case "bool":
719             if(!$choosen){
720               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
721             }else{
722               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
723             }
724           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
725           break;
727           case "string":
728             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
729           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
730           break;
732         }
733         $macrotab.= "</td></tr>";
735       }
736       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
737     }//is_array()
739     /* Give smarty the table */
740     $smarty->assign("macrotab",$macrotab);
742     /* Do we represent a valid account? */
743     if (!$this->is_account && $this->parent == NULL){
744       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
745         _("This account has no phone extensions.")."</b>";
746       $display.= back_to_main();
747       return($display);
748     }
750     $display= "";
752     /* Show tab dialog headers */
753     if ($this->parent != NULL){
754       if ($this->is_account){
755         $display= $this->show_header(_("Remove phone account"),
756             _("This account has phone features enabled. You can disable them by clicking below."));
757       } else {
758         if(empty($this->uid)){
759           $display= $this->show_header(_("Create phone account"),
760               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
761         }else{
762           $display= $this->show_header(_("Create phone account"),
763               _("This account has phone features disabled. You can enable them by clicking below."));
764         }
765         return ($display);
766       }
767     }
769     /* Add phone number */
770     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
771       if (is_phone_nr($_POST['phonenumber'])){
772         $number= $_POST["phonenumber"];
773         $this->phoneNumbers[$number]= $number;
774         $this->is_modified= TRUE;
775       } else {
776         print_red(_("Please enter a valid phone number!"));
777       }
778     }
780     /* Remove phone number */
781     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
782       foreach ($_POST['phonenumber_list'] as $number){
783         unset($this->phoneNumbers[$number]);
784         $this->is_modified= TRUE;
785       }
786     }
788     /* Transfer ACL's */
789     foreach($this->attributes as $val){
790       $smarty->assign($val."ACL", chkacl($this->acl,$val));
791       if(isset($this->$val)){
792         $smarty->assign($val,$this->$val);
793       }else{
794         $smarty->assign($val,"");
795       }
796     }
798     /* Fill arrays */
799     $smarty->assign ("goFonHardware", $this->goFonHardware);
800     if (!count($this->phoneNumbers)){
801       $smarty->assign ("phoneNumbers", array());
802     } else {
803       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
804     }
805     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
806       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
807     foreach ($this->hardware_list as $cn => $description){
808       if ($cn == $this->goFonHardware){
809         $selected= "selected";
810       } else {
811         $selected= "";
812       }
813       if (isset($this->used_hardware[$cn])){
814         $color= "style=\"color:#A0A0A0\"";
815       } else {
816         $color= "";
817       }
818       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
819     }
820     $hl.= "</select>\n";
821     $smarty->assign ("hardware_list", $hl);
823     /* Show main page */
824     $this->lastmacro = $this->macro;
825     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
826     return($display);
827   }
830   function save_object()
831   {
832     if (isset($_POST["phoneTab"])){
833       plugin::save_object();
835       /* Save checkbox */
836       if (isset($_POST['fon_to_mail'])){
837         $tmp= "[M]";
838       } else {
839         $tmp= "[]";
840       }
841       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
842         if ($this->goFonDeliveryMode != $tmp){
843           $this->is_modified= TRUE;
844         }
845         $this->goFonDeliveryMode= $tmp;
846       }
848       /* Every macro in the select box are available */
849       if((isset($_POST['macro']))){
850         $this->macrostillavailable=true;
851       }
853       if(is_array($this->phoneNumbers)){
854         foreach($this->phoneNumbers as $telenumms) {
855           $nummsinorder[]=$telenumms; 
856         }
857       }else{
858         $nummsinorder=array("");
859       }
861       /* get all Postvars */
862       if(isset($this->macroarray[$this->macro])){ 
863         foreach($this->macroarray[$this->macro] as $key => $paras){
864           if(isset($_POST[$paras['var']])){
865             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
866           }
868           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
869              We need this code below to read and save checkboxes correct
870            */
872           if(isset($_POST['post_success'])){
873             if($this->macroarray[$this->macro][$key]['type']=="bool"){
874               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
875                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
876               }else{
877                 $this->macroarray[$this->macro][$key]['choosen']=false;
878               }
879             }
880           }
881         }
882       }
883     }
884   }
886   function check()
887   {
888     /* Call common method to give check the hook */
889     $message= plugin::check();
891     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
892       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
893     }else{
894       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
895         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
896       }
897     }
899     if((strlen($this->goFonPIN)<=0)){
900       $message[]=(_("Phone PIN must be at least one character long."));
901     }else{
902       if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
903         $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
904       }
905     }
907     if(!$this->generate_mysql_entension_entries()){
908       $message[] = $this->generate_error;
909     }
911     /* We need at least one phone number */
912     if (count($this->phoneNumbers) == 0){
913       $message[]= sprintf(_("You need to specify at least one phone number!"));
914     }
916     /* check for ! in any parameter setting*/
917     if(isset($this->macroarray[$this->macro])){
918       foreach($this->macroarray[$this->macro] as $val){
919         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
920           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
921         }
922       }
923     }
924     return ($message);
925   }
929   function save()
930   {
931     plugin::save();
933     /* Save arrays */
934     $this->attrs['telephoneNumber']= array();
935     foreach ($this->phoneNumbers as $number){
936       $this->attrs['telephoneNumber'][]= $number;
937     }
939     /* Save settings, or remove goFonMacro attribute*/
940     if($this->macro!="none"){    
941       $this->attrs['goFonMacro']=$this->macro;
942       if(isset($this->macroarray[$this->macro])){
943         foreach($this->macroarray[$this->macro] as $paras)  {
944           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
945         }
946       }
947     }else{
948       $this->attrs['goFonMacro']=array();
949     }
950     unset($this->attrs['macro'])  ;
952     $this->attrs['goFonForwarding']=array();
954     $this->generate_mysql_entension_entries(true);
956     if($this->attrs['goFonMacro']==""){
957       $this->attrs['goFonMacro']=array();
958     }
960     unset($this->attrs['cn']);
962     /* Write back to ldap */
963     $ldap= $this->config->get_ldap_link();
964     $ldap->cd($this->dn);
965     $this->cleanup();
966     $ldap->modify ($this->attrs); 
968     show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
970     /* Optionally execute a command after we're done */
972     if ($this->initially_was_account == $this->is_account){
973       if ($this->is_modified){
974         $this->handle_post_events("modify",array("uid" => $this->uid));
975       }
976     } else {
977       $this->handle_post_events("add",array("uid" => $this->uid));
978     }
980   }
983   function insert_after($entry, $nr, $list)
984   {
985     /* Is the entry free? No? Make it free... */
986     if (isset($list[$nr])) {
987       $dest= array();
988       $newidx= 0;
990       foreach ($list as $idx => $contents){
991         $dest[$newidx++]= $contents;
992         if ($idx == $nr){
993           $dest[$newidx++]= $entry;
994         }
995       }
996     } else {
997       $dest= $list;
998       $dest[$nr]= $entry;
999     }
1001     return ($dest);
1002   }
1005   function adapt_from_template($dn)
1006   {
1007     plugin::adapt_from_template($dn);
1009     /* Assemble phone numbers */
1010     if (isset($this->attrs['telephoneNumber'])){
1011       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1012         $number= $this->attrs['telephoneNumber'][$i];
1013         $this->phoneNumbers[$number]= $number;
1014       }
1015     }
1016   }
1019   function remove_from_parent()
1020   {
1021     if(!$this->initially_was_account) return;
1023     foreach($this->attributes as $key=>$val){
1024       if(in_array($val,array("uid","cn"))){
1025         unset($this->attributes[$key]);
1026         unset($this->$val);
1027       }
1028     }
1029     if(array_key_exists('config', $_SESSION) &&
1030        array_key_exists('SERVERS', $_SESSION['config']->data) &&
1031        array_key_exists('FON', $_SESSION['config']->data['SERVERS']) &&
1032         is_callable("mysql_pconnect")) {
1033       // Get Configuration for Mysql database Server
1034       $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
1035       $s_parameter  ="";
1037       // Connect to DB server
1038       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1040       // Check if we are  connected correctly
1041       if(!$r_con){
1042         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1043                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1044         gosa_log(@mysql_error());
1045         return false;
1046       }
1048       // Select database for Extensions
1049       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1051       // Test if we have the database selected correctly
1052       if(!$db){
1053         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1054         gosa_log(@mysql_error());
1055         return false;
1056       }
1058       $SQL="";
1060       /* If deletion starts from userslist, cn uid are not set */
1061       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1062         $this->uid = $this->parent->by_object['user']->uid;
1063       }
1065       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1066         $this->cn  = $this->parent->by_object['user']->cn;
1067       }
1069       $first_num = false;
1070       // Delete old entries
1071       foreach($this->a_old_telenums as $s_telenums){
1072         if(!$first_num){
1073           $first_num = $s_telenums;
1074         }
1075         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1076       }
1078       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1079       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1080       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1082       foreach($SQL as $query){
1083         if(!@mysql_query($query,$r_con)){
1084           print_red(_("Stop".mysql_error()));
1085           return false;
1086         }
1087       }
1088     }else{
1089       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1090       return false;
1091     }
1093     /* unset macro attr, it will cause an error */
1094     $tmp = array_flip($this->attributes);
1095     unset($tmp['macro']);
1096     $this->attributes=array_flip($tmp);
1098     /* Cancel if there's nothing to do here */
1099     if (!$this->initially_was_account){
1100       return;
1101     }
1103     plugin::remove_from_parent();
1105     /* Just keep one phone number */
1106     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1107       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1108     } else {
1109       $this->attrs['telephoneNumber']= array();
1110     }
1113     $ldap= $this->config->get_ldap_link();
1114     $ldap->cd($this->config->current['BASE']);
1115     $ldap->search("(objectClass=goFonQueue)", array("member"));
1116     while($attr = $ldap->fetch()){
1117       if(in_array($this->dn,$attr['member'])){
1118         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1119         unset($new->by_object['ogroup']->memberList[$this->dn]);
1120         unset($new->by_object['ogroup']->member[$this->dn]);
1121         $new->save();
1122         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1123       }
1124     }
1125     $ldap->cd($this->dn);
1126     $this->cleanup();
1127     $ldap->modify ($this->attrs); 
1129     show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1131     /* Optionally execute a command after we're done */
1132     @mysql_close($r_con);
1133     $this->handle_post_events('remove',array("uid"=> $this->uid));
1134   }
1138   /* This function checks if the given phonenumbers are available or already in use*/
1139   function is_number_used()
1140   {
1141     $ldap= $this->config->get_ldap_link();
1142     $ldap->cd($this->config->current['BASE']);
1143     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1144     while($attrs = $ldap->fetch()) {
1145       unset($attrs['telephoneNumber']['count']);
1146       foreach($attrs['telephoneNumber'] as $tele){
1147         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1148         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1149         $numbers[$tele]=$attrs;
1150       }
1151     }
1153     foreach($this->phoneNumbers as $num){
1154       if(!isset($this->cn)) $this->cn = "";
1156       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1157         if(isset($numbers[$num]['uid'][0])){
1158           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1159         }else{
1160           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1161         }
1162       }
1163     }
1164   }
1167   /* Create phoneAccount part of copy & paste dialog */
1168   function getCopyDialog()
1169   { 
1170     if(!$this->is_account) return("");
1171     $smarty = get_smarty();
1172     if (!count($this->phoneNumbers)){
1173       $smarty->assign ("phoneNumbers", array(""));
1174     } else {
1175       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1176     }
1178     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1179     $smarty->assign("goFonPIN",$this->goFonPIN);
1181     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1182     $ret =array();
1183     $ret['string'] = $display;
1184     $ret['status'] = "";
1185     return($ret);
1186   }
1188   /* Save posts from copy & paste dialog dialog  */
1189   function saveCopyDialog()
1190   {
1191     if(!$this->is_account) return;
1192     $this->execute();
1193     if(isset($_POST['goFonVoicemailPIN'])) {
1194       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1195     }
1196     if(isset($_POST['goFonPIN'])){
1197       $this->goFonPIN = $_POST['goFonPIN'];
1198     }
1199   }
1202 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1203 ?>