Code

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