Code

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