Code

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