Code

1693935245549a6bb16f4ec9973481e220742bc9
[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   var $view_logged = FALSE;
51   function phoneAccount ($config, $dn= NULL, $parent= NULL)
52   {
53     plugin::plugin ($config, $dn, $parent);
55     /* Assemble phone numbers */
56     if (isset($this->attrs['telephoneNumber'])){
57       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
58         $number= $this->attrs['telephoneNumber'][$i];
59         $this->phoneNumbers[$number]= $number;
60       }
61     }
63     /* Set up has_mailAccount */
64     if (isset($this->attrs['objectClass'])){
65       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
66         $this->has_mailAccount= TRUE;
67       }
68     }
70     /* Set uid */
71     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
72       $this->uid = $this->parent->by_object['user']->uid;
73     }
74     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
75       $this->cn  = $this->parent->by_object['user']->cn;
76     }
78     /* Check server configurations 
79      * Load all server configuration in $this->goFonHomeServers if available
80      *  and first server as default if necessary.
81      * Check if connection is successfull for the selected server $this->goFonHomeServer
82      */
84   
85     /* Set available server */
86     if(isset($_SESSION['config']->data['SERVERS']['FON'])){
87       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
88     }
90     $a_SETUP= array();
91     if($this->is_account &&
92        array_key_exists('config',$_SESSION) &&
93        array_key_exists('SERVERS',$_SESSION['config']->data) &&
94        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
95        is_callable("mysql_connect")
96        ) {
98       /* Servers defined? Watch here... */
99       if (count($this->goFonHomeServers)){
101         /* Set default server */
102         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
103           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
104         }
106         /* Remember inital home server, to be able to remove old entries */
107         $this->init_HomeServer = $this->goFonHomeServer;
109         /* Get config */
110         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
111           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']));
113           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
114           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
115         }    
116         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
118         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
119         if(!$r_con){
120 #          print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
121 #                $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
122           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
123         }
124         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
125         if(!$db){
126 #          print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
127           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
128         }
130         $first = false; 
131         foreach($this->phoneNumbers as $key => $val){
132           if(!$first){
133             $first = $key;
134           }
135         }
136       }
137     }
139     /* Get available phone hardware  
140      * Search for all available phone hardware  
141      */
142     $ldap= $this->config->get_ldap_link();
143     $ldap->cd($this->config->current['BASE']);
144     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
145     while ($attrs= $ldap->fetch()){
146       $cn= $attrs['cn'][0];
147       if (isset($attrs['description'])){
148         $description= " - ".$attrs['description'][0];
149       } else {
150         $description= "";
151       }
152       $this->hardware_list[$cn]= "$cn$description";
153     }
156     /* Get available Macros  
157      * Search for all Marcos that are visible and create 
158      *  an array with name and parameters 
159      */
160     $ldap->search("(&(objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
162     /* Add none for no macro*/
163     $this->macros['none']=_("no macro");    
164     $this->macro ="none";
166     /* Fetch all Macros*/
167     while ($attrs= $ldap->fetch()){
169       /* unset Count, we don't need that here */
170       unset($attrs['displayName']['count']);
172       /* Parse macro data, unset count for parameterarrays  */
173       if (isset($attrs['goFonMacroParameter']['count'])){
174         unset($attrs['goFonMacroParameter']['count']);
175       }
177       /* fill Selectfield variable with Macros */
178       if(isset($attrs['displayName'][0])){
179         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
180       }else{
181         $this->macros[$attrs['dn']] = _("undefined");
182       }
184       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
185       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
187         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
188           /* Split Data in readable values, by delimiter !  */
189           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
191           /* Set all attrs */
192           $id = $data[0];
193           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
194           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
195           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
196           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
197           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
198           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
199           if($data[2] == "bool"){
200             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
201           }
202         }//foreach
203       }//is_array
204     }//while
207     /* Parse used Macro  
208      * If we have a macro selected, parse it and set values 
209      *  in $this->macroarray[$this->macro]. 
210      */
211     $tmp = split("!",$this->goFonMacro);
212     if(is_array($tmp)){
214       /* First value is the macroname */
215       $this->macro = $tmp[0];
217       /* Macroname saved, delete that index */
218       unset($tmp[0]);
220       /* Check if makro has been removed */
221       if(!isset($this->macros[$this->macro])){
222         $this->macrostillavailable = false;
223       }else{
224         $this->macrostillavailable = true;
225       }
227       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
228       foreach($tmp as $var){
230         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
231         $varar = split("#",$var);
233         /* Only insert if the parameter still exists */
234         if(isset($this->macroarray[$this->macro][$varar[0]])){
235           /* Assign value */
236           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
237         }
238       }
239     }
242     /* Colorize phones 
243      * Used phones will be colored in grey, 
244      *  so we must detect which phones are currently in use.
245      */
246     $ldap->cd($this->config->current['BASE']);
247     foreach ($this->hardware_list as $cn => $desc){
248       $ldap->search("(goFonHardware=$cn)", array('cn'));
249       if ($ldap->count() > 0){
250         $ldap->fetch();
251         if ($ldap->getDN() != $this->dn){
252           $this->used_hardware[$cn]= $ldap->getDN();
253         }
254       }
255     }
256     $this->hardware_list["automatic"]= _("automatic");
257     ksort($this->hardware_list);
258     $this->a_old_telenums = $this->phoneNumbers;
260     /* Get voicemail PIN from MySQL DB 
261      * Because every user can change his PIN directly from the phone
262      *  without any update to the ldap
263      * This means, the PIN in the DB is up to date
264      */
265     // Connect to DB server
266     if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
267       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
268       if($r_con){
269         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
270         $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."'"));
272         if((isset($vp[0]))&&(!empty($vp[0]))){
273           $this->goFonPINVoice = $vp[0];
274         }
275       }
276     }
277     $this->lastmacro=$this->macro;
279     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
280       @mysql_close($r_con) ;
281     }
282   }
285   /* This function generates the Database entries. 
286    * The Parameter 'save' could be true or false.
287    *  false - means only testing no database transactions.
288    *  true  - write database entries.
289    *
290    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
291    * 
292    * If the phone hardware is 'automatic' the table entries will only be removed
293    *  and not added. 
294    */
295   function generate_mysql_entension_entries($save = false)
296   {
297     /* Check if there is at least one server available 
298      * If not, return and tell the user that saving failed 
299      */
300     if(!count($this->goFonHomeServers)){
301       if($save){
302         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."));
303       }
304       return(true);
305     }
307     /* Check if Mysql extension is available */
308     if(!is_callable("mysql_pconnect")){
309       if($save)
310       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
311       return(true);
312     }
313  
314     /********************** 
315      * Attribute Initialisation
316      **********************/
318     $old_connection = false;
320     // Get Configuration for Mysql database Server
321     $s_parameter    = "";                                           // Contains paramter for selected Macro 
322     $r_con          = false;                                        // DB connection
323     $r_db           = false;                                        // Selected DB
324     $r_res          = false;                                        // Result resource
325     $a_ldap_attrs   = array();                                      //  
327     $s_ip           = NULL;                   // Contains ip for Sip entry
328     $s_host         = NULL;                   // Contains host for Sip entry
329     $s_qualify      = "yes";                  // Qualify entry
330     $s_pin          = NULL;                   // Entry for secret
331     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
333     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
334     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
335     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
337     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
338     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
340     $s_sip_key      = "";     // Key for SIP entry index      
341     $s_sip_val      = "";     // Value for SIP entry index      
343     $b_first_deleted= false;  // Only delete first entry, 
344     $s_telenums     = "";     // for each value variable
346     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
348     restore_error_handler();
350     /* Prepare some basic attributes */
351     foreach($this->a_old_telenums as $tele){
352       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
353     }
354     foreach($this->phoneNumbers as $tele){
355       $newnums[]= preg_replace("/[^0-9]/","",$tele);
356     }
358     /* If deletion starts from userslist, cn uid are not set */
359     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
360       $this->uid = $this->parent->by_object['user']->uid;
361     }
362     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
363       $this->cn  = $this->parent->by_object['user']->cn;
364     }
365     /* Create voicemail entry 
366      */
367     if((!isset($this->cn))||(empty($this->cn))){
368       $CNname= $this->uid;
369     }else{
370       $CNname= $this->cn;
371     }
373     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
374       $s_mail = $this->parent->by_object['mailAccount']->mail;
375     }else{
376       $s_mail = "";
377     }
378     /* Get phonehardware to setup sip entry  */
379     $ldap         = $this->config->get_ldap_link();
380     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
381     $a_ldap_attrs = $ldap->fetch();
383     /* Check selected phone hardware, is a default IP set? */
384     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
385       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
386       $s_host     = $s_ip;
387     }else{
388       $s_ip       = NULL;
389       $s_host     = "dynamic";
390     }
392     // Attribute GoFonQualify set ?
393     if(isset($a_ldap_attrs['goFonQualify'])){
394       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
395     }
397     // Attribute GoFonPIN set ?
398     if(isset($this->goFonPIN)){
399       $s_pin      = $this->goFonPIN;
400     }
402     // Attribute GoFonType set ?
403     if(isset($a_ldap_attrs['goFonType'])){
404       $s_type = $a_ldap_attrs['goFonType'][0];
405     }
407     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
408       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
409     }else{
410       $sip_data_array['dtmfmode']     ="rfc2833";
411     }
413     /* Check if phone number is used */
414     if($this->is_number_used()){
415       $this->generate_error = $this->is_number_used(); 
416       return false;
417     }
421     /********************** 
422      * Check Server Connection Information
423      **********************/
424  
425     /* Create Mysql handle for the current goFonHomeServer, if possible  
426      * Get configuration to old asterisk home server 
427      */ 
428     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
429     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
430     if(!$new_connection){
431       $this->generate_error = sprintf(
432           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
433           $a_New['SERVER'],$a_New['LOGIN']);
434       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
435       return false;
436     }
437     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
438     if(!$new_database){
439       $this->generate_error = sprintf(
440           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
441           $a_New['DB'],$a_New['SERVER']);
442       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
443       return false;
444     }
446     /* If the home server has changed, we must remove entries from old 
447      *  server and add new entries in new server.  
448      */
449     if($this->init_HomeServer != $this->goFonHomeServer){
450     
451       /* Get configuration to old asterisk home server */ 
452       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
453  
454       /* Create connection to the database that contains the old entry. 
455        */
456       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
457       if(!$old_connection){
458         $this->generate_error = sprintf(
459             _("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."),
460             $a_Remove['SERVER'],$a_Remove['LOGIN']);
461         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
462         return false;
463       }
464       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
465       if(!$old_database){
466         $this->generate_error = sprintf(
467             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
468             $a_Remove['DB'],$a_Remove['SERVER']);
469         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
470         return false;
471       }
472     }
474     /* Save means that we must save changes, not only test  */
475     if($save == true){
476     
477       /********************** 
478        * Remove entries from old home server 
479        **********************/
481       /* Check if there is an old entry 
482        * If there is en old entry, get callerid and remove voicemail and extensions too 
483        */
484       if($old_connection){
485         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
486         $rid    = mysql_query($query,$old_connection);
488         /* Old entry found, remove it */
489         $query_a = array();
490         if(mysql_affected_rows($old_connection)){
491           $result = mysql_fetch_assoc($rid);
492           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
493           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
494           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
495           foreach($oldnums as $s_telenums) {
496             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
497           }
499           foreach($query_a as $qry){
500             if(!mysql_query($qry,$old_connection)){
501               echo $qry;
502               echo mysql_error($old_connection);
503             } 
504           }
505         }
506       }
508       /********************** 
509        * Update / Insert sip_users entry  
510        **********************/
512       /* Set the first given phone number as callerid */
513       reset($newnums);        
514       $i_new_key = key($newnums);
515       $sip_data_array['callerid']  =$newnums[$i_new_key];
516       $sip_data_array['mailbox']   =$newnums[$i_new_key];
518       /* Check if there is already an entry in sip_users for this uid */
519       $SQL_query_array = array();
520       $rid = mysql_query("SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n",$new_connection);
521       if(mysql_affected_rows($new_connection)){
523         /********************** 
524          * Update sip_users entry 
525          **********************/
526         $result                     = mysql_fetch_assoc($rid);
527         $sip_data_array['host']         = $s_host;
528         $sip_data_array['qualify']      = $s_qualify;
529         $sip_data_array['secret']       = $this->goFonPIN;
530         $sip_data_array['type']         = $s_type ;
531         $sip_data_array['username']     = $this->uid;
532         $sip_data_array['ipaddr']       = $s_ip;
534         /* Remove not changed attributes, to avoid updating table with same values */
535         foreach($sip_data_array as $name => $value){
536           if($result[$name] == $value){
537             unset($sip_data_array[$name]);
538           }
539         }
540         /* Only update entry if there is something to uopdate */
541         if(count($sip_data_array)){
542           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
543           foreach($sip_data_array as $key => $val){
544             $query.= "".$key."='".$val."',"; 
545           } 
546           $query = preg_replace("/,$/","",$query);
547           $query.= " WHERE name='".$this->uid."';";
548           $SQL_query_array[] = $query;
549         }
550       } else {
551  
552         /********************** 
553          * Insert sip_users entry 
554          **********************/
555         //generate SIP entry
556         $sip_data_array['id']           = "";
557         $sip_data_array['name']         = $this->uid;
558         $sip_data_array['accountcode']  = NULL;          
559         $sip_data_array['amaflags']     = NULL;
560         $sip_data_array['callgroup']    = NULL;
561         $sip_data_array['canreinvite']  = "no";
562         $sip_data_array['context']      = "default";
563         $sip_data_array['defaultip']    = NULL;
564         $sip_data_array['fromuser']     = NULL;
565         $sip_data_array['fromdomain']   = NULL;
566         $sip_data_array['host']         = $s_host;
567         $sip_data_array['insecure']     = NULL;
568         $sip_data_array['language']     = NULL;
569         $sip_data_array['mailbox']      = $newnums[$i_new_key];
570         $sip_data_array['md5secret']    = NULL;
571         $sip_data_array['nat']          = "no";
572         $sip_data_array['permit']       = NULL;
573         $sip_data_array['deny']         = NULL;
574         $sip_data_array['mask']         = NULL;
575         $sip_data_array['pickupgroup']  = NULL;
576         $sip_data_array['port']         = NULL;
577         $sip_data_array['qualify']      = $s_qualify;
578         $sip_data_array['restrictcid']  = "n";
579         $sip_data_array['rtptimeout']   = NULL;
580         $sip_data_array['rtpholdtimeout']=NULL;
581         $sip_data_array['secret']       = $this->goFonPIN;
582         $sip_data_array['type']         = $s_type ;
583         $sip_data_array['username']     = $this->uid;
584         $sip_data_array['disallow']     = NULL;
585         $sip_data_array['allow']        = NULL;
586         $sip_data_array['musiconhold']  = NULL;
587         $sip_data_array['regseconds']   = NULL;
588         $sip_data_array['ipaddr']       = $s_ip;
589         $sip_data_array['regexten']     = NULL;
590         $sip_data_array['cancallforward']=NULL;
592         /* There is currently no entry for this user in the sip_users table. 
593          * We should create one i
594          */
595         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
596           if($s_sip_val == NULL) continue;
597           $s_sip_values.="'".$s_sip_val."',";
598           $s_sip_keys  .="`".$s_sip_key."`,";
599         }
600         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
601         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
603         /* Add sip entries to mysql queries */
604         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
605       }
608       /********************** 
609        * Update / Insert Voice mail entry  
610        **********************/
612       $customer_id = $newnums[$i_new_key];
614       $voice_data_array = array(
615           "customer_id" => $customer_id,
616           "mailbox"     => $customer_id,
617           "password"    => $this->goFonVoicemailPIN,
618           "fullname"    => $CNname,
619           "email"       => $s_mail);
621       /* Set pager number if available */
622       if(isset($this->parent->by_object['user']->pager)){
623         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
624       }
626       /* Check if there is already an entry in sip_users for this uid */
627       $rid = mysql_query("SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n",$new_connection);
628       if(mysql_affected_rows($new_connection)){
630         /********************** 
631          * Update Voice mail entry  
632          **********************/
633         $result = mysql_fetch_assoc($rid)  ;
635         foreach($voice_data_array as $name => $value){
636           if($result[$name] == $value){
637             unset($voice_data_array[$name]);
638           }
639         }
641         /* Only update entry if there is something to uopdate */
642         if(count($voice_data_array)){
643           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
644           foreach($voice_data_array as $key => $val){
645             $query.= "".$key."='".$val."',"; 
646           } 
647           $query = preg_replace("/,$/","",$query);
648           $query.= " WHERE customer_id='".$customer_id."';";
649           $SQL_query_array[] = $query;
650         }
651       }else{
653         /********************** 
654          * Insert Voice mail entry  
655          **********************/
656         $voice_data_array['context'] = "default";
657   
658         /* There is currently no voice mail entry for this user. 
659          * We should create one 
660          */
661         $s_voi_values = $s_voi_keys = "";
662         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
663           if($s_voi_val == NULL) continue;
664           $s_voi_values.="'".$s_voi_val."',";
665           $s_voi_keys  .="`".$s_voi_key."`,";
666         }
667         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
668         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
670         /* Add sip entries to mysql queries */
671         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
672       }
674      
675       /********************** 
676        * Remove/Insert extension entries
677        **********************/
678       
679       /* Remove old entries */
680       $query = array();
681       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
682       foreach($newnums as $s_telenums){
683         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
684       }
685       foreach($query as $qry){
686         if(!mysql_query($qry,$new_connection)){
687           echo mysql_error($new_connection);
688         } 
689       }
690  
691       /********************** 
692        * Insert extension entries
693        **********************/
694  
695       // Get selected Macro Parameter and create parameter entry 
696       if(isset($this->macroarray[$this->macro])){
697         foreach($this->macroarray[$this->macro] as $key => $val ){
698           $s_parameter .= $val['choosen']."|";
699         }
700         $s_parameter = preg_replace("/\|$/","",$s_parameter);
701       }
702      
703       $i = 0; 
704       $EXT = array();
705       if(!is_numeric($this->uid)){
706         $EXT[$i]['context'] = 'GOsa';
707         $EXT[$i]['exten']   = $this->uid;
708         $EXT[$i]['priority']= 1;
709         $EXT[$i]['app']     = "Goto";
710         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
711         $i ++;
712       }
714       // Entension entries  Hint / Dial / Goto
715       foreach($newnums as $s_telenums){
717         /* Hint Entry */
718         $EXT[$i]['context'] = 'GOsa';
719         $EXT[$i]['exten']   = $s_telenums;
720         $EXT[$i]['priority']= "Hint";
721         $EXT[$i]['app']     = 'SIP/'.$this->uid;
722         $i ++;  
723         /* SetCID */
724         //$EXT[$i]['context'] = 'GOsa';
725         //$EXT[$i]['exten']   = $s_telenums;
726         //$EXT[$i]['priority']= 1;
727         //$EXT[$i]['app']     = "SetCIDName";
728         //$EXT[$i]['appdata'] = $CNname;
729         //$i ++;  
731         // If no macro is selected use Dial
732         if($this->macro!="none"){ 
733           $macroname = preg_replace("/,.*$/","",$this->macro);        
734           $macroname = preg_replace("/^.*=/","",$macroname);        
735           $s_app = "Macro";$macroname;
736           $s_par = $macroname."|".$s_parameter; 
737         }else{
738           $s_app = "Dial";
739           $s_par = 'SIP/'.$this->uid."|20|r";
740         }
742         $EXT[$i]['context'] = 'GOsa';
743         $EXT[$i]['exten']   = $s_telenums;
744         $EXT[$i]['priority']= 1;
745         $EXT[$i]['app']     = $s_app;
746         $EXT[$i]['appdata'] = $s_par;
747         $i ++;
748       }
750       // Append all these Entries 
751       foreach($EXT as $entr){
752         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
753         foreach($entr as $key2 => $val2){
754           $SQL_syn.= "`".$key2."`,";
755         }
756         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
757         $SQL_syn .= ") VALUES ("; 
758         foreach($entr as $key2 => $val2){
759           $SQL_syn .= "'".$val2."',";
760         }
761         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
762         $SQL_syn .=");\n";
764         $SQL_query_array[] =$SQL_syn;
765         $SQL_syn ="";
766       }
768       // Perform queries ...
769       if($this->goFonHardware != "automatic"){
770         foreach($SQL_query_array as $query){
771           if(!@mysql_query($query,$new_connection)){
772             print_red(_("Error while performing query:")." ".mysql_error());
773             return false;
774           }
775         }
776       }
777     }
778     @mysql_close($new_connection);
779     return true;
780   }
783   function execute()
784   {
785     /* Call parent execute */
786     plugin::execute();
788     /* Log view */
789     if($this->is_account && !$this->view_logged){
790       $this->view_logged = TRUE;
791       new log("view","users/".get_class($this),$this->dn);
792     }
794     $display = "";
795     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
796     if(empty($this->macro)&&(!empty($this->goFonMacro))){
798       /* Go through already saved values, for a parameter */
799       $tmp = split("!",$this->goFonMacro);
801       /* it is possible that nothing has been saved yet */
802       if(is_array($tmp)){
804         /* First value is the macroname */
805         $this->macro = $tmp[0];
807         /* Macroname saved, delete that index */
808         unset($tmp[0]);
810         /* Check if macro has been removed */
811         if(!isset($this->macroarray[$this->macro])){
812           $this->macrostillavailable = false;
813         }else{
814           $this->macrostillavailable = true;
815         }
817         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
818         foreach($tmp as $var){
820           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
821           $varar = split("#",$var);
823           /* Only insert if the parameter still exists */
824           if(isset($this->macroarray[$this->macro][$varar[0]])){
825             /* Assign value */
826             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
827           }
828         }
829       }
830     }
831     
832     /* Do we represent a valid account? */
833     if (!$this->is_account && $this->parent == NULL){
834       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
835         _("This account has no phone extensions.")."</b>";
836       $display.= back_to_main();
837       return ($display);
838     }
840     /* Do we need to flip is_account state? */
841     if (isset($_POST['modify_state'])){
842       $this->is_account= !$this->is_account;
843     }
845     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
846     if(empty($this->macro)){
847       $this->macro ="none";
848     }
850     /* Prepare templating */
851     $smarty= get_smarty();
853     /* tell user that the selected plugin is no longer available */
854     if((!$this->macrostillavailable)&&($this->macro!="none")){
855       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
856     }
858     /* Assing macroselectbox values  */
859     $smarty->assign("macros",$this->macros);   
860     $smarty->assign("macro", $this->macro);   
862     /* check if there is a FON server created */
863     if(!count($this->goFonHomeServer)){
864       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."));
865     }
867     /* Create html parameter table for selected macro parameters 
868      *  skip if no parameters given 
869      */
870     if(!isset($this->macroarray[$this->macro])){
871       $macrotab="";
872     }else{
874       $macrotab ="<table summary=\""._("Parameter")."\">";
875       /* for every single parameter-> display textfile,combo, or true false switch*/
877       foreach($this->phoneNumbers as $phonenum){
878         $tmp[] = $phonenum;
879       }
880     
881       if($this->macro != $this->lastmacro){
882         /* Go through all params */
883         foreach($this->macroarray[$this->macro] as $key => $paras){
885           $string = $paras['default'];
887           $string=preg_replace("/%uid/i",$this->uid,$string);
889           if(isset($this->cn)){
890             $string=preg_replace("/%cn/i",$this->cn,$string);
891           }
893           for($i = 0 ; $i < 10; $i++){
894             if(isset($tmp[$i])){
895               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
896             }
897           }
898           if(isset($tmp[0])){
899             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
900           }
901           $this->macroarray[$this->macro][$key]['choosen']=$string;
902         }
903       }
905       foreach($this->macroarray[$this->macro] as $paras){
907         /* get al vars */
908         $var        = $paras['var'];           
909         $name       = $paras['name'];           
910         $default    = $paras['default'];
911         $type       = $paras['type'];
912         $choosen    = $paras['choosen'] ; 
913         $str        = $default;
915         $dis = "";
916         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
917           $dis = " disabled ";
918         }
920         /* in case of a combo box display a combobox with selected attr */
921         $macrotab.= "<tr>";
922         switch ($type){
924           case "combo":
925             $str= "<select name='".$var."' ".$dis." >";
926           foreach(split(":",$default) as $choice){
927             if($choosen==$choice){
928               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
929             }else{
930               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
931             }
932           }
933           $str.="</select>";
934           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
935           break;
937           case "bool":
938             if(!$choosen){
939               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
940             }else{
941               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
942             }
943           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
944           break;
946           case "string":
947             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
948           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
949           break;
951         }
952         $macrotab.= "</td></tr>";
954       }
955       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
956     }//is_array()
958     /* Give smarty the table */
959     $smarty->assign("macrotab",$macrotab);
962     /* Do we represent a valid account? */
963     if (!$this->is_account && $this->parent == NULL){
964       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
965         _("This account has no phone extensions.")."</b>";
966       $display.= back_to_main();
967       return($display);
968     }
970     $display= "";
971  /* Show tab dialog headers */
972     if ($this->parent != NULL){
973       if ($this->is_account){
974         $display= $this->show_disable_header(_("Remove phone account"),
975             _("This account has phone features enabled. You can disable them by clicking below."));
976       } else {
977         if(empty($this->uid)){
978           $display= $this->show_enable_header(_("Create phone account"),
979               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
980         }else{
981           $display= $this->show_enable_header(_("Create phone account"),
982               _("This account has phone features disabled. You can enable them by clicking below."));
983         }
984         return ($display);
985       }
986     }
988     /* Add phone number */
989     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
990       if (is_phone_nr($_POST['phonenumber'])){
991         $number= $_POST["phonenumber"];
992         $this->phoneNumbers[$number]= $number;
993         $this->is_modified= TRUE;
994       } else {
995         print_red(_("Please enter a valid phone number!"));
996       }
997     }
999     /* Remove phone number */
1000     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1001       foreach ($_POST['phonenumber_list'] as $number){
1002         unset($this->phoneNumbers[$number]);
1003         $this->is_modified= TRUE;
1004       }
1005     }
1007     /* Assign acls */
1008     $tmp = $this->plInfo();
1009     foreach($tmp['plProvidedAcls'] as $name => $translation){
1010       $smarty->assign($name."ACL",$this->getacl($name));
1011     }
1013     /* Transfer ACL's */
1014     foreach($this->attributes as $val){
1015       if(isset($this->$val)){
1016         $smarty->assign($val,$this->$val);
1017       }else{
1018         $smarty->assign($val,"");
1019       }
1020     }
1022     /* Create home server array */
1023     $tmp = array();
1024     foreach($this->goFonHomeServers as $dn => $attrs){
1025       if(!is_numeric($dn)){
1026         $tmp[$dn] = $attrs['SERVER'];
1027       }
1028     }
1029     $smarty->assign("goFonHomeServers",$tmp);
1031     /* Fill arrays */
1032     $smarty->assign ("goFonHardware", $this->goFonHardware);
1033     if (!count($this->phoneNumbers)){
1034       $smarty->assign ("phoneNumbers", array());
1035     } else {
1036       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1037     }
1039     $dis = "";
1040     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1041       $dis= " disabled ";
1042     }
1043     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1044        _("Choose your private phone")."\">\n";
1046     foreach ($this->hardware_list as $cn => $description){
1047       if ($cn == $this->goFonHardware){
1048         $selected= "selected";
1049       } else {
1050         $selected= "";
1051       }
1052       if (isset($this->used_hardware[$cn])){
1053         $color= "style=\"color:#A0A0A0\"";
1054       } else {
1055         $color= "";
1056       }
1057       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1058     }
1059     $hl.= "</select>\n";
1060     $smarty->assign ("hardware_list", $hl);
1062     /* Show main page */
1063     $this->lastmacro = $this->macro;
1064     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1065     return($display);
1066   }
1069   function save_object()
1070   {
1071     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
1072     if (isset($_POST["phoneTab"])){
1073     
1074       plugin::save_object();
1076       /* Save checkbox */
1077       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1078       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1079         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1080           $tmp .= "M";
1081         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1082           $tmp  = preg_replace ("/M/","",$tmp);
1083         }
1084       }
1085       $this->goFonDeliveryMode= "[".$tmp."]";
1088       /* Every macro in the select box are available */
1089       if((isset($_POST['macro']))){
1090         $this->macrostillavailable=true;
1091       }
1093       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1094         $this->is_modified =true;
1095       }
1097       if(is_array($this->phoneNumbers)){
1098         foreach($this->phoneNumbers as $telenumms) {
1099           $nummsinorder[]=$telenumms; 
1100         }
1101       }else{
1102         $nummsinorder=array("");
1103       }
1106       /* get all Postvars */
1107       if(isset($this->macroarray[$this->macro])){
1109         if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1110           foreach($this->macroarray[$this->macro] as $key => $paras){
1112             $backup = $this->macroarray[$this->macro][$key];
1114             if(isset($_POST[$paras['var']])){
1115               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1116             }
1118             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1119                We need this code below to read and save checkboxes correct
1120              */
1122             if(isset($_POST['post_success'])){
1123               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1124                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1125                   $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1126                 }else{
1127                   $this->macroarray[$this->macro][$key]['choosen']=false;
1128                 }
1129               }
1130             }
1131           }
1132           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1133             $this->modified = TRUE;
1134           }
1135         }
1136       }
1137     }
1138   }
1140   function check()
1141   {
1142     /* Call common method to give check the hook */
1143     $message= plugin::check();
1145     if(!count($this->goFonHomeServers)){
1146       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1147     }
1149     if(empty($this->goFonHomeServer)){
1150       $message[] = _("Please select a valid goFonHomeServer.");
1151     }
1153     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1154       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1155     }else{
1156       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1157         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1158       }
1159     }
1161     if((strlen($this->goFonPIN)<=0)){
1162       $message[]=(_("Phone PIN must be at least one character long."));
1163     }else{
1164       if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1165         $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1166       }
1167     }
1169     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1170       if(!$this->generate_mysql_entension_entries()){
1171         $message[] = $this->generate_error;
1172       }
1173     }
1175     /* We need at least one phone number */
1176     if (count($this->phoneNumbers) == 0){
1177       $message[]= sprintf(_("You need to specify at least one phone number!"));
1178     }
1180     /* check for ! in any parameter setting*/
1181     if(isset($this->macroarray[$this->macro])){
1182       foreach($this->macroarray[$this->macro] as $val){
1183         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1184           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1185         }
1186       }
1187     }
1188     return ($message);
1189   }
1193   function save()
1194   {
1195     plugin::save();
1197     /* Force saving macro again 
1198      * This ensures that 
1199      *  - the macro is available on the destiantion server.
1200      *  - the macro saved is up to date on the destination server.
1201      */
1202     if(!empty($this->macro) && $this->macro != "none")  {
1203       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1204       $macro_tab -> save();
1205     }
1207     /* Save arrays */
1208     $tmp_numbers = array();
1209     foreach ($this->phoneNumbers as $number){
1210       $tmp_numbers[] = $number;
1211     }
1213     /* Save settings, or remove goFonMacro attribute*/
1214     if($this->macro!="none"){    
1215       $this->attrs['goFonMacro']=$this->macro;
1216       if(isset($this->macroarray[$this->macro])){
1217         foreach($this->macroarray[$this->macro] as $paras)  {
1218           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1219         }
1220       }
1221     }else{
1222       $this->attrs['goFonMacro']=array();
1223     }
1224     unset($this->attrs['macro'])  ;
1226     $this->attrs['goFonForwarding']=array();
1228     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1229       $str = $this->generate_mysql_entension_entries(true);
1230       if(empty($str)){
1231         print_red($str);
1232       }
1233     }
1235     if($this->attrs['goFonMacro']==""){
1236       $this->attrs['goFonMacro']=array();
1237     }
1239     unset($this->attrs['cn']);
1241     /* Write back to ldap */
1242     $ldap= $this->config->get_ldap_link();
1243     $ldap->cd($this->dn);
1244     $this->cleanup();
1245     
1246     /* Force saving numbers, else it will be overwriten by user account. */
1247     $this->attrs['telephoneNumber'] =$tmp_numbers;
1248     $ldap->modify ($this->attrs); 
1250     /* Log last action */
1251     if($this->initially_was_account){
1252       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1253     }else{
1254       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1255     }
1257     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/phone account with dn '%s' failed."),$this->dn));
1259     /* Optionally execute a command after we're done */
1261     if ($this->initially_was_account == $this->is_account){
1262       if ($this->is_modified){
1263         $this->handle_post_events("modify",array("uid" => $this->uid));
1264       }
1265     } else {
1266       $this->handle_post_events("add",array("uid" => $this->uid));
1267     }
1269   }
1272   function adapt_from_template($dn)
1273   {
1274     plugin::adapt_from_template($dn);
1276     /* Assemble phone numbers */
1277     if (isset($this->attrs['telephoneNumber'])){
1278       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1279         $number= $this->attrs['telephoneNumber'][$i];
1280         $this->phoneNumbers[$number]= $number;
1281       }
1282     }
1283   }
1286   function remove_from_parent()
1287   {
1288     if(!$this->initially_was_account) return;
1290     foreach($this->attributes as $key=>$val){
1291       if(in_array($val,array("uid","cn"))){
1292         unset($this->attributes[$key]);
1293         unset($this->$val);
1294       }
1295     }
1296     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1298       // Get Configuration for initial Mysql database Server
1299       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1300       $s_parameter  ="";
1302       // Connect to DB server
1303       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1305       // Check if we are  connected correctly
1306       if(!$r_con){
1307         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1308                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1309         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1310         return false;
1311       }
1313       // Select database for Extensions
1314       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1316       // Test if we have the database selected correctly
1317       if(!$db){
1318         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1319         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1320         return false;
1321       }
1323       $SQL="";
1325       /* If deletion starts from userslist, cn uid are not set */
1326       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1327         $this->uid = $this->parent->by_object['user']->uid;
1328       }
1330       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1331         $this->cn  = $this->parent->by_object['user']->cn;
1332       }
1334       $first_num = false;
1335       // Delete old entries
1336       foreach($this->a_old_telenums as $s_telenums){
1337         if(!$first_num){
1338           $first_num = $s_telenums;
1339         }
1340         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1341       }
1343       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1344       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1345       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1347       foreach($SQL as $query){
1348         if(!@mysql_query($query,$r_con)){
1349           print_red(_("Stop".mysql_error()));
1350           return false;
1351         }
1352       }
1353     }else{
1354       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1355       return false;
1356     }
1358     /* unset macro attr, it will cause an error */
1359     $tmp = array_flip($this->attributes);
1360     unset($tmp['macro']);
1361     $this->attributes=array_flip($tmp);
1363     /* Cancel if there's nothing to do here */
1364     if (!$this->initially_was_account){
1365       return;
1366     }
1368     plugin::remove_from_parent();
1370     /* Just keep one phone number */
1371     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1372       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1373     } else {
1374       $this->attrs['telephoneNumber']= array();
1375     }
1378     $ldap= $this->config->get_ldap_link();
1379     $ldap->cd($this->config->current['BASE']);
1380     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1381     while($attr = $ldap->fetch()){
1382       if(in_array($this->dn,$attr['member'])){
1383         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1384         unset($new->by_object['ogroup']->memberList[$this->dn]);
1385         unset($new->by_object['ogroup']->member[$this->dn]);
1386         $new->save();
1387         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1388       }
1389     }
1390     $ldap->cd($this->dn);
1391     $this->cleanup();
1392     $ldap->modify ($this->attrs); 
1394     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1395     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/phone account with dn '%s' failed."),$this->dn));
1397     /* Optionally execute a command after we're done */
1398     @mysql_close($r_con);
1399     $this->handle_post_events('remove',array("uid"=> $this->uid));
1400   }
1404   /* This function checks if the given phonenumbers are available or already in use*/
1405   function is_number_used()
1406   {
1407     $ldap= $this->config->get_ldap_link();
1408     $ldap->cd($this->config->current['BASE']);
1409     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1410     while($attrs = $ldap->fetch()) {
1411       unset($attrs['telephoneNumber']['count']);
1412       foreach($attrs['telephoneNumber'] as $tele){
1413         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1414         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1415         $numbers[$tele]=$attrs;
1416       }
1417     }
1419     foreach($this->phoneNumbers as $num){
1420       if(!isset($this->cn)) $this->cn = "";
1422       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1423         if(isset($numbers[$num]['uid'][0])){
1424           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1425         }else{
1426           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1427         }
1428       }
1429     }
1430   }
1433   /* Create phoneAccount part of copy & paste dialog */
1434   function getCopyDialog()
1435   { 
1436     if(!$this->is_account) return("");
1437     $smarty = get_smarty();
1438     if (!count($this->phoneNumbers)){
1439       $smarty->assign ("phoneNumbers", array(""));
1440     } else {
1441       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1442     }
1444     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1445     $smarty->assign("goFonPIN",$this->goFonPIN);
1447     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1448     $ret =array();
1449     $ret['string'] = $display;
1450     $ret['status'] = "";
1451     return($ret);
1452   }
1454   /* Save posts from copy & paste dialog dialog  */
1455   function saveCopyDialog()
1456   {
1457     if(!$this->is_account) return;
1458     $this->execute();
1459     if(isset($_POST['goFonVoicemailPIN'])) {
1460       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1461     }
1462     if(isset($_POST['goFonPIN'])){
1463       $this->goFonPIN = $_POST['goFonPIN'];
1464     }
1465   }
1468   function allow_remove()
1469   {
1470     /* Check if previously selected server is still available */
1471     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1472       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1473     }
1474   }
1476   /* Return plugin informations for acl handling */
1477   function plInfo()
1478   {
1479     return (array(
1480           "plShortName"     => _("Phone"),
1481           "plDescription"   => _("Phone account settings"),
1482           "plSelfModify"    => TRUE,
1483           "plDepends"       => array("user"),
1484           "plPriority"      => 7,                                 // Position in tabs
1485           "plSection"       => "personal",                        // This belongs to personal
1486           "plCategory"      => array("gofonreport" => array("description" => _("GOfon reports"),
1487               "objectClass" => "")),
1489           "plOptions"       => array(),
1491           "plProvidedAcls"  => array(
1492             "telephoneNumber"     => _("Telephone number"),
1493             "goFonHomeServer"     => _("Home server"),
1494             "goFonMacro"          => _("Macro settings"),
1495             "goFonHardware"       => _("Phone hardware"),
1496             "goFonPIN"            => _("Telephone pin"),
1497             "goFonVoicemailPIN"   => _("Voicemail pin"))
1498           ));
1499   }
1502 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1503 ?>