Code

Added create move acls
[gosa.git] / gosa-plugins / gofon / 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   var $context                = "default";
35   var $voice_context          = "default";
37   /* attribute list for save action */
38   var $CopyPasteVars          = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
39                                       "hardware_list","used_hardware");
41   var $attributes             = array("goFonDeliveryMode", "goFonFormat","cn","goFonHomeServer","goFonContext","goFonVoiceMailContext",
42       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
43   var $objectclasses= array("goFonAccount");
45   var $uid;
47   var $view_logged = FALSE;
48   var $multiple_support = TRUE;
50   function phoneAccount (&$config, $dn= NULL, $parent= NULL)
51   {
52     plugin::plugin ($config, $dn, $parent);
54     /* Assemble phone numbers */
55     if (isset($this->attrs['telephoneNumber'])){
56       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
57         $number= $this->attrs['telephoneNumber'][$i];
58         $this->phoneNumbers[$number]= $number;
59       }
60     }
62     /* Set up has_mailAccount */
63     if (isset($this->attrs['objectClass'])){
64       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
65         $this->has_mailAccount= TRUE;
66       }
67     }
69     /* Set parent object to tab object */
70     $this->parent = $parent->parent;
72     /* Set uid */
73     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
74       $this->uid = $this->parent->by_object['user']->uid;
75     }
76     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
77       $this->cn  = $this->parent->by_object['user']->cn;
78     }
80     /* Check server configurations 
81      * Load all server configuration in $this->goFonHomeServers if available
82      *  and first server as default if necessary.
83      * Check if connection is successfull for the selected server $this->goFonHomeServer
84      */
86   
87     /* Set available server */
88     $config = session::get('config');
89     if(isset($config->data['SERVERS']['FON'])){
90       $this->goFonHomeServers = $config->data['SERVERS']['FON'];
91     }
93     $a_SETUP= array();
94     if($this->is_account && isset($config->data['SERVERS']['FON']) &&
95        array_key_exists('FON',$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           msg_dialog::display(_("Obsolete entry"), sprintf(_("The current home server is not available anymore. It will be moved to '%s' if you save this entry!"), preg_replace("/,/",", ",$this->goFonHomeServers[0]['DN'])), ERROR_DIALOG);
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           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
122         }
123         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
124         if(!$db){
125           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
126         }
128         $first = false; 
129         foreach($this->phoneNumbers as $key => $val){
130           if(!$first){
131             $first = $key;
132           }
133         }
134       }
135     }
137     /* Get available phone hardware  
138      * Search for all available phone hardware  
139      */
140     $tmp = get_sub_list("(objectClass=goFonHardware)","phone",array(get_ou("phoneou")),
141                   $this->config->current['BASE'],array("cn","description"), GL_NO_ACL_CHECK);
142     foreach($tmp as $attrs){
143       $cn= $attrs['cn'][0];
144       $description= "";
145       if (isset($attrs['description'])){
146         $description= " - ".$attrs['description'][0];
147       }
148       $this->hardware_list[$cn]= "$cn$description";
149     }
150     $this->hardware_list["automatic"]= _("automatic");
151     ksort($this->hardware_list);
154      /* Collect all usd phones 
155         goFonHardware set.
156      */
157     $deps_a = array(
158         get_people_ou(),
159         get_ou("ogroupou"),
160         get_ou("serverou"),
161         get_ou("terminalou"),
162         get_ou("workstationou"),
163         get_ou("printerou"),
164         get_ou("componentou"),
165         get_ou("phoneou"));
167     $tmp = get_sub_list("(goFonHardware=*)","phone",$deps_a,$this->config->current['BASE'],
168         array('cn','dn','goFonHardware'),GL_NO_ACL_CHECK);
169     foreach($tmp as $attrs){
170       $cn = $attrs['goFonHardware'][0];
171       if(isset($this->hardware_list[$cn])){
172         $this->used_hardware[$cn]= $cn;
173       }
174     }
177     /* Get available Macros  
178      * Search for all Marcos that are visible and create 
179      *  an array with name and parameters 
180      */
181     $tmp = get_sub_list("(&(objectClass=goFonMacro)(goFonMacroVisible=1))","gofonmacro",array(get_ou("macroou")),
182                   $this->config->current['BASE'],array("displayName","goFonMacroParameter","dn","cn"), GL_NONE);
183     
185     /* Add none for no macro*/
186     $this->macros['none']=_("no macro");    
187     $this->macro ="none";
189     /* Fetch all Macros*/
190     foreach($tmp as $attrs){
192       /* unset Count, we don't need that here */
193       unset($attrs['displayName']['count']);
195       /* Parse macro data, unset count for parameterarrays  */
196       if (isset($attrs['goFonMacroParameter']['count'])){
197         unset($attrs['goFonMacroParameter']['count']);
198       }
200       /* fill Selectfield variable with Macros */
201       if(isset($attrs['displayName'][0])){
202         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
203       }else{
204         $this->macros[$attrs['dn']] = _("undefined");
205       }
207       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
208       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
210         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
211           /* Split Data in readable values, by delimiter !  */
212           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
214           /* Set all attrs */
215           $id = $data[0];
216           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
217           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
218           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
219           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
220           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
221           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
222           if($data[2] == "bool"){
223             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
224           }
225         }//foreach
226       }//is_array
227     }//while
230     /* Parse used Macro  
231      * If we have a macro selected, parse it and set values 
232      *  in $this->macroarray[$this->macro]. 
233      */
234     $tmp = split("!",$this->goFonMacro);
235     if(is_array($tmp)){
237       /* First value is the macroname */
238       $this->macro = $tmp[0];
240       /* Macroname saved, delete that index */
241       unset($tmp[0]);
243       /* Check if makro has been removed */
244       if(!isset($this->macros[$this->macro])){
245         $this->macrostillavailable = false;
246       }else{
247         $this->macrostillavailable = true;
248       }
250       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
251       foreach($tmp as $var){
253         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
254         $varar = split("#",$var);
256         /* Only insert if the parameter still exists */
257         if(isset($this->macroarray[$this->macro][$varar[0]])){
258           /* Assign value */
259           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
260         }
261       }
262     }
265     $this->a_old_telenums = $this->phoneNumbers;
267     /* Get voicemail PIN from MySQL DB 
268      * Because every user can change his PIN directly from the phone
269      *  without any update to the ldap
270      * This means, the PIN in the DB is up to date
271      */
272     // Connect to DB server
273     if( (is_callable("mysql_pconnect"))&&
274         (isset($cur_cfg))&&
275         (isset($cur_cfg['SERVER']))&&
276         (isset($cur_cfg['LOGIN']))&&
277         (isset($cur_cfg['PASSWORD']))){
279       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
280       if($r_con){
281         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
282   
283         $query_tmp = "SELECT ".$cur_cfg['VOICE_TABLE'].".context as 'v_context', 
284                              ".$cur_cfg['SIP_TABLE'].".context, 
285                              ".$cur_cfg['VOICE_TABLE'].".password 
286                        FROM  ".$cur_cfg['VOICE_TABLE'].", 
287                              ".$cur_cfg['SIP_TABLE']." 
288                        WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'";
291         $res = mysql_query($query_tmp);
292         $vp  = mysql_fetch_assoc($res);
293   
294         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
295         if((isset($vp['password']))&&(!empty($vp['password']))){
296           $this->goFonPINVoice = $vp['password'];
297         }
298         if((isset($vp['context']))&&(!empty($vp['context']))){
299           $this->context = $vp['context'];
300         }
301         if((isset($vp['v_context']))&&(!empty($vp['v_context']))){
302           $this->voice_context = $vp['v_context'];
303         }
304       }
305     }
306     $this->lastmacro=$this->macro;
308     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
309       @mysql_close($r_con) ;
310     }
311   }
314   /* This function generates the Database entries. 
315    * The Parameter 'save' could be true or false.
316    *  false - means only testing no database transactions.
317    *  true  - write database entries.
318    *
319    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
320    * 
321    * If the phone hardware is 'automatic' the table entries will only be removed
322    *  and not added. 
323    */
324   function generate_mysql_entension_entries($save = false)
325   {
326     /* Check if there is at least one server available 
327      * If not, return and tell the user that saving failed 
328      */
329     if(!count($this->goFonHomeServers)){
330       if($save){
331         msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
332       }
333       return(true);
334     }
336     /* Check if Mysql extension is available */
337     if(!is_callable("mysql_pconnect")){
338       if($save){
339         msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
340       }
341       return(true);
342     }
343  
344     /********************** 
345      * Attribute Initialisation
346      **********************/
348     $old_connection = false;
350     // Get Configuration for Mysql database Server
351     $s_parameter    = "";                                           // Contains paramter for selected Macro 
352     $r_con          = false;                                        // DB connection
353     $r_db           = false;                                        // Selected DB
354     $r_res          = false;                                        // Result resource
355     $a_ldap_attrs   = array();                                      //  
357     $s_ip           = NULL;                   // Contains ip for Sip entry
358     $s_host         = NULL;                   // Contains host for Sip entry
359     $s_qualify      = "yes";                  // Qualify entry
360     $s_pin          = NULL;                   // Entry for secret
361     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
363     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
364     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
365     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
367     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
368     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
370     $s_sip_key      = "";     // Key for SIP entry index      
371     $s_sip_val      = "";     // Value for SIP entry index      
373     $b_first_deleted= false;  // Only delete first entry, 
374     $s_telenums     = "";     // for each value variable
376     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
378     restore_error_handler();
380     /* Prepare some basic attributes */
381     $oldnums = array();
382     foreach($this->a_old_telenums as $tele){
383       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
384     }
385     foreach($this->phoneNumbers as $tele){
386       $newnums[]= preg_replace("/[^0-9]/","",$tele);
387     }
389     /* If deletion starts from userslist, cn uid are not set */
390     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
391       $this->uid = $this->parent->by_object['user']->uid;
392     }
393     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
394       $this->cn  = $this->parent->by_object['user']->cn;
395     }
396     /* Create voicemail entry 
397      */
398     if((!isset($this->cn))||(empty($this->cn))){
399       $CNname= $this->uid;
400     }else{
401       $CNname= $this->cn;
402     }
404     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
405       $s_mail = $this->parent->by_object['mailAccount']->mail;
406     }else{
407       $s_mail = "";
408     }
409     /* Get phonehardware to setup sip entry  */
410     $ldap         = $this->config->get_ldap_link();
411     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
412     $a_ldap_attrs = $ldap->fetch();
414     /* Check selected phone hardware, is a default IP set? */
415     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
416       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
417       $s_host     = $s_ip;
418     }else{
419       $s_ip       = NULL;
420       $s_host     = "dynamic";
421     }
423     // Attribute GoFonQualify set ?
424     if(isset($a_ldap_attrs['goFonQualify'])){
425       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
426     }
428     // Attribute GoFonPIN set ?
429     if(isset($this->goFonPIN)){
430       $s_pin      = $this->goFonPIN;
431     }
433     // Attribute GoFonType set ?
434     if(isset($a_ldap_attrs['goFonType'])){
435       $s_type = $a_ldap_attrs['goFonType'][0];
436     }
438     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
439       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
440     }else{
441       $sip_data_array['dtmfmode']     ="rfc2833";
442     }
444     /* Check if phone number is used */
445     if($this->is_number_used()){
446       $this->generate_error = $this->is_number_used(); 
447       return false;
448     }
452     /********************** 
453      * Check Server Connection Information
454      **********************/
455  
456     /* Create Mysql handle for the current goFonHomeServer, if possible  
457      * Get configuration to old asterisk home server 
458      */ 
459     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
460     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
461     if(!$new_connection){
462       $this->generate_error =  msgPool::dbconnect($a_New['SERVER'],@mysql_error($new_connection),
463           _("Abort saving entries to keep the database consistent."));
464       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
465       return false;
466     }
467     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
468     if(!$new_database){
469       $this->generate_error =  msgPool::dbselect($a_New['DB'],@mysql_error($new_connection),
470           _("Abort saving entries to keep the database consistent."));
471       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
472       return false;
473     }
475     /* If the home server has changed, we must remove entries from old 
476      *  server and add new entries in new server.  
477      */
478     if($this->init_HomeServer != $this->goFonHomeServer){
479     
480       /* Get configuration to old asterisk home server */ 
481       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
482  
483       /* Create connection to the database that contains the old entry. 
484        */
485       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
486       if(!$old_connection){
487         $this->generate_error =  msgPool::dbconnect($a_Remove['SERVER'],@mysql_error($old_connection),
488             _("Abort saving entries to keep the database consistent."));
489         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
490         return false;
491       }
492       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
493       if(!$old_database){
494         $this->generate_error =  msgPool::dbselect($a_Remove['DB'],@mysql_error($old_connection),
495             _("Abort saving entries to keep the database consistent."));
496         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
497         return false;
498       }
499     }
501     /* Save means that we must save changes, not only test  */
502     if($save == true){
503     
504       /********************** 
505        * Remove entries from old home server 
506        **********************/
508       /* Check if there is an old entry 
509        * If there is an old entry, get callerid and remove voicemail and extensions 
510        */
511       if($old_connection){
512         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
513         $rid    = mysql_query($query,$old_connection);
514         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
516         /* Old entry found, remove it */
517         $query_a = array();
518         if(mysql_affected_rows($old_connection)){
519           $result = mysql_fetch_assoc($rid);
520           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
521           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
522           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
523           foreach($oldnums as $s_telenums) {
524             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
525           }
527           foreach($query_a as $qry){
528                   @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
529             if(!mysql_query($qry,$old_connection)){
530               trigger_error(mysql_error($old_connection));
531             } 
532           }
533         }
534       }
536       /********************** 
537        * Update / Insert sip_users entry  
538        **********************/
540       /* Set the first given phone number as callerid */
541       reset($newnums);        
542       $i_new_key = key($newnums);
543       $sip_data_array['callerid']  =$newnums[$i_new_key];
544       $sip_data_array['mailbox']   =$newnums[$i_new_key];
546       /* Check if there is already an entry in sip_users for this uid */
547       $SQL_query_array = array();
548       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
549       $rid = mysql_query($query,$new_connection);
550       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
551       if(mysql_affected_rows($new_connection)){
553         /********************** 
554          * Update sip_users entry 
555          **********************/
556         $result                     = mysql_fetch_assoc($rid);
557         $sip_data_array['host']         = $s_host;
558         $sip_data_array['qualify']      = $s_qualify;
559         $sip_data_array['secret']       = $this->goFonPIN;
560         $sip_data_array['type']         = $s_type ;
561         $sip_data_array['username']     = $this->uid;
562         $sip_data_array['ipaddr']       = $s_ip;
563         $sip_data_array['context']      = $this->context;
565         /* Remove not changed attributes, to avoid updating table with same values */
566         foreach($sip_data_array as $name => $value){
567           if($result[$name] == $value){
568             unset($sip_data_array[$name]);
569           }
570         }
571         /* Only update entry if there is something to uopdate */
572         if(count($sip_data_array)){
573           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
574           foreach($sip_data_array as $key => $val){
575             $query.= "".$key."='".$val."',"; 
576           } 
577           $query = preg_replace("/,$/","",$query);
578           $query.= " WHERE name='".$this->uid."';";
579           $SQL_query_array[] = $query;
580         }
581       } else {
582  
583         /********************** 
584          * Insert sip_users entry 
585          **********************/
586         //generate SIP entry
587         $sip_data_array['id']           = "";
588         $sip_data_array['name']         = $this->uid;
589         $sip_data_array['accountcode']  = NULL;          
590         $sip_data_array['amaflags']     = NULL;
591         $sip_data_array['callgroup']    = NULL;
592         $sip_data_array['canreinvite']  = "no";
593         $sip_data_array['context']      = $this->context;
594         $sip_data_array['defaultip']    = NULL;
595         $sip_data_array['fromuser']     = NULL;
596         $sip_data_array['fromdomain']   = NULL;
597         $sip_data_array['host']         = $s_host;
598         $sip_data_array['insecure']     = NULL;
599         $sip_data_array['language']     = NULL;
600         $sip_data_array['mailbox']      = $newnums[$i_new_key];
601         $sip_data_array['md5secret']    = NULL;
602         $sip_data_array['nat']          = "no";
603         $sip_data_array['permit']       = NULL;
604         $sip_data_array['deny']         = NULL;
605         $sip_data_array['mask']         = NULL;
606         $sip_data_array['pickupgroup']  = NULL;
607         $sip_data_array['port']         = NULL;
608         $sip_data_array['qualify']      = $s_qualify;
609         $sip_data_array['restrictcid']  = "n";
610         $sip_data_array['rtptimeout']   = NULL;
611         $sip_data_array['rtpholdtimeout']=NULL;
612         $sip_data_array['secret']       = $this->goFonPIN;
613         $sip_data_array['type']         = $s_type ;
614         $sip_data_array['username']     = $this->uid;
615         $sip_data_array['disallow']     = NULL;
616         $sip_data_array['allow']        = NULL;
617         $sip_data_array['musiconhold']  = NULL;
618         $sip_data_array['regseconds']   = NULL;
619         $sip_data_array['ipaddr']       = $s_ip;
620         $sip_data_array['regexten']     = NULL;
621         $sip_data_array['cancallforward']=NULL;
623         /* There is currently no entry for this user in the sip_users table. 
624          * We should create one i
625          */
626         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
627           if($s_sip_val === NULL) continue;
628           $s_sip_values.="'".$s_sip_val."',";
629           $s_sip_keys  .="`".$s_sip_key."`,";
630         }
631         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
632         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
634         /* Add sip entries to mysql queries */
635         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
636       }
639       /********************** 
640        * Update / Insert Voice mail entry  
641        **********************/
643       $customer_id = $newnums[$i_new_key];
645       $voice_data_array = array(
646           "customer_id" => $customer_id,
647           "mailbox"     => $customer_id,
648           "password"    => $this->goFonVoicemailPIN,
649           "fullname"    => $CNname,
650           "context"     => $this->voice_context,
651           "email"       => $s_mail);
653       /* Set pager number if available */
654       if(isset($this->parent->by_object['user']->pager)){
655         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
656       }
658       /* Check if there is already an entry in sip_users for this uid */
659       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n";
660       $rid = mysql_query($query_tmp,$new_connection);
661       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
662       if(mysql_affected_rows($new_connection)){
664         /********************** 
665          * Update Voice mail entry  
666          **********************/
667         $result = mysql_fetch_assoc($rid)  ;
669         foreach($voice_data_array as $name => $value){
670           if($result[$name] == $value){
671             unset($voice_data_array[$name]);
672           }
673         }
675         /* Only update entry if there is something to uopdate */
676         if(count($voice_data_array)){
677           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
678           foreach($voice_data_array as $key => $val){
679             $query.= "".$key."='".$val."',"; 
680           } 
681           $query = preg_replace("/,$/","",$query);
682           $query.= " WHERE customer_id='".$customer_id."';";
683           $SQL_query_array[] = $query;
684         }
685       }else{
687         /********************** 
688          * Insert Voice mail entry  
689          **********************/
690         $voice_data_array['context'] = $this->voice_context;
691   
692         /* There is currently no voice mail entry for this user. 
693          * We should create one 
694          */
695         $s_voi_values = $s_voi_keys = "";
696         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
697           if($s_voi_val === NULL) continue;
698           $s_voi_values.="'".$s_voi_val."',";
699           $s_voi_keys  .="`".$s_voi_key."`,";
700         }
701         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
702         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
704         /* Add sip entries to mysql queries */
705         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
706       }
708      
709       /********************** 
710        * Remove/Insert extension entries
711        **********************/
712       
713       /* Remove old entries */
714       $query = array();
715       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
716       $oldnums= array();
717       foreach($oldnums as $s_telenums){
718         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
719       }
720       foreach($newnums as $s_telenums){
721         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
722       }
723       foreach($query as $qry){
724         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
725         if(!mysql_query($qry,$new_connection)){
726           trigger_error(mysql_error($new_connection));
727         } 
728       }
729  
730       /********************** 
731        * Insert extension entries
732        **********************/
733  
734       // Get selected Macro Parameter and create parameter entry 
735       if(isset($this->macroarray[$this->macro])){
736         foreach($this->macroarray[$this->macro] as $key => $val ){
737           $s_parameter .= $val['choosen']."|";
738         }
739         $s_parameter = preg_replace("/\|$/","",$s_parameter);
740       }
741      
742       $i = 0; 
743       $EXT = array();
744       if(!is_numeric($this->uid)){
745         $EXT[$i]['context'] = 'GOsa';
746         $EXT[$i]['exten']   = $this->uid;
747         $EXT[$i]['priority']= 1;
748         $EXT[$i]['app']     = "Goto";
749         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
750         $i ++;
751       }
753       // Entension entries  Hint / Dial / Goto
754       foreach($newnums as $s_telenums){
756         /* Hint Entry */
757         $EXT[$i]['context'] = 'GOsa';
758         $EXT[$i]['exten']   = $s_telenums;
759         $EXT[$i]['priority']= "Hint";
760         $EXT[$i]['app']     = 'SIP/'.$this->uid;
761         $i ++;  
762         /* SetCID */
763         //$EXT[$i]['context'] = 'GOsa';
764         //$EXT[$i]['exten']   = $s_telenums;
765         //$EXT[$i]['priority']= 1;
766         //$EXT[$i]['app']     = "SetCIDName";
767         //$EXT[$i]['appdata'] = $CNname;
768         //$i ++;  
770         // If no macro is selected use Dial
771         if($this->macro!="none"){ 
772           $macroname = preg_replace("/,.*$/","",$this->macro);        
773           $macroname = preg_replace("/^.*=/","",$macroname);        
774           $s_app = "Macro";$macroname;
775           $s_par = $macroname."|".$s_parameter; 
776         }else{
777           $s_app = "Dial";
778           $s_par = 'SIP/'.$this->uid."|20|r";
779         }
781         $EXT[$i]['context'] = 'GOsa';
782         $EXT[$i]['exten']   = $s_telenums;
783         $EXT[$i]['priority']= 1;
784         $EXT[$i]['app']     = $s_app;
785         $EXT[$i]['appdata'] = $s_par;
786         $i ++;
787       }
789       // Append all these Entries 
790       foreach($EXT as $entr){
791         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
792         foreach($entr as $key2 => $val2){
793           $SQL_syn.= "`".$key2."`,";
794         }
795         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
796         $SQL_syn .= ") VALUES ("; 
797         foreach($entr as $key2 => $val2){
798           $SQL_syn .= "'".$val2."',";
799         }
800         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
801         $SQL_syn .=");\n";
803         $SQL_query_array[] =$SQL_syn;
804         $SQL_syn ="";
805       }
807       // Perform queries ...
808       if($this->goFonHardware != "automatic"){
809         foreach($SQL_query_array as $query){
810           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
811           if(!@mysql_query($query,$new_connection)){
812             $this->generate_error =  msgPool::dbquery("GOfon",@mysql_error($old_connection));
813             return false;
814           }
815         }
816       }
817     }
818     @mysql_close($new_connection);
819     return true;
820   }
823   function execute()
824   {
825     /* Call parent execute */
826     plugin::execute();
828     /* Log view */
829     if($this->is_account && !$this->view_logged){
830       $this->view_logged = TRUE;
831       new log("view","users/".get_class($this),$this->dn);
832     }
834     $display = "";
835     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
836     if(empty($this->macro)&&(!empty($this->goFonMacro))){
838       /* Go through already saved values, for a parameter */
839       $tmp = split("!",$this->goFonMacro);
841       /* it is possible that nothing has been saved yet */
842       if(is_array($tmp)){
844         /* First value is the macroname */
845         $this->macro = $tmp[0];
847         /* Macroname saved, delete that index */
848         unset($tmp[0]);
850         /* Check if macro has been removed */
851         if(!isset($this->macroarray[$this->macro])){
852           $this->macrostillavailable = false;
853         }else{
854           $this->macrostillavailable = true;
855         }
857         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
858         foreach($tmp as $var){
860           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
861           $varar = split("#",$var);
863           /* Only insert if the parameter still exists */
864           if(isset($this->macroarray[$this->macro][$varar[0]])){
865             /* Assign value */
866             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
867           }
868         }
869       }
870     }
871     
872     /* Do we represent a valid account? */
873     if (!$this->is_account && $this->parent === NULL){
874       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
875         msgPool::noValidExtension(_("Phone"))."</b>";
876       $display.= back_to_main();
877       return ($display);
878     }
880     /* Do we need to flip is_account state? */
881     if (isset($_POST['modify_state'])){
882       $this->is_account= !$this->is_account;
883     }
885     /* Do we represent a valid account? */
886     if (!$this->is_account && $this->parent === NULL){
887       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
888         msgPool::noValidExtension(_("Phone"))."</b>";
889       $display.= back_to_main();
890       return($display);
891     }
893     $display= "";
895     /* Show tab dialog headers */
896     
897     if (!$this->multiple_support_active && $this->parent !== NULL){
898       if ($this->is_account){
899         $display= $this->show_disable_header(_("Remove phone account"),
900             msgPool::featuresEnabled(_("Phone")));
901       } else {
902         if(empty($this->uid)){
903           $display= $this->show_enable_header(_("Create phone account"),
904             msgPool::featuresDisabled(_("Phone"),_("User uid")));
905         }else{
906           $display= $this->show_enable_header(_("Create phone account"),
907             msgPool::featuresDisabled(_("Phone")));
908         }
909         return ($display);
910       }
911     }
912     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
913     if(empty($this->macro)){
914       $this->macro ="none";
915     }
917     /* Prepare templating */
918     $smarty= get_smarty();
920     /* tell user that the selected plugin is no longer available */
921     if((!$this->macrostillavailable)&&($this->macro!="none")){
922       msg_dialog::display(_("Error"), _("Selected macro is not available anymore!"), ERROR_DIALOG);
923     }
925     /* Assing macroselectbox values  */
926     $smarty->assign("macros",$this->macros);   
927     $smarty->assign("macro", $this->macro);   
929     /* Assign contexts */
930     $smarty->assign("contexts",$this->get_asterisk_contexts());
931     $smarty->assign("context" ,$this->context);
932     $smarty->assign("voice_context" ,$this->voice_context);
934     /* check if there is a FON server created */
935     if(!count($this->goFonHomeServer)){
936       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
937     }
939     /* Create html parameter table for selected macro parameters 
940      *  skip if no parameters given 
941      */
942     if(!isset($this->macroarray[$this->macro])){
943       $macrotab="";
944     }else{
946       $macrotab ="<table summary=\""._("Parameter")."\">";
947       /* for every single parameter-> display textfile,combo, or true false switch*/
949       foreach($this->phoneNumbers as $phonenum){
950         $tmp[] = $phonenum;
951       }
952     
953       if($this->macro != $this->lastmacro){
954         /* Go through all params */
955         foreach($this->macroarray[$this->macro] as $key => $paras){
957           $string = $paras['default'];
959           $string=preg_replace("/%uid/i",$this->uid,$string);
961           if(isset($this->cn)){
962             $string=preg_replace("/%cn/i",$this->cn,$string);
963           }
965           for($i = 0 ; $i < 10; $i++){
966             if(isset($tmp[$i])){
967               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
968             }
969           }
970           if(isset($tmp[0])){
971             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
972           }
973           $this->macroarray[$this->macro][$key]['choosen']=$string;
974         }
975       }
977       foreach($this->macroarray[$this->macro] as $paras){
979         /* get al vars */
980         $var        = $paras['var'];           
981         $name       = $paras['name'];           
982         $default    = $paras['default'];
983         $type       = $paras['type'];
984         $choosen    = $paras['choosen'] ; 
985         $str        = $default;
987         $dis = "";
988         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
989           $dis = " disabled ";
990         }
992         /* in case of a combo box display a combobox with selected attr */
993         $macrotab.= "<tr>";
994         switch ($type){
996           case "combo":
997             $str= "<select name='".$var."' ".$dis." >";
998           foreach(split(":",$default) as $choice){
999             if($choosen==$choice){
1000               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
1001             }else{
1002               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
1003             }
1004           }
1005           $str.="</select>";
1006           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1007           break;
1009           case "bool":
1010             if(!$choosen){
1011               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
1012             }else{
1013               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
1014             }
1015           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
1016           break;
1018           case "string":
1019             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
1020           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1021           break;
1023         }
1024         $macrotab.= "</td></tr>";
1026       }
1027       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1028     }//is_array()
1030     /* Give smarty the table */
1031     $smarty->assign("macrotab",$macrotab);
1034     /* Add phone number */
1035     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1036       if (tests::is_phone_nr($_POST['phonenumber'])){
1037         $number= $_POST["phonenumber"];
1038         $this->phoneNumbers[$number]= $number;
1039         $this->is_modified= TRUE;
1040       } else {
1041         msg_dialog::display(_("Error"), msgPool::invalid("Phone number"), ERROR_DIALOG);
1042       }
1043     }
1045     /* Remove phone number */
1046     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1047       foreach ($_POST['phonenumber_list'] as $number){
1048         unset($this->phoneNumbers[$number]);
1049         $this->is_modified= TRUE;
1050       }
1051     }
1053     /* Assign acls */
1054     $tmp = $this->plInfo();
1055     foreach($tmp['plProvidedAcls'] as $name => $translation){
1056       $smarty->assign($name."ACL",$this->getacl($name));
1057     }
1059     /* Transfer ACL's */
1060     foreach($this->attributes as $val){
1061       if(isset($this->$val)){
1062         $smarty->assign($val,$this->$val);
1063       }else{
1064         $smarty->assign($val,"");
1065       }
1066     }
1068     /* Create home server array */
1069     $tmp = array();
1070     foreach($this->goFonHomeServers as $dn => $attrs){
1071       if(!is_numeric($dn)){
1072         $tmp[$dn] = $attrs['SERVER'];
1073       }
1074     }
1075     $smarty->assign("goFonHomeServers",$tmp);
1077     /* Fill arrays */
1078     $smarty->assign ("goFonHardware", $this->goFonHardware);
1079     if (!count($this->phoneNumbers)){
1080       $smarty->assign ("phoneNumbers", array());
1081     } else {
1082       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1083     }
1085     $dis = "";
1086     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1087       $dis= " disabled ";
1088     }
1089     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1090        _("Choose your private phone")."\">\n";
1092     foreach ($this->hardware_list as $cn => $description){
1093       if ($cn == $this->goFonHardware){
1094         $selected= "selected";
1095       } else {
1096         $selected= "";
1097       }
1098       if (isset($this->used_hardware[$cn])){
1099         $color= "style=\"color:#A0A0A0\"";
1100       } else {
1101         $color= "";
1102       }
1103       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1104     }
1105     $hl.= "</select>\n";
1106     $smarty->assign ("hardware_list", $hl);
1109     foreach($this->attributes as $attr){
1110       if(in_array($attr,$this->multi_boxes)){
1111         $smarty->assign("use_".$attr,TRUE);
1112       }else{
1113         $smarty->assign("use_".$attr,FALSE);
1114       }
1115     }
1117     /* Show main page */
1118     $this->lastmacro = $this->macro;
1119     $smarty->assign("multiple_support",$this->multiple_support_active);
1120     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1121     return($display);
1122   }
1125   function save_object()
1126   {
1127     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1128     if (isset($_POST["phoneTab"])){
1129     
1130       plugin::save_object();
1132       /* Save checkbox */
1133       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1134       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1135         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1136           $tmp .= "M";
1137         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1138           $tmp  = preg_replace ("/M/","",$tmp);
1139         }
1140       }
1141       $this->goFonDeliveryMode= "[".$tmp."]";
1144       /* Every macro in the select box are available */
1145       if((isset($_POST['macro']))){
1146         $this->macrostillavailable=true;
1147       }
1149       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1150         $this->is_modified =true;
1151       }
1153       /* Save context */
1154       if(isset($_POST['context'])){
1155         if($this->context != $_POST['context']){
1156           $this->is_modified= TRUE;
1157         }
1158         $this->context= $_POST['context'];
1159       }
1161       /* Save voice context */
1162       if(isset($_POST['voice_context'])){
1163         if($this->voice_context != $_POST['voice_context']){
1164           $this->is_modified= TRUE;
1165         }
1166         $this->voice_context= $_POST['voice_context'];
1167       }
1169       if(is_array($this->phoneNumbers)){
1170         foreach($this->phoneNumbers as $telenumms) {
1171           $nummsinorder[]=$telenumms; 
1172         }
1173       }else{
1174         $nummsinorder=array("");
1175       }
1178       /* get all Postvars */
1179       if(isset($this->macroarray[$this->macro])){
1181         if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1182           foreach($this->macroarray[$this->macro] as $key => $paras){
1184             $backup = $this->macroarray[$this->macro][$key];
1186             if(isset($_POST[$paras['var']])){
1187               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1188             }
1190             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1191                We need this code below to read and save checkboxes correct
1192              */
1194             if(isset($_POST['post_success'])){
1195               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1196                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1197                   $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1198                 }else{
1199                   $this->macroarray[$this->macro][$key]['choosen']=false;
1200                 }
1201               }
1202             }
1203           }
1204           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1205             $this->modified = TRUE;
1206           }
1207         }
1208       }
1209     }
1210   }
1212   function check()
1213   {
1214     /* Call common method to give check the hook */
1215     $message= plugin::check();
1217     if(!count($this->goFonHomeServers)){
1218       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1219     }
1221     if(empty($this->goFonHomeServer)){
1222       $message[] = msgPool::invalid(_("Home server"));
1223     }
1225     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1226       $message[]= msgPool::invalid(_("Voicemail PIN"),"","",_("Between 1-4 charactes"));
1227     }else{
1228       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1229         $message[]= msgPool::invalid(_("Voicemail PIN"),preg_replace("/[0-9]/","X",$this->goFonVoicemailPIN),"/X/");
1230       }
1231     }
1233     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1234       $message[]= msgPool::invalid(_("Phone PIN"),preg_replace("/[0-9a-z]/i","X",$this->goFonPIN),"/X/");
1235     }
1237     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1238       if(!$this->generate_mysql_entension_entries()){
1239         $message[] = $this->generate_error;
1240       }
1241     }
1243     /* We need at least one phone number */
1244     if (count($this->phoneNumbers) == 0){
1245       $message[]= msgPool::required("Phone number");
1246     }
1248     /* check for ! in any parameter setting*/
1249     if(isset($this->macroarray[$this->macro])){
1250       foreach($this->macroarray[$this->macro] as $val){
1251         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1252           $message[] = msgPool::invalid(sprintf(_("macro parameter %s"),$val['name']),$val['choosen'],"/[^\#]/");
1253         }
1254       }
1255     }
1256     return ($message);
1257   }
1261   function save()
1262   {
1263     plugin::save();
1265     /* Force saving macro again 
1266      * This ensures that 
1267      *  - the macro is available on the destiantion server.
1268      *  - the macro saved is up to date on the destination server.
1269      */
1270     if(!empty($this->macro) && $this->macro != "none")  {
1271       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1272       $macro_tab -> save();
1273     }
1275     /* Save arrays */
1276     $tmp_numbers = array();
1277     foreach ($this->phoneNumbers as $number){
1278       $tmp_numbers[] = $number;
1279     }
1281     /* Save settings, or remove goFonMacro attribute*/
1282     if($this->macro!="none"){    
1283       $this->attrs['goFonMacro']=$this->macro;
1284       if(isset($this->macroarray[$this->macro])){
1285         foreach($this->macroarray[$this->macro] as $paras)  {
1286           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1287         }
1288       }
1289     }else{
1290       $this->attrs['goFonMacro']=array();
1291     }
1292     unset($this->attrs['macro'])  ;
1294     $this->attrs['goFonForwarding']=array();
1296     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1297       $str = $this->generate_mysql_entension_entries(true);
1298       if(empty($str)){
1299         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
1300       }
1301     }
1303     if($this->attrs['goFonMacro']==""){
1304       $this->attrs['goFonMacro']=array();
1305     }
1307     unset($this->attrs['cn']);
1309     /* Write back to ldap */
1310     $ldap= $this->config->get_ldap_link();
1311     $ldap->cd($this->dn);
1312     $this->cleanup();
1313     
1314     /* Force saving numbers, else it will be overwriten by user account. */
1315     $this->attrs['telephoneNumber'] =$tmp_numbers;
1316     $ldap->modify ($this->attrs); 
1318     /* Log last action */
1319     if($this->initially_was_account){
1320       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1321     }else{
1322       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1323     }
1325     if (!$ldap->success()){
1326       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
1327     }
1329     /* Optionally execute a command after we're done */
1331     if ($this->initially_was_account == $this->is_account){
1332       if ($this->is_modified){
1333         $this->handle_post_events("modify",array("uid" => $this->uid));
1334       }
1335     } else {
1336       $this->handle_post_events("add",array("uid" => $this->uid));
1337     }
1339   }
1342   function adapt_from_template($dn, $skip= array())
1343   {
1344     plugin::adapt_from_template($dn, $skip);
1346     /* Assemble phone numbers */
1347     if (isset($this->attrs['telephoneNumber']) && !in_array("telephoneNumber", $skip)){
1348       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1349         $number= $this->attrs['telephoneNumber'][$i];
1350         $this->phoneNumbers[$number]= $number;
1351       }
1352     }
1353   }
1356   function remove_from_parent()
1357   {
1358     if(!$this->initially_was_account) return;
1360     foreach($this->attributes as $key=>$val){
1361       if(in_array($val,array("uid","cn"))){
1362         unset($this->attributes[$key]);
1363         unset($this->$val);
1364       }
1365     }
1366     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1368       // Get Configuration for initial Mysql database Server
1369       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1370       $s_parameter  ="";
1372       // Connect to DB server
1373       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1375       // Check if we are  connected correctly
1376       if(!$r_con){
1377         msg_dialog::display(_("Error"), msgPool::dbconnect("GOfon",@mysql_error()), ERROR_DIALOG);
1378         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1379         return false;
1380       }
1382       // Select database for Extensions
1383       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1385       // Test if we have the database selected correctly
1386       if(!$db){
1387         msg_dialog::display(_("Error"), msgPool::dbselect("GOfon", @mysql_error()), ERROR_DIALOG);
1388         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1389         return false;
1390       }
1392       $SQL="";
1394       /* If deletion starts from userslist, cn uid are not set */
1395       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1396         $this->uid = $this->parent->by_object['user']->uid;
1397       }
1399       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1400         $this->cn  = $this->parent->by_object['user']->cn;
1401       }
1403       $first_num = false;
1404       // Delete old entries
1405       foreach($this->a_old_telenums as $s_telenums){
1406         if(!$first_num){
1407           $first_num = $s_telenums;
1408         }
1409         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1410       }
1412       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1413       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1414       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1416       foreach($SQL as $query){
1417         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1418         if(!@mysql_query($query,$r_con)){
1419           msg_dialog::display(_("Error"), msgPool::dbquery("GOfon",@mysql_error()), ERROR_DIALOG);
1420           return false;
1421         }
1422       }
1423     }else{
1424       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
1425       return false;
1426     }
1428     /* unset macro attr, it will cause an error */
1429     $tmp = array_flip($this->attributes);
1430     unset($tmp['macro']);
1431     $this->attributes=array_flip($tmp);
1433     /* Cancel if there's nothing to do here */
1434     if (!$this->initially_was_account){
1435       return;
1436     }
1438     plugin::remove_from_parent();
1440     /* Just keep one phone number */
1441     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1442       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1443     } else {
1444       $this->attrs['telephoneNumber']= array();
1445     }
1448     $ldap= $this->config->get_ldap_link();
1449     $ldap->cd($this->config->current['BASE']);
1450     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1451     while($attr = $ldap->fetch()){
1452       if(in_array($this->dn,$attr['member'])){
1453         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1454         unset($new->by_object['ogroup']->memberList[$this->dn]);
1455         unset($new->by_object['ogroup']->member[$this->dn]);
1456         $new->save();
1457         msg_dialog::display(_("Information"), sprintf(_("User '%s' has been removed from phone queue '%s'."), $this->cn, $new->by_object['ogroup']->cn), INFO_DIALOG);
1458       }
1459     }
1460     $ldap->cd($this->dn);
1461     $this->cleanup();
1462     $ldap->modify ($this->attrs); 
1464     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1465     if (!$ldap->success()){
1466       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1467     }
1469     /* Optionally execute a command after we're done */
1470     @mysql_close($r_con);
1471     $this->handle_post_events('remove',array("uid"=> $this->uid));
1472   }
1476   /* This function checks if the given phonenumbers are available or already in use*/
1477   function is_number_used()
1478   {
1479     $ldap= $this->config->get_ldap_link();
1480     $ldap->cd($this->config->current['BASE']);
1481     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1482     while($attrs = $ldap->fetch()) {
1483       unset($attrs['telephoneNumber']['count']);
1484       foreach($attrs['telephoneNumber'] as $tele){
1485         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1486         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1487         $numbers[$tele]=$attrs;
1488       }
1489     }
1491     foreach($this->phoneNumbers as $num){
1492       if(!isset($this->cn)) $this->cn = "";
1494       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1495         if(isset($numbers[$num]['uid'][0])){
1496           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1497         }else{
1498           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1499         }
1500       }
1501     }
1502   }
1505   /* Create phoneAccount part of copy & paste dialog */
1506   function getCopyDialog()
1507   { 
1508     if(!$this->is_account) return("");
1509     $smarty = get_smarty();
1510     if (!count($this->phoneNumbers)){
1511       $smarty->assign ("phoneNumbers", array(""));
1512     } else {
1513       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1514     }
1516     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1517     $smarty->assign("goFonPIN",$this->goFonPIN);
1519     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1520     $ret =array();
1521     $ret['string'] = $display;
1522     $ret['status'] = "";
1523     return($ret);
1524   }
1526   /* Save posts from copy & paste dialog dialog  */
1527   function saveCopyDialog()
1528   {
1529     if(!$this->is_account) return;
1530     $this->execute();
1531     if(isset($_POST['goFonVoicemailPIN'])) {
1532       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1533     }
1534     if(isset($_POST['goFonPIN'])){
1535       $this->goFonPIN = $_POST['goFonPIN'];
1536     }
1537   }
1540   function allow_remove()
1541   {
1542     /* Check if previously selected server is still available */
1543     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1544       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1545     }
1546   }
1548   /* Return plugin informations for acl handling */
1549   static function plInfo()
1550   {
1551     return (array(
1552           "plShortName"     => _("Phone"),
1553           "plDescription"   => _("Phone account settings"),
1554           "plSelfModify"    => TRUE,
1555           "plDepends"       => array("user"),
1556           "plPriority"      => 7,                                 // Position in tabs
1557           "plSection"         => array("personal" => _("My account")),
1558           "plCategory"        => array("users"),
1561           "plOptions"       => array(),
1563           "plProvidedAcls"  => array(
1564             "telephoneNumber"     => _("Telephone number"),
1565             "goFonHomeServer"     => _("Home server"),
1566             "goFonMacro"          => _("Macro settings"),
1567             "goFonHardware"       => _("Phone hardware"),
1568             "goFonContext"          => _("Phone context"),
1569             "goFonVoiceMailContext" => _("Voice mail context"),
1570             "goFonPIN"            => _("Telephone pin"),
1571             "goFonVoicemailPIN"   => _("Voicemail pin"))
1572           ));
1573   }
1577   function multiple_execute()
1578   {
1579     plugin::multiple_execute();
1580     return($this->execute());
1581   }
1583   function get_multi_init_values()
1584   {
1585     $ret = plugin::get_multi_init_values();
1586     $ret['phoneNumbers'] = array();
1587     foreach($this->phoneNumbers as $number){
1588       $ret['phoneNumbers'][] = $number."  [".$this->attrs['cn'][0]."]"; 
1589     }
1590     $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1591     return($ret);
1592   }
1594   function init_multiple_support($attrs,$all)
1595   {
1596     plugin::init_multiple_support($attrs,$all);
1598     $this->phoneNumbers = array();
1599     if(isset($all['phoneNumbers'])){
1600       for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1601         $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1602       }
1603     }
1604   }
1606   function multiple_save_object()
1607   {
1608     /* Simply call parents save_object */
1609     if (isset($_POST["phoneTab"])){
1611       plugin::save_object();
1612       plugin::multiple_save_object();
1614       /* Every macro in the select box are available */
1615       if((isset($_POST['macro']))){
1616         $this->macrostillavailable=true;
1617       }
1619       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1620         $this->is_modified =true;
1621       }
1623       /* get all Postvars */
1624       if(isset($this->macroarray[$this->macro])){
1625         foreach($this->macroarray[$this->macro] as $key => $paras){
1626           $backup = $this->macroarray[$this->macro][$key];
1627           if(isset($_POST[$paras['var']])){
1628             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1629           }
1630           if(isset($_POST['post_success'])){
1631             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1632               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1633                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1634               }else{
1635                 $this->macroarray[$this->macro][$key]['choosen']=false;
1636               }
1637             }
1638           }
1639         }
1640         if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1641           $this->modified = TRUE;
1642         }
1643       }
1644     }
1645   }
1647   function multiple_check()
1648   {
1649     $message = plugin::multiple_check();
1651     if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1652       $message[] = _("There is currently no asterisk server defined!");
1653     }
1655     if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1656       $message[] = _("Asterisk server is invalid!");
1657     }
1659     if(in_array("goFonVoicemailPIN",$this->multi_boxes) && 
1660         ( (strlen($this->goFonVoicemailPIN)==0)||
1661           (strlen($this->goFonVoicemailPIN)>4))){
1662       $message[]=(_("Voicemail PIN must be 4 characters long!"));
1663     }else{
1664       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1665         $message[]=(_("Voicemail PIN contains invalid characters!"));
1666       }
1667     }
1669     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1670       $message[]=(_("Phone pin contains invalid characters!"));
1671     }
1673     /* check for ! in any parameter setting*/
1674     if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1675       foreach($this->macroarray[$this->macro] as $val){
1676         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1677           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1678         }
1679       }
1680     }
1682     return($message);
1683   }
1685   function get_multi_edit_values()
1686   {
1687     $ret = plugin::get_multi_edit_values();
1688     if(in_array("macro",$this->multi_boxes)){
1689       $ret['macro'] = $this->macro;
1690       $ret['macroarray'] = $this->macroarray;
1691       $ret['macros'] = $this->macros;
1692     }
1693     return($ret);
1694   }
1697   /* Return asterisk contexts
1698    * Additionaly read contexts from file.
1699    */
1700   function get_asterisk_contexts()
1701   {
1702     $contexts = array();
1703     $contexts[] = "default";
1704     $contexts[] = "parkedcalls";
1705     $contexts[] = "from-sip";
1706     $contexts[] = "from-capi";
1707     $file = "/etc/gosa/asterisk_contexts.conf";
1708     if(file_exists($file) && is_readable($file)){
1709       foreach(file($file) as $context){
1710         $contexts[] = trim($context);
1711       }
1712     }
1713     array_unique($contexts);
1714     return($contexts);
1715   }
1718 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1719 ?>