Code

ec07ef3ed2da32d702dc4f9642f47a77b8e548ab
[gosa.git] / gosa-core / 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;
50   var $multiple_support = TRUE;
52   function phoneAccount (&$config, $dn= NULL, $parent= NULL)
53   {
54     plugin::plugin ($config, $dn, $parent);
56     /* Assemble phone numbers */
57     if (isset($this->attrs['telephoneNumber'])){
58       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
59         $number= $this->attrs['telephoneNumber'][$i];
60         $this->phoneNumbers[$number]= $number;
61       }
62     }
64     /* Set up has_mailAccount */
65     if (isset($this->attrs['objectClass'])){
66       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
67         $this->has_mailAccount= TRUE;
68       }
69     }
71     /* Set uid */
72     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
73       $this->uid = $this->parent->by_object['user']->uid;
74     }
75     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
76       $this->cn  = $this->parent->by_object['user']->cn;
77     }
79     /* Check server configurations 
80      * Load all server configuration in $this->goFonHomeServers if available
81      *  and first server as default if necessary.
82      * Check if connection is successfull for the selected server $this->goFonHomeServer
83      */
85   
86     /* Set available server */
87     if(isset($_SESSION['config']->data['SERVERS']['FON'])){
88       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
89     }
91     $a_SETUP= array();
92     if($this->is_account &&
93        array_key_exists('config',$_SESSION) &&
94        array_key_exists('SERVERS',$_SESSION['config']->data) &&
95        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
96        is_callable("mysql_connect")
97        ) {
99       /* Servers defined? Watch here... */
100       if (count($this->goFonHomeServers)){
102         /* Set default server */
103         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
104           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
105         }
107         /* Remember inital home server, to be able to remove old entries */
108         $this->init_HomeServer = $this->goFonHomeServer;
110         /* Get config */
111         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
112           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']));
114           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
115           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
116         }    
117         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
119         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
120         if(!$r_con){
121 #          print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
122 #                $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
123           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
124         }
125         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
126         if(!$db){
127 #          print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
128           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
129         }
131         $first = false; 
132         foreach($this->phoneNumbers as $key => $val){
133           if(!$first){
134             $first = $key;
135           }
136         }
137       }
138     }
140     /* Get available phone hardware  
141      * Search for all available phone hardware  
142      */
143     $ldap= $this->config->get_ldap_link();
144     $ldap->cd($this->config->current['BASE']);
145     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
146     while ($attrs= $ldap->fetch()){
147       $cn= $attrs['cn'][0];
148       if (isset($attrs['description'])){
149         $description= " - ".$attrs['description'][0];
150       } else {
151         $description= "";
152       }
153       $this->hardware_list[$cn]= "$cn$description";
154     }
157     /* Get available Macros  
158      * Search for all Marcos that are visible and create 
159      *  an array with name and parameters 
160      */
161     $ldap->search("(&(objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
163     /* Add none for no macro*/
164     $this->macros['none']=_("no macro");    
165     $this->macro ="none";
167     /* Fetch all Macros*/
168     while ($attrs= $ldap->fetch()){
170       /* unset Count, we don't need that here */
171       unset($attrs['displayName']['count']);
173       /* Parse macro data, unset count for parameterarrays  */
174       if (isset($attrs['goFonMacroParameter']['count'])){
175         unset($attrs['goFonMacroParameter']['count']);
176       }
178       /* fill Selectfield variable with Macros */
179       if(isset($attrs['displayName'][0])){
180         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
181       }else{
182         $this->macros[$attrs['dn']] = _("undefined");
183       }
185       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
186       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
188         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
189           /* Split Data in readable values, by delimiter !  */
190           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
192           /* Set all attrs */
193           $id = $data[0];
194           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
195           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
196           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
197           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
198           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
199           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
200           if($data[2] == "bool"){
201             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
202           }
203         }//foreach
204       }//is_array
205     }//while
208     /* Parse used Macro  
209      * If we have a macro selected, parse it and set values 
210      *  in $this->macroarray[$this->macro]. 
211      */
212     $tmp = split("!",$this->goFonMacro);
213     if(is_array($tmp)){
215       /* First value is the macroname */
216       $this->macro = $tmp[0];
218       /* Macroname saved, delete that index */
219       unset($tmp[0]);
221       /* Check if makro has been removed */
222       if(!isset($this->macros[$this->macro])){
223         $this->macrostillavailable = false;
224         echo "1";
225       }else{
226         $this->macrostillavailable = true;
227       }
229       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
230       foreach($tmp as $var){
232         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
233         $varar = split("#",$var);
235         /* Only insert if the parameter still exists */
236         if(isset($this->macroarray[$this->macro][$varar[0]])){
237           /* Assign value */
238           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
239         }
240       }
241     }
244     /* Colorize phones 
245      * Used phones will be colored in grey, 
246      *  so we must detect which phones are currently in use.
247      */
248     $ldap->cd($this->config->current['BASE']);
249     $ldap->search("(goFonHardware=*)",array('cn','dn','goFonHardware'));
250     while($attrs = $ldap->fetch()){
251         $cn = $attrs['goFonHardware'][0];
252         if(isset($this->hardware_list[$cn])){
253           $this->used_hardware[$cn]= $cn;
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   
271         $query_tmp = "SELECT ".$cur_cfg['VOICE_TABLE'].".password FROM  ".$cur_cfg['VOICE_TABLE'].", ".
272                      $cur_cfg['SIP_TABLE']."  WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'";
274         $vp = mysql_fetch_row(mysql_query($query_tmp));
275         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
276         if((isset($vp[0]))&&(!empty($vp[0]))){
277           $this->goFonPINVoice = $vp[0];
278         }
279       }
280     }
281     $this->lastmacro=$this->macro;
283     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
284       @mysql_close($r_con) ;
285     }
286   }
289   /* This function generates the Database entries. 
290    * The Parameter 'save' could be true or false.
291    *  false - means only testing no database transactions.
292    *  true  - write database entries.
293    *
294    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
295    * 
296    * If the phone hardware is 'automatic' the table entries will only be removed
297    *  and not added. 
298    */
299   function generate_mysql_entension_entries($save = false)
300   {
301     /* Check if there is at least one server available 
302      * If not, return and tell the user that saving failed 
303      */
304     if(!count($this->goFonHomeServers)){
305       if($save){
306         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."));
307       }
308       return(true);
309     }
311     /* Check if Mysql extension is available */
312     if(!is_callable("mysql_pconnect")){
313       if($save)
314       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
315       return(true);
316     }
317  
318     /********************** 
319      * Attribute Initialisation
320      **********************/
322     $old_connection = false;
324     // Get Configuration for Mysql database Server
325     $s_parameter    = "";                                           // Contains paramter for selected Macro 
326     $r_con          = false;                                        // DB connection
327     $r_db           = false;                                        // Selected DB
328     $r_res          = false;                                        // Result resource
329     $a_ldap_attrs   = array();                                      //  
331     $s_ip           = NULL;                   // Contains ip for Sip entry
332     $s_host         = NULL;                   // Contains host for Sip entry
333     $s_qualify      = "yes";                  // Qualify entry
334     $s_pin          = NULL;                   // Entry for secret
335     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
337     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
338     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
339     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
341     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
342     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
344     $s_sip_key      = "";     // Key for SIP entry index      
345     $s_sip_val      = "";     // Value for SIP entry index      
347     $b_first_deleted= false;  // Only delete first entry, 
348     $s_telenums     = "";     // for each value variable
350     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
352     restore_error_handler();
354     /* Prepare some basic attributes */
355     foreach($this->a_old_telenums as $tele){
356       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
357     }
358     foreach($this->phoneNumbers as $tele){
359       $newnums[]= preg_replace("/[^0-9]/","",$tele);
360     }
362     /* If deletion starts from userslist, cn uid are not set */
363     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
364       $this->uid = $this->parent->by_object['user']->uid;
365     }
366     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
367       $this->cn  = $this->parent->by_object['user']->cn;
368     }
369     /* Create voicemail entry 
370      */
371     if((!isset($this->cn))||(empty($this->cn))){
372       $CNname= $this->uid;
373     }else{
374       $CNname= $this->cn;
375     }
377     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
378       $s_mail = $this->parent->by_object['mailAccount']->mail;
379     }else{
380       $s_mail = "";
381     }
382     /* Get phonehardware to setup sip entry  */
383     $ldap         = $this->config->get_ldap_link();
384     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
385     $a_ldap_attrs = $ldap->fetch();
387     /* Check selected phone hardware, is a default IP set? */
388     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
389       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
390       $s_host     = $s_ip;
391     }else{
392       $s_ip       = NULL;
393       $s_host     = "dynamic";
394     }
396     // Attribute GoFonQualify set ?
397     if(isset($a_ldap_attrs['goFonQualify'])){
398       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
399     }
401     // Attribute GoFonPIN set ?
402     if(isset($this->goFonPIN)){
403       $s_pin      = $this->goFonPIN;
404     }
406     // Attribute GoFonType set ?
407     if(isset($a_ldap_attrs['goFonType'])){
408       $s_type = $a_ldap_attrs['goFonType'][0];
409     }
411     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
412       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
413     }else{
414       $sip_data_array['dtmfmode']     ="rfc2833";
415     }
417     /* Check if phone number is used */
418     if($this->is_number_used()){
419       $this->generate_error = $this->is_number_used(); 
420       return false;
421     }
425     /********************** 
426      * Check Server Connection Information
427      **********************/
428  
429     /* Create Mysql handle for the current goFonHomeServer, if possible  
430      * Get configuration to old asterisk home server 
431      */ 
432     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
433     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
434     if(!$new_connection){
435       $this->generate_error = sprintf(
436           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
437           $a_New['SERVER'],$a_New['LOGIN']);
438       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
439       return false;
440     }
441     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
442     if(!$new_database){
443       $this->generate_error = sprintf(
444           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
445           $a_New['DB'],$a_New['SERVER']);
446       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
447       return false;
448     }
450     /* If the home server has changed, we must remove entries from old 
451      *  server and add new entries in new server.  
452      */
453     if($this->init_HomeServer != $this->goFonHomeServer){
454     
455       /* Get configuration to old asterisk home server */ 
456       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
457  
458       /* Create connection to the database that contains the old entry. 
459        */
460       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
461       if(!$old_connection){
462         $this->generate_error = sprintf(
463             _("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."),
464             $a_Remove['SERVER'],$a_Remove['LOGIN']);
465         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
466         return false;
467       }
468       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
469       if(!$old_database){
470         $this->generate_error = sprintf(
471             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
472             $a_Remove['DB'],$a_Remove['SERVER']);
473         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
474         return false;
475       }
476     }
478     /* Save means that we must save changes, not only test  */
479     if($save == true){
480     
481       /********************** 
482        * Remove entries from old home server 
483        **********************/
485       /* Check if there is an old entry 
486        * If there is an old entry, get callerid and remove voicemail and extensions 
487        */
488       if($old_connection){
489         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
490         $rid    = mysql_query($query,$old_connection);
491         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
493         /* Old entry found, remove it */
494         $query_a = array();
495         if(mysql_affected_rows($old_connection)){
496           $result = mysql_fetch_assoc($rid);
497           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
498           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
499           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
500           foreach($oldnums as $s_telenums) {
501             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
502           }
504           foreach($query_a as $qry){
505                   @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
506             if(!mysql_query($qry,$old_connection)){
507               echo mysql_error($old_connection);
508             } 
509           }
510         }
511       }
513       /********************** 
514        * Update / Insert sip_users entry  
515        **********************/
517       /* Set the first given phone number as callerid */
518       reset($newnums);        
519       $i_new_key = key($newnums);
520       $sip_data_array['callerid']  =$newnums[$i_new_key];
521       $sip_data_array['mailbox']   =$newnums[$i_new_key];
523       /* Check if there is already an entry in sip_users for this uid */
524       $SQL_query_array = array();
525       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
526       $rid = mysql_query($query,$new_connection);
527       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
528       if(mysql_affected_rows($new_connection)){
530         /********************** 
531          * Update sip_users entry 
532          **********************/
533         $result                     = mysql_fetch_assoc($rid);
534         $sip_data_array['host']         = $s_host;
535         $sip_data_array['qualify']      = $s_qualify;
536         $sip_data_array['secret']       = $this->goFonPIN;
537         $sip_data_array['type']         = $s_type ;
538         $sip_data_array['username']     = $this->uid;
539         $sip_data_array['ipaddr']       = $s_ip;
541         /* Remove not changed attributes, to avoid updating table with same values */
542         foreach($sip_data_array as $name => $value){
543           if($result[$name] == $value){
544             unset($sip_data_array[$name]);
545           }
546         }
547         /* Only update entry if there is something to uopdate */
548         if(count($sip_data_array)){
549           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
550           foreach($sip_data_array as $key => $val){
551             $query.= "".$key."='".$val."',"; 
552           } 
553           $query = preg_replace("/,$/","",$query);
554           $query.= " WHERE name='".$this->uid."';";
555           $SQL_query_array[] = $query;
556         }
557       } else {
558  
559         /********************** 
560          * Insert sip_users entry 
561          **********************/
562         //generate SIP entry
563         $sip_data_array['id']           = "";
564         $sip_data_array['name']         = $this->uid;
565         $sip_data_array['accountcode']  = NULL;          
566         $sip_data_array['amaflags']     = NULL;
567         $sip_data_array['callgroup']    = NULL;
568         $sip_data_array['canreinvite']  = "no";
569         $sip_data_array['context']      = "default";
570         $sip_data_array['defaultip']    = NULL;
571         $sip_data_array['fromuser']     = NULL;
572         $sip_data_array['fromdomain']   = NULL;
573         $sip_data_array['host']         = $s_host;
574         $sip_data_array['insecure']     = NULL;
575         $sip_data_array['language']     = NULL;
576         $sip_data_array['mailbox']      = $newnums[$i_new_key];
577         $sip_data_array['md5secret']    = NULL;
578         $sip_data_array['nat']          = "no";
579         $sip_data_array['permit']       = NULL;
580         $sip_data_array['deny']         = NULL;
581         $sip_data_array['mask']         = NULL;
582         $sip_data_array['pickupgroup']  = NULL;
583         $sip_data_array['port']         = NULL;
584         $sip_data_array['qualify']      = $s_qualify;
585         $sip_data_array['restrictcid']  = "n";
586         $sip_data_array['rtptimeout']   = NULL;
587         $sip_data_array['rtpholdtimeout']=NULL;
588         $sip_data_array['secret']       = $this->goFonPIN;
589         $sip_data_array['type']         = $s_type ;
590         $sip_data_array['username']     = $this->uid;
591         $sip_data_array['disallow']     = NULL;
592         $sip_data_array['allow']        = NULL;
593         $sip_data_array['musiconhold']  = NULL;
594         $sip_data_array['regseconds']   = NULL;
595         $sip_data_array['ipaddr']       = $s_ip;
596         $sip_data_array['regexten']     = NULL;
597         $sip_data_array['cancallforward']=NULL;
599         /* There is currently no entry for this user in the sip_users table. 
600          * We should create one i
601          */
602         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
603           if($s_sip_val === NULL) continue;
604           $s_sip_values.="'".$s_sip_val."',";
605           $s_sip_keys  .="`".$s_sip_key."`,";
606         }
607         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
608         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
610         /* Add sip entries to mysql queries */
611         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
612       }
615       /********************** 
616        * Update / Insert Voice mail entry  
617        **********************/
619       $customer_id = $newnums[$i_new_key];
621       $voice_data_array = array(
622           "customer_id" => $customer_id,
623           "mailbox"     => $customer_id,
624           "password"    => $this->goFonVoicemailPIN,
625           "fullname"    => $CNname,
626           "email"       => $s_mail);
628       /* Set pager number if available */
629       if(isset($this->parent->by_object['user']->pager)){
630         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
631       }
633       /* Check if there is already an entry in sip_users for this uid */
634       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n";
635       $rid = mysql_query($query_tmp,$new_connection);
636       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
637       if(mysql_affected_rows($new_connection)){
639         /********************** 
640          * Update Voice mail entry  
641          **********************/
642         $result = mysql_fetch_assoc($rid)  ;
644         foreach($voice_data_array as $name => $value){
645           if($result[$name] == $value){
646             unset($voice_data_array[$name]);
647           }
648         }
650         /* Only update entry if there is something to uopdate */
651         if(count($voice_data_array)){
652           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
653           foreach($voice_data_array as $key => $val){
654             $query.= "".$key."='".$val."',"; 
655           } 
656           $query = preg_replace("/,$/","",$query);
657           $query.= " WHERE customer_id='".$customer_id."';";
658           $SQL_query_array[] = $query;
659         }
660       }else{
662         /********************** 
663          * Insert Voice mail entry  
664          **********************/
665         $voice_data_array['context'] = "default";
666   
667         /* There is currently no voice mail entry for this user. 
668          * We should create one 
669          */
670         $s_voi_values = $s_voi_keys = "";
671         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
672           if($s_voi_val === NULL) continue;
673           $s_voi_values.="'".$s_voi_val."',";
674           $s_voi_keys  .="`".$s_voi_key."`,";
675         }
676         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
677         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
679         /* Add sip entries to mysql queries */
680         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
681       }
683      
684       /********************** 
685        * Remove/Insert extension entries
686        **********************/
687       
688       /* Remove old entries */
689       $query = array();
690       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
691       foreach($oldnums as $s_telenums){
692         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
693       }
694       foreach($newnums as $s_telenums){
695         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
696       }
697       foreach($query as $qry){
698         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
699         if(!mysql_query($qry,$new_connection)){
700           echo mysql_error($new_connection);
701         } 
702       }
703  
704       /********************** 
705        * Insert extension entries
706        **********************/
707  
708       // Get selected Macro Parameter and create parameter entry 
709       if(isset($this->macroarray[$this->macro])){
710         foreach($this->macroarray[$this->macro] as $key => $val ){
711           $s_parameter .= $val['choosen']."|";
712         }
713         $s_parameter = preg_replace("/\|$/","",$s_parameter);
714       }
715      
716       $i = 0; 
717       $EXT = array();
718       if(!is_numeric($this->uid)){
719         $EXT[$i]['context'] = 'GOsa';
720         $EXT[$i]['exten']   = $this->uid;
721         $EXT[$i]['priority']= 1;
722         $EXT[$i]['app']     = "Goto";
723         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
724         $i ++;
725       }
727       // Entension entries  Hint / Dial / Goto
728       foreach($newnums as $s_telenums){
730         /* Hint Entry */
731         $EXT[$i]['context'] = 'GOsa';
732         $EXT[$i]['exten']   = $s_telenums;
733         $EXT[$i]['priority']= "Hint";
734         $EXT[$i]['app']     = 'SIP/'.$this->uid;
735         $i ++;  
736         /* SetCID */
737         //$EXT[$i]['context'] = 'GOsa';
738         //$EXT[$i]['exten']   = $s_telenums;
739         //$EXT[$i]['priority']= 1;
740         //$EXT[$i]['app']     = "SetCIDName";
741         //$EXT[$i]['appdata'] = $CNname;
742         //$i ++;  
744         // If no macro is selected use Dial
745         if($this->macro!="none"){ 
746           $macroname = preg_replace("/,.*$/","",$this->macro);        
747           $macroname = preg_replace("/^.*=/","",$macroname);        
748           $s_app = "Macro";$macroname;
749           $s_par = $macroname."|".$s_parameter; 
750         }else{
751           $s_app = "Dial";
752           $s_par = 'SIP/'.$this->uid."|20|r";
753         }
755         $EXT[$i]['context'] = 'GOsa';
756         $EXT[$i]['exten']   = $s_telenums;
757         $EXT[$i]['priority']= 1;
758         $EXT[$i]['app']     = $s_app;
759         $EXT[$i]['appdata'] = $s_par;
760         $i ++;
761       }
763       // Append all these Entries 
764       foreach($EXT as $entr){
765         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
766         foreach($entr as $key2 => $val2){
767           $SQL_syn.= "`".$key2."`,";
768         }
769         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
770         $SQL_syn .= ") VALUES ("; 
771         foreach($entr as $key2 => $val2){
772           $SQL_syn .= "'".$val2."',";
773         }
774         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
775         $SQL_syn .=");\n";
777         $SQL_query_array[] =$SQL_syn;
778         $SQL_syn ="";
779       }
781       // Perform queries ...
782       if($this->goFonHardware != "automatic"){
783         foreach($SQL_query_array as $query){
784           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
785           if(!@mysql_query($query,$new_connection)){
786             print_red(_("Error while performing query:")." ".mysql_error());
787             return false;
788           }
789         }
790       }
791     }
792     @mysql_close($new_connection);
793     return true;
794   }
797   function execute()
798   {
799     /* Call parent execute */
800     plugin::execute();
802     /* Log view */
803     if($this->is_account && !$this->view_logged){
804       $this->view_logged = TRUE;
805       new log("view","users/".get_class($this),$this->dn);
806     }
808     $display = "";
809     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
810     if(empty($this->macro)&&(!empty($this->goFonMacro))){
812       /* Go through already saved values, for a parameter */
813       $tmp = split("!",$this->goFonMacro);
815       /* it is possible that nothing has been saved yet */
816       if(is_array($tmp)){
818         /* First value is the macroname */
819         $this->macro = $tmp[0];
821         /* Macroname saved, delete that index */
822         unset($tmp[0]);
824         /* Check if macro has been removed */
825         if(!isset($this->macroarray[$this->macro])){
826           $this->macrostillavailable = false;
827         echo "2";
828         }else{
829           $this->macrostillavailable = true;
830         }
832         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
833         foreach($tmp as $var){
835           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
836           $varar = split("#",$var);
838           /* Only insert if the parameter still exists */
839           if(isset($this->macroarray[$this->macro][$varar[0]])){
840             /* Assign value */
841             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
842           }
843         }
844       }
845     }
846     
847     /* Do we represent a valid account? */
848     if (!$this->is_account && $this->parent === NULL){
849       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
850         _("This account has no phone extensions.")."</b>";
851       $display.= back_to_main();
852       return ($display);
853     }
855     /* Do we need to flip is_account state? */
856     if (isset($_POST['modify_state'])){
857       $this->is_account= !$this->is_account;
858     }
860     /* Do we represent a valid account? */
861     if (!$this->is_account && $this->parent === NULL){
862       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
863         _("This account has no phone extensions.")."</b>";
864       $display.= back_to_main();
865       return($display);
866     }
868     $display= "";
870     /* Show tab dialog headers */
871     
872     if (!$this->multiple_support_active && $this->parent !== NULL){
873       if ($this->is_account){
874         $display= $this->show_disable_header(_("Remove phone account"),
875             _("This account has phone features enabled. You can disable them by clicking below."));
876       } else {
877         if(empty($this->uid)){
878           $display= $this->show_enable_header(_("Create phone account"),
879               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
880         }else{
881           $display= $this->show_enable_header(_("Create phone account"),
882               _("This account has phone features disabled. You can enable them by clicking below."));
883         }
884         return ($display);
885       }
886     }
887     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
888     if(empty($this->macro)){
889       $this->macro ="none";
890     }
892     /* Prepare templating */
893     $smarty= get_smarty();
895     /* tell user that the selected plugin is no longer available */
896     if((!$this->macrostillavailable)&&($this->macro!="none")){
897       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
898     }
900     /* Assing macroselectbox values  */
901     $smarty->assign("macros",$this->macros);   
902     $smarty->assign("macro", $this->macro);   
904     /* check if there is a FON server created */
905     if(!count($this->goFonHomeServer)){
906       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."));
907     }
909     /* Create html parameter table for selected macro parameters 
910      *  skip if no parameters given 
911      */
912     if(!isset($this->macroarray[$this->macro])){
913       $macrotab="";
914     }else{
916       $macrotab ="<table summary=\""._("Parameter")."\">";
917       /* for every single parameter-> display textfile,combo, or true false switch*/
919       foreach($this->phoneNumbers as $phonenum){
920         $tmp[] = $phonenum;
921       }
922     
923       if($this->macro != $this->lastmacro){
924         /* Go through all params */
925         foreach($this->macroarray[$this->macro] as $key => $paras){
927           $string = $paras['default'];
929           $string=preg_replace("/%uid/i",$this->uid,$string);
931           if(isset($this->cn)){
932             $string=preg_replace("/%cn/i",$this->cn,$string);
933           }
935           for($i = 0 ; $i < 10; $i++){
936             if(isset($tmp[$i])){
937               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
938             }
939           }
940           if(isset($tmp[0])){
941             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
942           }
943           $this->macroarray[$this->macro][$key]['choosen']=$string;
944         }
945       }
947       foreach($this->macroarray[$this->macro] as $paras){
949         /* get al vars */
950         $var        = $paras['var'];           
951         $name       = $paras['name'];           
952         $default    = $paras['default'];
953         $type       = $paras['type'];
954         $choosen    = $paras['choosen'] ; 
955         $str        = $default;
957         $dis = "";
958         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
959           $dis = " disabled ";
960         }
962         /* in case of a combo box display a combobox with selected attr */
963         $macrotab.= "<tr>";
964         switch ($type){
966           case "combo":
967             $str= "<select name='".$var."' ".$dis." >";
968           foreach(split(":",$default) as $choice){
969             if($choosen==$choice){
970               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
971             }else{
972               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
973             }
974           }
975           $str.="</select>";
976           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
977           break;
979           case "bool":
980             if(!$choosen){
981               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
982             }else{
983               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
984             }
985           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
986           break;
988           case "string":
989             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
990           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
991           break;
993         }
994         $macrotab.= "</td></tr>";
996       }
997       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
998     }//is_array()
1000     /* Give smarty the table */
1001     $smarty->assign("macrotab",$macrotab);
1004     /* Add phone number */
1005     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1006       if (is_phone_nr($_POST['phonenumber'])){
1007         $number= $_POST["phonenumber"];
1008         $this->phoneNumbers[$number]= $number;
1009         $this->is_modified= TRUE;
1010       } else {
1011         print_red(_("Please enter a valid phone number!"));
1012       }
1013     }
1015     /* Remove phone number */
1016     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1017       foreach ($_POST['phonenumber_list'] as $number){
1018         unset($this->phoneNumbers[$number]);
1019         $this->is_modified= TRUE;
1020       }
1021     }
1023     /* Assign acls */
1024     $tmp = $this->plInfo();
1025     foreach($tmp['plProvidedAcls'] as $name => $translation){
1026       $smarty->assign($name."ACL",$this->getacl($name));
1027     }
1029     /* Transfer ACL's */
1030     foreach($this->attributes as $val){
1031       if(isset($this->$val)){
1032         $smarty->assign($val,$this->$val);
1033       }else{
1034         $smarty->assign($val,"");
1035       }
1036     }
1038     /* Create home server array */
1039     $tmp = array();
1040     foreach($this->goFonHomeServers as $dn => $attrs){
1041       if(!is_numeric($dn)){
1042         $tmp[$dn] = $attrs['SERVER'];
1043       }
1044     }
1045     $smarty->assign("goFonHomeServers",$tmp);
1047     /* Fill arrays */
1048     $smarty->assign ("goFonHardware", $this->goFonHardware);
1049     if (!count($this->phoneNumbers)){
1050       $smarty->assign ("phoneNumbers", array());
1051     } else {
1052       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1053     }
1055     $dis = "";
1056     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1057       $dis= " disabled ";
1058     }
1059     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1060        _("Choose your private phone")."\">\n";
1062     foreach ($this->hardware_list as $cn => $description){
1063       if ($cn == $this->goFonHardware){
1064         $selected= "selected";
1065       } else {
1066         $selected= "";
1067       }
1068       if (isset($this->used_hardware[$cn])){
1069         $color= "style=\"color:#A0A0A0\"";
1070       } else {
1071         $color= "";
1072       }
1073       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1074     }
1075     $hl.= "</select>\n";
1076     $smarty->assign ("hardware_list", $hl);
1079     foreach($this->attributes as $attr){
1080       if(in_array($attr,$this->multi_boxes)){
1081         $smarty->assign("use_".$attr,TRUE);
1082       }else{
1083         $smarty->assign("use_".$attr,FALSE);
1084       }
1085     }
1087     /* Show main page */
1088     $this->lastmacro = $this->macro;
1089     $smarty->assign("multiple_support",$this->multiple_support_active);
1090     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1091     return($display);
1092   }
1095   function save_object()
1096   {
1097     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
1098     if (isset($_POST["phoneTab"])){
1099     
1100       plugin::save_object();
1102       /* Save checkbox */
1103       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1104       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1105         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1106           $tmp .= "M";
1107         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1108           $tmp  = preg_replace ("/M/","",$tmp);
1109         }
1110       }
1111       $this->goFonDeliveryMode= "[".$tmp."]";
1114       /* Every macro in the select box are available */
1115       if((isset($_POST['macro']))){
1116         $this->macrostillavailable=true;
1117       }
1119       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1120         $this->is_modified =true;
1121       }
1123       if(is_array($this->phoneNumbers)){
1124         foreach($this->phoneNumbers as $telenumms) {
1125           $nummsinorder[]=$telenumms; 
1126         }
1127       }else{
1128         $nummsinorder=array("");
1129       }
1132       /* get all Postvars */
1133       if(isset($this->macroarray[$this->macro])){
1135         if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1136           foreach($this->macroarray[$this->macro] as $key => $paras){
1138             $backup = $this->macroarray[$this->macro][$key];
1140             if(isset($_POST[$paras['var']])){
1141               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1142             }
1144             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1145                We need this code below to read and save checkboxes correct
1146              */
1148             if(isset($_POST['post_success'])){
1149               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1150                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1151                   $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1152                 }else{
1153                   $this->macroarray[$this->macro][$key]['choosen']=false;
1154                 }
1155               }
1156             }
1157           }
1158           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1159             $this->modified = TRUE;
1160           }
1161         }
1162       }
1163     }
1164   }
1166   function check()
1167   {
1168     /* Call common method to give check the hook */
1169     $message= plugin::check();
1171     if(!count($this->goFonHomeServers)){
1172       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1173     }
1175     if(empty($this->goFonHomeServer)){
1176       $message[] = _("Please select a valid goFonHomeServer.");
1177     }
1179     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1180       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1181     }else{
1182       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1183         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1184       }
1185     }
1187     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1188       $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1189     }
1191     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1192       if(!$this->generate_mysql_entension_entries()){
1193         $message[] = $this->generate_error;
1194       }
1195     }
1197     /* We need at least one phone number */
1198     if (count($this->phoneNumbers) == 0){
1199       $message[]= sprintf(_("You need to specify at least one phone number!"));
1200     }
1202     /* check for ! in any parameter setting*/
1203     if(isset($this->macroarray[$this->macro])){
1204       foreach($this->macroarray[$this->macro] as $val){
1205         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1206           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1207         }
1208       }
1209     }
1210     return ($message);
1211   }
1215   function save()
1216   {
1217     plugin::save();
1219     /* Force saving macro again 
1220      * This ensures that 
1221      *  - the macro is available on the destiantion server.
1222      *  - the macro saved is up to date on the destination server.
1223      */
1224     if(!empty($this->macro) && $this->macro != "none")  {
1225       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1226       $macro_tab -> save();
1227     }
1229     /* Save arrays */
1230     $tmp_numbers = array();
1231     foreach ($this->phoneNumbers as $number){
1232       $tmp_numbers[] = $number;
1233     }
1235     /* Save settings, or remove goFonMacro attribute*/
1236     if($this->macro!="none"){    
1237       $this->attrs['goFonMacro']=$this->macro;
1238       if(isset($this->macroarray[$this->macro])){
1239         foreach($this->macroarray[$this->macro] as $paras)  {
1240           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1241         }
1242       }
1243     }else{
1244       $this->attrs['goFonMacro']=array();
1245     }
1246     unset($this->attrs['macro'])  ;
1248     $this->attrs['goFonForwarding']=array();
1250     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1251       $str = $this->generate_mysql_entension_entries(true);
1252       if(empty($str)){
1253         print_red($str);
1254       }
1255     }
1257     if($this->attrs['goFonMacro']==""){
1258       $this->attrs['goFonMacro']=array();
1259     }
1261     unset($this->attrs['cn']);
1263     /* Write back to ldap */
1264     $ldap= $this->config->get_ldap_link();
1265     $ldap->cd($this->dn);
1266     $this->cleanup();
1267     
1268     /* Force saving numbers, else it will be overwriten by user account. */
1269     $this->attrs['telephoneNumber'] =$tmp_numbers;
1270     $ldap->modify ($this->attrs); 
1272     /* Log last action */
1273     if($this->initially_was_account){
1274       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1275     }else{
1276       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1277     }
1279     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/phone account with dn '%s' failed."),$this->dn));
1281     /* Optionally execute a command after we're done */
1283     if ($this->initially_was_account == $this->is_account){
1284       if ($this->is_modified){
1285         $this->handle_post_events("modify",array("uid" => $this->uid));
1286       }
1287     } else {
1288       $this->handle_post_events("add",array("uid" => $this->uid));
1289     }
1291   }
1294   function adapt_from_template($dn)
1295   {
1296     plugin::adapt_from_template($dn);
1298     /* Assemble phone numbers */
1299     if (isset($this->attrs['telephoneNumber'])){
1300       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1301         $number= $this->attrs['telephoneNumber'][$i];
1302         $this->phoneNumbers[$number]= $number;
1303       }
1304     }
1305   }
1308   function remove_from_parent()
1309   {
1310     if(!$this->initially_was_account) return;
1312     foreach($this->attributes as $key=>$val){
1313       if(in_array($val,array("uid","cn"))){
1314         unset($this->attributes[$key]);
1315         unset($this->$val);
1316       }
1317     }
1318     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1320       // Get Configuration for initial Mysql database Server
1321       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1322       $s_parameter  ="";
1324       // Connect to DB server
1325       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1327       // Check if we are  connected correctly
1328       if(!$r_con){
1329         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1330                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1331         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1332         return false;
1333       }
1335       // Select database for Extensions
1336       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1338       // Test if we have the database selected correctly
1339       if(!$db){
1340         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1341         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1342         return false;
1343       }
1345       $SQL="";
1347       /* If deletion starts from userslist, cn uid are not set */
1348       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1349         $this->uid = $this->parent->by_object['user']->uid;
1350       }
1352       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1353         $this->cn  = $this->parent->by_object['user']->cn;
1354       }
1356       $first_num = false;
1357       // Delete old entries
1358       foreach($this->a_old_telenums as $s_telenums){
1359         if(!$first_num){
1360           $first_num = $s_telenums;
1361         }
1362         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1363       }
1365       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1366       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1367       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1369       foreach($SQL as $query){
1370         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1371         if(!@mysql_query($query,$r_con)){
1372           print_red(_("Stop".mysql_error()));
1373           return false;
1374         }
1375       }
1376     }else{
1377       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1378       return false;
1379     }
1381     /* unset macro attr, it will cause an error */
1382     $tmp = array_flip($this->attributes);
1383     unset($tmp['macro']);
1384     $this->attributes=array_flip($tmp);
1386     /* Cancel if there's nothing to do here */
1387     if (!$this->initially_was_account){
1388       return;
1389     }
1391     plugin::remove_from_parent();
1393     /* Just keep one phone number */
1394     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1395       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1396     } else {
1397       $this->attrs['telephoneNumber']= array();
1398     }
1401     $ldap= $this->config->get_ldap_link();
1402     $ldap->cd($this->config->current['BASE']);
1403     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1404     while($attr = $ldap->fetch()){
1405       if(in_array($this->dn,$attr['member'])){
1406         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1407         unset($new->by_object['ogroup']->memberList[$this->dn]);
1408         unset($new->by_object['ogroup']->member[$this->dn]);
1409         $new->save();
1410         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1411       }
1412     }
1413     $ldap->cd($this->dn);
1414     $this->cleanup();
1415     $ldap->modify ($this->attrs); 
1417     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1418     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/phone account with dn '%s' failed."),$this->dn));
1420     /* Optionally execute a command after we're done */
1421     @mysql_close($r_con);
1422     $this->handle_post_events('remove',array("uid"=> $this->uid));
1423   }
1427   /* This function checks if the given phonenumbers are available or already in use*/
1428   function is_number_used()
1429   {
1430     $ldap= $this->config->get_ldap_link();
1431     $ldap->cd($this->config->current['BASE']);
1432     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1433     while($attrs = $ldap->fetch()) {
1434       unset($attrs['telephoneNumber']['count']);
1435       foreach($attrs['telephoneNumber'] as $tele){
1436         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1437         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1438         $numbers[$tele]=$attrs;
1439       }
1440     }
1442     foreach($this->phoneNumbers as $num){
1443       if(!isset($this->cn)) $this->cn = "";
1445       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1446         if(isset($numbers[$num]['uid'][0])){
1447           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1448         }else{
1449           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1450         }
1451       }
1452     }
1453   }
1456   /* Create phoneAccount part of copy & paste dialog */
1457   function getCopyDialog()
1458   { 
1459     if(!$this->is_account) return("");
1460     $smarty = get_smarty();
1461     if (!count($this->phoneNumbers)){
1462       $smarty->assign ("phoneNumbers", array(""));
1463     } else {
1464       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1465     }
1467     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1468     $smarty->assign("goFonPIN",$this->goFonPIN);
1470     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1471     $ret =array();
1472     $ret['string'] = $display;
1473     $ret['status'] = "";
1474     return($ret);
1475   }
1477   /* Save posts from copy & paste dialog dialog  */
1478   function saveCopyDialog()
1479   {
1480     if(!$this->is_account) return;
1481     $this->execute();
1482     if(isset($_POST['goFonVoicemailPIN'])) {
1483       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1484     }
1485     if(isset($_POST['goFonPIN'])){
1486       $this->goFonPIN = $_POST['goFonPIN'];
1487     }
1488   }
1491   function allow_remove()
1492   {
1493     /* Check if previously selected server is still available */
1494     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1495       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1496     }
1497   }
1499   /* Return plugin informations for acl handling */
1500   static function plInfo()
1501   {
1502     return (array(
1503           "plShortName"     => _("Phone"),
1504           "plDescription"   => _("Phone account settings"),
1505           "plSelfModify"    => TRUE,
1506           "plDepends"       => array("user"),
1507           "plPriority"      => 7,                                 // Position in tabs
1508           "plSection"       => "personal",                        // This belongs to personal
1509           "plCategory"      => array("gofonreport" => array("description" => _("GOfon reports"),
1510               "objectClass" => "")),
1512           "plOptions"       => array(),
1514           "plProvidedAcls"  => array(
1515             "telephoneNumber"     => _("Telephone number"),
1516             "goFonHomeServer"     => _("Home server"),
1517             "goFonMacro"          => _("Macro settings"),
1518             "goFonHardware"       => _("Phone hardware"),
1519             "goFonPIN"            => _("Telephone pin"),
1520             "goFonVoicemailPIN"   => _("Voicemail pin"))
1521           ));
1522   }
1526   function multiple_execute()
1527   {
1528     plugin::multiple_execute();
1529     return($this->execute());
1530   }
1532   function get_multi_init_values()
1533   {
1534     $ret = plugin::get_multi_init_values();
1535     $ret['phoneNumbers'] = array();
1536     foreach($this->phoneNumbers as $number){
1537       $ret['phoneNumbers'][] = $number."  [".$this->attrs['cn'][0]."]"; 
1538     }
1539     $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1540     return($ret);
1541   }
1543   function init_multiple_support($attrs,$all)
1544   {
1545     plugin::init_multiple_support($attrs,$all);
1547     $this->phoneNumbers = array();
1548     if(isset($all['phoneNumbers'])){
1549       for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1550         $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1551       }
1552     }
1553   }
1555   function multiple_save_object()
1556   {
1557     /* Simply call parents save_object */
1558     if (isset($_POST["phoneTab"])){
1560       plugin::save_object();
1561       plugin::multiple_save_object();
1563       /* Every macro in the select box are available */
1564       if((isset($_POST['macro']))){
1565         $this->macrostillavailable=true;
1566       }
1568       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1569         $this->is_modified =true;
1570       }
1572       /* get all Postvars */
1573       if(isset($this->macroarray[$this->macro])){
1574         foreach($this->macroarray[$this->macro] as $key => $paras){
1575           $backup = $this->macroarray[$this->macro][$key];
1576           if(isset($_POST[$paras['var']])){
1577             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1578           }
1579           if(isset($_POST['post_success'])){
1580             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1581               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1582                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1583               }else{
1584                 $this->macroarray[$this->macro][$key]['choosen']=false;
1585               }
1586             }
1587           }
1588         }
1589         if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1590           $this->modified = TRUE;
1591         }
1592       }
1593     }
1594   }
1596   function multiple_check()
1597   {
1598     $message = plugin::multiple_check();
1600     if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1601       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1602     }
1604     if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1605       $message[] = _("Please select a valid goFonHomeServer.");
1606     }
1608     if(in_array("goFonVoicemailPIN",$this->multi_boxes) && 
1609         ( (strlen($this->goFonVoicemailPIN)==0)||
1610           (strlen($this->goFonVoicemailPIN)>4))){
1611       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1612     }else{
1613       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1614         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1615       }
1616     }
1618     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1619       $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1620     }
1622     /* check for ! in any parameter setting*/
1623     if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1624       foreach($this->macroarray[$this->macro] as $val){
1625         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1626           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1627         }
1628       }
1629     }
1631     return($message);
1632   }
1634   function get_multi_edit_values()
1635   {
1636     $ret = plugin::get_multi_edit_values();
1637     if(in_array("macro",$this->multi_boxes)){
1638       $ret['macro'] = $this->macro;
1639       $ret['macroarray'] = $this->macroarray;
1640       $ret['macros'] = $this->macros;
1641     }
1642     return($ret);
1643   }
1646 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1647 ?>