Code

Allow saving voice mial context
[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          = "automatic";
13   var $goFonFormat            = "wav";
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          = "";
30   var $goFonHomeServer        = "0";            // Contains the dn of the server that manage this account 
31   var $init_HomeServer        = "0";            // Contains the dn of the server that manage this account 
32   var $goFonHomeServers       = array();        // Contains all available server configurations 
34   var $context                = "default";
35   var $voice_context          = "default";
36     
37   /* attribute list for save action */
38   var $CopyPasteVars          = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
39                                       "hardware_list","used_hardware");
41   var $attributes             = array("goFonDeliveryMode", "goFonFormat","uid","cn","goFonHomeServer",
42       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
43   var $objectclasses= array("goFonAccount");
45   var $uid;
47   function phoneAccount ($config, $dn= NULL, $parent= NULL)
48   {
49     plugin::plugin ($config, $dn, $parent);
51     /* Assemble phone numbers */
52     if (isset($this->attrs['telephoneNumber'])){
53       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
54         $number= $this->attrs['telephoneNumber'][$i];
55         $this->phoneNumbers[$number]= $number;
56       }
57     }
59     /* Set up has_mailAccount */
60     if (isset($this->attrs['objectClass'])){
61       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
62         $this->has_mailAccount= TRUE;
63       }
64     }
66     /* Set uid */
67     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
68       $this->uid = $this->parent->by_object['user']->uid;
69     }
70     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
71       $this->cn  = $this->parent->by_object['user']->cn;
72     }
74     /* Check server configurations 
75      * Load all server configuration in $this->goFonHomeServers if available
76      *  and first server as default if necessary.
77      * Check if connection is successfull for the selected server $this->goFonHomeServer
78      */
80     /* Set available server */
81     if(isset($_SESSION['config']->data['SERVERS']['FON'])){
82       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
83     }
85     $a_SETUP= array();
86     if($this->is_account &&
87        array_key_exists('config',$_SESSION) &&
88        array_key_exists('SERVERS',$_SESSION['config']->data) &&
89        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
90        is_callable("mysql_connect")
91        ) {
93       /* Servers defined? Watch here... */
94       if (count($this->goFonHomeServers)){
96         /* Set default server */
97         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
98           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
99         }
101         /* Remember inital home server, to be able to remove old entries */
102         $this->init_HomeServer = $this->goFonHomeServer;
104         /* Get config */
105         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
106           print_red(sprintf(_("The specified goFonHomeServer '%s' is not available in GOsa server configuration. Saving this account will create a new entry on the server '%s'. Use cancel if you do not want to create a new entry ignoring old accounts."),$this->goFonHomeServer, $this->goFonHomeServers[0]['DN']));
108           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
109           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
110         }    
111         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
113         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
114         if(!$r_con){
115 #          print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
116 #                $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
117           gosa_log(mysql_error());
118         }
119         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
120         if(!$db){
121 #         print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
122           gosa_log(mysql_error());
123         }
125         $first = false; 
126         foreach($this->phoneNumbers as $key => $val){
127           if(!$first){
128             $first = $key;
129           }
130         }
131       }
132     }
134     /* Get available phone hardware  
135      * Search for all available phone hardware  
136      */
137     $ldap= $this->config->get_ldap_link();
138     $ldap->cd($this->config->current['BASE']);
139     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
140     while ($attrs= $ldap->fetch()){
141       $cn= $attrs['cn'][0];
142       if (isset($attrs['description'])){
143         $description= " - ".$attrs['description'][0];
144       } else {
145         $description= "";
146       }
147       $this->hardware_list[$cn]= "$cn$description";
148     }
151     /* Get available Macros  
152      * Search for all Marcos that are visible and create 
153      *  an array with name and parameters 
154      */
155     $ldap->search("(&(objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
157     /* Add none for no macro*/
158     $this->macros['none']=_("no macro");    
159     $this->macro ="none";
161     /* Fetch all Macros*/
162     while ($attrs= $ldap->fetch()){
164       /* unset Count, we don't need that here */
165       unset($attrs['displayName']['count']);
167       /* Parse macro data, unset count for parameterarrays  */
168       if (isset($attrs['goFonMacroParameter']['count'])){
169         unset($attrs['goFonMacroParameter']['count']);
170       }
172       /* fill Selectfield variable with Macros */
173       if(isset($attrs['displayName'][0])){
174         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
175       }else{
176         $this->macros[$attrs['dn']] = _("undefined");
177       }
179       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
180       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
182         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
183           /* Split Data in readable values, by delimiter !  */
184           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
186           /* Set all attrs */
187           $id = $data[0];
188           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
189           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
190           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
191           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
192           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
193           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
194           if($data[2] == "bool"){
195             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
196           }
197         }//foreach
198       }//is_array
199     }//while
202     /* Parse used Macro  
203      * If we have a macro selected, parse it and set values 
204      *  in $this->macroarray[$this->macro]. 
205      */
206     $tmp = split("!",$this->goFonMacro);
207     if(is_array($tmp)){
209       /* First value is the macroname */
210       $this->macro = $tmp[0];
212       /* Macroname saved, delete that index */
213       unset($tmp[0]);
215       /* Check if makro has been removed */
216       if(!isset($this->macros[$this->macro])){
217         $this->macrostillavailable = false;
218       }else{
219         $this->macrostillavailable = true;
220       }
222       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
223       foreach($tmp as $var){
225         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
226         $varar = split("#",$var);
228         /* Only insert if the parameter still exists */
229         if(isset($this->macroarray[$this->macro][$varar[0]])){
230           /* Assign value */
231           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
232         }
233       }
234     }
237     /* Colorize phones 
238      * Used phones will be colored in grey, 
239      *  so we must detect which phones are currently in use.
240      */
241     $ldap->cd($this->config->current['BASE']);
242     $ldap->search("(goFonHardware=*)",array('cn','dn','goFonHardware'));
243     while($attrs = $ldap->fetch()){
244         $cn = $attrs['goFonHardware'][0];
245         if(isset($this->hardware_list[$cn])){
246           $this->used_hardware[$cn]= $cn;
247         }
248     }
249     $this->hardware_list["automatic"]= _("automatic");
250     ksort($this->hardware_list);
251     $this->a_old_telenums = $this->phoneNumbers;
253     /* Get voicemail PIN from MySQL DB 
254      * Because every user can change his PIN directly from the phone
255      *  without any update to the ldap
256      * This means, the PIN in the DB is up to date
257      */
258     if( (is_callable("mysql_pconnect"))&&
259         (isset($cur_cfg))&&
260         (isset($cur_cfg['SERVER']))&&
261         (isset($cur_cfg['LOGIN']))&&
262         (isset($cur_cfg['PASSWORD']))){
263       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
264       if($r_con){
265         restore_error_handler();
266         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
267         $query_tmp = "
268           SELECT 
269           ".$cur_cfg['VOICE_TABLE'].".context as 'v_context', 
270           ".$cur_cfg['SIP_TABLE'].".context,
271           ".$cur_cfg['VOICE_TABLE'].".password 
272             FROM  ".$cur_cfg['VOICE_TABLE'].", 
273           ".$cur_cfg['SIP_TABLE']."  
274             WHERE customer_id = sip_users.mailbox AND name='".$this->uid."';";
276         $res = mysql_query($query_tmp);
277         $vp  = mysql_fetch_assoc($res);
278         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
279         if((isset($vp['password']))&&(!empty($vp['password']))){
280           $this->goFonPINVoice = $vp['password'];
281         }
282         if((isset($vp['context']))&&(!empty($vp['context']))){
283           $this->context = $vp['context'];
284         }
285         if((isset($vp['v_context']))&&(!empty($vp['v_context']))){
286           $this->voice_context = $vp['v_context'];
287         }
288       }
289     }
290     $this->lastmacro=$this->macro;
292     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
293       @mysql_close($r_con) ;
294     }
295   }
298   /* This function generates the Database entries. 
299    * The Parameter 'save' could be true or false.
300    *  false - means only testing no database transactions.
301    *  true  - write database entries.
302    *
303    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
304    * 
305    * If the phone hardware is 'automatic' the table entries will only be removed
306    *  and not added. 
307    */
308   function generate_mysql_entension_entries($save = false)
309   {
310     /* Check if there is at least one server available 
311      * If not, return and tell the user that saving failed 
312      */
313     if(!count($this->goFonHomeServers)){
314       if($save){
315         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."));
316       }
317       return(true);
318     }
320     /* Check if Mysql extension is available */
321     if(!is_callable("mysql_pconnect")){
322       if($save)
323       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
324       return(true);
325     }
326  
327     /********************** 
328      * Attribute Initialisation
329      **********************/
331     $old_connection = false;
333     // Get Configuration for Mysql database Server
334     $s_parameter    = "";                                           // Contains paramter for selected Macro 
335     $r_con          = false;                                        // DB connection
336     $r_db           = false;                                        // Selected DB
337     $r_res          = false;                                        // Result resource
338     $a_ldap_attrs   = array();                                      //  
340     $s_ip           = NULL;                   // Contains ip for Sip entry
341     $s_host         = NULL;                   // Contains host for Sip entry
342     $s_qualify      = "yes";                  // Qualify entry
343     $s_pin          = NULL;                   // Entry for secret
344     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
346     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
347     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
348     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
350     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
351     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
353     $s_sip_key      = "";     // Key for SIP entry index      
354     $s_sip_val      = "";     // Value for SIP entry index      
356     $b_first_deleted= false;  // Only delete first entry, 
357     $s_telenums     = "";     // for each value variable
359     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
361     /* Prepare some basic attributes */
362     $oldnums= array();
363     foreach($this->a_old_telenums as $tele){
364       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
365     }
366     foreach($this->phoneNumbers as $tele){
367       $newnums[]= preg_replace("/[^0-9]/","",$tele);
368     }
370     /* If deletion starts from userslist, cn uid are not set */
371     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
372       $this->uid = $this->parent->by_object['user']->uid;
373     }
374     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
375       $this->cn  = $this->parent->by_object['user']->cn;
376     }
377     /* Create voicemail entry 
378      */
379     if((!isset($this->cn))||(empty($this->cn))){
380       $CNname= $this->uid;
381     }else{
382       $CNname= $this->cn;
383     }
385     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
386       $s_mail = $this->parent->by_object['mailAccount']->mail;
387     }else{
388       $s_mail = "";
389     }
390     /* Get phonehardware to setup sip entry  */
391     $ldap         = $this->config->get_ldap_link();
392     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
393     $a_ldap_attrs = $ldap->fetch();
395     /* Check selected phone hardware, is a default IP set? */
396     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
397       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
398       $s_host     = $s_ip;
399     }else{
400       $s_ip       = NULL;
401       $s_host     = "dynamic";
402     }
404     // Attribute GoFonQualify set ?
405     if(isset($a_ldap_attrs['goFonQualify'])){
406       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
407     }
409     // Attribute GoFonPIN set ?
410     if(isset($this->goFonPIN)){
411       $s_pin      = $this->goFonPIN;
412     }
414     // Attribute GoFonType set ?
415     if(isset($a_ldap_attrs['goFonType'])){
416       $s_type = $a_ldap_attrs['goFonType'][0];
417     }
419     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
420       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
421     }else{
422       $sip_data_array['dtmfmode']     ="rfc2833";
423     }
425     /* Check if phone number is used */
426     if($this->is_number_used()){
427       $this->generate_error = $this->is_number_used(); 
428       return false;
429     }
433     /********************** 
434      * Check Server Connection Information
435      **********************/
436  
437     /* Create Mysql handle for the current goFonHomeServer, if possible  
438      * Get configuration to old asterisk home server 
439      */ 
440     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
441     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
442     if(!$new_connection){
443       $this->generate_error = sprintf(
444           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
445           $a_New['SERVER'],$a_New['LOGIN']);
446       gosa_log(@mysql_error($new_connection));
447       return false;
448     }
449     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
450     if(!$new_database){
451       $this->generate_error = sprintf(
452           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
453           $a_New['DB'],$a_New['SERVER']);
454       gosa_log( @mysql_error($new_connection));
455       return false;
456     }
458     /* If the home server has changed, we must remove entries from old 
459      *  server and add new entries in new server.  
460      */
461     if($this->init_HomeServer != $this->goFonHomeServer){
462     
463       /* Get configuration to old asterisk home server */ 
464       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
465  
466       /* Create connection to the database that contains the old entry. 
467        */
468       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
469       if(!$old_connection){
470         $this->generate_error = sprintf(
471             _("The old MySQL home server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
472             $a_Remove['SERVER'],$a_Remove['LOGIN']);
473         gosa_log(@mysql_error($old_connection));
474         return false;
475       }
476       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
477       if(!$old_database){
478         $this->generate_error = sprintf(
479             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
480             $a_Remove['DB'],$a_Remove['SERVER']);
481         gosa_log(@mysql_error($old_connection));
482         return false;
483       }
484     }
486     /* Save means that we must save changes, not only test  */
487     if($save == true){
488     
489       /********************** 
490        * Remove entries from old home server 
491        **********************/
493       /* Check if there is an old entry 
494        * If there is an old entry, get callerid and remove voicemail and extensions 
495        */
496       if($old_connection){
497         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
498         $rid    = mysql_query($query,$old_connection);
499         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
501         /* Old entry found, remove it */
502         $query_a = array();
503         if(mysql_affected_rows($old_connection)){
504           $result = mysql_fetch_assoc($rid);
505           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
506           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
507           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
508           foreach($oldnums as $s_telenums) {
509             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
510           }
512           foreach($query_a as $qry){
513                   @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
514             if(!mysql_query($qry,$old_connection)){
515               echo mysql_error($old_connection);
516             } 
517           }
518         }
519       }
521       /********************** 
522        * Update / Insert sip_users entry  
523        **********************/
525       /* Set the first given phone number as callerid */
526       reset($newnums);        
527       $i_new_key = key($newnums);
528       $sip_data_array['callerid']  =$newnums[$i_new_key];
529       $sip_data_array['mailbox']   =$newnums[$i_new_key];
531       /* Check if there is already an entry in sip_users for this uid */
532       $SQL_query_array = array();
533       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
534       $rid = mysql_query($query,$new_connection);
535       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
536       if(mysql_affected_rows($new_connection)){
538         /********************** 
539          * Update sip_users entry 
540          **********************/
541         $result                     = mysql_fetch_assoc($rid);
542         $sip_data_array['host']         = $s_host;
543         $sip_data_array['qualify']      = $s_qualify;
544         $sip_data_array['secret']       = $this->goFonPIN;
545         $sip_data_array['type']         = $s_type ;
546         $sip_data_array['username']     = $this->uid;
547         $sip_data_array['ipaddr']       = $s_ip;
548         $sip_data_array['context']      = $this->context;
550         /* Remove not changed attributes, to avoid updating table with same values */
551         foreach($sip_data_array as $name => $value){
552           if($result[$name] == $value){
553             unset($sip_data_array[$name]);
554           }
555         }
556         /* Only update entry if there is something to uopdate */
557         if(count($sip_data_array)){
558           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
559           foreach($sip_data_array as $key => $val){
560             $query.= "".$key."='".$val."',"; 
561           } 
562           $query = preg_replace("/,$/","",$query);
563           $query.= " WHERE name='".$this->uid."';";
564           $SQL_query_array[] = $query;
565         }
566       } else {
567  
568         /********************** 
569          * Insert sip_users entry 
570          **********************/
571         //generate SIP entry
572         $sip_data_array['id']           = "";
573         $sip_data_array['name']         = $this->uid;
574         $sip_data_array['accountcode']  = NULL;          
575         $sip_data_array['amaflags']     = NULL;
576         $sip_data_array['callgroup']    = NULL;
577         $sip_data_array['canreinvite']  = "no";
578         $sip_data_array['context']      = $this->context;
579         $sip_data_array['defaultip']    = NULL;
580         $sip_data_array['fromuser']     = NULL;
581         $sip_data_array['fromdomain']   = NULL;
582         $sip_data_array['host']         = $s_host;
583         $sip_data_array['insecure']     = NULL;
584         $sip_data_array['language']     = NULL;
585         $sip_data_array['mailbox']      = $newnums[$i_new_key];
586         $sip_data_array['md5secret']    = NULL;
587         $sip_data_array['nat']          = "no";
588         $sip_data_array['permit']       = NULL;
589         $sip_data_array['deny']         = NULL;
590         $sip_data_array['mask']         = NULL;
591         $sip_data_array['pickupgroup']  = NULL;
592         $sip_data_array['port']         = NULL;
593         $sip_data_array['qualify']      = $s_qualify;
594         $sip_data_array['restrictcid']  = "n";
595         $sip_data_array['rtptimeout']   = NULL;
596         $sip_data_array['rtpholdtimeout']=NULL;
597         $sip_data_array['secret']       = $this->goFonPIN;
598         $sip_data_array['type']         = $s_type ;
599         $sip_data_array['username']     = $this->uid;
600         $sip_data_array['disallow']     = NULL;
601         $sip_data_array['allow']        = NULL;
602         $sip_data_array['musiconhold']  = NULL;
603         $sip_data_array['regseconds']   = NULL;
604         $sip_data_array['ipaddr']       = $s_ip;
605         $sip_data_array['regexten']     = NULL;
606         $sip_data_array['cancallforward']=NULL;
608         /* There is currently no entry for this user in the sip_users table. 
609          * We should create one i
610          */
611         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
612           if($s_sip_val == NULL) continue;
613           $s_sip_values.="'".$s_sip_val."',";
614           $s_sip_keys  .="`".$s_sip_key."`,";
615         }
616         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
617         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
619         /* Add sip entries to mysql queries */
620         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
621       }
624       /********************** 
625        * Update / Insert Voice mail entry  
626        **********************/
628       $customer_id = $newnums[$i_new_key];
630       $voice_data_array = array(
631           "customer_id" => $customer_id,
632           "mailbox"     => $customer_id,
633           "password"    => $this->goFonVoicemailPIN,
634           "fullname"    => $CNname,
635           "context"     => $this->voice_context,
636           "email"       => $s_mail);
638       /* Set pager number if available */
639       if(isset($this->parent->by_object['user']->pager)){
640         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
641       }
643       /* Check if there is already an entry in sip_users for this uid */
644       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n";
645       $rid = mysql_query($query_tmp,$new_connection);
646       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
647       if(mysql_affected_rows($new_connection)){
649         /********************** 
650          * Update Voice mail entry  
651          **********************/
652         $result = mysql_fetch_assoc($rid)  ;
654         foreach($voice_data_array as $name => $value){
655           if($result[$name] == $value){
656             unset($voice_data_array[$name]);
657           }
658         }
660         /* Only update entry if there is something to uopdate */
661         if(count($voice_data_array)){
662           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
663           foreach($voice_data_array as $key => $val){
664             $query.= "".$key."='".$val."',"; 
665           } 
666           $query = preg_replace("/,$/","",$query);
667           $query.= " WHERE customer_id='".$customer_id."';";
668           $SQL_query_array[] = $query;
669         }
670       }else{
672         /********************** 
673          * Insert Voice mail entry  
674          **********************/
675         $voice_data_array['context'] = $this->voice_context;
676   
677         /* There is currently no voice mail entry for this user. 
678          * We should create one 
679          */
680         $s_voi_values = $s_voi_keys = "";
681         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
682           if($s_voi_val == NULL) continue;
683           $s_voi_values.="'".$s_voi_val."',";
684           $s_voi_keys  .="`".$s_voi_key."`,";
685         }
686         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
687         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
689         /* Add sip entries to mysql queries */
690         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
691       }
693      
694       /********************** 
695        * Remove/Insert extension entries
696        **********************/
697       
698       /* Remove old entries */
699       $query = array();
700       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
701       foreach($oldnums as $s_telenums){
702         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
703       }
704       foreach($newnums as $s_telenums){
705         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
706       }
707       foreach($query as $qry){
708         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
709         if(!mysql_query($qry,$new_connection)){
710           echo mysql_error($new_connection);
711         } 
712       }
713  
714       /********************** 
715        * Insert extension entries
716        **********************/
717  
718       // Get selected Macro Parameter and create parameter entry 
719       if(isset($this->macroarray[$this->macro])){
720         foreach($this->macroarray[$this->macro] as $key => $val ){
721           $s_parameter .= $val['choosen']."|";
722         }
723         $s_parameter = preg_replace("/\|$/","",$s_parameter);
724       }
725      
726       $i = 0; 
727       $EXT = array();
728     
729       if(!is_numeric($this->uid)){
730         $EXT[$i]['context'] = "GOsa";//$this->context;
731         $EXT[$i]['exten']   = $this->uid;
732         $EXT[$i]['priority']= 1;
733         $EXT[$i]['app']     = "Goto";
734         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
735         $i ++;
736       }
738       // Entension entries  Hint / Dial / Goto
739       foreach($newnums as $s_telenums){
741         /* Hint Entry */
742         $EXT[$i]['context'] = "GOsa";//$this->context;
743         $EXT[$i]['exten']   = $s_telenums;
744         $EXT[$i]['priority']= "Hint";
745         $EXT[$i]['app']     = 'SIP/'.$this->uid;
746         $i ++;  
747         /* SetCID */
748         //$EXT[$i]['context'] = "GOsa";//$this->context;
749         //$EXT[$i]['exten']   = $s_telenums;
750         //$EXT[$i]['priority']= 1;
751         //$EXT[$i]['app']     = "SetCIDName";
752         //$EXT[$i]['appdata'] = $CNname;
753         //$i ++;  
755         // If no macro is selected use Dial
756         if($this->macro!="none"){ 
757           $macroname = preg_replace("/,.*$/","",$this->macro);        
758           $macroname = preg_replace("/^.*=/","",$macroname);        
759           $s_app = "Macro";$macroname;
760           $s_par = $macroname."|".$s_parameter; 
761         }else{
762           $s_app = "Dial";
763           $s_par = 'SIP/'.$this->uid."|20|r";
764         }
766         $EXT[$i]['context'] = "GOsa";//$this->context;
767         $EXT[$i]['exten']   = $s_telenums;
768         $EXT[$i]['priority']= 1;
769         $EXT[$i]['app']     = $s_app;
770         $EXT[$i]['appdata'] = $s_par;
771         $i ++;
772       }
774       // Append all these Entries 
775       foreach($EXT as $entr){
776         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
777         foreach($entr as $key2 => $val2){
778           $SQL_syn.= "`".$key2."`,";
779         }
780         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
781         $SQL_syn .= ") VALUES ("; 
782         foreach($entr as $key2 => $val2){
783           $SQL_syn .= "'".$val2."',";
784         }
785         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
786         $SQL_syn .=");\n";
788         $SQL_query_array[] =$SQL_syn;
789         $SQL_syn ="";
790       }
792       // Perform queries ...
793       if($this->goFonHardware != "automatic"){
794         foreach($SQL_query_array as $query){
795           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
796           if(!@mysql_query($query,$new_connection)){
797             print_red(_("Error while performing query:")." ".mysql_error());
798             return false;
799           }
800         }
801       }
802     }
803     @mysql_close($new_connection);
804     return true;
805   }
808   /* Return asterisk contexts 
809    * Additionaly read contexts from file.
810    */
811   function get_asterisk_contexts()
812   {
813     $contexts = array();
814     $contexts[] = "default";
815     $contexts[] = "parkedcalls";
816     $contexts[] = "from-sip";
817     $contexts[] = "from-capi";
818     $file = "/etc/gosa/asterisk_contexts.conf";
819     if(file_exists($file) && is_readable($file)){
820       foreach(file($file) as $context){
821         $contexts[] = trim($context);
822       }
823     }
824     array_unique($contexts);
825     return($contexts);
826   }
829   function execute()
830   {
831     /* Call parent execute */
832     plugin::execute();
834     $display = "";
836     if(empty($this->macro)&&(!empty($this->goFonMacro))){
838       /* Go through already saved values, for a parameter */
839       $tmp = split("!",$this->goFonMacro);
841       /* it is possible that nothing has been saved yet */
842       if(is_array($tmp)){
844         /* First value is the macroname */
845         $this->macro = $tmp[0];
847         /* Macroname saved, delete that index */
848         unset($tmp[0]);
850         /* Check if macro has been removed */
851         if(!isset($this->macroarray[$this->macro])){
852           $this->macrostillavailable = false;
853         }else{
854           $this->macrostillavailable = true;
855         }
857         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
858         foreach($tmp as $var){
860           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
861           $varar = split("#",$var);
863           /* Only insert if the parameter still exists */
864           if(isset($this->macroarray[$this->macro][$varar[0]])){
865             /* Assign value */
866             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
867           }
868         }
869       }
870     }
871     
872     /* Do we represent a valid account? */
873     if (!$this->is_account && $this->parent == NULL){
874       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
875         _("This account has no phone extensions.")."</b>";
876       $display.= back_to_main();
877       return ($display);
878     }
880     /* Do we need to flip is_account state? */
881     if (isset($_POST['modify_state'])){
883       /* Onyl change account state if allowed */
884       if($this->is_account && $this->acl == "#all#"){
885         $this->is_account= !$this->is_account;
886       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
887         $this->is_account= !$this->is_account;
888       }
889     }
891     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
892     if(empty($this->macro)){
893       $this->macro ="none";
894     }
896     /* Prepare templating */
897     $smarty= get_smarty();
899     /* tell user that the selected plugin is no longer available */
900     if((!$this->macrostillavailable)&&($this->macro!="none")){
901       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
902     }
904     /* Assign contexts */
905     $smarty->assign("contexts",$this->get_asterisk_contexts());
906     $smarty->assign("context" ,$this->context);
907     $smarty->assign("voice_context" ,$this->voice_context);
908     $smarty->assign("goFonContextACL", chkacl($this->acl,"context"));
910     /* Assing macroselectbox values  */
911     $smarty->assign("macros",$this->macros);   
912     $smarty->assign("macro", $this->macro);   
914     /* check if there is a FON server created */
915     if(!count($this->goFonHomeServer)){
916       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."));
917     }
919     /* Create html parameter table for selected macro parameters 
920      *  skip if no parameters given 
921      */
922     if(!isset($this->macroarray[$this->macro])){
923       $macrotab="";
924     }else{
926       $macrotab ="<table summary=\""._("Parameter")."\">";
927       /* for every single parameter-> display textfile,combo, or true false switch*/
929       foreach($this->phoneNumbers as $phonenum){
930         $tmp[] = $phonenum;
931       }
932     
933       if($this->macro != $this->lastmacro){
934         /* Go through all params */
935         foreach($this->macroarray[$this->macro] as $key => $paras){
937           $string = $paras['default'];
939           $string=preg_replace("/%uid/i",$this->uid,$string);
941           if(isset($this->cn)){
942             $string=preg_replace("/%cn/i",$this->cn,$string);
943           }
945           for($i = 0 ; $i < 10; $i++){
946             if(isset($tmp[$i])){
947               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
948             }
949           }
950           if(isset($tmp[0])){
951             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
952           }
953           $this->macroarray[$this->macro][$key]['choosen']=$string;
954         }
955       }
957       foreach($this->macroarray[$this->macro] as $paras){
959         /* get al vars */
960         $var        = $paras['var'];           
961         $name       = $paras['name'];           
962         $default    = $paras['default'];
963         $type       = $paras['type'];
964         $choosen    = $paras['choosen'] ; 
965         $str        = $default;
967         /* in case of a combo box display a combobox with selected attr */
968         $macrotab.= "<tr>";
969         switch ($type){
971           case "combo":
972             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
973           foreach(split(":",$default) as $choice){
974             if($choosen==$choice){
975               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
976             }else{
977               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
978             }
979           }
980           $str.="</select>";
981           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
982           break;
984           case "bool":
985             if(!$choosen){
986               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
987             }else{
988               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
989             }
990           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
991           break;
993           case "string":
994             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
995           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
996           break;
998         }
999         $macrotab.= "</td></tr>";
1001       }
1002       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1003     }//is_array()
1005     /* Give smarty the table */
1006     $smarty->assign("macrotab",$macrotab);
1009     /* Do we represent a valid account? */
1010     if (!$this->is_account && $this->parent == NULL){
1011       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
1012         _("This account has no phone extensions.")."</b>";
1013       $display.= back_to_main();
1014       return($display);
1015     }
1017     $display= "";
1019     /* Show tab dialog headers */
1020     if ($this->parent != NULL){
1021       if ($this->is_account){
1022         $display= $this->show_header(_("Remove phone account"),
1023             _("This account has phone features enabled. You can disable them by clicking below."));
1024       } else {
1025         if(empty($this->uid)){
1026           $display= $this->show_header(_("Create phone account"),
1027               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
1028         }else{
1029           $display= $this->show_header(_("Create phone account"),
1030               _("This account has phone features disabled. You can enable them by clicking below."));
1031         }
1032         return ($display);
1033       }
1034     }
1036     /* Add phone number */
1037     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1038       if (is_phone_nr($_POST['phonenumber']) && strlen($_POST['phonenumber']) <=10){
1039         $number= $_POST["phonenumber"];
1040         $this->phoneNumbers[$number]= $number;
1041         $this->is_modified= TRUE;
1042       } else {
1043         print_red(_("Please enter a valid phone number! Because of the realtime extension tables, the number must be less than 11 digits."));
1044       }
1045     }
1047     /* Remove phone number */
1048     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1049       foreach ($_POST['phonenumber_list'] as $number){
1050         unset($this->phoneNumbers[$number]);
1051         $this->is_modified= TRUE;
1052       }
1053     }
1055     /* Transfer ACL's */
1056     foreach($this->attributes as $val){
1057       $smarty->assign($val."ACL", chkacl($this->acl,$val));
1058       if(isset($this->$val)){
1059         $smarty->assign($val,$this->$val);
1060       }else{
1061         $smarty->assign($val,"");
1062       }
1063     }
1065     /* Create home server array */
1066     $tmp = array();
1067     foreach($this->goFonHomeServers as $dn => $attrs){
1068       if(!is_numeric($dn)){
1069         $tmp[$dn] = $attrs['SERVER'];
1070       }
1071     }
1072     $smarty->assign("goFonHomeServers",$tmp);
1074     /* Fill arrays */
1075     $smarty->assign ("goFonHardware", $this->goFonHardware);
1076     if (!count($this->phoneNumbers)){
1077       $smarty->assign ("phoneNumbers", array());
1078     } else {
1079       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1080     }
1081     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
1082       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
1083     foreach ($this->hardware_list as $cn => $description){
1084       if ($cn == $this->goFonHardware){
1085         $selected= "selected";
1086       } else {
1087         $selected= "";
1088       }
1089       if (isset($this->used_hardware[$cn])){
1090         $color= "style=\"color:#A0A0A0\"";
1091       } else {
1092         $color= "";
1093       }
1094       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1095     }
1096     $hl.= "</select>\n";
1097     $smarty->assign ("hardware_list", $hl);
1099     /* Show main page */
1100     $this->lastmacro = $this->macro;
1101     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1102     return($display);
1103   }
1106   function save_object()
1107   {
1108     if (isset($_POST["phoneTab"])){
1109     
1110       plugin::save_object();
1112       /* Save checkbox */
1113       if (isset($_POST['fon_to_mail'])){
1114         $tmp= "[M]";
1115       } else {
1116         $tmp= "[]";
1117       }
1118       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
1119         if ($this->goFonDeliveryMode != $tmp){
1120           $this->is_modified= TRUE;
1121         }
1122         $this->goFonDeliveryMode= $tmp;
1123       }
1125       /* Every macro in the select box are available */
1126       if((isset($_POST['macro']))){
1127         $this->macrostillavailable=true;
1128       }
1130       /* Save context */
1131       if(isset($_POST['context'])){
1132         if($this->context != $_POST['context']){
1133           $this->is_modified= TRUE;
1134         }
1135         $this->context= $_POST['context'];
1136       }
1138       /* Save voice_context */
1139       if(isset($_POST['voice_context'])){
1140         if($this->voice_context != $_POST['voice_context']){
1141           $this->is_modified= TRUE;
1142         }
1143         $this->voice_context= $_POST['voice_context'];
1144       }
1146       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1147         $this->is_modified =true;
1148       }
1150       if(is_array($this->phoneNumbers)){
1151         foreach($this->phoneNumbers as $telenumms) {
1152           $nummsinorder[]=$telenumms; 
1153         }
1154       }else{
1155         $nummsinorder=array("");
1156       }
1158       /* get all Postvars */
1159       if(isset($this->macroarray[$this->macro])){
1160  
1161         foreach($this->macroarray[$this->macro] as $key => $paras){
1163           $backup = $this->macroarray[$this->macro][$key];  
1165           if(isset($_POST[$paras['var']])){
1166             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1167           }
1169           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
1170              We need this code below to read and save checkboxes correct
1171            */
1173           if(isset($_POST['post_success'])){
1174             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1175               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1176                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1177               }else{
1178                 $this->macroarray[$this->macro][$key]['choosen']=false;
1179               }
1180             }
1181           }
1182           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1183             $this->modified = TRUE;
1184           }
1185         }
1186       }
1187     }
1188   }
1190   function check()
1191   {
1192     /* Call common method to give check the hook */
1193     $message= plugin::check();
1195     if(!count($this->goFonHomeServers)){
1196       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1197     }
1199     if(empty($this->goFonHomeServer)){
1200       $message[] = _("Please select a valid goFonHomeServer.");
1201     }
1203     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1204       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1205     }else{
1206       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1207         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1208       }
1209     }
1211     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1212       $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1213     }
1215     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1216       if(!$this->generate_mysql_entension_entries()){
1217         $message[] = $this->generate_error;
1218       }
1219     }
1221     /* We need at least one phone number */
1222     if (count($this->phoneNumbers) == 0){
1223       $message[]= sprintf(_("You need to specify at least one phone number!"));
1224     }
1226     /* check for ! in any parameter setting*/
1227     if(isset($this->macroarray[$this->macro])){
1228       foreach($this->macroarray[$this->macro] as $val){
1229         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1230           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1231         }
1232       }
1233     }
1234     return ($message);
1235   }
1239   function save()
1240   {
1241     plugin::save();
1243     /* Force saving macro again 
1244      * This ensures that 
1245      *  - the macro is available on the destiantion server.
1246      *  - the macro saved is up to date on the destination server.
1247      */
1248     if(!empty($this->macro) && $this->macro != "none")  {
1249       $macro_tab = new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro);
1250       $macro_tab -> save();
1251     }
1253     /* Save arrays */
1254     $tmp_numbers = array();
1255     foreach ($this->phoneNumbers as $number){
1256       $tmp_numbers[] = $number;
1257     }
1259     /* Save settings, or remove goFonMacro attribute*/
1260     if($this->macro!="none"){    
1261       $this->attrs['goFonMacro']=$this->macro;
1262       if(isset($this->macroarray[$this->macro])){
1263         foreach($this->macroarray[$this->macro] as $paras)  {
1264           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1265         }
1266       }
1267     }else{
1268       $this->attrs['goFonMacro']=array();
1269     }
1270     unset($this->attrs['macro'])  ;
1272     $this->attrs['goFonForwarding']=array();
1274     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1275       $str = $this->generate_mysql_entension_entries(true);
1276       if(empty($str)){
1277         print_red($str);
1278       }
1279     }
1281     if($this->attrs['goFonMacro']==""){
1282       $this->attrs['goFonMacro']=array();
1283     }
1285     unset($this->attrs['cn']);
1287     /* Write back to ldap */
1288     $ldap= $this->config->get_ldap_link();
1289     $ldap->cd($this->dn);
1290     $this->cleanup();
1291     
1292     /* Force saving numbers, else it will be overwriten by user account. */
1293     $this->attrs['telephoneNumber'] =$tmp_numbers;
1294     $ldap->modify ($this->attrs); 
1296     show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
1298     /* Optionally execute a command after we're done */
1300     if ($this->initially_was_account == $this->is_account){
1301       if ($this->is_modified){
1302         $this->handle_post_events("modify",array("uid" => $this->uid));
1303       }
1304     } else {
1305       $this->handle_post_events("add",array("uid" => $this->uid));
1306     }
1308   }
1311   function adapt_from_template($dn)
1312   {
1313     plugin::adapt_from_template($dn);
1315     /* Assemble phone numbers */
1316     if (isset($this->attrs['telephoneNumber'])){
1317       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1318         $number= $this->attrs['telephoneNumber'][$i];
1319         $this->phoneNumbers[$number]= $number;
1320       }
1321     }
1322   }
1325   function remove_from_parent()
1326   {
1327     if(!$this->initially_was_account) return;
1329     foreach($this->attributes as $key=>$val){
1330       if(in_array($val,array("uid","cn"))){
1331         unset($this->attributes[$key]);
1332         unset($this->$val);
1333       }
1334     }
1335     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1337       // Get Configuration for initial Mysql database Server
1338       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1339       $s_parameter  ="";
1341       // Connect to DB server
1342       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1344       // Check if we are  connected correctly
1345       if(!$r_con){
1346         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1347                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1348         gosa_log(@mysql_error());
1349         return false;
1350       }
1352       // Select database for Extensions
1353       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1355       // Test if we have the database selected correctly
1356       if(!$db){
1357         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1358         gosa_log(@mysql_error());
1359         return false;
1360       }
1362       $SQL="";
1364       /* If deletion starts from userslist, cn uid are not set */
1365       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1366         $this->uid = $this->parent->by_object['user']->uid;
1367       }
1369       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1370         $this->cn  = $this->parent->by_object['user']->cn;
1371       }
1373       $first_num = false;
1374       // Delete old entries
1375       foreach($this->a_old_telenums as $s_telenums){
1376         if(!$first_num){
1377           $first_num = $s_telenums;
1378         }
1379         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1380       }
1382       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1383       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1384       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1386       foreach($SQL as $query){
1387         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1388         if(!@mysql_query($query,$r_con)){
1389           print_red(_("Stop".mysql_error()));
1390           return false;
1391         }
1392       }
1393     }else{
1394       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1395       return false;
1396     }
1398     /* unset macro attr, it will cause an error */
1399     $tmp = array_flip($this->attributes);
1400     unset($tmp['macro']);
1401     $this->attributes=array_flip($tmp);
1403     /* Cancel if there's nothing to do here */
1404     if (!$this->initially_was_account){
1405       return;
1406     }
1408     plugin::remove_from_parent();
1410     /* Just keep one phone number */
1411     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1412       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1413     } else {
1414       $this->attrs['telephoneNumber']= array();
1415     }
1418     $ldap= $this->config->get_ldap_link();
1419     $ldap->cd($this->config->current['BASE']);
1420     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1421     while($attr = $ldap->fetch()){
1422       if(in_array($this->dn,$attr['member'])){
1423         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1424         unset($new->by_object['ogroup']->memberList[$this->dn]);
1425         unset($new->by_object['ogroup']->member[$this->dn]);
1426         $new->save();
1427         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1428       }
1429     }
1430     $ldap->cd($this->dn);
1431     $this->cleanup();
1432     $ldap->modify ($this->attrs); 
1434     show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1436     /* Optionally execute a command after we're done */
1437     @mysql_close($r_con);
1438     $this->handle_post_events('remove',array("uid"=> $this->uid));
1439   }
1443   /* This function checks if the given phonenumbers are available or already in use*/
1444   function is_number_used()
1445   {
1446     $ldap= $this->config->get_ldap_link();
1447     $ldap->cd($this->config->current['BASE']);
1448     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1449     while($attrs = $ldap->fetch()) {
1450       unset($attrs['telephoneNumber']['count']);
1451       foreach($attrs['telephoneNumber'] as $tele){
1452         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1453         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1454         $numbers[$tele]=$attrs;
1455       }
1456     }
1458     foreach($this->phoneNumbers as $num){
1459       if(!isset($this->cn)) $this->cn = "";
1461       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1462         if(isset($numbers[$num]['uid'][0])){
1463           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1464         }else{
1465           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1466         }
1467       }
1468     }
1469   }
1472   /* Create phoneAccount part of copy & paste dialog */
1473   function getCopyDialog()
1474   { 
1475     if(!$this->is_account) return("");
1476     $smarty = get_smarty();
1477     if (!count($this->phoneNumbers)){
1478       $smarty->assign ("phoneNumbers", array(""));
1479     } else {
1480       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1481     }
1483     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1484     $smarty->assign("goFonPIN",$this->goFonPIN);
1486     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1487     $ret =array();
1488     $ret['string'] = $display;
1489     $ret['status'] = "";
1490     return($ret);
1491   }
1493   /* Save posts from copy & paste dialog dialog  */
1494   function saveCopyDialog()
1495   {
1496     if(!$this->is_account) return;
1497     $this->execute();
1498     if(isset($_POST['goFonVoicemailPIN'])) {
1499       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1500     }
1501     if(isset($_POST['goFonPIN'])){
1502       $this->goFonPIN = $_POST['goFonPIN'];
1503     }
1504   }
1507   function allow_remove()
1508   {
1509     /* Check if previously selected server is still available */
1510     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1511       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1512     }
1513   }
1516 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1517 ?>