Code

Fixed Phone usage detection - is 100 time faster now.
[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         $vp = mysql_fetch_row(mysql_query("SELECT ".$cur_cfg['VOICE_TABLE'].".password FROM  ".$cur_cfg['VOICE_TABLE'].", ".$cur_cfg['SIP_TABLE']."  WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'"));
262         if((isset($vp[0]))&&(!empty($vp[0]))){
263           $this->goFonPINVoice = $vp[0];
264         }
265       }
266     }
267     $this->lastmacro=$this->macro;
269     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
270       @mysql_close($r_con) ;
271     }
272   }
275   /* This function generates the Database entries. 
276    * The Parameter 'save' could be true or false.
277    *  false - means only testing no database transactions.
278    *  true  - write database entries.
279    *
280    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
281    * 
282    * If the phone hardware is 'automatic' the table entries will only be removed
283    *  and not added. 
284    */
285   function generate_mysql_entension_entries($save = false)
286   {
287     /* Check if there is at least one server available 
288      * If not, return and tell the user that saving failed 
289      */
290     if(!count($this->goFonHomeServers)){
291       if($save){
292         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."));
293       }
294       return(true);
295     }
297     /* Check if Mysql extension is available */
298     if(!is_callable("mysql_pconnect")){
299       if($save)
300       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
301       return(true);
302     }
303  
304     /********************** 
305      * Attribute Initialisation
306      **********************/
308     $old_connection = false;
310     // Get Configuration for Mysql database Server
311     $s_parameter    = "";                                           // Contains paramter for selected Macro 
312     $r_con          = false;                                        // DB connection
313     $r_db           = false;                                        // Selected DB
314     $r_res          = false;                                        // Result resource
315     $a_ldap_attrs   = array();                                      //  
317     $s_ip           = NULL;                   // Contains ip for Sip entry
318     $s_host         = NULL;                   // Contains host for Sip entry
319     $s_qualify      = "yes";                  // Qualify entry
320     $s_pin          = NULL;                   // Entry for secret
321     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
323     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
324     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
325     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
327     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
328     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
330     $s_sip_key      = "";     // Key for SIP entry index      
331     $s_sip_val      = "";     // Value for SIP entry index      
333     $b_first_deleted= false;  // Only delete first entry, 
334     $s_telenums     = "";     // for each value variable
336     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
338     /* Prepare some basic attributes */
339     foreach($this->a_old_telenums as $tele){
340       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
341     }
342     foreach($this->phoneNumbers as $tele){
343       $newnums[]= preg_replace("/[^0-9]/","",$tele);
344     }
346     /* If deletion starts from userslist, cn uid are not set */
347     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
348       $this->uid = $this->parent->by_object['user']->uid;
349     }
350     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
351       $this->cn  = $this->parent->by_object['user']->cn;
352     }
353     /* Create voicemail entry 
354      */
355     if((!isset($this->cn))||(empty($this->cn))){
356       $CNname= $this->uid;
357     }else{
358       $CNname= $this->cn;
359     }
361     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
362       $s_mail = $this->parent->by_object['mailAccount']->mail;
363     }else{
364       $s_mail = "";
365     }
366     /* Get phonehardware to setup sip entry  */
367     $ldap         = $this->config->get_ldap_link();
368     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
369     $a_ldap_attrs = $ldap->fetch();
371     /* Check selected phone hardware, is a default IP set? */
372     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
373       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
374       $s_host     = $s_ip;
375     }else{
376       $s_ip       = NULL;
377       $s_host     = "dynamic";
378     }
380     // Attribute GoFonQualify set ?
381     if(isset($a_ldap_attrs['goFonQualify'])){
382       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
383     }
385     // Attribute GoFonPIN set ?
386     if(isset($this->goFonPIN)){
387       $s_pin      = $this->goFonPIN;
388     }
390     // Attribute GoFonType set ?
391     if(isset($a_ldap_attrs['goFonType'])){
392       $s_type = $a_ldap_attrs['goFonType'][0];
393     }
395     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
396       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
397     }else{
398       $sip_data_array['dtmfmode']     ="rfc2833";
399     }
401     /* Check if phone number is used */
402     if($this->is_number_used()){
403       $this->generate_error = $this->is_number_used(); 
404       return false;
405     }
409     /********************** 
410      * Check Server Connection Information
411      **********************/
412  
413     /* Create Mysql handle for the current goFonHomeServer, if possible  
414      * Get configuration to old asterisk home server 
415      */ 
416     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
417     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
418     if(!$new_connection){
419       $this->generate_error = sprintf(
420           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
421           $a_New['SERVER'],$a_New['LOGIN']);
422       gosa_log(@mysql_error($new_connection));
423       return false;
424     }
425     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
426     if(!$new_database){
427       $this->generate_error = sprintf(
428           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
429           $a_New['DB'],$a_New['SERVER']);
430       gosa_log( @mysql_error($new_connection));
431       return false;
432     }
434     /* If the home server has changed, we must remove entries from old 
435      *  server and add new entries in new server.  
436      */
437     if($this->init_HomeServer != $this->goFonHomeServer){
438     
439       /* Get configuration to old asterisk home server */ 
440       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
441  
442       /* Create connection to the database that contains the old entry. 
443        */
444       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
445       if(!$old_connection){
446         $this->generate_error = sprintf(
447             _("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."),
448             $a_Remove['SERVER'],$a_Remove['LOGIN']);
449         gosa_log(@mysql_error($old_connection));
450         return false;
451       }
452       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
453       if(!$old_database){
454         $this->generate_error = sprintf(
455             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
456             $a_Remove['DB'],$a_Remove['SERVER']);
457         gosa_log(@mysql_error($old_connection));
458         return false;
459       }
460     }
462     /* Save means that we must save changes, not only test  */
463     if($save == true){
464     
465       /********************** 
466        * Remove entries from old home server 
467        **********************/
469       /* Check if there is an old entry 
470        * If there is en old entry, get callerid and remove voicemail and extensions too 
471        */
472       if($old_connection){
473         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
474         $rid    = mysql_query($query,$old_connection);
476         /* Old entry found, remove it */
477         $query_a = array();
478         if(mysql_affected_rows($old_connection)){
479           $result = mysql_fetch_assoc($rid);
480           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
481           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
482           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
483           foreach($oldnums as $s_telenums) {
484             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
485           }
487           foreach($query_a as $qry){
488             if(!mysql_query($qry,$old_connection)){
489               echo $qry;
490               echo mysql_error($old_connection);
491             } 
492           }
493         }
494       }
496       /********************** 
497        * Update / Insert sip_users entry  
498        **********************/
500       /* Set the first given phone number as callerid */
501       reset($newnums);        
502       $i_new_key = key($newnums);
503       $sip_data_array['callerid']  =$newnums[$i_new_key];
504       $sip_data_array['mailbox']   =$newnums[$i_new_key];
506       /* Check if there is already an entry in sip_users for this uid */
507       $SQL_query_array = array();
508       $rid = mysql_query("SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n",$new_connection);
509       if(mysql_affected_rows($new_connection)){
511         /********************** 
512          * Update sip_users entry 
513          **********************/
514         $result                     = mysql_fetch_assoc($rid);
515         $sip_data_array['host']         = $s_host;
516         $sip_data_array['qualify']      = $s_qualify;
517         $sip_data_array['secret']       = $this->goFonPIN;
518         $sip_data_array['type']         = $s_type ;
519         $sip_data_array['username']     = $this->uid;
520         $sip_data_array['ipaddr']       = $s_ip;
522         /* Remove not changed attributes, to avoid updating table with same values */
523         foreach($sip_data_array as $name => $value){
524           if($result[$name] == $value){
525             unset($sip_data_array[$name]);
526           }
527         }
528         /* Only update entry if there is something to uopdate */
529         if(count($sip_data_array)){
530           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
531           foreach($sip_data_array as $key => $val){
532             $query.= "".$key."='".$val."',"; 
533           } 
534           $query = preg_replace("/,$/","",$query);
535           $query.= " WHERE name='".$this->uid."';";
536           $SQL_query_array[] = $query;
537         }
538       } else {
539  
540         /********************** 
541          * Insert sip_users entry 
542          **********************/
543         //generate SIP entry
544         $sip_data_array['id']           = "";
545         $sip_data_array['name']         = $this->uid;
546         $sip_data_array['accountcode']  = NULL;          
547         $sip_data_array['amaflags']     = NULL;
548         $sip_data_array['callgroup']    = NULL;
549         $sip_data_array['canreinvite']  = "no";
550         $sip_data_array['context']      = "default";
551         $sip_data_array['defaultip']    = NULL;
552         $sip_data_array['fromuser']     = NULL;
553         $sip_data_array['fromdomain']   = NULL;
554         $sip_data_array['host']         = $s_host;
555         $sip_data_array['insecure']     = NULL;
556         $sip_data_array['language']     = NULL;
557         $sip_data_array['mailbox']      = $newnums[$i_new_key];
558         $sip_data_array['md5secret']    = NULL;
559         $sip_data_array['nat']          = "no";
560         $sip_data_array['permit']       = NULL;
561         $sip_data_array['deny']         = NULL;
562         $sip_data_array['mask']         = NULL;
563         $sip_data_array['pickupgroup']  = NULL;
564         $sip_data_array['port']         = NULL;
565         $sip_data_array['qualify']      = $s_qualify;
566         $sip_data_array['restrictcid']  = "n";
567         $sip_data_array['rtptimeout']   = NULL;
568         $sip_data_array['rtpholdtimeout']=NULL;
569         $sip_data_array['secret']       = $this->goFonPIN;
570         $sip_data_array['type']         = $s_type ;
571         $sip_data_array['username']     = $this->uid;
572         $sip_data_array['disallow']     = NULL;
573         $sip_data_array['allow']        = NULL;
574         $sip_data_array['musiconhold']  = NULL;
575         $sip_data_array['regseconds']   = NULL;
576         $sip_data_array['ipaddr']       = $s_ip;
577         $sip_data_array['regexten']     = NULL;
578         $sip_data_array['cancallforward']=NULL;
580         /* There is currently no entry for this user in the sip_users table. 
581          * We should create one i
582          */
583         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
584           if($s_sip_val == NULL) continue;
585           $s_sip_values.="'".$s_sip_val."',";
586           $s_sip_keys  .="`".$s_sip_key."`,";
587         }
588         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
589         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
591         /* Add sip entries to mysql queries */
592         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
593       }
596       /********************** 
597        * Update / Insert Voice mail entry  
598        **********************/
600       $customer_id = $newnums[$i_new_key];
602       $voice_data_array = array(
603           "customer_id" => $customer_id,
604           "mailbox"     => $customer_id,
605           "password"    => $this->goFonVoicemailPIN,
606           "fullname"    => $CNname,
607           "email"       => $s_mail);
609       /* Set pager number if available */
610       if(isset($this->parent->by_object['user']->pager)){
611         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
612       }
614       /* Check if there is already an entry in sip_users for this uid */
615       $rid = mysql_query("SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n",$new_connection);
616       if(mysql_affected_rows($new_connection)){
618         /********************** 
619          * Update Voice mail entry  
620          **********************/
621         $result = mysql_fetch_assoc($rid)  ;
623         foreach($voice_data_array as $name => $value){
624           if($result[$name] == $value){
625             unset($voice_data_array[$name]);
626           }
627         }
629         /* Only update entry if there is something to uopdate */
630         if(count($voice_data_array)){
631           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
632           foreach($voice_data_array as $key => $val){
633             $query.= "".$key."='".$val."',"; 
634           } 
635           $query = preg_replace("/,$/","",$query);
636           $query.= " WHERE customer_id='".$customer_id."';";
637           $SQL_query_array[] = $query;
638         }
639       }else{
641         /********************** 
642          * Insert Voice mail entry  
643          **********************/
644         $voice_data_array['context'] = "default";
645   
646         /* There is currently no voice mail entry for this user. 
647          * We should create one 
648          */
649         $s_voi_values = $s_voi_keys = "";
650         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
651           if($s_voi_val == NULL) continue;
652           $s_voi_values.="'".$s_voi_val."',";
653           $s_voi_keys  .="`".$s_voi_key."`,";
654         }
655         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
656         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
658         /* Add sip entries to mysql queries */
659         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
660       }
662      
663       /********************** 
664        * Remove/Insert extension entries
665        **********************/
666       
667       /* Remove old entries */
668       $query = array();
669       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
670       foreach($newnums as $s_telenums){
671         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
672       }
673       foreach($query as $qry){
674         if(!mysql_query($qry,$new_connection)){
675           echo mysql_error($new_connection);
676         } 
677       }
678  
679       /********************** 
680        * Insert extension entries
681        **********************/
682  
683       // Get selected Macro Parameter and create parameter entry 
684       if(isset($this->macroarray[$this->macro])){
685         foreach($this->macroarray[$this->macro] as $key => $val ){
686           $s_parameter .= $val['choosen']."|";
687         }
688         $s_parameter = preg_replace("/\|$/","",$s_parameter);
689       }
690      
691       $i = 0; 
692       $EXT = array();
693     
694       if(!is_numeric($this->uid)){
695         $EXT[$i]['context'] = 'GOsa';
696         $EXT[$i]['exten']   = $this->uid;
697         $EXT[$i]['priority']= 1;
698         $EXT[$i]['app']     = "Goto";
699         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
700         $i ++;
701       }
703       // Entension entries  Hint / Dial / Goto
704       foreach($newnums as $s_telenums){
706         /* Hint Entry */
707         $EXT[$i]['context'] = 'GOsa';
708         $EXT[$i]['exten']   = $s_telenums;
709         $EXT[$i]['priority']= "Hint";
710         $EXT[$i]['app']     = 'SIP/'.$this->uid;
711         $i ++;  
712         /* SetCID */
713         //$EXT[$i]['context'] = 'GOsa';
714         //$EXT[$i]['exten']   = $s_telenums;
715         //$EXT[$i]['priority']= 1;
716         //$EXT[$i]['app']     = "SetCIDName";
717         //$EXT[$i]['appdata'] = $CNname;
718         //$i ++;  
720         // If no macro is selected use Dial
721         if($this->macro!="none"){ 
722           $macroname = preg_replace("/,.*$/","",$this->macro);        
723           $macroname = preg_replace("/^.*=/","",$macroname);        
724           $s_app = "Macro";$macroname;
725           $s_par = $macroname."|".$s_parameter; 
726         }else{
727           $s_app = "Dial";
728           $s_par = 'SIP/'.$this->uid."|20|r";
729         }
731         $EXT[$i]['context'] = 'GOsa';
732         $EXT[$i]['exten']   = $s_telenums;
733         $EXT[$i]['priority']= 1;
734         $EXT[$i]['app']     = $s_app;
735         $EXT[$i]['appdata'] = $s_par;
736         $i ++;
737       }
739       // Append all these Entries 
740       foreach($EXT as $entr){
741         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
742         foreach($entr as $key2 => $val2){
743           $SQL_syn.= "`".$key2."`,";
744         }
745         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
746         $SQL_syn .= ") VALUES ("; 
747         foreach($entr as $key2 => $val2){
748           $SQL_syn .= "'".$val2."',";
749         }
750         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
751         $SQL_syn .=");\n";
753         $SQL_query_array[] =$SQL_syn;
754         $SQL_syn ="";
755       }
757       // Perform queries ...
758       if($this->goFonHardware != "automatic"){
759         foreach($SQL_query_array as $query){
760           if(!@mysql_query($query,$new_connection)){
761             print_red(_("Error while performing query:")." ".mysql_error());
762             return false;
763           }
764         }
765       }
766     }
767     @mysql_close($new_connection);
768     return true;
769   }
772   function execute()
773   {
774     /* Call parent execute */
775     plugin::execute();
777     $display = "";
779     if(empty($this->macro)&&(!empty($this->goFonMacro))){
781       /* Go through already saved values, for a parameter */
782       $tmp = split("!",$this->goFonMacro);
784       /* it is possible that nothing has been saved yet */
785       if(is_array($tmp)){
787         /* First value is the macroname */
788         $this->macro = $tmp[0];
790         /* Macroname saved, delete that index */
791         unset($tmp[0]);
793         /* Check if macro has been removed */
794         if(!isset($this->macroarray[$this->macro])){
795           $this->macrostillavailable = false;
796         }else{
797           $this->macrostillavailable = true;
798         }
800         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
801         foreach($tmp as $var){
803           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
804           $varar = split("#",$var);
806           /* Only insert if the parameter still exists */
807           if(isset($this->macroarray[$this->macro][$varar[0]])){
808             /* Assign value */
809             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
810           }
811         }
812       }
813     }
814     
815     /* Do we represent a valid account? */
816     if (!$this->is_account && $this->parent == NULL){
817       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
818         _("This account has no phone extensions.")."</b>";
819       $display.= back_to_main();
820       return ($display);
821     }
823     /* Do we need to flip is_account state? */
824     if (isset($_POST['modify_state'])){
826       /* Onyl change account state if allowed */
827       if($this->is_account && $this->acl == "#all#"){
828         $this->is_account= !$this->is_account;
829       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
830         $this->is_account= !$this->is_account;
831       }
832     }
834     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
835     if(empty($this->macro)){
836       $this->macro ="none";
837     }
839     /* Prepare templating */
840     $smarty= get_smarty();
842     /* tell user that the selected plugin is no longer available */
843     if((!$this->macrostillavailable)&&($this->macro!="none")){
844       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
845     }
847     /* Assing macroselectbox values  */
848     $smarty->assign("macros",$this->macros);   
849     $smarty->assign("macro", $this->macro);   
851     /* check if there is a FON server created */
852     if(!count($this->goFonHomeServer)){
853       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."));
854     }
856     /* Create html parameter table for selected macro parameters 
857      *  skip if no parameters given 
858      */
859     if(!isset($this->macroarray[$this->macro])){
860       $macrotab="";
861     }else{
863       $macrotab ="<table summary=\""._("Parameter")."\">";
864       /* for every single parameter-> display textfile,combo, or true false switch*/
866       foreach($this->phoneNumbers as $phonenum){
867         $tmp[] = $phonenum;
868       }
869     
870       if($this->macro != $this->lastmacro){
871         /* Go through all params */
872         foreach($this->macroarray[$this->macro] as $key => $paras){
874           $string = $paras['default'];
876           $string=preg_replace("/%uid/i",$this->uid,$string);
878           if(isset($this->cn)){
879             $string=preg_replace("/%cn/i",$this->cn,$string);
880           }
882           for($i = 0 ; $i < 10; $i++){
883             if(isset($tmp[$i])){
884               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
885             }
886           }
887           if(isset($tmp[0])){
888             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
889           }
890           $this->macroarray[$this->macro][$key]['choosen']=$string;
891         }
892       }
894       foreach($this->macroarray[$this->macro] as $paras){
896         /* get al vars */
897         $var        = $paras['var'];           
898         $name       = $paras['name'];           
899         $default    = $paras['default'];
900         $type       = $paras['type'];
901         $choosen    = $paras['choosen'] ; 
902         $str        = $default;
904         /* in case of a combo box display a combobox with selected attr */
905         $macrotab.= "<tr>";
906         switch ($type){
908           case "combo":
909             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
910           foreach(split(":",$default) as $choice){
911             if($choosen==$choice){
912               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
913             }else{
914               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
915             }
916           }
917           $str.="</select>";
918           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
919           break;
921           case "bool":
922             if(!$choosen){
923               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
924             }else{
925               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
926             }
927           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
928           break;
930           case "string":
931             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
932           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
933           break;
935         }
936         $macrotab.= "</td></tr>";
938       }
939       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
940     }//is_array()
942     /* Give smarty the table */
943     $smarty->assign("macrotab",$macrotab);
946     /* Do we represent a valid account? */
947     if (!$this->is_account && $this->parent == NULL){
948       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
949         _("This account has no phone extensions.")."</b>";
950       $display.= back_to_main();
951       return($display);
952     }
954     $display= "";
956     /* Show tab dialog headers */
957     if ($this->parent != NULL){
958       if ($this->is_account){
959         $display= $this->show_header(_("Remove phone account"),
960             _("This account has phone features enabled. You can disable them by clicking below."));
961       } else {
962         if(empty($this->uid)){
963           $display= $this->show_header(_("Create phone account"),
964               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
965         }else{
966           $display= $this->show_header(_("Create phone account"),
967               _("This account has phone features disabled. You can enable them by clicking below."));
968         }
969         return ($display);
970       }
971     }
973     /* Add phone number */
974     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
975       if (is_phone_nr($_POST['phonenumber'])){
976         $number= $_POST["phonenumber"];
977         $this->phoneNumbers[$number]= $number;
978         $this->is_modified= TRUE;
979       } else {
980         print_red(_("Please enter a valid phone number!"));
981       }
982     }
984     /* Remove phone number */
985     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
986       foreach ($_POST['phonenumber_list'] as $number){
987         unset($this->phoneNumbers[$number]);
988         $this->is_modified= TRUE;
989       }
990     }
992     /* Transfer ACL's */
993     foreach($this->attributes as $val){
994       $smarty->assign($val."ACL", chkacl($this->acl,$val));
995       if(isset($this->$val)){
996         $smarty->assign($val,$this->$val);
997       }else{
998         $smarty->assign($val,"");
999       }
1000     }
1002     /* Create home server array */
1003     $tmp = array();
1004     foreach($this->goFonHomeServers as $dn => $attrs){
1005       if(!is_numeric($dn)){
1006         $tmp[$dn] = $attrs['SERVER'];
1007       }
1008     }
1009     $smarty->assign("goFonHomeServers",$tmp);
1011     /* Fill arrays */
1012     $smarty->assign ("goFonHardware", $this->goFonHardware);
1013     if (!count($this->phoneNumbers)){
1014       $smarty->assign ("phoneNumbers", array());
1015     } else {
1016       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1017     }
1018     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
1019       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
1020     foreach ($this->hardware_list as $cn => $description){
1021       if ($cn == $this->goFonHardware){
1022         $selected= "selected";
1023       } else {
1024         $selected= "";
1025       }
1026       if (isset($this->used_hardware[$cn])){
1027         $color= "style=\"color:#A0A0A0\"";
1028       } else {
1029         $color= "";
1030       }
1031       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1032     }
1033     $hl.= "</select>\n";
1034     $smarty->assign ("hardware_list", $hl);
1036     /* Show main page */
1037     $this->lastmacro = $this->macro;
1038     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1039     return($display);
1040   }
1043   function save_object()
1044   {
1045     if (isset($_POST["phoneTab"])){
1046     
1047       plugin::save_object();
1049       /* Save checkbox */
1050       if (isset($_POST['fon_to_mail'])){
1051         $tmp= "[M]";
1052       } else {
1053         $tmp= "[]";
1054       }
1055       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
1056         if ($this->goFonDeliveryMode != $tmp){
1057           $this->is_modified= TRUE;
1058         }
1059         $this->goFonDeliveryMode= $tmp;
1060       }
1062       /* Every macro in the select box are available */
1063       if((isset($_POST['macro']))){
1064         $this->macrostillavailable=true;
1065       }
1067       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1068         $this->is_modified =true;
1069       }
1071       if(is_array($this->phoneNumbers)){
1072         foreach($this->phoneNumbers as $telenumms) {
1073           $nummsinorder[]=$telenumms; 
1074         }
1075       }else{
1076         $nummsinorder=array("");
1077       }
1079       /* get all Postvars */
1080       if(isset($this->macroarray[$this->macro])){
1081  
1082         foreach($this->macroarray[$this->macro] as $key => $paras){
1084           $backup = $this->macroarray[$this->macro][$key];  
1086           if(isset($_POST[$paras['var']])){
1087             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1088           }
1090           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
1091              We need this code below to read and save checkboxes correct
1092            */
1094           if(isset($_POST['post_success'])){
1095             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1096               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1097                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1098               }else{
1099                 $this->macroarray[$this->macro][$key]['choosen']=false;
1100               }
1101             }
1102           }
1103           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1104             $this->modified = TRUE;
1105           }
1106         }
1107       }
1108     }
1109   }
1111   function check()
1112   {
1113     /* Call common method to give check the hook */
1114     $message= plugin::check();
1116     if(!count($this->goFonHomeServers)){
1117       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1118     }
1120     if(empty($this->goFonHomeServer)){
1121       $message[] = _("Please select a valid goFonHomeServer.");
1122     }
1124     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1125       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1126     }else{
1127       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1128         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1129       }
1130     }
1132     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1133       $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1134     }
1136     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1137       if(!$this->generate_mysql_entension_entries()){
1138         $message[] = $this->generate_error;
1139       }
1140     }
1142     /* We need at least one phone number */
1143     if (count($this->phoneNumbers) == 0){
1144       $message[]= sprintf(_("You need to specify at least one phone number!"));
1145     }
1147     /* check for ! in any parameter setting*/
1148     if(isset($this->macroarray[$this->macro])){
1149       foreach($this->macroarray[$this->macro] as $val){
1150         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1151           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1152         }
1153       }
1154     }
1155     return ($message);
1156   }
1160   function save()
1161   {
1162     plugin::save();
1164     /* Force saving macro again 
1165      * This ensures that 
1166      *  - the macro is available on the destiantion server.
1167      *  - the macro saved is up to date on the destination server.
1168      */
1169     if(!empty($this->macro) && $this->macro != "none")  {
1170       $macro_tab = new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro);
1171       $macro_tab -> save();
1172     }
1174     /* Save arrays */
1175     $tmp_numbers = array();
1176     foreach ($this->phoneNumbers as $number){
1177       $tmp_numbers[] = $number;
1178     }
1180     /* Save settings, or remove goFonMacro attribute*/
1181     if($this->macro!="none"){    
1182       $this->attrs['goFonMacro']=$this->macro;
1183       if(isset($this->macroarray[$this->macro])){
1184         foreach($this->macroarray[$this->macro] as $paras)  {
1185           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1186         }
1187       }
1188     }else{
1189       $this->attrs['goFonMacro']=array();
1190     }
1191     unset($this->attrs['macro'])  ;
1193     $this->attrs['goFonForwarding']=array();
1195     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1196       $str = $this->generate_mysql_entension_entries(true);
1197       if(empty($str)){
1198         print_red($str);
1199       }
1200     }
1202     if($this->attrs['goFonMacro']==""){
1203       $this->attrs['goFonMacro']=array();
1204     }
1206     unset($this->attrs['cn']);
1208     /* Write back to ldap */
1209     $ldap= $this->config->get_ldap_link();
1210     $ldap->cd($this->dn);
1211     $this->cleanup();
1212     
1213     /* Force saving numbers, else it will be overwriten by user account. */
1214     $this->attrs['telephoneNumber'] =$tmp_numbers;
1215     $ldap->modify ($this->attrs); 
1217     show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
1219     /* Optionally execute a command after we're done */
1221     if ($this->initially_was_account == $this->is_account){
1222       if ($this->is_modified){
1223         $this->handle_post_events("modify",array("uid" => $this->uid));
1224       }
1225     } else {
1226       $this->handle_post_events("add",array("uid" => $this->uid));
1227     }
1229   }
1232   function adapt_from_template($dn)
1233   {
1234     plugin::adapt_from_template($dn);
1236     /* Assemble phone numbers */
1237     if (isset($this->attrs['telephoneNumber'])){
1238       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1239         $number= $this->attrs['telephoneNumber'][$i];
1240         $this->phoneNumbers[$number]= $number;
1241       }
1242     }
1243   }
1246   function remove_from_parent()
1247   {
1248     if(!$this->initially_was_account) return;
1250     foreach($this->attributes as $key=>$val){
1251       if(in_array($val,array("uid","cn"))){
1252         unset($this->attributes[$key]);
1253         unset($this->$val);
1254       }
1255     }
1256     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1258       // Get Configuration for initial Mysql database Server
1259       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1260       $s_parameter  ="";
1262       // Connect to DB server
1263       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1265       // Check if we are  connected correctly
1266       if(!$r_con){
1267         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1268                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1269         gosa_log(@mysql_error());
1270         return false;
1271       }
1273       // Select database for Extensions
1274       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1276       // Test if we have the database selected correctly
1277       if(!$db){
1278         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1279         gosa_log(@mysql_error());
1280         return false;
1281       }
1283       $SQL="";
1285       /* If deletion starts from userslist, cn uid are not set */
1286       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1287         $this->uid = $this->parent->by_object['user']->uid;
1288       }
1290       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1291         $this->cn  = $this->parent->by_object['user']->cn;
1292       }
1294       $first_num = false;
1295       // Delete old entries
1296       foreach($this->a_old_telenums as $s_telenums){
1297         if(!$first_num){
1298           $first_num = $s_telenums;
1299         }
1300         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1301       }
1303       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1304       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1305       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1307       foreach($SQL as $query){
1308         if(!@mysql_query($query,$r_con)){
1309           print_red(_("Stop".mysql_error()));
1310           return false;
1311         }
1312       }
1313     }else{
1314       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1315       return false;
1316     }
1318     /* unset macro attr, it will cause an error */
1319     $tmp = array_flip($this->attributes);
1320     unset($tmp['macro']);
1321     $this->attributes=array_flip($tmp);
1323     /* Cancel if there's nothing to do here */
1324     if (!$this->initially_was_account){
1325       return;
1326     }
1328     plugin::remove_from_parent();
1330     /* Just keep one phone number */
1331     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1332       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1333     } else {
1334       $this->attrs['telephoneNumber']= array();
1335     }
1338     $ldap= $this->config->get_ldap_link();
1339     $ldap->cd($this->config->current['BASE']);
1340     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1341     while($attr = $ldap->fetch()){
1342       if(in_array($this->dn,$attr['member'])){
1343         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1344         unset($new->by_object['ogroup']->memberList[$this->dn]);
1345         unset($new->by_object['ogroup']->member[$this->dn]);
1346         $new->save();
1347         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1348       }
1349     }
1350     $ldap->cd($this->dn);
1351     $this->cleanup();
1352     $ldap->modify ($this->attrs); 
1354     show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1356     /* Optionally execute a command after we're done */
1357     @mysql_close($r_con);
1358     $this->handle_post_events('remove',array("uid"=> $this->uid));
1359   }
1363   /* This function checks if the given phonenumbers are available or already in use*/
1364   function is_number_used()
1365   {
1366     $ldap= $this->config->get_ldap_link();
1367     $ldap->cd($this->config->current['BASE']);
1368     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1369     while($attrs = $ldap->fetch()) {
1370       unset($attrs['telephoneNumber']['count']);
1371       foreach($attrs['telephoneNumber'] as $tele){
1372         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1373         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1374         $numbers[$tele]=$attrs;
1375       }
1376     }
1378     foreach($this->phoneNumbers as $num){
1379       if(!isset($this->cn)) $this->cn = "";
1381       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1382         if(isset($numbers[$num]['uid'][0])){
1383           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1384         }else{
1385           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1386         }
1387       }
1388     }
1389   }
1392   /* Create phoneAccount part of copy & paste dialog */
1393   function getCopyDialog()
1394   { 
1395     if(!$this->is_account) return("");
1396     $smarty = get_smarty();
1397     if (!count($this->phoneNumbers)){
1398       $smarty->assign ("phoneNumbers", array(""));
1399     } else {
1400       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1401     }
1403     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1404     $smarty->assign("goFonPIN",$this->goFonPIN);
1406     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1407     $ret =array();
1408     $ret['string'] = $display;
1409     $ret['status'] = "";
1410     return($ret);
1411   }
1413   /* Save posts from copy & paste dialog dialog  */
1414   function saveCopyDialog()
1415   {
1416     if(!$this->is_account) return;
1417     $this->execute();
1418     if(isset($_POST['goFonVoicemailPIN'])) {
1419       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1420     }
1421     if(isset($_POST['goFonPIN'])){
1422       $this->goFonPIN = $_POST['goFonPIN'];
1423     }
1424   }
1427   function allow_remove()
1428   {
1429     /* Check if previously selected server is still available */
1430     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1431       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1432     }
1433   }
1436 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1437 ?>