Code

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