Code

Removed print_red calls
[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   /* 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     $config = session::get('config');
88     if(isset($config->data['SERVERS']['FON'])){
89       $this->goFonHomeServers = $config->data['SERVERS']['FON'];
90     }
92     $a_SETUP= array();
93     if($this->is_account && isset($config->data['SERVERS']['FON']) &&
94        array_key_exists('FON',$config->data['SERVERS']) &&
95        is_callable("mysql_connect")
96        ) {
98       /* Servers defined? Watch here... */
99       if (count($this->goFonHomeServers)){
101         /* Set default server */
102         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
103           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
104         }
106         /* Remember inital home server, to be able to remove old entries */
107         $this->init_HomeServer = $this->goFonHomeServer;
109         /* Get config */
110         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
111           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);
113           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
114           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
115         }    
116         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
118         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
119         if(!$r_con){
120           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
121         }
122         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
123         if(!$db){
124           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
125         }
127         $first = false; 
128         foreach($this->phoneNumbers as $key => $val){
129           if(!$first){
130             $first = $key;
131           }
132         }
133       }
134     }
136     /* Get available phone hardware  
137      * Search for all available phone hardware  
138      */
139     $tmp = get_sub_list("(objectClass=goFonHardware)","",array(get_ou("phoneou")),
140                   $this->config->current['BASE'],array("cn","description"), GL_NO_ACL_CHECK);
141     foreach($tmp as $attrs){
142       $cn= $attrs['cn'][0];
143       $description= "";
144       if (isset($attrs['description'])){
145         $description= " - ".$attrs['description'][0];
146       }
147       $this->hardware_list[$cn]= "$cn$description";
148     }
149     $this->hardware_list["automatic"]= _("automatic");
150     ksort($this->hardware_list);
153      /* Collect all usd phones 
154         goFonHardware set.
155      */
156     $deps_a = array(
157         get_people_ou(),
158         get_ou("ogroupou"),
159         get_ou("serverou"),
160         get_ou("terminalou"),
161         get_ou("workstationou"),
162         get_ou("printerou"),
163         get_ou("componentou"),
164         get_ou("phoneou"));
166     $tmp = get_sub_list("(goFonHardware=*)","",$deps_a,$this->config->current['BASE'],
167         array('cn','dn','goFonHardware'),GL_NO_ACL_CHECK);
168     foreach($tmp as $attrs){
169       $cn = $attrs['goFonHardware'][0];
170       if(isset($this->hardware_list[$cn])){
171         $this->used_hardware[$cn]= $cn;
172       }
173     }
176     /* Get available Macros  
177      * Search for all Marcos that are visible and create 
178      *  an array with name and parameters 
179      */
180     $tmp = get_sub_list("(&(objectClass=goFonMacro)(goFonMacroVisible=1))","",array(get_ou("macroou")),
181                   $this->config->current['BASE'],array("displayName","goFonMacroParameter","dn"), GL_NONE);
182     
184     /* Add none for no macro*/
185     $this->macros['none']=_("no macro");    
186     $this->macro ="none";
188     /* Fetch all Macros*/
189     foreach($tmp as $attrs){
191       /* unset Count, we don't need that here */
192       unset($attrs['displayName']['count']);
194       /* Parse macro data, unset count for parameterarrays  */
195       if (isset($attrs['goFonMacroParameter']['count'])){
196         unset($attrs['goFonMacroParameter']['count']);
197       }
199       /* fill Selectfield variable with Macros */
200       if(isset($attrs['displayName'][0])){
201         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
202       }else{
203         $this->macros[$attrs['dn']] = _("undefined");
204       }
206       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
207       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
209         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
210           /* Split Data in readable values, by delimiter !  */
211           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
213           /* Set all attrs */
214           $id = $data[0];
215           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
216           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
217           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
218           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
219           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
220           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
221           if($data[2] == "bool"){
222             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
223           }
224         }//foreach
225       }//is_array
226     }//while
229     /* Parse used Macro  
230      * If we have a macro selected, parse it and set values 
231      *  in $this->macroarray[$this->macro]. 
232      */
233     $tmp = split("!",$this->goFonMacro);
234     if(is_array($tmp)){
236       /* First value is the macroname */
237       $this->macro = $tmp[0];
239       /* Macroname saved, delete that index */
240       unset($tmp[0]);
242       /* Check if makro has been removed */
243       if(!isset($this->macros[$this->macro])){
244         $this->macrostillavailable = false;
245       }else{
246         $this->macrostillavailable = true;
247       }
249       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
250       foreach($tmp as $var){
252         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
253         $varar = split("#",$var);
255         /* Only insert if the parameter still exists */
256         if(isset($this->macroarray[$this->macro][$varar[0]])){
257           /* Assign value */
258           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
259         }
260       }
261     }
264     $this->a_old_telenums = $this->phoneNumbers;
266     /* Get voicemail PIN from MySQL DB 
267      * Because every user can change his PIN directly from the phone
268      *  without any update to the ldap
269      * This means, the PIN in the DB is up to date
270      */
271     // Connect to DB server
272     if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
273       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
274       if($r_con){
275         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
276   
277         $query_tmp = "SELECT ".$cur_cfg['VOICE_TABLE'].".password FROM  ".$cur_cfg['VOICE_TABLE'].", ".
278                      $cur_cfg['SIP_TABLE']."  WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'";
280         $vp = mysql_fetch_row(mysql_query($query_tmp));
281         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
282         if((isset($vp[0]))&&(!empty($vp[0]))){
283           $this->goFonPINVoice = $vp[0];
284         }
285       }
286     }
287     $this->lastmacro=$this->macro;
289     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
290       @mysql_close($r_con) ;
291     }
292   }
295   /* This function generates the Database entries. 
296    * The Parameter 'save' could be true or false.
297    *  false - means only testing no database transactions.
298    *  true  - write database entries.
299    *
300    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
301    * 
302    * If the phone hardware is 'automatic' the table entries will only be removed
303    *  and not added. 
304    */
305   function generate_mysql_entension_entries($save = false)
306   {
307     /* Check if there is at least one server available 
308      * If not, return and tell the user that saving failed 
309      */
310     if(!count($this->goFonHomeServers)){
311       if($save){
312         msg_dialog::display(_("Configuration error"), _("There is currently no asterisk server defined!"), WARNING_DIALOG);
313       }
314       return(true);
315     }
317     /* Check if Mysql extension is available */
318     if(!is_callable("mysql_pconnect")){
319       if($save){
320         msg_dialog::display(_("Configuration error"), sprintf(_("Missing %s PHP extension!"), "mysql"), WARNING_DIALOG);
321       }
322       return(true);
323     }
324  
325     /********************** 
326      * Attribute Initialisation
327      **********************/
329     $old_connection = false;
331     // Get Configuration for Mysql database Server
332     $s_parameter    = "";                                           // Contains paramter for selected Macro 
333     $r_con          = false;                                        // DB connection
334     $r_db           = false;                                        // Selected DB
335     $r_res          = false;                                        // Result resource
336     $a_ldap_attrs   = array();                                      //  
338     $s_ip           = NULL;                   // Contains ip for Sip entry
339     $s_host         = NULL;                   // Contains host for Sip entry
340     $s_qualify      = "yes";                  // Qualify entry
341     $s_pin          = NULL;                   // Entry for secret
342     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
344     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
345     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
346     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
348     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
349     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
351     $s_sip_key      = "";     // Key for SIP entry index      
352     $s_sip_val      = "";     // Value for SIP entry index      
354     $b_first_deleted= false;  // Only delete first entry, 
355     $s_telenums     = "";     // for each value variable
357     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
359     restore_error_handler();
361     /* Prepare some basic attributes */
362     $oldnums = array();
363     foreach($this->a_old_telenums as $tele){
364       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
365     }
366     foreach($this->phoneNumbers as $tele){
367       $newnums[]= preg_replace("/[^0-9]/","",$tele);
368     }
370     /* If deletion starts from userslist, cn uid are not set */
371     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
372       $this->uid = $this->parent->by_object['user']->uid;
373     }
374     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
375       $this->cn  = $this->parent->by_object['user']->cn;
376     }
377     /* Create voicemail entry 
378      */
379     if((!isset($this->cn))||(empty($this->cn))){
380       $CNname= $this->uid;
381     }else{
382       $CNname= $this->cn;
383     }
385     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
386       $s_mail = $this->parent->by_object['mailAccount']->mail;
387     }else{
388       $s_mail = "";
389     }
390     /* Get phonehardware to setup sip entry  */
391     $ldap         = $this->config->get_ldap_link();
392     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
393     $a_ldap_attrs = $ldap->fetch();
395     /* Check selected phone hardware, is a default IP set? */
396     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
397       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
398       $s_host     = $s_ip;
399     }else{
400       $s_ip       = NULL;
401       $s_host     = "dynamic";
402     }
404     // Attribute GoFonQualify set ?
405     if(isset($a_ldap_attrs['goFonQualify'])){
406       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
407     }
409     // Attribute GoFonPIN set ?
410     if(isset($this->goFonPIN)){
411       $s_pin      = $this->goFonPIN;
412     }
414     // Attribute GoFonType set ?
415     if(isset($a_ldap_attrs['goFonType'])){
416       $s_type = $a_ldap_attrs['goFonType'][0];
417     }
419     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
420       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
421     }else{
422       $sip_data_array['dtmfmode']     ="rfc2833";
423     }
425     /* Check if phone number is used */
426     if($this->is_number_used()){
427       $this->generate_error = $this->is_number_used(); 
428       return false;
429     }
433     /********************** 
434      * Check Server Connection Information
435      **********************/
436  
437     /* Create Mysql handle for the current goFonHomeServer, if possible  
438      * Get configuration to old asterisk home server 
439      */ 
440     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
441     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
442     if(!$new_connection){
443       $this->generate_error = sprintf(
444           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
445           $a_New['SERVER'],$a_New['LOGIN']);
446       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
447       return false;
448     }
449     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
450     if(!$new_database){
451       $this->generate_error = sprintf(
452           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
453           $a_New['DB'],$a_New['SERVER']);
454       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
455       return false;
456     }
458     /* If the home server has changed, we must remove entries from old 
459      *  server and add new entries in new server.  
460      */
461     if($this->init_HomeServer != $this->goFonHomeServer){
462     
463       /* Get configuration to old asterisk home server */ 
464       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
465  
466       /* Create connection to the database that contains the old entry. 
467        */
468       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
469       if(!$old_connection){
470         $this->generate_error = sprintf(
471             _("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."),
472             $a_Remove['SERVER'],$a_Remove['LOGIN']);
473         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
474         return false;
475       }
476       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
477       if(!$old_database){
478         $this->generate_error = sprintf(
479             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
480             $a_Remove['DB'],$a_Remove['SERVER']);
481         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
482         return false;
483       }
484     }
486     /* Save means that we must save changes, not only test  */
487     if($save == true){
488     
489       /********************** 
490        * Remove entries from old home server 
491        **********************/
493       /* Check if there is an old entry 
494        * If there is an old entry, get callerid and remove voicemail and extensions 
495        */
496       if($old_connection){
497         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
498         $rid    = mysql_query($query,$old_connection);
499         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
501         /* Old entry found, remove it */
502         $query_a = array();
503         if(mysql_affected_rows($old_connection)){
504           $result = mysql_fetch_assoc($rid);
505           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
506           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
507           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
508           foreach($oldnums as $s_telenums) {
509             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
510           }
512           foreach($query_a as $qry){
513                   @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
514             if(!mysql_query($qry,$old_connection)){
515               trigger_error(mysql_error($old_connection));
516             } 
517           }
518         }
519       }
521       /********************** 
522        * Update / Insert sip_users entry  
523        **********************/
525       /* Set the first given phone number as callerid */
526       reset($newnums);        
527       $i_new_key = key($newnums);
528       $sip_data_array['callerid']  =$newnums[$i_new_key];
529       $sip_data_array['mailbox']   =$newnums[$i_new_key];
531       /* Check if there is already an entry in sip_users for this uid */
532       $SQL_query_array = array();
533       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
534       $rid = mysql_query($query,$new_connection);
535       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
536       if(mysql_affected_rows($new_connection)){
538         /********************** 
539          * Update sip_users entry 
540          **********************/
541         $result                     = mysql_fetch_assoc($rid);
542         $sip_data_array['host']         = $s_host;
543         $sip_data_array['qualify']      = $s_qualify;
544         $sip_data_array['secret']       = $this->goFonPIN;
545         $sip_data_array['type']         = $s_type ;
546         $sip_data_array['username']     = $this->uid;
547         $sip_data_array['ipaddr']       = $s_ip;
549         /* Remove not changed attributes, to avoid updating table with same values */
550         foreach($sip_data_array as $name => $value){
551           if($result[$name] == $value){
552             unset($sip_data_array[$name]);
553           }
554         }
555         /* Only update entry if there is something to uopdate */
556         if(count($sip_data_array)){
557           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
558           foreach($sip_data_array as $key => $val){
559             $query.= "".$key."='".$val."',"; 
560           } 
561           $query = preg_replace("/,$/","",$query);
562           $query.= " WHERE name='".$this->uid."';";
563           $SQL_query_array[] = $query;
564         }
565       } else {
566  
567         /********************** 
568          * Insert sip_users entry 
569          **********************/
570         //generate SIP entry
571         $sip_data_array['id']           = "";
572         $sip_data_array['name']         = $this->uid;
573         $sip_data_array['accountcode']  = NULL;          
574         $sip_data_array['amaflags']     = NULL;
575         $sip_data_array['callgroup']    = NULL;
576         $sip_data_array['canreinvite']  = "no";
577         $sip_data_array['context']      = "default";
578         $sip_data_array['defaultip']    = NULL;
579         $sip_data_array['fromuser']     = NULL;
580         $sip_data_array['fromdomain']   = NULL;
581         $sip_data_array['host']         = $s_host;
582         $sip_data_array['insecure']     = NULL;
583         $sip_data_array['language']     = NULL;
584         $sip_data_array['mailbox']      = $newnums[$i_new_key];
585         $sip_data_array['md5secret']    = NULL;
586         $sip_data_array['nat']          = "no";
587         $sip_data_array['permit']       = NULL;
588         $sip_data_array['deny']         = NULL;
589         $sip_data_array['mask']         = NULL;
590         $sip_data_array['pickupgroup']  = NULL;
591         $sip_data_array['port']         = NULL;
592         $sip_data_array['qualify']      = $s_qualify;
593         $sip_data_array['restrictcid']  = "n";
594         $sip_data_array['rtptimeout']   = NULL;
595         $sip_data_array['rtpholdtimeout']=NULL;
596         $sip_data_array['secret']       = $this->goFonPIN;
597         $sip_data_array['type']         = $s_type ;
598         $sip_data_array['username']     = $this->uid;
599         $sip_data_array['disallow']     = NULL;
600         $sip_data_array['allow']        = NULL;
601         $sip_data_array['musiconhold']  = NULL;
602         $sip_data_array['regseconds']   = NULL;
603         $sip_data_array['ipaddr']       = $s_ip;
604         $sip_data_array['regexten']     = NULL;
605         $sip_data_array['cancallforward']=NULL;
607         /* There is currently no entry for this user in the sip_users table. 
608          * We should create one i
609          */
610         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
611           if($s_sip_val === NULL) continue;
612           $s_sip_values.="'".$s_sip_val."',";
613           $s_sip_keys  .="`".$s_sip_key."`,";
614         }
615         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
616         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
618         /* Add sip entries to mysql queries */
619         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
620       }
623       /********************** 
624        * Update / Insert Voice mail entry  
625        **********************/
627       $customer_id = $newnums[$i_new_key];
629       $voice_data_array = array(
630           "customer_id" => $customer_id,
631           "mailbox"     => $customer_id,
632           "password"    => $this->goFonVoicemailPIN,
633           "fullname"    => $CNname,
634           "email"       => $s_mail);
636       /* Set pager number if available */
637       if(isset($this->parent->by_object['user']->pager)){
638         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
639       }
641       /* Check if there is already an entry in sip_users for this uid */
642       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n";
643       $rid = mysql_query($query_tmp,$new_connection);
644       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
645       if(mysql_affected_rows($new_connection)){
647         /********************** 
648          * Update Voice mail entry  
649          **********************/
650         $result = mysql_fetch_assoc($rid)  ;
652         foreach($voice_data_array as $name => $value){
653           if($result[$name] == $value){
654             unset($voice_data_array[$name]);
655           }
656         }
658         /* Only update entry if there is something to uopdate */
659         if(count($voice_data_array)){
660           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
661           foreach($voice_data_array as $key => $val){
662             $query.= "".$key."='".$val."',"; 
663           } 
664           $query = preg_replace("/,$/","",$query);
665           $query.= " WHERE customer_id='".$customer_id."';";
666           $SQL_query_array[] = $query;
667         }
668       }else{
670         /********************** 
671          * Insert Voice mail entry  
672          **********************/
673         $voice_data_array['context'] = "default";
674   
675         /* There is currently no voice mail entry for this user. 
676          * We should create one 
677          */
678         $s_voi_values = $s_voi_keys = "";
679         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
680           if($s_voi_val === NULL) continue;
681           $s_voi_values.="'".$s_voi_val."',";
682           $s_voi_keys  .="`".$s_voi_key."`,";
683         }
684         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
685         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
687         /* Add sip entries to mysql queries */
688         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
689       }
691      
692       /********************** 
693        * Remove/Insert extension entries
694        **********************/
695       
696       /* Remove old entries */
697       $query = array();
698       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
699       foreach($oldnums as $s_telenums){
700         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
701       }
702       foreach($newnums as $s_telenums){
703         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
704       }
705       foreach($query as $qry){
706         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
707         if(!mysql_query($qry,$new_connection)){
708           trigger_error(mysql_error($new_connection));
709         } 
710       }
711  
712       /********************** 
713        * Insert extension entries
714        **********************/
715  
716       // Get selected Macro Parameter and create parameter entry 
717       if(isset($this->macroarray[$this->macro])){
718         foreach($this->macroarray[$this->macro] as $key => $val ){
719           $s_parameter .= $val['choosen']."|";
720         }
721         $s_parameter = preg_replace("/\|$/","",$s_parameter);
722       }
723      
724       $i = 0; 
725       $EXT = array();
726       if(!is_numeric($this->uid)){
727         $EXT[$i]['context'] = 'GOsa';
728         $EXT[$i]['exten']   = $this->uid;
729         $EXT[$i]['priority']= 1;
730         $EXT[$i]['app']     = "Goto";
731         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
732         $i ++;
733       }
735       // Entension entries  Hint / Dial / Goto
736       foreach($newnums as $s_telenums){
738         /* Hint Entry */
739         $EXT[$i]['context'] = 'GOsa';
740         $EXT[$i]['exten']   = $s_telenums;
741         $EXT[$i]['priority']= "Hint";
742         $EXT[$i]['app']     = 'SIP/'.$this->uid;
743         $i ++;  
744         /* SetCID */
745         //$EXT[$i]['context'] = 'GOsa';
746         //$EXT[$i]['exten']   = $s_telenums;
747         //$EXT[$i]['priority']= 1;
748         //$EXT[$i]['app']     = "SetCIDName";
749         //$EXT[$i]['appdata'] = $CNname;
750         //$i ++;  
752         // If no macro is selected use Dial
753         if($this->macro!="none"){ 
754           $macroname = preg_replace("/,.*$/","",$this->macro);        
755           $macroname = preg_replace("/^.*=/","",$macroname);        
756           $s_app = "Macro";$macroname;
757           $s_par = $macroname."|".$s_parameter; 
758         }else{
759           $s_app = "Dial";
760           $s_par = 'SIP/'.$this->uid."|20|r";
761         }
763         $EXT[$i]['context'] = 'GOsa';
764         $EXT[$i]['exten']   = $s_telenums;
765         $EXT[$i]['priority']= 1;
766         $EXT[$i]['app']     = $s_app;
767         $EXT[$i]['appdata'] = $s_par;
768         $i ++;
769       }
771       // Append all these Entries 
772       foreach($EXT as $entr){
773         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
774         foreach($entr as $key2 => $val2){
775           $SQL_syn.= "`".$key2."`,";
776         }
777         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
778         $SQL_syn .= ") VALUES ("; 
779         foreach($entr as $key2 => $val2){
780           $SQL_syn .= "'".$val2."',";
781         }
782         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
783         $SQL_syn .=");\n";
785         $SQL_query_array[] =$SQL_syn;
786         $SQL_syn ="";
787       }
789       // Perform queries ...
790       if($this->goFonHardware != "automatic"){
791         foreach($SQL_query_array as $query){
792           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
793           if(!@mysql_query($query,$new_connection)){
794             msg_dialog::display(_("Error"), sprintf(_("Cannot query %s database!"), "GOfon"), ERROR_DIALOG);
795             return false;
796           }
797         }
798       }
799     }
800     @mysql_close($new_connection);
801     return true;
802   }
805   function execute()
806   {
807     /* Call parent execute */
808     plugin::execute();
810     /* Log view */
811     if($this->is_account && !$this->view_logged){
812       $this->view_logged = TRUE;
813       new log("view","users/".get_class($this),$this->dn);
814     }
816     $display = "";
817     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
818     if(empty($this->macro)&&(!empty($this->goFonMacro))){
820       /* Go through already saved values, for a parameter */
821       $tmp = split("!",$this->goFonMacro);
823       /* it is possible that nothing has been saved yet */
824       if(is_array($tmp)){
826         /* First value is the macroname */
827         $this->macro = $tmp[0];
829         /* Macroname saved, delete that index */
830         unset($tmp[0]);
832         /* Check if macro has been removed */
833         if(!isset($this->macroarray[$this->macro])){
834           $this->macrostillavailable = false;
835         }else{
836           $this->macrostillavailable = true;
837         }
839         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
840         foreach($tmp as $var){
842           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
843           $varar = split("#",$var);
845           /* Only insert if the parameter still exists */
846           if(isset($this->macroarray[$this->macro][$varar[0]])){
847             /* Assign value */
848             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
849           }
850         }
851       }
852     }
853     
854     /* Do we represent a valid account? */
855     if (!$this->is_account && $this->parent === NULL){
856       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
857         _("This account has no phone extensions.")."</b>";
858       $display.= back_to_main();
859       return ($display);
860     }
862     /* Do we need to flip is_account state? */
863     if (isset($_POST['modify_state'])){
864       $this->is_account= !$this->is_account;
865     }
867     /* Do we represent a valid account? */
868     if (!$this->is_account && $this->parent === NULL){
869       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
870         _("This account has no phone extensions.")."</b>";
871       $display.= back_to_main();
872       return($display);
873     }
875     $display= "";
877     /* Show tab dialog headers */
878     
879     if (!$this->multiple_support_active && $this->parent !== NULL){
880       if ($this->is_account){
881         $display= $this->show_disable_header(_("Remove phone account"),
882             _("This account has phone features enabled. You can disable them by clicking below."));
883       } else {
884         if(empty($this->uid)){
885           $display= $this->show_enable_header(_("Create phone account"),
886               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
887         }else{
888           $display= $this->show_enable_header(_("Create phone account"),
889               _("This account has phone features disabled. You can enable them by clicking below."));
890         }
891         return ($display);
892       }
893     }
894     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
895     if(empty($this->macro)){
896       $this->macro ="none";
897     }
899     /* Prepare templating */
900     $smarty= get_smarty();
902     /* tell user that the selected plugin is no longer available */
903     if((!$this->macrostillavailable)&&($this->macro!="none")){
904       msg_dialog::display(_("Error"), _("Selected macro is not available anymore!"), ERROR_DIALOG);
905     }
907     /* Assing macroselectbox values  */
908     $smarty->assign("macros",$this->macros);   
909     $smarty->assign("macro", $this->macro);   
911     /* check if there is a FON server created */
912     if(!count($this->goFonHomeServer)){
913       msg_dialog::display(_("Configuration error"), _("There is currently no asterisk server defined!"), WARNING_DIALOG);
914     }
916     /* Create html parameter table for selected macro parameters 
917      *  skip if no parameters given 
918      */
919     if(!isset($this->macroarray[$this->macro])){
920       $macrotab="";
921     }else{
923       $macrotab ="<table summary=\""._("Parameter")."\">";
924       /* for every single parameter-> display textfile,combo, or true false switch*/
926       foreach($this->phoneNumbers as $phonenum){
927         $tmp[] = $phonenum;
928       }
929     
930       if($this->macro != $this->lastmacro){
931         /* Go through all params */
932         foreach($this->macroarray[$this->macro] as $key => $paras){
934           $string = $paras['default'];
936           $string=preg_replace("/%uid/i",$this->uid,$string);
938           if(isset($this->cn)){
939             $string=preg_replace("/%cn/i",$this->cn,$string);
940           }
942           for($i = 0 ; $i < 10; $i++){
943             if(isset($tmp[$i])){
944               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
945             }
946           }
947           if(isset($tmp[0])){
948             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
949           }
950           $this->macroarray[$this->macro][$key]['choosen']=$string;
951         }
952       }
954       foreach($this->macroarray[$this->macro] as $paras){
956         /* get al vars */
957         $var        = $paras['var'];           
958         $name       = $paras['name'];           
959         $default    = $paras['default'];
960         $type       = $paras['type'];
961         $choosen    = $paras['choosen'] ; 
962         $str        = $default;
964         $dis = "";
965         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
966           $dis = " disabled ";
967         }
969         /* in case of a combo box display a combobox with selected attr */
970         $macrotab.= "<tr>";
971         switch ($type){
973           case "combo":
974             $str= "<select name='".$var."' ".$dis." >";
975           foreach(split(":",$default) as $choice){
976             if($choosen==$choice){
977               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
978             }else{
979               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
980             }
981           }
982           $str.="</select>";
983           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
984           break;
986           case "bool":
987             if(!$choosen){
988               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
989             }else{
990               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
991             }
992           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
993           break;
995           case "string":
996             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
997           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
998           break;
1000         }
1001         $macrotab.= "</td></tr>";
1003       }
1004       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1005     }//is_array()
1007     /* Give smarty the table */
1008     $smarty->assign("macrotab",$macrotab);
1011     /* Add phone number */
1012     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1013       if (tests::is_phone_nr($_POST['phonenumber'])){
1014         $number= $_POST["phonenumber"];
1015         $this->phoneNumbers[$number]= $number;
1016         $this->is_modified= TRUE;
1017       } else {
1018         msg_dialog::display(_("Error"), _("Phone number is invalid!"), ERROR_DIALOG);
1019       }
1020     }
1022     /* Remove phone number */
1023     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1024       foreach ($_POST['phonenumber_list'] as $number){
1025         unset($this->phoneNumbers[$number]);
1026         $this->is_modified= TRUE;
1027       }
1028     }
1030     /* Assign acls */
1031     $tmp = $this->plInfo();
1032     foreach($tmp['plProvidedAcls'] as $name => $translation){
1033       $smarty->assign($name."ACL",$this->getacl($name));
1034     }
1036     /* Transfer ACL's */
1037     foreach($this->attributes as $val){
1038       if(isset($this->$val)){
1039         $smarty->assign($val,$this->$val);
1040       }else{
1041         $smarty->assign($val,"");
1042       }
1043     }
1045     /* Create home server array */
1046     $tmp = array();
1047     foreach($this->goFonHomeServers as $dn => $attrs){
1048       if(!is_numeric($dn)){
1049         $tmp[$dn] = $attrs['SERVER'];
1050       }
1051     }
1052     $smarty->assign("goFonHomeServers",$tmp);
1054     /* Fill arrays */
1055     $smarty->assign ("goFonHardware", $this->goFonHardware);
1056     if (!count($this->phoneNumbers)){
1057       $smarty->assign ("phoneNumbers", array());
1058     } else {
1059       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1060     }
1062     $dis = "";
1063     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1064       $dis= " disabled ";
1065     }
1066     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1067        _("Choose your private phone")."\">\n";
1069     foreach ($this->hardware_list as $cn => $description){
1070       if ($cn == $this->goFonHardware){
1071         $selected= "selected";
1072       } else {
1073         $selected= "";
1074       }
1075       if (isset($this->used_hardware[$cn])){
1076         $color= "style=\"color:#A0A0A0\"";
1077       } else {
1078         $color= "";
1079       }
1080       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1081     }
1082     $hl.= "</select>\n";
1083     $smarty->assign ("hardware_list", $hl);
1086     foreach($this->attributes as $attr){
1087       if(in_array($attr,$this->multi_boxes)){
1088         $smarty->assign("use_".$attr,TRUE);
1089       }else{
1090         $smarty->assign("use_".$attr,FALSE);
1091       }
1092     }
1094     /* Show main page */
1095     $this->lastmacro = $this->macro;
1096     $smarty->assign("multiple_support",$this->multiple_support_active);
1097     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1098     return($display);
1099   }
1102   function save_object()
1103   {
1104     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1105     if (isset($_POST["phoneTab"])){
1106     
1107       plugin::save_object();
1109       /* Save checkbox */
1110       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1111       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1112         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1113           $tmp .= "M";
1114         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1115           $tmp  = preg_replace ("/M/","",$tmp);
1116         }
1117       }
1118       $this->goFonDeliveryMode= "[".$tmp."]";
1121       /* Every macro in the select box are available */
1122       if((isset($_POST['macro']))){
1123         $this->macrostillavailable=true;
1124       }
1126       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1127         $this->is_modified =true;
1128       }
1130       if(is_array($this->phoneNumbers)){
1131         foreach($this->phoneNumbers as $telenumms) {
1132           $nummsinorder[]=$telenumms; 
1133         }
1134       }else{
1135         $nummsinorder=array("");
1136       }
1139       /* get all Postvars */
1140       if(isset($this->macroarray[$this->macro])){
1142         if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1143           foreach($this->macroarray[$this->macro] as $key => $paras){
1145             $backup = $this->macroarray[$this->macro][$key];
1147             if(isset($_POST[$paras['var']])){
1148               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1149             }
1151             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1152                We need this code below to read and save checkboxes correct
1153              */
1155             if(isset($_POST['post_success'])){
1156               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1157                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1158                   $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1159                 }else{
1160                   $this->macroarray[$this->macro][$key]['choosen']=false;
1161                 }
1162               }
1163             }
1164           }
1165           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1166             $this->modified = TRUE;
1167           }
1168         }
1169       }
1170     }
1171   }
1173   function check()
1174   {
1175     /* Call common method to give check the hook */
1176     $message= plugin::check();
1178     if(!count($this->goFonHomeServers)){
1179       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1180     }
1182     if(empty($this->goFonHomeServer)){
1183       $message[] = _("Please select a valid goFonHomeServer.");
1184     }
1186     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1187       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1188     }else{
1189       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1190         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1191       }
1192     }
1194     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1195       $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1196     }
1198     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1199       if(!$this->generate_mysql_entension_entries()){
1200         $message[] = $this->generate_error;
1201       }
1202     }
1204     /* We need at least one phone number */
1205     if (count($this->phoneNumbers) == 0){
1206       $message[]= sprintf(_("You need to specify at least one phone number!"));
1207     }
1209     /* check for ! in any parameter setting*/
1210     if(isset($this->macroarray[$this->macro])){
1211       foreach($this->macroarray[$this->macro] as $val){
1212         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1213           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1214         }
1215       }
1216     }
1217     return ($message);
1218   }
1222   function save()
1223   {
1224     plugin::save();
1226     /* Force saving macro again 
1227      * This ensures that 
1228      *  - the macro is available on the destiantion server.
1229      *  - the macro saved is up to date on the destination server.
1230      */
1231     if(!empty($this->macro) && $this->macro != "none")  {
1232       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1233       $macro_tab -> save();
1234     }
1236     /* Save arrays */
1237     $tmp_numbers = array();
1238     foreach ($this->phoneNumbers as $number){
1239       $tmp_numbers[] = $number;
1240     }
1242     /* Save settings, or remove goFonMacro attribute*/
1243     if($this->macro!="none"){    
1244       $this->attrs['goFonMacro']=$this->macro;
1245       if(isset($this->macroarray[$this->macro])){
1246         foreach($this->macroarray[$this->macro] as $paras)  {
1247           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1248         }
1249       }
1250     }else{
1251       $this->attrs['goFonMacro']=array();
1252     }
1253     unset($this->attrs['macro'])  ;
1255     $this->attrs['goFonForwarding']=array();
1257     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1258       $str = $this->generate_mysql_entension_entries(true);
1259       if(empty($str)){
1260         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
1261       }
1262     }
1264     if($this->attrs['goFonMacro']==""){
1265       $this->attrs['goFonMacro']=array();
1266     }
1268     unset($this->attrs['cn']);
1270     /* Write back to ldap */
1271     $ldap= $this->config->get_ldap_link();
1272     $ldap->cd($this->dn);
1273     $this->cleanup();
1274     
1275     /* Force saving numbers, else it will be overwriten by user account. */
1276     $this->attrs['telephoneNumber'] =$tmp_numbers;
1277     $ldap->modify ($this->attrs); 
1279     /* Log last action */
1280     if($this->initially_was_account){
1281       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1282     }else{
1283       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1284     }
1286     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/phone account with dn '%s' failed."),$this->dn));
1288     /* Optionally execute a command after we're done */
1290     if ($this->initially_was_account == $this->is_account){
1291       if ($this->is_modified){
1292         $this->handle_post_events("modify",array("uid" => $this->uid));
1293       }
1294     } else {
1295       $this->handle_post_events("add",array("uid" => $this->uid));
1296     }
1298   }
1301   function adapt_from_template($dn)
1302   {
1303     plugin::adapt_from_template($dn);
1305     /* Assemble phone numbers */
1306     if (isset($this->attrs['telephoneNumber'])){
1307       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1308         $number= $this->attrs['telephoneNumber'][$i];
1309         $this->phoneNumbers[$number]= $number;
1310       }
1311     }
1312   }
1315   function remove_from_parent()
1316   {
1317     if(!$this->initially_was_account) return;
1319     foreach($this->attributes as $key=>$val){
1320       if(in_array($val,array("uid","cn"))){
1321         unset($this->attributes[$key]);
1322         unset($this->$val);
1323       }
1324     }
1325     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1327       // Get Configuration for initial Mysql database Server
1328       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1329       $s_parameter  ="";
1331       // Connect to DB server
1332       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1334       // Check if we are  connected correctly
1335       if(!$r_con){
1336         msg_dialog::display(_("Error"), sprintf(_("Cannot connect to %s database!"), "GOfon"), ERROR_DIALOG);
1337         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1338         return false;
1339       }
1341       // Select database for Extensions
1342       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1344       // Test if we have the database selected correctly
1345       if(!$db){
1346         msg_dialog::display(_("Error"), sprintf(_("Cannot select %s database!"), "GOfon"), ERROR_DIALOG);
1347         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1348         return false;
1349       }
1351       $SQL="";
1353       /* If deletion starts from userslist, cn uid are not set */
1354       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1355         $this->uid = $this->parent->by_object['user']->uid;
1356       }
1358       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1359         $this->cn  = $this->parent->by_object['user']->cn;
1360       }
1362       $first_num = false;
1363       // Delete old entries
1364       foreach($this->a_old_telenums as $s_telenums){
1365         if(!$first_num){
1366           $first_num = $s_telenums;
1367         }
1368         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1369       }
1371       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1372       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1373       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1375       foreach($SQL as $query){
1376         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1377         if(!@mysql_query($query,$r_con)){
1378           msg_dialog::display(_("Error"), sprintf(_("Cannot query %s database!"), "GOfon"), ERROR_DIALOG);
1379           return false;
1380         }
1381       }
1382     }else{
1383       msg_dialog::display(_("Configuration error"), sprintf(_("Missing %s PHP extension!"), "mysql"), WARNING_DIALOG);
1384       return false;
1385     }
1387     /* unset macro attr, it will cause an error */
1388     $tmp = array_flip($this->attributes);
1389     unset($tmp['macro']);
1390     $this->attributes=array_flip($tmp);
1392     /* Cancel if there's nothing to do here */
1393     if (!$this->initially_was_account){
1394       return;
1395     }
1397     plugin::remove_from_parent();
1399     /* Just keep one phone number */
1400     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1401       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1402     } else {
1403       $this->attrs['telephoneNumber']= array();
1404     }
1407     $ldap= $this->config->get_ldap_link();
1408     $ldap->cd($this->config->current['BASE']);
1409     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1410     while($attr = $ldap->fetch()){
1411       if(in_array($this->dn,$attr['member'])){
1412         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1413         unset($new->by_object['ogroup']->memberList[$this->dn]);
1414         unset($new->by_object['ogroup']->member[$this->dn]);
1415         $new->save();
1416         msg_dialog::display(_("Information"), sprintf(_("User '%s' has been removed from phone queue '%s'."), $this->cn, $new->by_object['ogroup']->cn), INFO_DIALOG);
1417       }
1418     }
1419     $ldap->cd($this->dn);
1420     $this->cleanup();
1421     $ldap->modify ($this->attrs); 
1423     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1424     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/phone account with dn '%s' failed."),$this->dn));
1426     /* Optionally execute a command after we're done */
1427     @mysql_close($r_con);
1428     $this->handle_post_events('remove',array("uid"=> $this->uid));
1429   }
1433   /* This function checks if the given phonenumbers are available or already in use*/
1434   function is_number_used()
1435   {
1436     $ldap= $this->config->get_ldap_link();
1437     $ldap->cd($this->config->current['BASE']);
1438     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1439     while($attrs = $ldap->fetch()) {
1440       unset($attrs['telephoneNumber']['count']);
1441       foreach($attrs['telephoneNumber'] as $tele){
1442         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1443         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1444         $numbers[$tele]=$attrs;
1445       }
1446     }
1448     foreach($this->phoneNumbers as $num){
1449       if(!isset($this->cn)) $this->cn = "";
1451       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1452         if(isset($numbers[$num]['uid'][0])){
1453           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1454         }else{
1455           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1456         }
1457       }
1458     }
1459   }
1462   /* Create phoneAccount part of copy & paste dialog */
1463   function getCopyDialog()
1464   { 
1465     if(!$this->is_account) return("");
1466     $smarty = get_smarty();
1467     if (!count($this->phoneNumbers)){
1468       $smarty->assign ("phoneNumbers", array(""));
1469     } else {
1470       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1471     }
1473     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1474     $smarty->assign("goFonPIN",$this->goFonPIN);
1476     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1477     $ret =array();
1478     $ret['string'] = $display;
1479     $ret['status'] = "";
1480     return($ret);
1481   }
1483   /* Save posts from copy & paste dialog dialog  */
1484   function saveCopyDialog()
1485   {
1486     if(!$this->is_account) return;
1487     $this->execute();
1488     if(isset($_POST['goFonVoicemailPIN'])) {
1489       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1490     }
1491     if(isset($_POST['goFonPIN'])){
1492       $this->goFonPIN = $_POST['goFonPIN'];
1493     }
1494   }
1497   function allow_remove()
1498   {
1499     /* Check if previously selected server is still available */
1500     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1501       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1502     }
1503   }
1505   /* Return plugin informations for acl handling */
1506   static function plInfo()
1507   {
1508     return (array(
1509           "plShortName"     => _("Phone"),
1510           "plDescription"   => _("Phone account settings"),
1511           "plSelfModify"    => TRUE,
1512           "plDepends"       => array("user"),
1513           "plPriority"      => 7,                                 // Position in tabs
1514           "plSection"       => "personal",                        // This belongs to personal
1515           "plCategory"      => array("gofonreport" => array("description" => _("GOfon reports"),
1516               "objectClass" => "")),
1518           "plOptions"       => array(),
1520           "plProvidedAcls"  => array(
1521             "telephoneNumber"     => _("Telephone number"),
1522             "goFonHomeServer"     => _("Home server"),
1523             "goFonMacro"          => _("Macro settings"),
1524             "goFonHardware"       => _("Phone hardware"),
1525             "goFonPIN"            => _("Telephone pin"),
1526             "goFonVoicemailPIN"   => _("Voicemail pin"))
1527           ));
1528   }
1532   function multiple_execute()
1533   {
1534     plugin::multiple_execute();
1535     return($this->execute());
1536   }
1538   function get_multi_init_values()
1539   {
1540     $ret = plugin::get_multi_init_values();
1541     $ret['phoneNumbers'] = array();
1542     foreach($this->phoneNumbers as $number){
1543       $ret['phoneNumbers'][] = $number."  [".$this->attrs['cn'][0]."]"; 
1544     }
1545     $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1546     return($ret);
1547   }
1549   function init_multiple_support($attrs,$all)
1550   {
1551     plugin::init_multiple_support($attrs,$all);
1553     $this->phoneNumbers = array();
1554     if(isset($all['phoneNumbers'])){
1555       for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1556         $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1557       }
1558     }
1559   }
1561   function multiple_save_object()
1562   {
1563     /* Simply call parents save_object */
1564     if (isset($_POST["phoneTab"])){
1566       plugin::save_object();
1567       plugin::multiple_save_object();
1569       /* Every macro in the select box are available */
1570       if((isset($_POST['macro']))){
1571         $this->macrostillavailable=true;
1572       }
1574       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1575         $this->is_modified =true;
1576       }
1578       /* get all Postvars */
1579       if(isset($this->macroarray[$this->macro])){
1580         foreach($this->macroarray[$this->macro] as $key => $paras){
1581           $backup = $this->macroarray[$this->macro][$key];
1582           if(isset($_POST[$paras['var']])){
1583             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1584           }
1585           if(isset($_POST['post_success'])){
1586             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1587               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1588                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1589               }else{
1590                 $this->macroarray[$this->macro][$key]['choosen']=false;
1591               }
1592             }
1593           }
1594         }
1595         if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1596           $this->modified = TRUE;
1597         }
1598       }
1599     }
1600   }
1602   function multiple_check()
1603   {
1604     $message = plugin::multiple_check();
1606     if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1607       $message[] = _("There is currently no asterisk server defined!");
1608     }
1610     if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1611       $message[] = _("Asterisk server is invalid!");
1612     }
1614     if(in_array("goFonVoicemailPIN",$this->multi_boxes) && 
1615         ( (strlen($this->goFonVoicemailPIN)==0)||
1616           (strlen($this->goFonVoicemailPIN)>4))){
1617       $message[]=(_("Voicemail PIN must be 4 characters long!"));
1618     }else{
1619       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1620         $message[]=(_("Voicemail PIN contains invalid characters!"));
1621       }
1622     }
1624     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1625       $message[]=(_("Phone pin contains invalid characters!"));
1626     }
1628     /* check for ! in any parameter setting*/
1629     if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1630       foreach($this->macroarray[$this->macro] as $val){
1631         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1632           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1633         }
1634       }
1635     }
1637     return($message);
1638   }
1640   function get_multi_edit_values()
1641   {
1642     $ret = plugin::get_multi_edit_values();
1643     if(in_array("macro",$this->multi_boxes)){
1644       $ret['macro'] = $this->macro;
1645       $ret['macroarray'] = $this->macroarray;
1646       $ret['macros'] = $this->macros;
1647     }
1648     return($ret);
1649   }
1652 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1653 ?>