Code

Updated gohpone account.
[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       foreach($SQL_query_array as $query){
805         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
806         if(!@mysql_query($query,$new_connection)){
807           print_red(_("Error while performing query:")." ".mysql_error());
808           return false;
809         }
810       }
811     }
812     @mysql_close($new_connection);
813     return true;
814   }
817   /* Return asterisk contexts 
818    * Additionaly read contexts from file.
819    */
820   function get_asterisk_contexts()
821   {
822     $contexts = array();
823     $contexts[] = "default";
824     $contexts[] = "parkedcalls";
825     $contexts[] = "from-sip";
826     $contexts[] = "from-capi";
827     $file = "/etc/gosa/asterisk_contexts.conf";
828     if(file_exists($file) && is_readable($file)){
829       foreach(file($file) as $context){
830         $contexts[] = trim($context);
831       }
832     }
833     array_unique($contexts);
834     return($contexts);
835   }
838   function execute()
839   {
840     /* Call parent execute */
841     plugin::execute();
843     $display = "";
845     if(empty($this->macro)&&(!empty($this->goFonMacro))){
847       /* Go through already saved values, for a parameter */
848       $tmp = split("!",$this->goFonMacro);
850       /* it is possible that nothing has been saved yet */
851       if(is_array($tmp)){
853         /* First value is the macroname */
854         $this->macro = $tmp[0];
856         /* Macroname saved, delete that index */
857         unset($tmp[0]);
859         /* Check if macro has been removed */
860         if(!isset($this->macroarray[$this->macro])){
861           $this->macrostillavailable = false;
862         }else{
863           $this->macrostillavailable = true;
864         }
866         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
867         foreach($tmp as $var){
869           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
870           $varar = split("#",$var);
872           /* Only insert if the parameter still exists */
873           if(isset($this->macroarray[$this->macro][$varar[0]])){
874             /* Assign value */
875             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
876           }
877         }
878       }
879     }
880     
881     /* Do we represent a valid account? */
882     if (!$this->is_account && $this->parent == NULL){
883       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
884         _("This account has no phone extensions.")."</b>";
885       $display.= back_to_main();
886       return ($display);
887     }
889     /* Do we need to flip is_account state? */
890     if (isset($_POST['modify_state'])){
892       /* Onyl change account state if allowed */
893       if($this->is_account && $this->acl == "#all#"){
894         $this->is_account= !$this->is_account;
895       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
896         $this->is_account= !$this->is_account;
897       }
898     }
900     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
901     if(empty($this->macro)){
902       $this->macro ="none";
903     }
905     /* Prepare templating */
906     $smarty= get_smarty();
908     /* tell user that the selected plugin is no longer available */
909     if((!$this->macrostillavailable)&&($this->macro!="none")){
910       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
911     }
913     /* Assign contexts */
914     $smarty->assign("contexts",$this->get_asterisk_contexts());
915     $smarty->assign("context" ,$this->context);
916     $smarty->assign("voice_context" ,$this->voice_context);
917     $smarty->assign("goFonContextACL", chkacl($this->acl,"context"));
919     /* Assing macroselectbox values  */
920     $smarty->assign("macros",$this->macros);   
921     $smarty->assign("macro", $this->macro);   
923     /* check if there is a FON server created */
924     if(!count($this->goFonHomeServer)){
925       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."));
926     }
928     /* Create html parameter table for selected macro parameters 
929      *  skip if no parameters given 
930      */
931     if(!isset($this->macroarray[$this->macro])){
932       $macrotab="";
933     }else{
935       $macrotab ="<table summary=\""._("Parameter")."\">";
936       /* for every single parameter-> display textfile,combo, or true false switch*/
938       foreach($this->phoneNumbers as $phonenum){
939         $tmp[] = $phonenum;
940       }
941     
942       if($this->macro != $this->lastmacro){
943         /* Go through all params */
944         foreach($this->macroarray[$this->macro] as $key => $paras){
946           $string = $paras['default'];
948           $string=preg_replace("/%uid/i",$this->uid,$string);
950           if(isset($this->cn)){
951             $string=preg_replace("/%cn/i",$this->cn,$string);
952           }
954           for($i = 0 ; $i < 10; $i++){
955             if(isset($tmp[$i])){
956               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
957             }
958           }
959           if(isset($tmp[0])){
960             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
961           }
962           $this->macroarray[$this->macro][$key]['choosen']=$string;
963         }
964       }
966       foreach($this->macroarray[$this->macro] as $paras){
968         /* get al vars */
969         $var        = $paras['var'];           
970         $name       = $paras['name'];           
971         $default    = $paras['default'];
972         $type       = $paras['type'];
973         $choosen    = $paras['choosen'] ; 
974         $str        = $default;
976         /* in case of a combo box display a combobox with selected attr */
977         $macrotab.= "<tr>";
978         switch ($type){
980           case "combo":
981             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
982           foreach(split(":",$default) as $choice){
983             if($choosen==$choice){
984               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
985             }else{
986               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
987             }
988           }
989           $str.="</select>";
990           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
991           break;
993           case "bool":
994             if(!$choosen){
995               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
996             }else{
997               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
998             }
999           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
1000           break;
1002           case "string":
1003             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
1004           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1005           break;
1007         }
1008         $macrotab.= "</td></tr>";
1010       }
1011       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1012     }//is_array()
1014     /* Give smarty the table */
1015     $smarty->assign("macrotab",$macrotab);
1018     /* Do we represent a valid account? */
1019     if (!$this->is_account && $this->parent == NULL){
1020       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
1021         _("This account has no phone extensions.")."</b>";
1022       $display.= back_to_main();
1023       return($display);
1024     }
1026     $display= "";
1028     /* Show tab dialog headers */
1029     if ($this->parent != NULL){
1030       if ($this->is_account){
1031         $display= $this->show_header(_("Remove phone account"),
1032             _("This account has phone features enabled. You can disable them by clicking below."));
1033       } else {
1034         if(empty($this->uid)){
1035           $display= $this->show_header(_("Create phone account"),
1036               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
1037         }else{
1038           $display= $this->show_header(_("Create phone account"),
1039               _("This account has phone features disabled. You can enable them by clicking below."));
1040         }
1041         return ($display);
1042       }
1043     }
1045     /* Add phone number */
1046     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1047       if (is_phone_nr($_POST['phonenumber']) && strlen($_POST['phonenumber']) <=10){
1048         $number= $_POST["phonenumber"];
1049         $this->phoneNumbers[$number]= $number;
1050         $this->is_modified= TRUE;
1051       } else {
1052         print_red(_("Please enter a valid phone number! Because of the realtime extension tables, the number must be less than 11 digits."));
1053       }
1054     }
1056     /* Remove phone number */
1057     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1058       foreach ($_POST['phonenumber_list'] as $number){
1059         unset($this->phoneNumbers[$number]);
1060         $this->is_modified= TRUE;
1061       }
1062     }
1064     /* Transfer ACL's */
1065     foreach($this->attributes as $val){
1066       $smarty->assign($val."ACL", chkacl($this->acl,$val));
1067       if(isset($this->$val)){
1068         $smarty->assign($val,$this->$val);
1069       }else{
1070         $smarty->assign($val,"");
1071       }
1072     }
1074     /* Create home server array */
1075     $tmp = array();
1076     foreach($this->goFonHomeServers as $dn => $attrs){
1077       if(!is_numeric($dn)){
1078         $tmp[$dn] = $attrs['SERVER'];
1079       }
1080     }
1081     $smarty->assign("goFonHomeServers",$tmp);
1083     /* Fill arrays */
1084     $smarty->assign ("goFonHardware", $this->goFonHardware);
1085     if (!count($this->phoneNumbers)){
1086       $smarty->assign ("phoneNumbers", array());
1087     } else {
1088       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1089     }
1090     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
1091       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
1092     foreach ($this->hardware_list as $cn => $description){
1093       if ($cn == $this->goFonHardware){
1094         $selected= "selected";
1095       } else {
1096         $selected= "";
1097       }
1098       if (isset($this->used_hardware[$cn])){
1099         $color= "style=\"color:#A0A0A0\"";
1100       } else {
1101         $color= "";
1102       }
1103       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1104     }
1105     $hl.= "</select>\n";
1106     $smarty->assign ("hardware_list", $hl);
1108     /* Show main page */
1109     $this->lastmacro = $this->macro;
1110     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1111     return($display);
1112   }
1115   function save_object()
1116   {
1117     if (isset($_POST["phoneTab"])){
1118     
1119       plugin::save_object();
1121       /* Save checkbox */
1122       if (isset($_POST['fon_to_mail'])){
1123         $tmp= "[M]";
1124       } else {
1125         $tmp= "[]";
1126       }
1127       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
1128         if ($this->goFonDeliveryMode != $tmp){
1129           $this->is_modified= TRUE;
1130         }
1131         $this->goFonDeliveryMode= $tmp;
1132       }
1134       /* Every macro in the select box are available */
1135       if((isset($_POST['macro']))){
1136         $this->macrostillavailable=true;
1137       }
1139       /* Save context */
1140       if(isset($_POST['context'])){
1141         if($this->context != $_POST['context']){
1142           $this->is_modified= TRUE;
1143         }
1144         $this->context= $_POST['context'];
1145       }
1147       /* Save voice_context */
1148       if(isset($_POST['voice_context'])){
1149         if($this->voice_context != $_POST['voice_context']){
1150           $this->is_modified= TRUE;
1151         }
1152         $this->voice_context= $_POST['voice_context'];
1153       }
1155       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1156         $this->is_modified =true;
1157       }
1159       if(is_array($this->phoneNumbers)){
1160         foreach($this->phoneNumbers as $telenumms) {
1161           $nummsinorder[]=$telenumms; 
1162         }
1163       }else{
1164         $nummsinorder=array("");
1165       }
1167       /* get all Postvars */
1168       if(isset($this->macroarray[$this->macro])){
1169  
1170         foreach($this->macroarray[$this->macro] as $key => $paras){
1172           $old_macro_settings = $this->macroarray[$this->macro][$key];
1173           $backup = $this->macroarray[$this->macro][$key];  
1175           if(isset($_POST[$paras['var']])){
1176             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1177           }
1179           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
1180              We need this code below to read and save checkboxes correct
1181            */
1183           if(isset($_POST['post_success'])){
1184             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1185               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1186                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1187               }else{
1188                 $this->macroarray[$this->macro][$key]['choosen']=false;
1189               }
1190             }
1191           }
1192           if(array_differs($old_macro_settings,$this->macroarray[$this->macro][$key])){
1193             $this->is_modified = TRUE;
1194           }
1195           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1196             $this->is_modified = TRUE;
1197           }
1198         }
1199       }
1200     }
1201   }
1203   function check()
1204   {
1205     /* Call common method to give check the hook */
1206     $message= plugin::check();
1208     if(!count($this->goFonHomeServers)){
1209       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1210     }
1212     if(empty($this->goFonHomeServer)){
1213       $message[] = _("Please select a valid goFonHomeServer.");
1214     }
1216     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1217       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1218     }else{
1219       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1220         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1221       }
1222     }
1224     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1225       $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1226     }
1228     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1229       if(!$this->generate_mysql_entension_entries()){
1230         $message[] = $this->generate_error;
1231       }
1232     }
1234     /* We need at least one phone number */
1235     if (count($this->phoneNumbers) == 0){
1236       $message[]= sprintf(_("You need to specify at least one phone number!"));
1237     }
1239     /* check for ! in any parameter setting*/
1240     if(isset($this->macroarray[$this->macro])){
1241       foreach($this->macroarray[$this->macro] as $val){
1242         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1243           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1244         }
1245       }
1246     }
1247     return ($message);
1248   }
1252   function save()
1253   {
1254     plugin::save();
1256     /* Force saving macro again 
1257      * This ensures that 
1258      *  - the macro is available on the destiantion server.
1259      *  - the macro saved is up to date on the destination server.
1260      */
1261     if(!empty($this->macro) && $this->macro != "none")  {
1262       $macro_tab = new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro);
1263       $macro_tab -> save();
1264     }
1266     /* Save arrays */
1267     $tmp_numbers = array();
1268     foreach ($this->phoneNumbers as $number){
1269       $tmp_numbers[] = $number;
1270     }
1272     /* Save settings, or remove goFonMacro attribute*/
1273     if($this->macro!="none"){    
1274       $this->attrs['goFonMacro']=$this->macro;
1275       if(isset($this->macroarray[$this->macro])){
1276         foreach($this->macroarray[$this->macro] as $paras)  {
1277           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1278         }
1279       }
1280     }else{
1281       $this->attrs['goFonMacro']=array();
1282     }
1283     unset($this->attrs['macro'])  ;
1285     $this->attrs['goFonForwarding']=array();
1287     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1288       $str = $this->generate_mysql_entension_entries(true);
1289       if(empty($str)){
1290         print_red($str);
1291       }
1292     }
1294     if($this->attrs['goFonMacro']==""){
1295       $this->attrs['goFonMacro']=array();
1296     }
1298     unset($this->attrs['cn']);
1300     /* Write back to ldap */
1301     $ldap= $this->config->get_ldap_link();
1302     $ldap->cd($this->dn);
1303     $this->cleanup();
1304     
1305     /* Force saving numbers, else it will be overwriten by user account. */
1306     $this->attrs['telephoneNumber'] =$tmp_numbers;
1307     $ldap->modify ($this->attrs); 
1309     show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
1311     /* Optionally execute a command after we're done */
1313     if ($this->initially_was_account == $this->is_account){
1314       if ($this->is_modified){
1315         $this->handle_post_events("modify",array("uid" => $this->uid));
1316       }
1317     } else {
1318       $this->handle_post_events("add",array("uid" => $this->uid));
1319     }
1321   }
1324   function adapt_from_template($dn)
1325   {
1326     plugin::adapt_from_template($dn);
1328     /* Assemble phone numbers */
1329     if (isset($this->attrs['telephoneNumber'])){
1330       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1331         $number= $this->attrs['telephoneNumber'][$i];
1332         $this->phoneNumbers[$number]= $number;
1333       }
1334     }
1335   }
1338   function remove_from_parent()
1339   {
1340     if(!$this->initially_was_account) return;
1342     foreach($this->attributes as $key=>$val){
1343       if(in_array($val,array("uid","cn"))){
1344         unset($this->attributes[$key]);
1345         unset($this->$val);
1346       }
1347     }
1348     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1350       // Get Configuration for initial Mysql database Server
1351       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1352       $s_parameter  ="";
1354       // Connect to DB server
1355       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1357       // Check if we are  connected correctly
1358       if(!$r_con){
1359         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1360                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1361         gosa_log(@mysql_error());
1362         return false;
1363       }
1365       // Select database for Extensions
1366       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1368       // Test if we have the database selected correctly
1369       if(!$db){
1370         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1371         gosa_log(@mysql_error());
1372         return false;
1373       }
1375       $SQL="";
1377       /* If deletion starts from userslist, cn uid are not set */
1378       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1379         $this->uid = $this->parent->by_object['user']->uid;
1380       }
1382       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1383         $this->cn  = $this->parent->by_object['user']->cn;
1384       }
1386       $first_num = false;
1387       // Delete old entries
1388       foreach($this->a_old_telenums as $s_telenums){
1389         if(!$first_num){
1390           $first_num = $s_telenums;
1391         }
1392         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1393       }
1395       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1396       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1397       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1399       foreach($SQL as $query){
1400         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1401         if(!@mysql_query($query,$r_con)){
1402           print_red(_("Stop".mysql_error()));
1403           return false;
1404         }
1405       }
1406     }else{
1407       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1408       return false;
1409     }
1411     /* unset macro attr, it will cause an error */
1412     $tmp = array_flip($this->attributes);
1413     unset($tmp['macro']);
1414     $this->attributes=array_flip($tmp);
1416     /* Cancel if there's nothing to do here */
1417     if (!$this->initially_was_account){
1418       return;
1419     }
1421     plugin::remove_from_parent();
1423     /* Just keep one phone number */
1424     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1425       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1426     } else {
1427       $this->attrs['telephoneNumber']= array();
1428     }
1431     $ldap= $this->config->get_ldap_link();
1432     $ldap->cd($this->config->current['BASE']);
1433     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1434     while($attr = $ldap->fetch()){
1435       if(in_array($this->dn,$attr['member'])){
1436         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1437         unset($new->by_object['ogroup']->memberList[$this->dn]);
1438         unset($new->by_object['ogroup']->member[$this->dn]);
1439         $new->save();
1440         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1441       }
1442     }
1443     $ldap->cd($this->dn);
1444     $this->cleanup();
1445     $ldap->modify ($this->attrs); 
1447     show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1449     /* Optionally execute a command after we're done */
1450     @mysql_close($r_con);
1451     $this->handle_post_events('remove',array("uid"=> $this->uid));
1452   }
1456   /* This function checks if the given phonenumbers are available or already in use*/
1457   function is_number_used()
1458   {
1459     $ldap= $this->config->get_ldap_link();
1460     $ldap->cd($this->config->current['BASE']);
1461     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1462     while($attrs = $ldap->fetch()) {
1463       unset($attrs['telephoneNumber']['count']);
1464       foreach($attrs['telephoneNumber'] as $tele){
1465         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1466         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1467         $numbers[$tele]=$attrs;
1468       }
1469     }
1471     foreach($this->phoneNumbers as $num){
1472       if(!isset($this->cn)) $this->cn = "";
1474       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1475         if(isset($numbers[$num]['uid'][0])){
1476           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1477         }else{
1478           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1479         }
1480       }
1481     }
1482   }
1485   /* Create phoneAccount part of copy & paste dialog */
1486   function getCopyDialog()
1487   { 
1488     if(!$this->is_account) return("");
1489     $smarty = get_smarty();
1490     if (!count($this->phoneNumbers)){
1491       $smarty->assign ("phoneNumbers", array(""));
1492     } else {
1493       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1494     }
1496     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1497     $smarty->assign("goFonPIN",$this->goFonPIN);
1499     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1500     $ret =array();
1501     $ret['string'] = $display;
1502     $ret['status'] = "";
1503     return($ret);
1504   }
1506   /* Save posts from copy & paste dialog dialog  */
1507   function saveCopyDialog()
1508   {
1509     if(!$this->is_account) return;
1510     $this->execute();
1511     if(isset($_POST['goFonVoicemailPIN'])) {
1512       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1513     }
1514     if(isset($_POST['goFonPIN'])){
1515       $this->goFonPIN = $_POST['goFonPIN'];
1516     }
1517   }
1520   function allow_remove()
1521   {
1522     /* Check if previously selected server is still available */
1523     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1524       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1525     }
1526   }
1529 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1530 ?>