Code

Aovid undefined index error msg
[gosa.git] / plugins / gofon / phoneaccount / class_phoneAccount.inc
1 <?php
3 class phoneAccount extends plugin
4 {
5   /* Definitions */
6   var $plHeadline= "Phone";
7   var $plDescription= "This does something";
8   var $has_mailAccount= FALSE;
10   /* Attributes */
11   var $telephoneNumber        = array();
12   var $goFonHardware          = "automatic";
13   var $goFonFormat            = "wav";
14   var $goFonPIN               = "";
15   var $goFonVoicemailPIN      = "";
16   var $goFonDeliveryMode      = "";
17   var $phoneNumbers           = array();
18   var $mail                   = "";
19   var $hardware_list          = array();
20   var $used_hardware          = array();
21   var $goFonMacro             = "";
22   var $macro                  = 0;              // Selected Macroi
23   var $lastmacro              = "";
24   var $macros                 = array();        // List of macros for smarty select box
25   var $macroarray             = array();        // All needed macro informations
26   var $macrostillavailable    = false;
27   var $generate_error         = "";
28   var $a_old_telenums         = array();
29   var $goFonPINVoice          = "";
30   var $goFonHomeServer        = "0";            // Contains the dn of the server that manage this account 
31   var $init_HomeServer        = "0";            // Contains the dn of the server that manage this account 
32   var $goFonHomeServers       = array();        // Contains all available server configurations 
34   /* CLI vars */
35   var $cli_summary            = "Manage users phone account";
36   var $cli_description        = "Some longer text\nfor help";
37   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
39   /* attribute list for save action */
40   var $CopyPasteVars          = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
41                                       "hardware_list","used_hardware");
43   var $attributes             = array("goFonDeliveryMode", "goFonFormat","cn","goFonHomeServer",
44       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
45   var $objectclasses= array("goFonAccount");
47   var $uid;
49   function phoneAccount ($config, $dn= NULL, $parent= NULL)
50   {
51     plugin::plugin ($config, $dn, $parent);
53     /* Assemble phone numbers */
54     if (isset($this->attrs['telephoneNumber'])){
55       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
56         $number= $this->attrs['telephoneNumber'][$i];
57         $this->phoneNumbers[$number]= $number;
58       }
59     }
61     /* Set up has_mailAccount */
62     if (isset($this->attrs['objectClass'])){
63       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
64         $this->has_mailAccount= TRUE;
65       }
66     }
68     /* Set uid */
69     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
70       $this->uid = $this->parent->by_object['user']->uid;
71     }
72     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
73       $this->cn  = $this->parent->by_object['user']->cn;
74     }
76     /* Check server configurations 
77      * Load all server configuration in $this->goFonHomeServers if available
78      *  and first server as default if necessary.
79      * Check if connection is successfull for the selected server $this->goFonHomeServer
80      */
81     $a_SETUP= array();
82     if(array_key_exists('config',$_SESSION) &&
83        array_key_exists('SERVERS',$_SESSION['config']->data) &&
84        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
85        is_callable("mysql_connect")
86        ) {
88       /* Set available server */
89       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
91       /* Servers defined? Watch here... */
92       if (count($this->goFonHomeServers)){
94         /* Set default server */
95         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
96           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
97         }
99         /* Remember inital home server, to be able to remove old entries */
100         $this->init_HomeServer = $this->goFonHomeServer;
102         /* Get config */
103         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
104           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']));
106           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
107           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
108         }    
109         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
111         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
112         if(!$r_con){
113           print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
114                 $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
115           gosa_log(mysql_error());
116         }
117         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
118         if(!$db){
119           print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
120           gosa_log(mysql_error());
121         }
123         $first = false; 
124         foreach($this->phoneNumbers as $key => $val){
125           if(!$first){
126             $first = $key;
127           }
128         }
129       }
130     }
132     /* Get available phone hardware  
133      * Search for all available phone hardware  
134      */
135     $ldap= $this->config->get_ldap_link();
136     $ldap->cd($this->config->current['BASE']);
137     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
138     while ($attrs= $ldap->fetch()){
139       $cn= $attrs['cn'][0];
140       if (isset($attrs['description'])){
141         $description= " - ".$attrs['description'][0];
142       } else {
143         $description= "";
144       }
145       $this->hardware_list[$cn]= "$cn$description";
146     }
149     /* Get available Macros  
150      * Search for all Marcos that are visible and create 
151      *  an array with name and parameters 
152      */
153     $ldap->search("(&(objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
155     /* Add none for no macro*/
156     $this->macros['none']=_("no macro");    
157     $this->macro ="none";
159     /* Fetch all Macros*/
160     while ($attrs= $ldap->fetch()){
162       /* unset Count, we don't need that here */
163       unset($attrs['displayName']['count']);
165       /* Parse macro data, unset count for parameterarrays  */
166       if (isset($attrs['goFonMacroParameter']['count'])){
167         unset($attrs['goFonMacroParameter']['count']);
168       }
170       /* fill Selectfield variable with Macros */
171       if(isset($attrs['displayName'][0])){
172         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
173       }else{
174         $this->macros[$attrs['dn']] = _("undefined");
175       }
177       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
178       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
180         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
181           /* Split Data in readable values, by delimiter !  */
182           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
184           /* Set all attrs */
185           $id = $data[0];
186           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
187           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
188           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
189           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
190           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
191           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
192           if($data[2] == "bool"){
193             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
194           }
195         }//foreach
196       }//is_array
197     }//while
200     /* Parse used Macro  
201      * If we have a macro selected, parse it and set values 
202      *  in $this->macroarray[$this->macro]. 
203      */
204     $tmp = split("!",$this->goFonMacro);
205     if(is_array($tmp)){
207       /* First value is the macroname */
208       $this->macro = $tmp[0];
210       /* Macroname saved, delete that index */
211       unset($tmp[0]);
213       /* Check if makro has been removed */
214       if(!isset($this->macros[$this->macro])){
215         $this->macrostillavailable = false;
216       }else{
217         $this->macrostillavailable = true;
218       }
220       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
221       foreach($tmp as $var){
223         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
224         $varar = split("#",$var);
226         /* Only insert if the parameter still exists */
227         if(isset($this->macroarray[$this->macro][$varar[0]])){
228           /* Assign value */
229           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
230         }
231       }
232     }
235     /* Colorize phones 
236      * Used phones will be colored in grey, 
237      *  so we must detect which phones are currently in use.
238      */
239     $ldap->cd($this->config->current['BASE']);
240     foreach ($this->hardware_list as $cn => $desc){
241       $ldap->search("(goFonHardware=$cn)", array('cn'));
242       if ($ldap->count() > 0){
243         $ldap->fetch();
244         if ($ldap->getDN() != $this->dn){
245           $this->used_hardware[$cn]= $ldap->getDN();
246         }
247       }
248     }
249     $this->hardware_list["automatic"]= _("automatic");
250     ksort($this->hardware_list);
251     $this->a_old_telenums = $this->phoneNumbers;
253     if($this->is_account){
254       $this->is_modified = true;
255     }
258     /* Get voicemail PIN from MySQL DB 
259      * Because every user can change his PIN directly from the phone
260      *  without any update to the ldap
261      * This means, the PIN in the DB is up to date
262      */
263     // Connect to DB server
264     if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
265       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
266       if($r_con){
267         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
268         $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."'"));
270         if((isset($vp[0]))&&(!empty($vp[0]))){
271           $this->goFonPINVoice = $vp[0];
272         }
273       }
274     }
275     $this->lastmacro=$this->macro;
277     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
278       @mysql_close($r_con) ;
279     }
280   }
283   /* This function generates the Database entries. 
284    * The Parameter 'save' could be true or false.
285    *  false - means only testing no database transactions.
286    *  true  - write database entries.
287    *
288    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
289    * 
290    * If the phone hardware is 'automatic' the table entries will only be removed
291    *  and not added. 
292    */
293   function generate_mysql_entension_entries($save = false)
294   {
295     /* Check if there is at least one server available 
296      * If not, return and tell the user that saving failed 
297      */
298     if(!count($this->goFonHomeServers)){
299       if($save){
300         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."));
301       }
302       return(true);
303     }
305     /* Check if Mysql extension is available */
306     if(!is_callable("mysql_pconnect")){
307       if($save)
308       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
309       return(true);
310     }
311  
312     /********************** 
313      * Attribute Initialisation
314      **********************/
316     $old_connection = false;
318     // Get Configuration for Mysql database Server
319     $s_parameter    = "";                                           // Contains paramter for selected Macro 
320     $r_con          = false;                                        // DB connection
321     $r_db           = false;                                        // Selected DB
322     $r_res          = false;                                        // Result resource
323     $a_ldap_attrs   = array();                                      //  
325     $s_ip           = NULL;                   // Contains ip for Sip entry
326     $s_host         = NULL;                   // Contains host for Sip entry
327     $s_qualify      = "yes";                  // Qualify entry
328     $s_pin          = NULL;                   // Entry for secret
329     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
331     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
332     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
333     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
335     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
336     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
338     $s_sip_key      = "";     // Key for SIP entry index      
339     $s_sip_val      = "";     // Value for SIP entry index      
341     $b_first_deleted= false;  // Only delete first entry, 
342     $s_telenums     = "";     // for each value variable
344     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
346     restore_error_handler();
348     /* Prepare some basic attributes */
349     foreach($this->a_old_telenums as $tele){
350       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
351     }
352     foreach($this->phoneNumbers as $tele){
353       $newnums[]= preg_replace("/[^0-9]/","",$tele);
354     }
356     /* If deletion starts from userslist, cn uid are not set */
357     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
358       $this->uid = $this->parent->by_object['user']->uid;
359     }
360     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
361       $this->cn  = $this->parent->by_object['user']->cn;
362     }
363     /* Create voicemail entry 
364      */
365     if((!isset($this->cn))||(empty($this->cn))){
366       $CNname= $this->uid;
367     }else{
368       $CNname= $this->cn;
369     }
371     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
372       $s_mail = $this->parent->by_object['mailAccount']->mail;
373     }else{
374       $s_mail = "";
375     }
376     /* Get phonehardware to setup sip entry  */
377     $ldap         = $this->config->get_ldap_link();
378     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
379     $a_ldap_attrs = $ldap->fetch();
381     /* Check selected phone hardware, is a default IP set? */
382     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
383       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
384       $s_host     = $s_ip;
385     }else{
386       $s_ip       = NULL;
387       $s_host     = "dynamic";
388     }
390     // Attribute GoFonQualify set ?
391     if(isset($a_ldap_attrs['goFonQualify'])){
392       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
393     }
395     // Attribute GoFonPIN set ?
396     if(isset($this->goFonPIN)){
397       $s_pin      = $this->goFonPIN;
398     }
400     // Attribute GoFonType set ?
401     if(isset($a_ldap_attrs['goFonType'])){
402       $s_type = $a_ldap_attrs['goFonType'][0];
403     }
405     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
406       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
407     }else{
408       $sip_data_array['dtmfmode']     ="rfc2833";
409     }
411     /* Check if phone number is used */
412     if($this->is_number_used()){
413       $this->generate_error = $this->is_number_used(); 
414       return false;
415     }
419     /********************** 
420      * Check Server Connection Information
421      **********************/
422  
423     /* Create Mysql handle for the current goFonHomeServer, if possible  
424      * Get configuration to old asterisk home server 
425      */ 
426     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
427     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
428     if(!$new_connection){
429       $this->generate_error = sprintf(
430           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
431           $a_New['SERVER'],$a_New['LOGIN']);
432       gosa_log(@mysql_error($new_connection));
433       return false;
434     }
435     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
436     if(!$new_database){
437       $this->generate_error = sprintf(
438           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
439           $a_New['DB'],$a_New['SERVER']);
440       gosa_log( @mysql_error($new_connection));
441       return false;
442     }
444     /* If the home server has changed, we must remove entries from old 
445      *  server and add new entries in new server.  
446      */
447     if($this->init_HomeServer != $this->goFonHomeServer){
448     
449       /* Get configuration to old asterisk home server */ 
450       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
451  
452       /* Create connection to the database that contains the old entry. 
453        */
454       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
455       if(!$old_connection){
456         $this->generate_error = sprintf(
457             _("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."),
458             $a_Remove['SERVER'],$a_Remove['LOGIN']);
459         gosa_log(@mysql_error($old_connection));
460         return false;
461       }
462       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
463       if(!$old_database){
464         $this->generate_error = sprintf(
465             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
466             $a_Remove['DB'],$a_Remove['SERVER']);
467         gosa_log(@mysql_error($old_connection));
468         return false;
469       }
470     }
472     /* Save means that we must save changes, not only test  */
473     if($save == true){
474     
475       /********************** 
476        * Remove entries from old home server 
477        **********************/
479       /* Check if there is an old entry 
480        * If there is en old entry, get callerid and remove voicemail and extensions too 
481        */
482       if($old_connection){
483         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
484         $rid    = mysql_query($query,$old_connection);
486         /* Old entry found, remove it */
487         $query_a = array();
488         if(mysql_affected_rows($old_connection)){
489           $result = mysql_fetch_assoc($rid);
490           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
491           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
492           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
493           foreach($oldnums as $s_telenums) {
494             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
495           }
497           foreach($query_a as $qry){
498             if(!mysql_query($qry,$old_connection)){
499               echo $qry;
500               echo mysql_error($old_connection);
501             } 
502           }
503         }
504       }
506       /********************** 
507        * Update / Insert sip_users entry  
508        **********************/
510       /* Set the first given phone number as callerid */
511       reset($newnums);        
512       $i_new_key = key($newnums);
513       $sip_data_array['callerid']  =$newnums[$i_new_key];
514       $sip_data_array['mailbox']   =$newnums[$i_new_key];
516       /* Check if there is already an entry in sip_users for this uid */
517       $SQL_query_array = array();
518       $rid = mysql_query("SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n",$new_connection);
519       if(mysql_affected_rows($new_connection)){
521         /********************** 
522          * Update sip_users entry 
523          **********************/
524         $result                     = mysql_fetch_assoc($rid);
525         $sip_data_array['host']         = $s_host;
526         $sip_data_array['qualify']      = $s_qualify;
527         $sip_data_array['secret']       = $this->goFonPIN;
528         $sip_data_array['type']         = $s_type ;
529         $sip_data_array['username']     = $this->uid;
530         $sip_data_array['ipaddr']       = $s_ip;
532         /* Remove not changed attributes, to avoid updating table with same values */
533         foreach($sip_data_array as $name => $value){
534           if($result[$name] == $value){
535             unset($sip_data_array[$name]);
536           }
537         }
538         /* Only update entry if there is something to uopdate */
539         if(count($sip_data_array)){
540           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
541           foreach($sip_data_array as $key => $val){
542             $query.= "".$key."='".$val."',"; 
543           } 
544           $query = preg_replace("/,$/","",$query);
545           $query.= " WHERE name='".$this->uid."';";
546           $SQL_query_array[] = $query;
547         }
548       } else {
549  
550         /********************** 
551          * Insert sip_users entry 
552          **********************/
553         //generate SIP entry
554         $sip_data_array['id']           = "";
555         $sip_data_array['name']         = $this->uid;
556         $sip_data_array['accountcode']  = NULL;          
557         $sip_data_array['amaflags']     = NULL;
558         $sip_data_array['callgroup']    = NULL;
559         $sip_data_array['canreinvite']  = "no";
560         $sip_data_array['context']      = "default";
561         $sip_data_array['defaultip']    = NULL;
562         $sip_data_array['fromuser']     = NULL;
563         $sip_data_array['fromdomain']   = NULL;
564         $sip_data_array['host']         = $s_host;
565         $sip_data_array['insecure']     = NULL;
566         $sip_data_array['language']     = NULL;
567         $sip_data_array['mailbox']      = $newnums[$i_new_key];
568         $sip_data_array['md5secret']    = NULL;
569         $sip_data_array['nat']          = "no";
570         $sip_data_array['permit']       = NULL;
571         $sip_data_array['deny']         = NULL;
572         $sip_data_array['mask']         = NULL;
573         $sip_data_array['pickupgroup']  = NULL;
574         $sip_data_array['port']         = NULL;
575         $sip_data_array['qualify']      = $s_qualify;
576         $sip_data_array['restrictcid']  = "n";
577         $sip_data_array['rtptimeout']   = NULL;
578         $sip_data_array['rtpholdtimeout']=NULL;
579         $sip_data_array['secret']       = $this->goFonPIN;
580         $sip_data_array['type']         = $s_type ;
581         $sip_data_array['username']     = $this->uid;
582         $sip_data_array['disallow']     = NULL;
583         $sip_data_array['allow']        = NULL;
584         $sip_data_array['musiconhold']  = NULL;
585         $sip_data_array['regseconds']   = NULL;
586         $sip_data_array['ipaddr']       = $s_ip;
587         $sip_data_array['regexten']     = NULL;
588         $sip_data_array['cancallforward']=NULL;
590         /* There is currently no entry for this user in the sip_users table. 
591          * We should create one i
592          */
593         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
594           if($s_sip_val == NULL) continue;
595           $s_sip_values.="'".$s_sip_val."',";
596           $s_sip_keys  .="`".$s_sip_key."`,";
597         }
598         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
599         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
601         /* Add sip entries to mysql queries */
602         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
603       }
606       /********************** 
607        * Update / Insert Voice mail entry  
608        **********************/
610       $customer_id = $newnums[$i_new_key];
612       $voice_data_array = array(
613           "customer_id" => $customer_id,
614           "mailbox"     => $customer_id,
615           "password"    => $this->goFonVoicemailPIN,
616           "fullname"    => $CNname,
617           "email"       => $s_mail);
619       /* Set pager number if available */
620       if(isset($this->parent->by_object['user']->pager)){
621         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
622       }
624       /* Check if there is already an entry in sip_users for this uid */
625       $rid = mysql_query("SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n",$new_connection);
626       if(mysql_affected_rows($new_connection)){
628         /********************** 
629          * Update Voice mail entry  
630          **********************/
631         $result = mysql_fetch_assoc($rid)  ;
633         foreach($voice_data_array as $name => $value){
634           if($result[$name] == $value){
635             unset($voice_data_array[$name]);
636           }
637         }
639         /* Only update entry if there is something to uopdate */
640         if(count($voice_data_array)){
641           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
642           foreach($voice_data_array as $key => $val){
643             $query.= "".$key."='".$val."',"; 
644           } 
645           $query = preg_replace("/,$/","",$query);
646           $query.= " WHERE customer_id='".$customer_id."';";
647           $SQL_query_array[] = $query;
648         }
649       }else{
651         /********************** 
652          * Insert Voice mail entry  
653          **********************/
654         $voice_data_array['context'] = "default";
655   
656         /* There is currently no voice mail entry for this user. 
657          * We should create one 
658          */
659         $s_voi_values = $s_voi_keys = "";
660         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
661           if($s_voi_val == NULL) continue;
662           $s_voi_values.="'".$s_voi_val."',";
663           $s_voi_keys  .="`".$s_voi_key."`,";
664         }
665         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
666         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
668         /* Add sip entries to mysql queries */
669         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
670       }
672      
673       /********************** 
674        * Remove/Insert extension entries
675        **********************/
676       
677       /* Remove old entries */
678       $query = array();
679       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
680       foreach($newnums as $s_telenums){
681         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
682       }
683       foreach($query as $qry){
684         if(!mysql_query($qry,$new_connection)){
685           echo mysql_error($new_connection);
686         } 
687       }
688  
689       /********************** 
690        * Insert extension entries
691        **********************/
692  
693       // Get selected Macro Parameter and create parameter entry 
694       if(isset($this->macroarray[$this->macro])){
695         foreach($this->macroarray[$this->macro] as $key => $val ){
696           $s_parameter .= $val['choosen']."|";
697         }
698         $s_parameter = preg_replace("/\|$/","",$s_parameter);
699       }
700      
701       $i = 0; 
702       $EXT = array();
703       $EXT[$i]['context'] = 'GOsa';
704       $EXT[$i]['exten']   = $this->uid;
705       $EXT[$i]['priority']= 1;
706       $EXT[$i]['app']     = "Goto";
707       $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
708       $i ++;
710       // Entension entries  Hint / Dial / Goto
711       foreach($newnums as $s_telenums){
713         /* Hint Entry */
714         $EXT[$i]['context'] = 'GOsa';
715         $EXT[$i]['exten']   = $s_telenums;
716         $EXT[$i]['priority']= "Hint";
717         $EXT[$i]['app']     = 'SIP/'.$this->uid;
718         $i ++;  
719         /* SetCID */
720         //$EXT[$i]['context'] = 'GOsa';
721         //$EXT[$i]['exten']   = $s_telenums;
722         //$EXT[$i]['priority']= 1;
723         //$EXT[$i]['app']     = "SetCIDName";
724         //$EXT[$i]['appdata'] = $CNname;
725         //$i ++;  
727         // If no macro is selected use Dial
728         if($this->macro!="none"){ 
729           $macroname = preg_replace("/,.*$/","",$this->macro);        
730           $macroname = preg_replace("/^.*=/","",$macroname);        
731           $s_app = "Macro";$macroname;
732           $s_par = $macroname."|".$s_parameter; 
733         }else{
734           $s_app = "Dial";
735           $s_par = 'SIP/'.$this->uid."|20|r";
736         }
738         $EXT[$i]['context'] = 'GOsa';
739         $EXT[$i]['exten']   = $s_telenums;
740         $EXT[$i]['priority']= 1;
741         $EXT[$i]['app']     = $s_app;
742         $EXT[$i]['appdata'] = $s_par;
743         $i ++;
744       }
746       // Append all these Entries 
747       foreach($EXT as $entr){
748         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
749         foreach($entr as $key2 => $val2){
750           $SQL_syn.= "`".$key2."`,";
751         }
752         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
753         $SQL_syn .= ") VALUES ("; 
754         foreach($entr as $key2 => $val2){
755           $SQL_syn .= "'".$val2."',";
756         }
757         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
758         $SQL_syn .=");\n";
760         $SQL_query_array[] =$SQL_syn;
761         $SQL_syn ="";
762       }
764       // Perform queries ...
765       if($this->goFonHardware != "automatic"){
766         foreach($SQL_query_array as $query){
767           if(!@mysql_query($query,$new_connection)){
768             print_red(_("Error while performing query:")." ".mysql_error());
769             return false;
770           }
771         }
772       }
773     }
774     @mysql_close($new_connection);
775     return true;
776   }
779   function execute()
780   {
781     /* Call parent execute */
782     plugin::execute();
784     $display = "";
786     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
788     if(empty($this->macro)&&(!empty($this->goFonMacro))){
790       /* Go through already saved values, for a parameter */
791       $tmp = split("!",$this->goFonMacro);
793       /* it is possible that nothing has been saved yet */
794       if(is_array($tmp)){
796         /* First value is the macroname */
797         $this->macro = $tmp[0];
799         /* Macroname saved, delete that index */
800         unset($tmp[0]);
802         /* Check if macro has been removed */
803         if(!isset($this->macroarray[$this->macro])){
804           $this->macrostillavailable = false;
805         }else{
806           $this->macrostillavailable = true;
807         }
809         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
810         foreach($tmp as $var){
812           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
813           $varar = split("#",$var);
815           /* Only insert if the parameter still exists */
816           if(isset($this->macroarray[$this->macro][$varar[0]])){
817             /* Assign value */
818             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
819           }
820         }
821       }
822     }
823     
824     /* Do we represent a valid account? */
825     if (!$this->is_account && $this->parent == NULL){
826       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
827         _("This account has no phone extensions.")."</b>";
828       $display.= back_to_main();
829       return ($display);
830     }
832     /* Do we need to flip is_account state? */
833     if (isset($_POST['modify_state'])){
834       $this->is_account= !$this->is_account;
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         $dis = "";
908         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
909           $dis = " disabled ";
910         }
912         /* in case of a combo box display a combobox with selected attr */
913         $macrotab.= "<tr>";
914         switch ($type){
916           case "combo":
917             $str= "<select name='".$var."' ".$dis." >";
918           foreach(split(":",$default) as $choice){
919             if($choosen==$choice){
920               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
921             }else{
922               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
923             }
924           }
925           $str.="</select>";
926           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
927           break;
929           case "bool":
930             if(!$choosen){
931               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
932             }else{
933               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
934             }
935           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
936           break;
938           case "string":
939             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
940           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
941           break;
943         }
944         $macrotab.= "</td></tr>";
946       }
947       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
948     }//is_array()
950     /* Give smarty the table */
951     $smarty->assign("macrotab",$macrotab);
954     /* Do we represent a valid account? */
955     if (!$this->is_account && $this->parent == NULL){
956       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
957         _("This account has no phone extensions.")."</b>";
958       $display.= back_to_main();
959       return($display);
960     }
962     $display= "";
963  /* Show tab dialog headers */
964     if ($this->parent != NULL){
965       if ($this->is_account){
966         $display= $this->show_disable_header(_("Remove phone account"),
967             _("This account has phone features enabled. You can disable them by clicking below."));
968       } else {
969         if(empty($this->uid)){
970           $display= $this->show_enable_header(_("Create phone account"),
971               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
972         }else{
973           $display= $this->show_enable_header(_("Create phone account"),
974               _("This account has phone features disabled. You can enable them by clicking below."));
975         }
976         return ($display);
977       }
978     }
980     /* Add phone number */
981     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
982       if (is_phone_nr($_POST['phonenumber'])){
983         $number= $_POST["phonenumber"];
984         $this->phoneNumbers[$number]= $number;
985         $this->is_modified= TRUE;
986       } else {
987         print_red(_("Please enter a valid phone number!"));
988       }
989     }
991     /* Remove phone number */
992     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
993       foreach ($_POST['phonenumber_list'] as $number){
994         unset($this->phoneNumbers[$number]);
995         $this->is_modified= TRUE;
996       }
997     }
999     /* Transfer ACL's */
1000     foreach($this->attributes as $val){
1001       $smarty->assign($val."ACL",$this->getacl($val,$SkipWrite));
1002       if(isset($this->$val)){
1003         $smarty->assign($val,$this->$val);
1004       }else{
1005         $smarty->assign($val,"");
1006       }
1007     }
1009     /* Create home server array */
1010     $tmp = array();
1011     foreach($this->goFonHomeServers as $dn => $attrs){
1012       if(!is_numeric($dn)){
1013         $tmp[$dn] = $attrs['SERVER'];
1014       }
1015     }
1016     $smarty->assign("goFonHomeServers",$tmp);
1018     /* Fill arrays */
1019     $smarty->assign ("goFonHardware", $this->goFonHardware);
1020     if (!count($this->phoneNumbers)){
1021       $smarty->assign ("phoneNumbers", array());
1022     } else {
1023       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1024     }
1026     $dis = "";
1027     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1028       $dis= " disabled ";
1029     }
1030     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1031        _("Choose your private phone")."\">\n";
1033     foreach ($this->hardware_list as $cn => $description){
1034       if ($cn == $this->goFonHardware){
1035         $selected= "selected";
1036       } else {
1037         $selected= "";
1038       }
1039       if (isset($this->used_hardware[$cn])){
1040         $color= "style=\"color:#A0A0A0\"";
1041       } else {
1042         $color= "";
1043       }
1044       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1045     }
1046     $hl.= "</select>\n";
1047     $smarty->assign ("hardware_list", $hl);
1049     /* Show main page */
1050     $this->lastmacro = $this->macro;
1051     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1052     return($display);
1053   }
1056   function save_object()
1057   {
1058     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
1059     if (isset($_POST["phoneTab"])){
1060       plugin::save_object();
1062       /* Save checkbox */
1063       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1064       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1065         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1066           $tmp .= "M";
1067         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1068           $tmp  = preg_replace ("/M/","",$tmp);
1069         }
1070       }
1071       $this->goFonDeliveryMode= "[".$tmp."]";
1074       /* Every macro in the select box are available */
1075       if((isset($_POST['macro']))){
1076         $this->macrostillavailable=true;
1077       }
1079       if(is_array($this->phoneNumbers)){
1080         foreach($this->phoneNumbers as $telenumms) {
1081           $nummsinorder[]=$telenumms; 
1082         }
1083       }else{
1084         $nummsinorder=array("");
1085       }
1088       /* get all Postvars */
1089       if(isset($this->macroarray[$this->macro])){
1090         if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1091           foreach($this->macroarray[$this->macro] as $key => $paras){
1092             if(isset($_POST[$paras['var']])){
1093               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1094             }
1096             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1097                We need this code below to read and save checkboxes correct
1098              */
1100             if(isset($_POST['post_success'])){
1101               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1102                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1103                   $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1104                 }else{
1105                   $this->macroarray[$this->macro][$key]['choosen']=false;
1106                 }
1107               }
1108             }
1109           }
1110         }
1111       }
1112     }
1113   }
1115   function check()
1116   {
1117     /* Call common method to give check the hook */
1118     $message= plugin::check();
1120     if(!count($this->goFonHomeServers)){
1121       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1122     }
1124     if(empty($this->goFonHomeServer)){
1125       $message[] = _("Please select a valid goFonHomeServer.");
1126     }
1128     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1129       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1130     }else{
1131       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1132         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1133       }
1134     }
1136     if((strlen($this->goFonPIN)<=0)){
1137       $message[]=(_("Phone PIN must be at least one character long."));
1138     }else{
1139       if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1140         $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1141       }
1142     }
1144     if(!$this->generate_mysql_entension_entries()){
1145       $message[] = $this->generate_error;
1146     }
1148     /* We need at least one phone number */
1149     if (count($this->phoneNumbers) == 0){
1150       $message[]= sprintf(_("You need to specify at least one phone number!"));
1151     }
1153     /* check for ! in any parameter setting*/
1154     if(isset($this->macroarray[$this->macro])){
1155       foreach($this->macroarray[$this->macro] as $val){
1156         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1157           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1158         }
1159       }
1160     }
1161     return ($message);
1162   }
1166   function save()
1167   {
1168     plugin::save();
1170     /* Force saving macro again 
1171      * This ensures that 
1172      *  - the macro is available on the destiantion server.
1173      *  - the macro saved is up to date on the destination server.
1174      */
1175     if(!empty($this->macro) && $this->macro != "none")  {
1176       $macro_tab = new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro);
1177       $macro_tab -> save();
1178     }
1180     /* Save arrays */
1181     $tmp_numbers = array();
1182     foreach ($this->phoneNumbers as $number){
1183       $tmp_numbers[] = $number;
1184     }
1186     /* Save settings, or remove goFonMacro attribute*/
1187     if($this->macro!="none"){    
1188       $this->attrs['goFonMacro']=$this->macro;
1189       if(isset($this->macroarray[$this->macro])){
1190         foreach($this->macroarray[$this->macro] as $paras)  {
1191           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1192         }
1193       }
1194     }else{
1195       $this->attrs['goFonMacro']=array();
1196     }
1197     unset($this->attrs['macro'])  ;
1199     $this->attrs['goFonForwarding']=array();
1201     $str = $this->generate_mysql_entension_entries(true);
1202     if(empty($str)){
1203       print_red($str);
1204     }
1206     if($this->attrs['goFonMacro']==""){
1207       $this->attrs['goFonMacro']=array();
1208     }
1210     unset($this->attrs['cn']);
1212     /* Write back to ldap */
1213     $ldap= $this->config->get_ldap_link();
1214     $ldap->cd($this->dn);
1215     $this->cleanup();
1216     
1217     /* Force saving numbers, else it will be overwriten by user account. */
1218     $this->attrs['telephoneNumber'] =$tmp_numbers;
1219     $ldap->modify ($this->attrs); 
1221     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/phone account with dn '%s' failed."),$this->dn));
1223     /* Optionally execute a command after we're done */
1225     if ($this->initially_was_account == $this->is_account){
1226       if ($this->is_modified){
1227         $this->handle_post_events("modify",array("uid" => $this->uid));
1228       }
1229     } else {
1230       $this->handle_post_events("add",array("uid" => $this->uid));
1231     }
1233   }
1236   function adapt_from_template($dn)
1237   {
1238     plugin::adapt_from_template($dn);
1240     /* Assemble phone numbers */
1241     if (isset($this->attrs['telephoneNumber'])){
1242       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1243         $number= $this->attrs['telephoneNumber'][$i];
1244         $this->phoneNumbers[$number]= $number;
1245       }
1246     }
1247   }
1250   function remove_from_parent()
1251   {
1252     if(!$this->initially_was_account) return;
1254     foreach($this->attributes as $key=>$val){
1255       if(in_array($val,array("uid","cn"))){
1256         unset($this->attributes[$key]);
1257         unset($this->$val);
1258       }
1259     }
1260     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1262       // Get Configuration for initial Mysql database Server
1263       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1264       $s_parameter  ="";
1266       // Connect to DB server
1267       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1269       // Check if we are  connected correctly
1270       if(!$r_con){
1271         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1272                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1273         gosa_log(@mysql_error());
1274         return false;
1275       }
1277       // Select database for Extensions
1278       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1280       // Test if we have the database selected correctly
1281       if(!$db){
1282         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1283         gosa_log(@mysql_error());
1284         return false;
1285       }
1287       $SQL="";
1289       /* If deletion starts from userslist, cn uid are not set */
1290       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1291         $this->uid = $this->parent->by_object['user']->uid;
1292       }
1294       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1295         $this->cn  = $this->parent->by_object['user']->cn;
1296       }
1298       $first_num = false;
1299       // Delete old entries
1300       foreach($this->a_old_telenums as $s_telenums){
1301         if(!$first_num){
1302           $first_num = $s_telenums;
1303         }
1304         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1305       }
1307       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1308       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1309       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1311       foreach($SQL as $query){
1312         if(!@mysql_query($query,$r_con)){
1313           print_red(_("Stop".mysql_error()));
1314           return false;
1315         }
1316       }
1317     }else{
1318       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1319       return false;
1320     }
1322     /* unset macro attr, it will cause an error */
1323     $tmp = array_flip($this->attributes);
1324     unset($tmp['macro']);
1325     $this->attributes=array_flip($tmp);
1327     /* Cancel if there's nothing to do here */
1328     if (!$this->initially_was_account){
1329       return;
1330     }
1332     plugin::remove_from_parent();
1334     /* Just keep one phone number */
1335     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1336       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1337     } else {
1338       $this->attrs['telephoneNumber']= array();
1339     }
1342     $ldap= $this->config->get_ldap_link();
1343     $ldap->cd($this->config->current['BASE']);
1344     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1345     while($attr = $ldap->fetch()){
1346       if(in_array($this->dn,$attr['member'])){
1347         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1348         unset($new->by_object['ogroup']->memberList[$this->dn]);
1349         unset($new->by_object['ogroup']->member[$this->dn]);
1350         $new->save();
1351         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1352       }
1353     }
1354     $ldap->cd($this->dn);
1355     $this->cleanup();
1356     $ldap->modify ($this->attrs); 
1358     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/phone account with dn '%s' failed."),$this->dn));
1360     /* Optionally execute a command after we're done */
1361     @mysql_close($r_con);
1362     $this->handle_post_events('remove',array("uid"=> $this->uid));
1363   }
1367   /* This function checks if the given phonenumbers are available or already in use*/
1368   function is_number_used()
1369   {
1370     $ldap= $this->config->get_ldap_link();
1371     $ldap->cd($this->config->current['BASE']);
1372     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1373     while($attrs = $ldap->fetch()) {
1374       unset($attrs['telephoneNumber']['count']);
1375       foreach($attrs['telephoneNumber'] as $tele){
1376         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1377         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1378         $numbers[$tele]=$attrs;
1379       }
1380     }
1382     foreach($this->phoneNumbers as $num){
1383       if(!isset($this->cn)) $this->cn = "";
1385       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1386         if(isset($numbers[$num]['uid'][0])){
1387           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1388         }else{
1389           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1390         }
1391       }
1392     }
1393   }
1396   /* Create phoneAccount part of copy & paste dialog */
1397   function getCopyDialog()
1398   { 
1399     if(!$this->is_account) return("");
1400     $smarty = get_smarty();
1401     if (!count($this->phoneNumbers)){
1402       $smarty->assign ("phoneNumbers", array(""));
1403     } else {
1404       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1405     }
1407     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1408     $smarty->assign("goFonPIN",$this->goFonPIN);
1410     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1411     $ret =array();
1412     $ret['string'] = $display;
1413     $ret['status'] = "";
1414     return($ret);
1415   }
1417   /* Save posts from copy & paste dialog dialog  */
1418   function saveCopyDialog()
1419   {
1420     if(!$this->is_account) return;
1421     $this->execute();
1422     if(isset($_POST['goFonVoicemailPIN'])) {
1423       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1424     }
1425     if(isset($_POST['goFonPIN'])){
1426       $this->goFonPIN = $_POST['goFonPIN'];
1427     }
1428   }
1431   function allow_remove()
1432   {
1433     /* Check if previously selected server is still available */
1434     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1435       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1436     }
1437   }
1439   /* Return plugin informations for acl handling */
1440   function plInfo()
1441   {
1442     return (array(
1443           "plShortName"     => _("Phone"),
1444           "plDescription"   => _("Phone account settings"),
1445           "plSelfModify"    => TRUE,
1446           "plDepends"       => array("user"),
1447           "plPriority"      => 7,                                 // Position in tabs
1448           "plSection"       => "personal",                        // This belongs to personal
1449           "plCategory"      => array("gofonreport" => array("description" => _("GOfon reports"),
1450               "objectClass" => "")),
1452           "plOptions"       => array(),
1454           "plProvidedAcls"  => array(
1455             "telephoneNumber"     => _("Telephone number"),
1456             "goFonMacro"          => _("Macro settings"),
1457             "goFonHardware"       => _("Phone hardware"),
1458             "goFonPIN"            => _("Telephone pin"),
1459             "goFonVoicemailPIN"   => _("Voicemail pin"))
1460           ));
1461   }
1464 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1465 ?>