Code

Removed old CLI stuff - cleanup
[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      */
76     $a_SETUP= array();
77     if(array_key_exists('config',$_SESSION) &&
78        array_key_exists('SERVERS',$_SESSION['config']->data) &&
79        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
80        is_callable("mysql_connect")
81        ) {
83       /* Set available server */
84       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
86       /* Servers defined? Watch here... */
87       if (count($this->goFonHomeServers)){
89         /* Set default server */
90         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
91           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
92         }
94         /* Remember inital home server, to be able to remove old entries */
95         $this->init_HomeServer = $this->goFonHomeServer;
97         /* Get config */
98         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
99           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']));
101           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
102           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
103         }    
104         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
106         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
107         if(!$r_con){
108           print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
109                 $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
110           gosa_log(mysql_error());
111         }
112         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
113         if(!$db){
114           print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
115           gosa_log(mysql_error());
116         }
118         $first = false; 
119         foreach($this->phoneNumbers as $key => $val){
120           if(!$first){
121             $first = $key;
122           }
123         }
124       }
125     }
127     /* Get available phone hardware  
128      * Search for all available phone hardware  
129      */
130     $ldap= $this->config->get_ldap_link();
131     $ldap->cd($this->config->current['BASE']);
132     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
133     while ($attrs= $ldap->fetch()){
134       $cn= $attrs['cn'][0];
135       if (isset($attrs['description'])){
136         $description= " - ".$attrs['description'][0];
137       } else {
138         $description= "";
139       }
140       $this->hardware_list[$cn]= "$cn$description";
141     }
144     /* Get available Macros  
145      * Search for all Marcos that are visible and create 
146      *  an array with name and parameters 
147      */
148     $ldap->search("(&(objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
150     /* Add none for no macro*/
151     $this->macros['none']=_("no macro");    
152     $this->macro ="none";
154     /* Fetch all Macros*/
155     while ($attrs= $ldap->fetch()){
157       /* unset Count, we don't need that here */
158       unset($attrs['displayName']['count']);
160       /* Parse macro data, unset count for parameterarrays  */
161       if (isset($attrs['goFonMacroParameter']['count'])){
162         unset($attrs['goFonMacroParameter']['count']);
163       }
165       /* fill Selectfield variable with Macros */
166       if(isset($attrs['displayName'][0])){
167         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
168       }else{
169         $this->macros[$attrs['dn']] = _("undefined");
170       }
172       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
173       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
175         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
176           /* Split Data in readable values, by delimiter !  */
177           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
179           /* Set all attrs */
180           $id = $data[0];
181           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
182           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
183           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
184           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
185           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
186           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
187           if($data[2] == "bool"){
188             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
189           }
190         }//foreach
191       }//is_array
192     }//while
195     /* Parse used Macro  
196      * If we have a macro selected, parse it and set values 
197      *  in $this->macroarray[$this->macro]. 
198      */
199     $tmp = split("!",$this->goFonMacro);
200     if(is_array($tmp)){
202       /* First value is the macroname */
203       $this->macro = $tmp[0];
205       /* Macroname saved, delete that index */
206       unset($tmp[0]);
208       /* Check if makro has been removed */
209       if(!isset($this->macros[$this->macro])){
210         $this->macrostillavailable = false;
211       }else{
212         $this->macrostillavailable = true;
213       }
215       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
216       foreach($tmp as $var){
218         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
219         $varar = split("#",$var);
221         /* Only insert if the parameter still exists */
222         if(isset($this->macroarray[$this->macro][$varar[0]])){
223           /* Assign value */
224           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
225         }
226       }
227     }
230     /* Colorize phones 
231      * Used phones will be colored in grey, 
232      *  so we must detect which phones are currently in use.
233      */
234     $ldap->cd($this->config->current['BASE']);
235     foreach ($this->hardware_list as $cn => $desc){
236       $ldap->search("(goFonHardware=$cn)", array('cn'));
237       if ($ldap->count() > 0){
238         $ldap->fetch();
239         if ($ldap->getDN() != $this->dn){
240           $this->used_hardware[$cn]= $ldap->getDN();
241         }
242       }
243     }
244     $this->hardware_list["automatic"]= _("automatic");
245     ksort($this->hardware_list);
246     $this->a_old_telenums = $this->phoneNumbers;
248     if($this->is_account){
249       $this->is_modified = true;
250     }
253     /* Get voicemail PIN from MySQL DB 
254      * Because every user can change his PIN directly from the phone
255      *  without any update to the ldap
256      * This means, the PIN in the DB is up to date
257      */
258     // Connect to DB server
259     if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
260       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
261       if($r_con){
262         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
263         $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."'"));
265         if((isset($vp[0]))&&(!empty($vp[0]))){
266           $this->goFonPINVoice = $vp[0];
267         }
268       }
269     }
270     $this->lastmacro=$this->macro;
272     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
273       @mysql_close($r_con) ;
274     }
275   }
278   /* This function generates the Database entries. 
279    * The Parameter 'save' could be true or false.
280    *  false - means only testing no database transactions.
281    *  true  - write database entries.
282    *
283    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
284    * 
285    * If the phone hardware is 'automatic' the table entries will only be removed
286    *  and not added. 
287    */
288   function generate_mysql_entension_entries($save = false)
289   {
290     /* Check if there is at least one server available 
291      * If not, return and tell the user that saving failed 
292      */
293     if(!count($this->goFonHomeServers)){
294       if($save){
295         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."));
296       }
297       return(true);
298     }
300     /* Check if Mysql extension is available */
301     if(!is_callable("mysql_pconnect")){
302       if($save)
303       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
304       return(true);
305     }
306  
307     /********************** 
308      * Attribute Initialisation
309      **********************/
311     $old_connection = false;
313     // Get Configuration for Mysql database Server
314     $s_parameter    = "";                                           // Contains paramter for selected Macro 
315     $r_con          = false;                                        // DB connection
316     $r_db           = false;                                        // Selected DB
317     $r_res          = false;                                        // Result resource
318     $a_ldap_attrs   = array();                                      //  
320     $s_ip           = NULL;                   // Contains ip for Sip entry
321     $s_host         = NULL;                   // Contains host for Sip entry
322     $s_qualify      = "yes";                  // Qualify entry
323     $s_pin          = NULL;                   // Entry for secret
324     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
326     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
327     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
328     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
330     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
331     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
333     $s_sip_key      = "";     // Key for SIP entry index      
334     $s_sip_val      = "";     // Value for SIP entry index      
336     $b_first_deleted= false;  // Only delete first entry, 
337     $s_telenums     = "";     // for each value variable
339     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
341     /* Prepare some basic attributes */
342     foreach($this->a_old_telenums as $tele){
343       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
344     }
345     foreach($this->phoneNumbers as $tele){
346       $newnums[]= preg_replace("/[^0-9]/","",$tele);
347     }
349     /* If deletion starts from userslist, cn uid are not set */
350     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
351       $this->uid = $this->parent->by_object['user']->uid;
352     }
353     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
354       $this->cn  = $this->parent->by_object['user']->cn;
355     }
356     /* Create voicemail entry 
357      */
358     if((!isset($this->cn))||(empty($this->cn))){
359       $CNname= $this->uid;
360     }else{
361       $CNname= $this->cn;
362     }
364     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
365       $s_mail = $this->parent->by_object['mailAccount']->mail;
366     }else{
367       $s_mail = "";
368     }
369     /* Get phonehardware to setup sip entry  */
370     $ldap         = $this->config->get_ldap_link();
371     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
372     $a_ldap_attrs = $ldap->fetch();
374     /* Check selected phone hardware, is a default IP set? */
375     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
376       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
377       $s_host     = $s_ip;
378     }else{
379       $s_ip       = NULL;
380       $s_host     = "dynamic";
381     }
383     // Attribute GoFonQualify set ?
384     if(isset($a_ldap_attrs['goFonQualify'])){
385       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
386     }
388     // Attribute GoFonPIN set ?
389     if(isset($this->goFonPIN)){
390       $s_pin      = $this->goFonPIN;
391     }
393     // Attribute GoFonType set ?
394     if(isset($a_ldap_attrs['goFonType'])){
395       $s_type = $a_ldap_attrs['goFonType'][0];
396     }
398     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
399       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
400     }else{
401       $sip_data_array['dtmfmode']     ="rfc2833";
402     }
404     /* Check if phone number is used */
405     if($this->is_number_used()){
406       $this->generate_error = $this->is_number_used(); 
407       return false;
408     }
412     /********************** 
413      * Check Server Connection Information
414      **********************/
415  
416     /* Create Mysql handle for the current goFonHomeServer, if possible  
417      * Get configuration to old asterisk home server 
418      */ 
419     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
420     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
421     if(!$new_connection){
422       $this->generate_error = sprintf(
423           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
424           $a_New['SERVER'],$a_New['LOGIN']);
425       gosa_log(@mysql_error($new_connection));
426       return false;
427     }
428     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
429     if(!$new_database){
430       $this->generate_error = sprintf(
431           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
432           $a_New['DB'],$a_New['SERVER']);
433       gosa_log( @mysql_error($new_connection));
434       return false;
435     }
437     /* If the home server has changed, we must remove entries from old 
438      *  server and add new entries in new server.  
439      */
440     if($this->init_HomeServer != $this->goFonHomeServer){
441     
442       /* Get configuration to old asterisk home server */ 
443       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
444  
445       /* Create connection to the database that contains the old entry. 
446        */
447       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
448       if(!$old_connection){
449         $this->generate_error = sprintf(
450             _("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."),
451             $a_Remove['SERVER'],$a_Remove['LOGIN']);
452         gosa_log(@mysql_error($old_connection));
453         return false;
454       }
455       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
456       if(!$old_database){
457         $this->generate_error = sprintf(
458             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
459             $a_Remove['DB'],$a_Remove['SERVER']);
460         gosa_log(@mysql_error($old_connection));
461         return false;
462       }
463     }
465     /* Save means that we must save changes, not only test  */
466     if($save == true){
467     
468       /********************** 
469        * Remove entries from old home server 
470        **********************/
472       /* Check if there is an old entry 
473        * If there is en old entry, get callerid and remove voicemail and extensions too 
474        */
475       if($old_connection){
476         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
477         $rid    = mysql_query($query,$old_connection);
479         /* Old entry found, remove it */
480         $query_a = array();
481         if(mysql_affected_rows($old_connection)){
482           $result = mysql_fetch_assoc($rid);
483           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
484           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
485           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
486           foreach($oldnums as $s_telenums) {
487             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
488           }
490           foreach($query_a as $qry){
491             if(!mysql_query($qry,$old_connection)){
492               echo $qry;
493               echo mysql_error($old_connection);
494             } 
495           }
496         }
497       }
499       /********************** 
500        * Update / Insert sip_users entry  
501        **********************/
503       /* Set the first given phone number as callerid */
504       reset($newnums);        
505       $i_new_key = key($newnums);
506       $sip_data_array['callerid']  =$newnums[$i_new_key];
507       $sip_data_array['mailbox']   =$newnums[$i_new_key];
509       /* Check if there is already an entry in sip_users for this uid */
510       $SQL_query_array = array();
511       $rid = mysql_query("SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n",$new_connection);
512       if(mysql_affected_rows($new_connection)){
514         /********************** 
515          * Update sip_users entry 
516          **********************/
517         $result                     = mysql_fetch_assoc($rid);
518         $sip_data_array['host']         = $s_host;
519         $sip_data_array['qualify']      = $s_qualify;
520         $sip_data_array['secret']       = $this->goFonPIN;
521         $sip_data_array['type']         = $s_type ;
522         $sip_data_array['username']     = $this->uid;
523         $sip_data_array['ipaddr']       = $s_ip;
525         /* Remove not changed attributes, to avoid updating table with same values */
526         foreach($sip_data_array as $name => $value){
527           if($result[$name] == $value){
528             unset($sip_data_array[$name]);
529           }
530         }
531         /* Only update entry if there is something to uopdate */
532         if(count($sip_data_array)){
533           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
534           foreach($sip_data_array as $key => $val){
535             $query.= "".$key."='".$val."',"; 
536           } 
537           $query = preg_replace("/,$/","",$query);
538           $query.= " WHERE name='".$this->uid."';";
539           $SQL_query_array[] = $query;
540         }
541       } else {
542  
543         /********************** 
544          * Insert sip_users entry 
545          **********************/
546         //generate SIP entry
547         $sip_data_array['id']           = "";
548         $sip_data_array['name']         = $this->uid;
549         $sip_data_array['accountcode']  = NULL;          
550         $sip_data_array['amaflags']     = NULL;
551         $sip_data_array['callgroup']    = NULL;
552         $sip_data_array['canreinvite']  = "no";
553         $sip_data_array['context']      = "default";
554         $sip_data_array['defaultip']    = NULL;
555         $sip_data_array['fromuser']     = NULL;
556         $sip_data_array['fromdomain']   = NULL;
557         $sip_data_array['host']         = $s_host;
558         $sip_data_array['insecure']     = NULL;
559         $sip_data_array['language']     = NULL;
560         $sip_data_array['mailbox']      = $newnums[$i_new_key];
561         $sip_data_array['md5secret']    = NULL;
562         $sip_data_array['nat']          = "no";
563         $sip_data_array['permit']       = NULL;
564         $sip_data_array['deny']         = NULL;
565         $sip_data_array['mask']         = NULL;
566         $sip_data_array['pickupgroup']  = NULL;
567         $sip_data_array['port']         = NULL;
568         $sip_data_array['qualify']      = $s_qualify;
569         $sip_data_array['restrictcid']  = "n";
570         $sip_data_array['rtptimeout']   = NULL;
571         $sip_data_array['rtpholdtimeout']=NULL;
572         $sip_data_array['secret']       = $this->goFonPIN;
573         $sip_data_array['type']         = $s_type ;
574         $sip_data_array['username']     = $this->uid;
575         $sip_data_array['disallow']     = NULL;
576         $sip_data_array['allow']        = NULL;
577         $sip_data_array['musiconhold']  = NULL;
578         $sip_data_array['regseconds']   = NULL;
579         $sip_data_array['ipaddr']       = $s_ip;
580         $sip_data_array['regexten']     = NULL;
581         $sip_data_array['cancallforward']=NULL;
583         /* There is currently no entry for this user in the sip_users table. 
584          * We should create one i
585          */
586         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
587           if($s_sip_val == NULL) continue;
588           $s_sip_values.="'".$s_sip_val."',";
589           $s_sip_keys  .="`".$s_sip_key."`,";
590         }
591         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
592         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
594         /* Add sip entries to mysql queries */
595         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
596       }
599       /********************** 
600        * Update / Insert Voice mail entry  
601        **********************/
603       $customer_id = $newnums[$i_new_key];
605       $voice_data_array = array(
606           "customer_id" => $customer_id,
607           "mailbox"     => $customer_id,
608           "password"    => $this->goFonVoicemailPIN,
609           "fullname"    => $CNname,
610           "email"       => $s_mail);
612       /* Set pager number if available */
613       if(isset($this->parent->by_object['user']->pager)){
614         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
615       }
617       /* Check if there is already an entry in sip_users for this uid */
618       $rid = mysql_query("SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n",$new_connection);
619       if(mysql_affected_rows($new_connection)){
621         /********************** 
622          * Update Voice mail entry  
623          **********************/
624         $result = mysql_fetch_assoc($rid)  ;
626         foreach($voice_data_array as $name => $value){
627           if($result[$name] == $value){
628             unset($voice_data_array[$name]);
629           }
630         }
632         /* Only update entry if there is something to uopdate */
633         if(count($voice_data_array)){
634           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
635           foreach($voice_data_array as $key => $val){
636             $query.= "".$key."='".$val."',"; 
637           } 
638           $query = preg_replace("/,$/","",$query);
639           $query.= " WHERE customer_id='".$customer_id."';";
640           $SQL_query_array[] = $query;
641         }
642       }else{
644         /********************** 
645          * Insert Voice mail entry  
646          **********************/
647         $voice_data_array['context'] = "default";
648   
649         /* There is currently no voice mail entry for this user. 
650          * We should create one 
651          */
652         $s_voi_values = $s_voi_keys = "";
653         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
654           if($s_voi_val == NULL) continue;
655           $s_voi_values.="'".$s_voi_val."',";
656           $s_voi_keys  .="`".$s_voi_key."`,";
657         }
658         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
659         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
661         /* Add sip entries to mysql queries */
662         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
663       }
665      
666       /********************** 
667        * Remove/Insert extension entries
668        **********************/
669       
670       /* Remove old entries */
671       $query = array();
672       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
673       foreach($newnums as $s_telenums){
674         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
675       }
676       foreach($query as $qry){
677         if(!mysql_query($qry,$new_connection)){
678           echo mysql_error($new_connection);
679         } 
680       }
681  
682       /********************** 
683        * Insert extension entries
684        **********************/
685  
686       // Get selected Macro Parameter and create parameter entry 
687       if(isset($this->macroarray[$this->macro])){
688         foreach($this->macroarray[$this->macro] as $key => $val ){
689           $s_parameter .= $val['choosen']."|";
690         }
691         $s_parameter = preg_replace("/\|$/","",$s_parameter);
692       }
693      
694       $i = 0; 
695       $EXT = array();
696     
697       if(!is_numeric($this->uid)){
698         $EXT[$i]['context'] = 'GOsa';
699         $EXT[$i]['exten']   = $this->uid;
700         $EXT[$i]['priority']= 1;
701         $EXT[$i]['app']     = "Goto";
702         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
703         $i ++;
704       }
706       // Entension entries  Hint / Dial / Goto
707       foreach($newnums as $s_telenums){
709         /* Hint Entry */
710         $EXT[$i]['context'] = 'GOsa';
711         $EXT[$i]['exten']   = $s_telenums;
712         $EXT[$i]['priority']= "Hint";
713         $EXT[$i]['app']     = 'SIP/'.$this->uid;
714         $i ++;  
715         /* SetCID */
716         //$EXT[$i]['context'] = 'GOsa';
717         //$EXT[$i]['exten']   = $s_telenums;
718         //$EXT[$i]['priority']= 1;
719         //$EXT[$i]['app']     = "SetCIDName";
720         //$EXT[$i]['appdata'] = $CNname;
721         //$i ++;  
723         // If no macro is selected use Dial
724         if($this->macro!="none"){ 
725           $macroname = preg_replace("/,.*$/","",$this->macro);        
726           $macroname = preg_replace("/^.*=/","",$macroname);        
727           $s_app = "Macro";$macroname;
728           $s_par = $macroname."|".$s_parameter; 
729         }else{
730           $s_app = "Dial";
731           $s_par = 'SIP/'.$this->uid."|20|r";
732         }
734         $EXT[$i]['context'] = 'GOsa';
735         $EXT[$i]['exten']   = $s_telenums;
736         $EXT[$i]['priority']= 1;
737         $EXT[$i]['app']     = $s_app;
738         $EXT[$i]['appdata'] = $s_par;
739         $i ++;
740       }
742       // Append all these Entries 
743       foreach($EXT as $entr){
744         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
745         foreach($entr as $key2 => $val2){
746           $SQL_syn.= "`".$key2."`,";
747         }
748         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
749         $SQL_syn .= ") VALUES ("; 
750         foreach($entr as $key2 => $val2){
751           $SQL_syn .= "'".$val2."',";
752         }
753         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
754         $SQL_syn .=");\n";
756         $SQL_query_array[] =$SQL_syn;
757         $SQL_syn ="";
758       }
760       // Perform queries ...
761       if($this->goFonHardware != "automatic"){
762         foreach($SQL_query_array as $query){
763           if(!@mysql_query($query,$new_connection)){
764             print_red(_("Error while performing query:")." ".mysql_error());
765             return false;
766           }
767         }
768       }
769     }
770     @mysql_close($new_connection);
771     return true;
772   }
775   function execute()
776   {
777     /* Call parent execute */
778     plugin::execute();
780     $display = "";
782     if(empty($this->macro)&&(!empty($this->goFonMacro))){
784       /* Go through already saved values, for a parameter */
785       $tmp = split("!",$this->goFonMacro);
787       /* it is possible that nothing has been saved yet */
788       if(is_array($tmp)){
790         /* First value is the macroname */
791         $this->macro = $tmp[0];
793         /* Macroname saved, delete that index */
794         unset($tmp[0]);
796         /* Check if macro has been removed */
797         if(!isset($this->macroarray[$this->macro])){
798           $this->macrostillavailable = false;
799         }else{
800           $this->macrostillavailable = true;
801         }
803         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
804         foreach($tmp as $var){
806           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
807           $varar = split("#",$var);
809           /* Only insert if the parameter still exists */
810           if(isset($this->macroarray[$this->macro][$varar[0]])){
811             /* Assign value */
812             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
813           }
814         }
815       }
816     }
817     
818     /* Do we represent a valid account? */
819     if (!$this->is_account && $this->parent == NULL){
820       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
821         _("This account has no phone extensions.")."</b>";
822       $display.= back_to_main();
823       return ($display);
824     }
826     /* Do we need to flip is_account state? */
827     if (isset($_POST['modify_state'])){
829       /* Onyl change account state if allowed */
830       if($this->is_account && $this->acl == "#all#"){
831         $this->is_account= !$this->is_account;
832       }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
833         $this->is_account= !$this->is_account;
834       }
835     }
837     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
838     if(empty($this->macro)){
839       $this->macro ="none";
840     }
842     /* Prepare templating */
843     $smarty= get_smarty();
845     /* tell user that the selected plugin is no longer available */
846     if((!$this->macrostillavailable)&&($this->macro!="none")){
847       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
848     }
850     /* Assing macroselectbox values  */
851     $smarty->assign("macros",$this->macros);   
852     $smarty->assign("macro", $this->macro);   
854     /* check if there is a FON server created */
855     if(!count($this->goFonHomeServer)){
856       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."));
857     }
859     /* Create html parameter table for selected macro parameters 
860      *  skip if no parameters given 
861      */
862     if(!isset($this->macroarray[$this->macro])){
863       $macrotab="";
864     }else{
866       $macrotab ="<table summary=\""._("Parameter")."\">";
867       /* for every single parameter-> display textfile,combo, or true false switch*/
869       foreach($this->phoneNumbers as $phonenum){
870         $tmp[] = $phonenum;
871       }
872     
873       if($this->macro != $this->lastmacro){
874         /* Go through all params */
875         foreach($this->macroarray[$this->macro] as $key => $paras){
877           $string = $paras['default'];
879           $string=preg_replace("/%uid/i",$this->uid,$string);
881           if(isset($this->cn)){
882             $string=preg_replace("/%cn/i",$this->cn,$string);
883           }
885           for($i = 0 ; $i < 10; $i++){
886             if(isset($tmp[$i])){
887               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
888             }
889           }
890           if(isset($tmp[0])){
891             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
892           }
893           $this->macroarray[$this->macro][$key]['choosen']=$string;
894         }
895       }
897       foreach($this->macroarray[$this->macro] as $paras){
899         /* get al vars */
900         $var        = $paras['var'];           
901         $name       = $paras['name'];           
902         $default    = $paras['default'];
903         $type       = $paras['type'];
904         $choosen    = $paras['choosen'] ; 
905         $str        = $default;
907         /* in case of a combo box display a combobox with selected attr */
908         $macrotab.= "<tr>";
909         switch ($type){
911           case "combo":
912             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
913           foreach(split(":",$default) as $choice){
914             if($choosen==$choice){
915               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
916             }else{
917               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
918             }
919           }
920           $str.="</select>";
921           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
922           break;
924           case "bool":
925             if(!$choosen){
926               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
927             }else{
928               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
929             }
930           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
931           break;
933           case "string":
934             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
935           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
936           break;
938         }
939         $macrotab.= "</td></tr>";
941       }
942       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
943     }//is_array()
945     /* Give smarty the table */
946     $smarty->assign("macrotab",$macrotab);
949     /* Do we represent a valid account? */
950     if (!$this->is_account && $this->parent == NULL){
951       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
952         _("This account has no phone extensions.")."</b>";
953       $display.= back_to_main();
954       return($display);
955     }
957     $display= "";
959     /* Show tab dialog headers */
960     if ($this->parent != NULL){
961       if ($this->is_account){
962         $display= $this->show_header(_("Remove phone account"),
963             _("This account has phone features enabled. You can disable them by clicking below."));
964       } else {
965         if(empty($this->uid)){
966           $display= $this->show_header(_("Create phone account"),
967               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
968         }else{
969           $display= $this->show_header(_("Create phone account"),
970               _("This account has phone features disabled. You can enable them by clicking below."));
971         }
972         return ($display);
973       }
974     }
976     /* Add phone number */
977     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
978       if (is_phone_nr($_POST['phonenumber'])){
979         $number= $_POST["phonenumber"];
980         $this->phoneNumbers[$number]= $number;
981         $this->is_modified= TRUE;
982       } else {
983         print_red(_("Please enter a valid phone number!"));
984       }
985     }
987     /* Remove phone number */
988     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
989       foreach ($_POST['phonenumber_list'] as $number){
990         unset($this->phoneNumbers[$number]);
991         $this->is_modified= TRUE;
992       }
993     }
995     /* Transfer ACL's */
996     foreach($this->attributes as $val){
997       $smarty->assign($val."ACL", chkacl($this->acl,$val));
998       if(isset($this->$val)){
999         $smarty->assign($val,$this->$val);
1000       }else{
1001         $smarty->assign($val,"");
1002       }
1003     }
1005     /* Create home server array */
1006     $tmp = array();
1007     foreach($this->goFonHomeServers as $dn => $attrs){
1008       if(!is_numeric($dn)){
1009         $tmp[$dn] = $attrs['SERVER'];
1010       }
1011     }
1012     $smarty->assign("goFonHomeServers",$tmp);
1014     /* Fill arrays */
1015     $smarty->assign ("goFonHardware", $this->goFonHardware);
1016     if (!count($this->phoneNumbers)){
1017       $smarty->assign ("phoneNumbers", array());
1018     } else {
1019       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1020     }
1021     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
1022       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
1023     foreach ($this->hardware_list as $cn => $description){
1024       if ($cn == $this->goFonHardware){
1025         $selected= "selected";
1026       } else {
1027         $selected= "";
1028       }
1029       if (isset($this->used_hardware[$cn])){
1030         $color= "style=\"color:#A0A0A0\"";
1031       } else {
1032         $color= "";
1033       }
1034       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1035     }
1036     $hl.= "</select>\n";
1037     $smarty->assign ("hardware_list", $hl);
1039     /* Show main page */
1040     $this->lastmacro = $this->macro;
1041     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1042     return($display);
1043   }
1046   function save_object()
1047   {
1048     if (isset($_POST["phoneTab"])){
1049       plugin::save_object();
1051       /* Save checkbox */
1052       if (isset($_POST['fon_to_mail'])){
1053         $tmp= "[M]";
1054       } else {
1055         $tmp= "[]";
1056       }
1057       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
1058         if ($this->goFonDeliveryMode != $tmp){
1059           $this->is_modified= TRUE;
1060         }
1061         $this->goFonDeliveryMode= $tmp;
1062       }
1064       /* Every macro in the select box are available */
1065       if((isset($_POST['macro']))){
1066         $this->macrostillavailable=true;
1067       }
1069       if(is_array($this->phoneNumbers)){
1070         foreach($this->phoneNumbers as $telenumms) {
1071           $nummsinorder[]=$telenumms; 
1072         }
1073       }else{
1074         $nummsinorder=array("");
1075       }
1077       /* get all Postvars */
1078       if(isset($this->macroarray[$this->macro])){ 
1079         foreach($this->macroarray[$this->macro] as $key => $paras){
1080           if(isset($_POST[$paras['var']])){
1081             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1082           }
1084           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
1085              We need this code below to read and save checkboxes correct
1086            */
1088           if(isset($_POST['post_success'])){
1089             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1090               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1091                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1092               }else{
1093                 $this->macroarray[$this->macro][$key]['choosen']=false;
1094               }
1095             }
1096           }
1097         }
1098       }
1099     }
1100   }
1102   function check()
1103   {
1104     /* Call common method to give check the hook */
1105     $message= plugin::check();
1107     if(!count($this->goFonHomeServers)){
1108       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1109     }
1111     if(empty($this->goFonHomeServer)){
1112       $message[] = _("Please select a valid goFonHomeServer.");
1113     }
1115     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1116       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1117     }else{
1118       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1119         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1120       }
1121     }
1123     if((strlen($this->goFonPIN)<=0)){
1124       $message[]=(_("Phone PIN must be at least one character long."));
1125     }else{
1126       if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1127         $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1128       }
1129     }
1131     if(!$this->generate_mysql_entension_entries()){
1132       $message[] = $this->generate_error;
1133     }
1135     /* We need at least one phone number */
1136     if (count($this->phoneNumbers) == 0){
1137       $message[]= sprintf(_("You need to specify at least one phone number!"));
1138     }
1140     /* check for ! in any parameter setting*/
1141     if(isset($this->macroarray[$this->macro])){
1142       foreach($this->macroarray[$this->macro] as $val){
1143         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1144           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1145         }
1146       }
1147     }
1148     return ($message);
1149   }
1153   function save()
1154   {
1155     plugin::save();
1157     /* Force saving macro again 
1158      * This ensures that 
1159      *  - the macro is available on the destiantion server.
1160      *  - the macro saved is up to date on the destination server.
1161      */
1162     if(!empty($this->macro) && $this->macro != "none")  {
1163       $macro_tab = new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro);
1164       $macro_tab -> save();
1165     }
1167     /* Save arrays */
1168     $tmp_numbers = array();
1169     foreach ($this->phoneNumbers as $number){
1170       $tmp_numbers[] = $number;
1171     }
1173     /* Save settings, or remove goFonMacro attribute*/
1174     if($this->macro!="none"){    
1175       $this->attrs['goFonMacro']=$this->macro;
1176       if(isset($this->macroarray[$this->macro])){
1177         foreach($this->macroarray[$this->macro] as $paras)  {
1178           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1179         }
1180       }
1181     }else{
1182       $this->attrs['goFonMacro']=array();
1183     }
1184     unset($this->attrs['macro'])  ;
1186     $this->attrs['goFonForwarding']=array();
1188     $str = $this->generate_mysql_entension_entries(true);
1189     if(empty($str)){
1190       print_red($str);
1191     }
1193     if($this->attrs['goFonMacro']==""){
1194       $this->attrs['goFonMacro']=array();
1195     }
1197     unset($this->attrs['cn']);
1199     /* Write back to ldap */
1200     $ldap= $this->config->get_ldap_link();
1201     $ldap->cd($this->dn);
1202     $this->cleanup();
1203     
1204     /* Force saving numbers, else it will be overwriten by user account. */
1205     $this->attrs['telephoneNumber'] =$tmp_numbers;
1206     $ldap->modify ($this->attrs); 
1208     show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
1210     /* Optionally execute a command after we're done */
1212     if ($this->initially_was_account == $this->is_account){
1213       if ($this->is_modified){
1214         $this->handle_post_events("modify",array("uid" => $this->uid));
1215       }
1216     } else {
1217       $this->handle_post_events("add",array("uid" => $this->uid));
1218     }
1220   }
1223   function adapt_from_template($dn)
1224   {
1225     plugin::adapt_from_template($dn);
1227     /* Assemble phone numbers */
1228     if (isset($this->attrs['telephoneNumber'])){
1229       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1230         $number= $this->attrs['telephoneNumber'][$i];
1231         $this->phoneNumbers[$number]= $number;
1232       }
1233     }
1234   }
1237   function remove_from_parent()
1238   {
1239     if(!$this->initially_was_account) return;
1241     foreach($this->attributes as $key=>$val){
1242       if(in_array($val,array("uid","cn"))){
1243         unset($this->attributes[$key]);
1244         unset($this->$val);
1245       }
1246     }
1247     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1249       // Get Configuration for initial Mysql database Server
1250       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1251       $s_parameter  ="";
1253       // Connect to DB server
1254       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1256       // Check if we are  connected correctly
1257       if(!$r_con){
1258         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1259                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1260         gosa_log(@mysql_error());
1261         return false;
1262       }
1264       // Select database for Extensions
1265       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1267       // Test if we have the database selected correctly
1268       if(!$db){
1269         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1270         gosa_log(@mysql_error());
1271         return false;
1272       }
1274       $SQL="";
1276       /* If deletion starts from userslist, cn uid are not set */
1277       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1278         $this->uid = $this->parent->by_object['user']->uid;
1279       }
1281       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1282         $this->cn  = $this->parent->by_object['user']->cn;
1283       }
1285       $first_num = false;
1286       // Delete old entries
1287       foreach($this->a_old_telenums as $s_telenums){
1288         if(!$first_num){
1289           $first_num = $s_telenums;
1290         }
1291         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1292       }
1294       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1295       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1296       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1298       foreach($SQL as $query){
1299         if(!@mysql_query($query,$r_con)){
1300           print_red(_("Stop".mysql_error()));
1301           return false;
1302         }
1303       }
1304     }else{
1305       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1306       return false;
1307     }
1309     /* unset macro attr, it will cause an error */
1310     $tmp = array_flip($this->attributes);
1311     unset($tmp['macro']);
1312     $this->attributes=array_flip($tmp);
1314     /* Cancel if there's nothing to do here */
1315     if (!$this->initially_was_account){
1316       return;
1317     }
1319     plugin::remove_from_parent();
1321     /* Just keep one phone number */
1322     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1323       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1324     } else {
1325       $this->attrs['telephoneNumber']= array();
1326     }
1329     $ldap= $this->config->get_ldap_link();
1330     $ldap->cd($this->config->current['BASE']);
1331     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1332     while($attr = $ldap->fetch()){
1333       if(in_array($this->dn,$attr['member'])){
1334         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1335         unset($new->by_object['ogroup']->memberList[$this->dn]);
1336         unset($new->by_object['ogroup']->member[$this->dn]);
1337         $new->save();
1338         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1339       }
1340     }
1341     $ldap->cd($this->dn);
1342     $this->cleanup();
1343     $ldap->modify ($this->attrs); 
1345     show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1347     /* Optionally execute a command after we're done */
1348     @mysql_close($r_con);
1349     $this->handle_post_events('remove',array("uid"=> $this->uid));
1350   }
1354   /* This function checks if the given phonenumbers are available or already in use*/
1355   function is_number_used()
1356   {
1357     $ldap= $this->config->get_ldap_link();
1358     $ldap->cd($this->config->current['BASE']);
1359     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1360     while($attrs = $ldap->fetch()) {
1361       unset($attrs['telephoneNumber']['count']);
1362       foreach($attrs['telephoneNumber'] as $tele){
1363         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1364         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1365         $numbers[$tele]=$attrs;
1366       }
1367     }
1369     foreach($this->phoneNumbers as $num){
1370       if(!isset($this->cn)) $this->cn = "";
1372       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1373         if(isset($numbers[$num]['uid'][0])){
1374           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1375         }else{
1376           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1377         }
1378       }
1379     }
1380   }
1383   /* Create phoneAccount part of copy & paste dialog */
1384   function getCopyDialog()
1385   { 
1386     if(!$this->is_account) return("");
1387     $smarty = get_smarty();
1388     if (!count($this->phoneNumbers)){
1389       $smarty->assign ("phoneNumbers", array(""));
1390     } else {
1391       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1392     }
1394     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1395     $smarty->assign("goFonPIN",$this->goFonPIN);
1397     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1398     $ret =array();
1399     $ret['string'] = $display;
1400     $ret['status'] = "";
1401     return($ret);
1402   }
1404   /* Save posts from copy & paste dialog dialog  */
1405   function saveCopyDialog()
1406   {
1407     if(!$this->is_account) return;
1408     $this->execute();
1409     if(isset($_POST['goFonVoicemailPIN'])) {
1410       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1411     }
1412     if(isset($_POST['goFonPIN'])){
1413       $this->goFonPIN = $_POST['goFonPIN'];
1414     }
1415   }
1418   function allow_remove()
1419   {
1420     /* Check if previously selected server is still available */
1421     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1422       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1423     }
1424   }
1427 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1428 ?>