Code

3acd47d61a64d8e0b1baaf23c9614a6125374629
[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       $query  = "SELECT id,name,callerid FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';";
645       $rid    = mysql_query($query,$new_connection);
646       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
647       $result = mysql_fetch_assoc($rid);
649       $old_customer_id = ""; 
650       if($result){
651         $old_customer_id = $result['callerid'];
652       }
654       /* Check if there is already an entry in sip_users for this uid */
655       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$old_customer_id."';\n";
656       $rid = mysql_query($query_tmp,$new_connection);
657       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
658       if(mysql_affected_rows($new_connection)){
660         /********************** 
661          * Update Voice mail entry  
662          **********************/
663         $result = mysql_fetch_assoc($rid)  ;
665         foreach($voice_data_array as $name => $value){
666           if($result[$name] == $value){
667             unset($voice_data_array[$name]);
668           }
669         }
671         /* Only update entry if there is something to uopdate */
672         if(count($voice_data_array)){
673           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
674           foreach($voice_data_array as $key => $val){
675             $query.= "".$key."='".$val."',"; 
676           } 
677           $query = preg_replace("/,$/","",$query);
678           $query.= " WHERE customer_id='".$old_customer_id."';";
679           $SQL_query_array[] = $query;
680         }
681       }else{
683         /********************** 
684          * Insert Voice mail entry  
685          **********************/
686         $voice_data_array['context'] = $this->voice_context;
687   
688         /* There is currently no voice mail entry for this user. 
689          * We should create one 
690          */
691         $s_voi_values = $s_voi_keys = "";
692         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
693           if($s_voi_val == NULL) continue;
694           $s_voi_values.="'".$s_voi_val."',";
695           $s_voi_keys  .="`".$s_voi_key."`,";
696         }
697         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
698         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
700         /* Add sip entries to mysql queries */
701         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
702       }
704      
705       /********************** 
706        * Remove/Insert extension entries
707        **********************/
708       
709       /* Remove old entries */
710       $query = array();
711       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
712       foreach($oldnums as $s_telenums){
713         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
714       }
715       foreach($newnums as $s_telenums){
716         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
717       }
718       foreach($query as $qry){
719         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
720         if(!mysql_query($qry,$new_connection)){
721           echo mysql_error($new_connection);
722         } 
723       }
724  
725       /********************** 
726        * Insert extension entries
727        **********************/
728  
729       // Get selected Macro Parameter and create parameter entry 
730       if(isset($this->macroarray[$this->macro])){
731         foreach($this->macroarray[$this->macro] as $key => $val ){
732           $s_parameter .= $val['choosen']."|";
733         }
734         $s_parameter = preg_replace("/\|$/","",$s_parameter);
735       }
736      
737       $i = 0; 
738       $EXT = array();
739     
740       if(!is_numeric($this->uid)){
741         $EXT[$i]['context'] = "GOsa";//$this->context;
742         $EXT[$i]['exten']   = $this->uid;
743         $EXT[$i]['priority']= 1;
744         $EXT[$i]['app']     = "Goto";
745         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
746         $i ++;
747       }
749       // Entension entries  Hint / Dial / Goto
750       foreach($newnums as $s_telenums){
752         /* Hint Entry */
753         $EXT[$i]['context'] = "GOsa";//$this->context;
754         $EXT[$i]['exten']   = $s_telenums;
755         $EXT[$i]['priority']= "Hint";
756         $EXT[$i]['app']     = 'SIP/'.$this->uid;
757         $i ++;  
758         /* SetCID */
759         //$EXT[$i]['context'] = "GOsa";//$this->context;
760         //$EXT[$i]['exten']   = $s_telenums;
761         //$EXT[$i]['priority']= 1;
762         //$EXT[$i]['app']     = "SetCIDName";
763         //$EXT[$i]['appdata'] = $CNname;
764         //$i ++;  
766         // If no macro is selected use Dial
767         if($this->macro!="none"){ 
768           $macroname = preg_replace("/,.*$/","",$this->macro);        
769           $macroname = preg_replace("/^.*=/","",$macroname);        
770           $s_app = "Macro";$macroname;
771           $s_par = $macroname."|".$s_parameter; 
772         }else{
773           $s_app = "Dial";
774           $s_par = 'SIP/'.$this->uid."|20|r";
775         }
777         $EXT[$i]['context'] = "GOsa";//$this->context;
778         $EXT[$i]['exten']   = $s_telenums;
779         $EXT[$i]['priority']= 1;
780         $EXT[$i]['app']     = $s_app;
781         $EXT[$i]['appdata'] = $s_par;
782         $i ++;
783       }
785       // Append all these Entries 
786       foreach($EXT as $entr){
787         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
788         foreach($entr as $key2 => $val2){
789           $SQL_syn.= "`".$key2."`,";
790         }
791         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
792         $SQL_syn .= ") VALUES ("; 
793         foreach($entr as $key2 => $val2){
794           $SQL_syn .= "'".$val2."',";
795         }
796         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
797         $SQL_syn .=");\n";
799         $SQL_query_array[] =$SQL_syn;
800         $SQL_syn ="";
801       }
803       // Perform queries ...
804       if($this->goFonHardware != "automatic"){
805         foreach($SQL_query_array as $query){
806           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
807           if(!@mysql_query($query,$new_connection)){
808             print_red(_("Error while performing query:")." ".mysql_error());
809             return false;
810           }
811         }
812       }
813     }
814     @mysql_close($new_connection);
815     return true;
816   }
819   /* Return asterisk contexts 
820    * Additionaly read contexts from file.
821    */
822   function get_asterisk_contexts()
823   {
824     $contexts = array();
825     $contexts[] = "default";
826     $contexts[] = "parkedcalls";
827     $contexts[] = "from-sip";
828     $contexts[] = "from-capi";
829     $file = "/etc/gosa/asterisk_contexts.conf";
830     if(file_exists($file) && is_readable($file)){
831       foreach(file($file) as $context){
832         $contexts[] = trim($context);
833       }
834     }
835     array_unique($contexts);
836     return($contexts);
837   }
840   function execute()
841   {
842     /* Call parent execute */
843     plugin::execute();
845     $display = "";
847     if(empty($this->macro)&&(!empty($this->goFonMacro))){
849       /* Go through already saved values, for a parameter */
850       $tmp = split("!",$this->goFonMacro);
852       /* it is possible that nothing has been saved yet */
853       if(is_array($tmp)){
855         /* First value is the macroname */
856         $this->macro = $tmp[0];
858         /* Macroname saved, delete that index */
859         unset($tmp[0]);
861         /* Check if macro has been removed */
862         if(!isset($this->macroarray[$this->macro])){
863           $this->macrostillavailable = false;
864         }else{
865           $this->macrostillavailable = true;
866         }
868         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
869         foreach($tmp as $var){
871           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
872           $varar = split("#",$var);
874           /* Only insert if the parameter still exists */
875           if(isset($this->macroarray[$this->macro][$varar[0]])){
876             /* Assign value */
877             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
878           }
879         }
880       }
881     }
882     
883     /* Do we represent a valid account? */
884     if (!$this->is_account && $this->parent == NULL){
885       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
886         _("This account has no phone extensions.")."</b>";
887       $display.= back_to_main();
888       return ($display);
889     }
891     /* Do we need to flip is_account state? */
892     if (isset($_POST['modify_state'])){
894       /* Onyl change account state if allowed */
895       if($this->is_account && $this->acl == "#all#"){
896         $this->is_account= !$this->is_account;
897       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
898         $this->is_account= !$this->is_account;
899       }
900     }
902     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
903     if(empty($this->macro)){
904       $this->macro ="none";
905     }
907     /* Prepare templating */
908     $smarty= get_smarty();
910     /* tell user that the selected plugin is no longer available */
911     if((!$this->macrostillavailable)&&($this->macro!="none")){
912       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
913     }
915     /* Assign contexts */
916     $smarty->assign("contexts",$this->get_asterisk_contexts());
917     $smarty->assign("context" ,$this->context);
918     $smarty->assign("voice_context" ,$this->voice_context);
919     $smarty->assign("goFonContextACL", chkacl($this->acl,"context"));
921     /* Assing macroselectbox values  */
922     $smarty->assign("macros",$this->macros);   
923     $smarty->assign("macro", $this->macro);   
925     /* check if there is a FON server created */
926     if(!count($this->goFonHomeServer)){
927       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."));
928     }
930     /* Create html parameter table for selected macro parameters 
931      *  skip if no parameters given 
932      */
933     if(!isset($this->macroarray[$this->macro])){
934       $macrotab="";
935     }else{
937       $macrotab ="<table summary=\""._("Parameter")."\">";
938       /* for every single parameter-> display textfile,combo, or true false switch*/
940       foreach($this->phoneNumbers as $phonenum){
941         $tmp[] = $phonenum;
942       }
943     
944       if($this->macro != $this->lastmacro){
945         /* Go through all params */
946         foreach($this->macroarray[$this->macro] as $key => $paras){
948           $string = $paras['default'];
950           $string=preg_replace("/%uid/i",$this->uid,$string);
952           if(isset($this->cn)){
953             $string=preg_replace("/%cn/i",$this->cn,$string);
954           }
956           for($i = 0 ; $i < 10; $i++){
957             if(isset($tmp[$i])){
958               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
959             }
960           }
961           if(isset($tmp[0])){
962             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
963           }
964           $this->macroarray[$this->macro][$key]['choosen']=$string;
965         }
966       }
968       foreach($this->macroarray[$this->macro] as $paras){
970         /* get al vars */
971         $var        = $paras['var'];           
972         $name       = $paras['name'];           
973         $default    = $paras['default'];
974         $type       = $paras['type'];
975         $choosen    = $paras['choosen'] ; 
976         $str        = $default;
978         /* in case of a combo box display a combobox with selected attr */
979         $macrotab.= "<tr>";
980         switch ($type){
982           case "combo":
983             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
984           foreach(split(":",$default) as $choice){
985             if($choosen==$choice){
986               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
987             }else{
988               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
989             }
990           }
991           $str.="</select>";
992           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
993           break;
995           case "bool":
996             if(!$choosen){
997               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
998             }else{
999               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
1000             }
1001           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
1002           break;
1004           case "string":
1005             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
1006           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1007           break;
1009         }
1010         $macrotab.= "</td></tr>";
1012       }
1013       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1014     }//is_array()
1016     /* Give smarty the table */
1017     $smarty->assign("macrotab",$macrotab);
1020     /* Do we represent a valid account? */
1021     if (!$this->is_account && $this->parent == NULL){
1022       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
1023         _("This account has no phone extensions.")."</b>";
1024       $display.= back_to_main();
1025       return($display);
1026     }
1028     $display= "";
1030     /* Show tab dialog headers */
1031     if ($this->parent != NULL){
1032       if ($this->is_account){
1033         $display= $this->show_header(_("Remove phone account"),
1034             _("This account has phone features enabled. You can disable them by clicking below."));
1035       } else {
1036         if(empty($this->uid)){
1037           $display= $this->show_header(_("Create phone account"),
1038               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
1039         }else{
1040           $display= $this->show_header(_("Create phone account"),
1041               _("This account has phone features disabled. You can enable them by clicking below."));
1042         }
1043         return ($display);
1044       }
1045     }
1047     /* Add phone number */
1048     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1049       if (is_phone_nr($_POST['phonenumber']) && strlen($_POST['phonenumber']) <=10){
1050         $number= $_POST["phonenumber"];
1051         $this->phoneNumbers[$number]= $number;
1052         $this->is_modified= TRUE;
1053       } else {
1054         print_red(_("Please enter a valid phone number! Because of the realtime extension tables, the number must be less than 11 digits."));
1055       }
1056     }
1058     /* Remove phone number */
1059     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1060       foreach ($_POST['phonenumber_list'] as $number){
1061         unset($this->phoneNumbers[$number]);
1062         $this->is_modified= TRUE;
1063       }
1064     }
1066     /* Transfer ACL's */
1067     foreach($this->attributes as $val){
1068       $smarty->assign($val."ACL", chkacl($this->acl,$val));
1069       if(isset($this->$val)){
1070         $smarty->assign($val,$this->$val);
1071       }else{
1072         $smarty->assign($val,"");
1073       }
1074     }
1076     /* Create home server array */
1077     $tmp = array();
1078     foreach($this->goFonHomeServers as $dn => $attrs){
1079       if(!is_numeric($dn)){
1080         $tmp[$dn] = $attrs['SERVER'];
1081       }
1082     }
1083     $smarty->assign("goFonHomeServers",$tmp);
1085     /* Fill arrays */
1086     $smarty->assign ("goFonHardware", $this->goFonHardware);
1087     if (!count($this->phoneNumbers)){
1088       $smarty->assign ("phoneNumbers", array());
1089     } else {
1090       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1091     }
1092     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
1093       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
1094     foreach ($this->hardware_list as $cn => $description){
1095       if ($cn == $this->goFonHardware){
1096         $selected= "selected";
1097       } else {
1098         $selected= "";
1099       }
1100       if (isset($this->used_hardware[$cn])){
1101         $color= "style=\"color:#A0A0A0\"";
1102       } else {
1103         $color= "";
1104       }
1105       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1106     }
1107     $hl.= "</select>\n";
1108     $smarty->assign ("hardware_list", $hl);
1110     /* Show main page */
1111     $this->lastmacro = $this->macro;
1112     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1113     return($display);
1114   }
1117   function save_object()
1118   {
1119     if (isset($_POST["phoneTab"])){
1120     
1121       plugin::save_object();
1123       /* Save checkbox */
1124       if (isset($_POST['fon_to_mail'])){
1125         $tmp= "[M]";
1126       } else {
1127         $tmp= "[]";
1128       }
1129       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
1130         if ($this->goFonDeliveryMode != $tmp){
1131           $this->is_modified= TRUE;
1132         }
1133         $this->goFonDeliveryMode= $tmp;
1134       }
1136       /* Every macro in the select box are available */
1137       if((isset($_POST['macro']))){
1138         $this->macrostillavailable=true;
1139       }
1141       /* Save context */
1142       if(isset($_POST['context'])){
1143         if($this->context != $_POST['context']){
1144           $this->is_modified= TRUE;
1145         }
1146         $this->context= $_POST['context'];
1147       }
1149       /* Save voice_context */
1150       if(isset($_POST['voice_context'])){
1151         if($this->voice_context != $_POST['voice_context']){
1152           $this->is_modified= TRUE;
1153         }
1154         $this->voice_context= $_POST['voice_context'];
1155       }
1157       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1158         $this->is_modified =true;
1159       }
1161       if(is_array($this->phoneNumbers)){
1162         foreach($this->phoneNumbers as $telenumms) {
1163           $nummsinorder[]=$telenumms; 
1164         }
1165       }else{
1166         $nummsinorder=array("");
1167       }
1169       /* get all Postvars */
1170       if(isset($this->macroarray[$this->macro])){
1171  
1172         foreach($this->macroarray[$this->macro] as $key => $paras){
1174           $old_macro_settings = $this->macroarray[$this->macro][$key];
1175           $backup = $this->macroarray[$this->macro][$key];  
1177           if(isset($_POST[$paras['var']])){
1178             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1179           }
1181           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
1182              We need this code below to read and save checkboxes correct
1183            */
1185           if(isset($_POST['post_success'])){
1186             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1187               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1188                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1189               }else{
1190                 $this->macroarray[$this->macro][$key]['choosen']=false;
1191               }
1192             }
1193           }
1194           if(array_differs($old_macro_settings,$this->macroarray[$this->macro][$key])){
1195             $this->is_modified = TRUE;
1196           }
1197           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1198             $this->is_modified = TRUE;
1199           }
1200         }
1201       }
1202     }
1203   }
1205   function check()
1206   {
1207     /* Call common method to give check the hook */
1208     $message= plugin::check();
1210     if(!count($this->goFonHomeServers)){
1211       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1212     }
1214     if(empty($this->goFonHomeServer)){
1215       $message[] = _("Please select a valid goFonHomeServer.");
1216     }
1218     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1219       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1220     }else{
1221       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1222         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1223       }
1224     }
1226     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1227       $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1228     }
1230     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1231       if(!$this->generate_mysql_entension_entries()){
1232         $message[] = $this->generate_error;
1233       }
1234     }
1236     /* We need at least one phone number */
1237     if (count($this->phoneNumbers) == 0){
1238       $message[]= sprintf(_("You need to specify at least one phone number!"));
1239     }
1241     /* check for ! in any parameter setting*/
1242     if(isset($this->macroarray[$this->macro])){
1243       foreach($this->macroarray[$this->macro] as $val){
1244         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1245           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1246         }
1247       }
1248     }
1249     return ($message);
1250   }
1254   function save()
1255   {
1256     plugin::save();
1258     /* Force saving macro again 
1259      * This ensures that 
1260      *  - the macro is available on the destiantion server.
1261      *  - the macro saved is up to date on the destination server.
1262      */
1263     if(!empty($this->macro) && $this->macro != "none")  {
1264       $macro_tab = new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro);
1265       $macro_tab -> save();
1266     }
1268     /* Save arrays */
1269     $tmp_numbers = array();
1270     foreach ($this->phoneNumbers as $number){
1271       $tmp_numbers[] = $number;
1272     }
1274     /* Save settings, or remove goFonMacro attribute*/
1275     if($this->macro!="none"){    
1276       $this->attrs['goFonMacro']=$this->macro;
1277       if(isset($this->macroarray[$this->macro])){
1278         foreach($this->macroarray[$this->macro] as $paras)  {
1279           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1280         }
1281       }
1282     }else{
1283       $this->attrs['goFonMacro']=array();
1284     }
1285     unset($this->attrs['macro'])  ;
1287     $this->attrs['goFonForwarding']=array();
1289     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1290       $str = $this->generate_mysql_entension_entries(true);
1291       if(empty($str)){
1292         print_red($str);
1293       }
1294     }
1296     if($this->attrs['goFonMacro']==""){
1297       $this->attrs['goFonMacro']=array();
1298     }
1300     unset($this->attrs['cn']);
1302     /* Write back to ldap */
1303     $ldap= $this->config->get_ldap_link();
1304     $ldap->cd($this->dn);
1305     $this->cleanup();
1306     
1307     /* Force saving numbers, else it will be overwriten by user account. */
1308     $this->attrs['telephoneNumber'] =$tmp_numbers;
1309     $ldap->modify ($this->attrs); 
1311     show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
1313     /* Optionally execute a command after we're done */
1315     if ($this->initially_was_account == $this->is_account){
1316       if ($this->is_modified){
1317         $this->handle_post_events("modify",array("uid" => $this->uid));
1318       }
1319     } else {
1320       $this->handle_post_events("add",array("uid" => $this->uid));
1321     }
1323   }
1326   function adapt_from_template($dn)
1327   {
1328     plugin::adapt_from_template($dn);
1330     /* Assemble phone numbers */
1331     if (isset($this->attrs['telephoneNumber'])){
1332       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1333         $number= $this->attrs['telephoneNumber'][$i];
1334         $this->phoneNumbers[$number]= $number;
1335       }
1336     }
1337   }
1340   function remove_from_parent()
1341   {
1342     if(!$this->initially_was_account) return;
1344     foreach($this->attributes as $key=>$val){
1345       if(in_array($val,array("uid","cn"))){
1346         unset($this->attributes[$key]);
1347         unset($this->$val);
1348       }
1349     }
1350     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1352       // Get Configuration for initial Mysql database Server
1353       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1354       $s_parameter  ="";
1356       // Connect to DB server
1357       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1359       // Check if we are  connected correctly
1360       if(!$r_con){
1361         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1362                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1363         gosa_log(@mysql_error());
1364         return false;
1365       }
1367       // Select database for Extensions
1368       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1370       // Test if we have the database selected correctly
1371       if(!$db){
1372         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1373         gosa_log(@mysql_error());
1374         return false;
1375       }
1377       $SQL="";
1379       /* If deletion starts from userslist, cn uid are not set */
1380       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1381         $this->uid = $this->parent->by_object['user']->uid;
1382       }
1384       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1385         $this->cn  = $this->parent->by_object['user']->cn;
1386       }
1388       $first_num = false;
1389       // Delete old entries
1390       foreach($this->a_old_telenums as $s_telenums){
1391         if(!$first_num){
1392           $first_num = $s_telenums;
1393         }
1394         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1395       }
1397       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1398       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1399       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1401       foreach($SQL as $query){
1402         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1403         if(!@mysql_query($query,$r_con)){
1404           print_red(_("Stop".mysql_error()));
1405           return false;
1406         }
1407       }
1408     }else{
1409       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1410       return false;
1411     }
1413     /* unset macro attr, it will cause an error */
1414     $tmp = array_flip($this->attributes);
1415     unset($tmp['macro']);
1416     $this->attributes=array_flip($tmp);
1418     /* Cancel if there's nothing to do here */
1419     if (!$this->initially_was_account){
1420       return;
1421     }
1423     plugin::remove_from_parent();
1425     /* Just keep one phone number */
1426     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1427       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1428     } else {
1429       $this->attrs['telephoneNumber']= array();
1430     }
1433     $ldap= $this->config->get_ldap_link();
1434     $ldap->cd($this->config->current['BASE']);
1435     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1436     while($attr = $ldap->fetch()){
1437       if(in_array($this->dn,$attr['member'])){
1438         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1439         unset($new->by_object['ogroup']->memberList[$this->dn]);
1440         unset($new->by_object['ogroup']->member[$this->dn]);
1441         $new->save();
1442         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1443       }
1444     }
1445     $ldap->cd($this->dn);
1446     $this->cleanup();
1447     $ldap->modify ($this->attrs); 
1449     show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1451     /* Optionally execute a command after we're done */
1452     @mysql_close($r_con);
1453     $this->handle_post_events('remove',array("uid"=> $this->uid));
1454   }
1458   /* This function checks if the given phonenumbers are available or already in use*/
1459   function is_number_used()
1460   {
1461     $ldap= $this->config->get_ldap_link();
1462     $ldap->cd($this->config->current['BASE']);
1463     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1464     while($attrs = $ldap->fetch()) {
1465       unset($attrs['telephoneNumber']['count']);
1466       foreach($attrs['telephoneNumber'] as $tele){
1467         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1468         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1469         $numbers[$tele]=$attrs;
1470       }
1471     }
1473     foreach($this->phoneNumbers as $num){
1474       if(!isset($this->cn)) $this->cn = "";
1476       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1477         if(isset($numbers[$num]['uid'][0])){
1478           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1479         }else{
1480           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1481         }
1482       }
1483     }
1484   }
1487   /* Create phoneAccount part of copy & paste dialog */
1488   function getCopyDialog()
1489   { 
1490     if(!$this->is_account) return("");
1491     $smarty = get_smarty();
1492     if (!count($this->phoneNumbers)){
1493       $smarty->assign ("phoneNumbers", array(""));
1494     } else {
1495       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1496     }
1498     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1499     $smarty->assign("goFonPIN",$this->goFonPIN);
1501     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1502     $ret =array();
1503     $ret['string'] = $display;
1504     $ret['status'] = "";
1505     return($ret);
1506   }
1508   /* Save posts from copy & paste dialog dialog  */
1509   function saveCopyDialog()
1510   {
1511     if(!$this->is_account) return;
1512     $this->execute();
1513     if(isset($_POST['goFonVoicemailPIN'])) {
1514       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1515     }
1516     if(isset($_POST['goFonPIN'])){
1517       $this->goFonPIN = $_POST['goFonPIN'];
1518     }
1519   }
1522   function allow_remove()
1523   {
1524     /* Check if previously selected server is still available */
1525     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1526       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1527     }
1528   }
1531 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1532 ?>