Code

Pre-initailized variable
[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)","phone",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=*)","phone",$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))","gofonmacro",array(get_ou("macroou")),
176                   $this->config->current['BASE'],array("displayName","goFonMacroParameter","dn","cn"), 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"), msgPool::noserver(_("GOfon")), 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"), msgPool::missingext("php-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 =  msgPool::dbconnect($a_New['SERVER'],@mysql_error($new_connection),
439           _("Abort saving entries to keep the database consistent."));
440       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
441       return false;
442     }
443     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
444     if(!$new_database){
445       $this->generate_error =  msgPool::dbselect($a_New['DB'],@mysql_error($new_connection),
446           _("Abort saving entries to keep the database consistent."));
447       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
448       return false;
449     }
451     /* If the home server has changed, we must remove entries from old 
452      *  server and add new entries in new server.  
453      */
454     if($this->init_HomeServer != $this->goFonHomeServer){
455     
456       /* Get configuration to old asterisk home server */ 
457       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
458  
459       /* Create connection to the database that contains the old entry. 
460        */
461       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
462       if(!$old_connection){
463         $this->generate_error =  msgPool::dbconnect($a_Remove['SERVER'],@mysql_error($old_connection),
464             _("Abort saving entries to keep the database consistent."));
465         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
466         return false;
467       }
468       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
469       if(!$old_database){
470         $this->generate_error =  msgPool::dbselect($a_Remove['DB'],@mysql_error($old_connection),
471             _("Abort saving entries to keep the database consistent."));
472         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
473         return false;
474       }
475     }
477     /* Save means that we must save changes, not only test  */
478     if($save == true){
479     
480       /********************** 
481        * Remove entries from old home server 
482        **********************/
484       /* Check if there is an old entry 
485        * If there is an old entry, get callerid and remove voicemail and extensions 
486        */
487       if($old_connection){
488         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
489         $rid    = mysql_query($query,$old_connection);
490         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
492         /* Old entry found, remove it */
493         $query_a = array();
494         if(mysql_affected_rows($old_connection)){
495           $result = mysql_fetch_assoc($rid);
496           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
497           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
498           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
499           foreach($oldnums as $s_telenums) {
500             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
501           }
503           foreach($query_a as $qry){
504                   @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
505             if(!mysql_query($qry,$old_connection)){
506               trigger_error(mysql_error($old_connection));
507             } 
508           }
509         }
510       }
512       /********************** 
513        * Update / Insert sip_users entry  
514        **********************/
516       /* Set the first given phone number as callerid */
517       reset($newnums);        
518       $i_new_key = key($newnums);
519       $sip_data_array['callerid']  =$newnums[$i_new_key];
520       $sip_data_array['mailbox']   =$newnums[$i_new_key];
522       /* Check if there is already an entry in sip_users for this uid */
523       $SQL_query_array = array();
524       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
525       $rid = mysql_query($query,$new_connection);
526       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
527       if(mysql_affected_rows($new_connection)){
529         /********************** 
530          * Update sip_users entry 
531          **********************/
532         $result                     = mysql_fetch_assoc($rid);
533         $sip_data_array['host']         = $s_host;
534         $sip_data_array['qualify']      = $s_qualify;
535         $sip_data_array['secret']       = $this->goFonPIN;
536         $sip_data_array['type']         = $s_type ;
537         $sip_data_array['username']     = $this->uid;
538         $sip_data_array['ipaddr']       = $s_ip;
540         /* Remove not changed attributes, to avoid updating table with same values */
541         foreach($sip_data_array as $name => $value){
542           if($result[$name] == $value){
543             unset($sip_data_array[$name]);
544           }
545         }
546         /* Only update entry if there is something to uopdate */
547         if(count($sip_data_array)){
548           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
549           foreach($sip_data_array as $key => $val){
550             $query.= "".$key."='".$val."',"; 
551           } 
552           $query = preg_replace("/,$/","",$query);
553           $query.= " WHERE name='".$this->uid."';";
554           $SQL_query_array[] = $query;
555         }
556       } else {
557  
558         /********************** 
559          * Insert sip_users entry 
560          **********************/
561         //generate SIP entry
562         $sip_data_array['id']           = "";
563         $sip_data_array['name']         = $this->uid;
564         $sip_data_array['accountcode']  = NULL;          
565         $sip_data_array['amaflags']     = NULL;
566         $sip_data_array['callgroup']    = NULL;
567         $sip_data_array['canreinvite']  = "no";
568         $sip_data_array['context']      = "default";
569         $sip_data_array['defaultip']    = NULL;
570         $sip_data_array['fromuser']     = NULL;
571         $sip_data_array['fromdomain']   = NULL;
572         $sip_data_array['host']         = $s_host;
573         $sip_data_array['insecure']     = NULL;
574         $sip_data_array['language']     = NULL;
575         $sip_data_array['mailbox']      = $newnums[$i_new_key];
576         $sip_data_array['md5secret']    = NULL;
577         $sip_data_array['nat']          = "no";
578         $sip_data_array['permit']       = NULL;
579         $sip_data_array['deny']         = NULL;
580         $sip_data_array['mask']         = NULL;
581         $sip_data_array['pickupgroup']  = NULL;
582         $sip_data_array['port']         = NULL;
583         $sip_data_array['qualify']      = $s_qualify;
584         $sip_data_array['restrictcid']  = "n";
585         $sip_data_array['rtptimeout']   = NULL;
586         $sip_data_array['rtpholdtimeout']=NULL;
587         $sip_data_array['secret']       = $this->goFonPIN;
588         $sip_data_array['type']         = $s_type ;
589         $sip_data_array['username']     = $this->uid;
590         $sip_data_array['disallow']     = NULL;
591         $sip_data_array['allow']        = NULL;
592         $sip_data_array['musiconhold']  = NULL;
593         $sip_data_array['regseconds']   = NULL;
594         $sip_data_array['ipaddr']       = $s_ip;
595         $sip_data_array['regexten']     = NULL;
596         $sip_data_array['cancallforward']=NULL;
598         /* There is currently no entry for this user in the sip_users table. 
599          * We should create one i
600          */
601         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
602           if($s_sip_val === NULL) continue;
603           $s_sip_values.="'".$s_sip_val."',";
604           $s_sip_keys  .="`".$s_sip_key."`,";
605         }
606         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
607         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
609         /* Add sip entries to mysql queries */
610         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
611       }
614       /********************** 
615        * Update / Insert Voice mail entry  
616        **********************/
618       $customer_id = $newnums[$i_new_key];
620       $voice_data_array = array(
621           "customer_id" => $customer_id,
622           "mailbox"     => $customer_id,
623           "password"    => $this->goFonVoicemailPIN,
624           "fullname"    => $CNname,
625           "email"       => $s_mail);
627       /* Set pager number if available */
628       if(isset($this->parent->by_object['user']->pager)){
629         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
630       }
632       /* Check if there is already an entry in sip_users for this uid */
633       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n";
634       $rid = mysql_query($query_tmp,$new_connection);
635       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
636       if(mysql_affected_rows($new_connection)){
638         /********************** 
639          * Update Voice mail entry  
640          **********************/
641         $result = mysql_fetch_assoc($rid)  ;
643         foreach($voice_data_array as $name => $value){
644           if($result[$name] == $value){
645             unset($voice_data_array[$name]);
646           }
647         }
649         /* Only update entry if there is something to uopdate */
650         if(count($voice_data_array)){
651           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
652           foreach($voice_data_array as $key => $val){
653             $query.= "".$key."='".$val."',"; 
654           } 
655           $query = preg_replace("/,$/","",$query);
656           $query.= " WHERE customer_id='".$customer_id."';";
657           $SQL_query_array[] = $query;
658         }
659       }else{
661         /********************** 
662          * Insert Voice mail entry  
663          **********************/
664         $voice_data_array['context'] = "default";
665   
666         /* There is currently no voice mail entry for this user. 
667          * We should create one 
668          */
669         $s_voi_values = $s_voi_keys = "";
670         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
671           if($s_voi_val === NULL) continue;
672           $s_voi_values.="'".$s_voi_val."',";
673           $s_voi_keys  .="`".$s_voi_key."`,";
674         }
675         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
676         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
678         /* Add sip entries to mysql queries */
679         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
680       }
682      
683       /********************** 
684        * Remove/Insert extension entries
685        **********************/
686       
687       /* Remove old entries */
688       $query = array();
689       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
690       $oldnums= array();
691       foreach($oldnums as $s_telenums){
692         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
693       }
694       foreach($newnums as $s_telenums){
695         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
696       }
697       foreach($query as $qry){
698         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
699         if(!mysql_query($qry,$new_connection)){
700           trigger_error(mysql_error($new_connection));
701         } 
702       }
703  
704       /********************** 
705        * Insert extension entries
706        **********************/
707  
708       // Get selected Macro Parameter and create parameter entry 
709       if(isset($this->macroarray[$this->macro])){
710         foreach($this->macroarray[$this->macro] as $key => $val ){
711           $s_parameter .= $val['choosen']."|";
712         }
713         $s_parameter = preg_replace("/\|$/","",$s_parameter);
714       }
715      
716       $i = 0; 
717       $EXT = array();
718       if(!is_numeric($this->uid)){
719         $EXT[$i]['context'] = 'GOsa';
720         $EXT[$i]['exten']   = $this->uid;
721         $EXT[$i]['priority']= 1;
722         $EXT[$i]['app']     = "Goto";
723         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
724         $i ++;
725       }
727       // Entension entries  Hint / Dial / Goto
728       foreach($newnums as $s_telenums){
730         /* Hint Entry */
731         $EXT[$i]['context'] = 'GOsa';
732         $EXT[$i]['exten']   = $s_telenums;
733         $EXT[$i]['priority']= "Hint";
734         $EXT[$i]['app']     = 'SIP/'.$this->uid;
735         $i ++;  
736         /* SetCID */
737         //$EXT[$i]['context'] = 'GOsa';
738         //$EXT[$i]['exten']   = $s_telenums;
739         //$EXT[$i]['priority']= 1;
740         //$EXT[$i]['app']     = "SetCIDName";
741         //$EXT[$i]['appdata'] = $CNname;
742         //$i ++;  
744         // If no macro is selected use Dial
745         if($this->macro!="none"){ 
746           $macroname = preg_replace("/,.*$/","",$this->macro);        
747           $macroname = preg_replace("/^.*=/","",$macroname);        
748           $s_app = "Macro";$macroname;
749           $s_par = $macroname."|".$s_parameter; 
750         }else{
751           $s_app = "Dial";
752           $s_par = 'SIP/'.$this->uid."|20|r";
753         }
755         $EXT[$i]['context'] = 'GOsa';
756         $EXT[$i]['exten']   = $s_telenums;
757         $EXT[$i]['priority']= 1;
758         $EXT[$i]['app']     = $s_app;
759         $EXT[$i]['appdata'] = $s_par;
760         $i ++;
761       }
763       // Append all these Entries 
764       foreach($EXT as $entr){
765         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
766         foreach($entr as $key2 => $val2){
767           $SQL_syn.= "`".$key2."`,";
768         }
769         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
770         $SQL_syn .= ") VALUES ("; 
771         foreach($entr as $key2 => $val2){
772           $SQL_syn .= "'".$val2."',";
773         }
774         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
775         $SQL_syn .=");\n";
777         $SQL_query_array[] =$SQL_syn;
778         $SQL_syn ="";
779       }
781       // Perform queries ...
782       if($this->goFonHardware != "automatic"){
783         foreach($SQL_query_array as $query){
784           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
785           if(!@mysql_query($query,$new_connection)){
786             $this->generate_error =  msgPool::dbquery("GOfon",@mysql_error($old_connection));
787             return false;
788           }
789         }
790       }
791     }
792     @mysql_close($new_connection);
793     return true;
794   }
797   function execute()
798   {
799     /* Call parent execute */
800     plugin::execute();
802     /* Log view */
803     if($this->is_account && !$this->view_logged){
804       $this->view_logged = TRUE;
805       new log("view","users/".get_class($this),$this->dn);
806     }
808     $display = "";
809     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
810     if(empty($this->macro)&&(!empty($this->goFonMacro))){
812       /* Go through already saved values, for a parameter */
813       $tmp = split("!",$this->goFonMacro);
815       /* it is possible that nothing has been saved yet */
816       if(is_array($tmp)){
818         /* First value is the macroname */
819         $this->macro = $tmp[0];
821         /* Macroname saved, delete that index */
822         unset($tmp[0]);
824         /* Check if macro has been removed */
825         if(!isset($this->macroarray[$this->macro])){
826           $this->macrostillavailable = false;
827         }else{
828           $this->macrostillavailable = true;
829         }
831         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
832         foreach($tmp as $var){
834           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
835           $varar = split("#",$var);
837           /* Only insert if the parameter still exists */
838           if(isset($this->macroarray[$this->macro][$varar[0]])){
839             /* Assign value */
840             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
841           }
842         }
843       }
844     }
845     
846     /* Do we represent a valid account? */
847     if (!$this->is_account && $this->parent === NULL){
848       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
849         msgPool::noValidExtension(_("Phone"))."</b>";
850       $display.= back_to_main();
851       return ($display);
852     }
854     /* Do we need to flip is_account state? */
855     if (isset($_POST['modify_state'])){
856       $this->is_account= !$this->is_account;
857     }
859     /* Do we represent a valid account? */
860     if (!$this->is_account && $this->parent === NULL){
861       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
862         msgPool::noValidExtension(_("Phone"))."</b>";
863       $display.= back_to_main();
864       return($display);
865     }
867     $display= "";
869     /* Show tab dialog headers */
870     
871     if (!$this->multiple_support_active && $this->parent !== NULL){
872       if ($this->is_account){
873         $display= $this->show_disable_header(_("Remove phone account"),
874             msgPool::featuresEnabled(_("Phone")));
875       } else {
876         if(empty($this->uid)){
877           $display= $this->show_enable_header(_("Create phone account"),
878             msgPool::featuresDisabled(_("Phone"),_("User uid")));
879         }else{
880           $display= $this->show_enable_header(_("Create phone account"),
881             msgPool::featuresDisabled(_("Phone")));
882         }
883         return ($display);
884       }
885     }
886     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
887     if(empty($this->macro)){
888       $this->macro ="none";
889     }
891     /* Prepare templating */
892     $smarty= get_smarty();
894     /* tell user that the selected plugin is no longer available */
895     if((!$this->macrostillavailable)&&($this->macro!="none")){
896       msg_dialog::display(_("Error"), _("Selected macro is not available anymore!"), ERROR_DIALOG);
897     }
899     /* Assing macroselectbox values  */
900     $smarty->assign("macros",$this->macros);   
901     $smarty->assign("macro", $this->macro);   
903     /* check if there is a FON server created */
904     if(!count($this->goFonHomeServer)){
905       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
906     }
908     /* Create html parameter table for selected macro parameters 
909      *  skip if no parameters given 
910      */
911     if(!isset($this->macroarray[$this->macro])){
912       $macrotab="";
913     }else{
915       $macrotab ="<table summary=\""._("Parameter")."\">";
916       /* for every single parameter-> display textfile,combo, or true false switch*/
918       foreach($this->phoneNumbers as $phonenum){
919         $tmp[] = $phonenum;
920       }
921     
922       if($this->macro != $this->lastmacro){
923         /* Go through all params */
924         foreach($this->macroarray[$this->macro] as $key => $paras){
926           $string = $paras['default'];
928           $string=preg_replace("/%uid/i",$this->uid,$string);
930           if(isset($this->cn)){
931             $string=preg_replace("/%cn/i",$this->cn,$string);
932           }
934           for($i = 0 ; $i < 10; $i++){
935             if(isset($tmp[$i])){
936               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
937             }
938           }
939           if(isset($tmp[0])){
940             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
941           }
942           $this->macroarray[$this->macro][$key]['choosen']=$string;
943         }
944       }
946       foreach($this->macroarray[$this->macro] as $paras){
948         /* get al vars */
949         $var        = $paras['var'];           
950         $name       = $paras['name'];           
951         $default    = $paras['default'];
952         $type       = $paras['type'];
953         $choosen    = $paras['choosen'] ; 
954         $str        = $default;
956         $dis = "";
957         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
958           $dis = " disabled ";
959         }
961         /* in case of a combo box display a combobox with selected attr */
962         $macrotab.= "<tr>";
963         switch ($type){
965           case "combo":
966             $str= "<select name='".$var."' ".$dis." >";
967           foreach(split(":",$default) as $choice){
968             if($choosen==$choice){
969               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
970             }else{
971               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
972             }
973           }
974           $str.="</select>";
975           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
976           break;
978           case "bool":
979             if(!$choosen){
980               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
981             }else{
982               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
983             }
984           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
985           break;
987           case "string":
988             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
989           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
990           break;
992         }
993         $macrotab.= "</td></tr>";
995       }
996       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
997     }//is_array()
999     /* Give smarty the table */
1000     $smarty->assign("macrotab",$macrotab);
1003     /* Add phone number */
1004     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1005       if (tests::is_phone_nr($_POST['phonenumber'])){
1006         $number= $_POST["phonenumber"];
1007         $this->phoneNumbers[$number]= $number;
1008         $this->is_modified= TRUE;
1009       } else {
1010         msg_dialog::display(_("Error"), msgPool::invalid("Phone number"), ERROR_DIALOG);
1011       }
1012     }
1014     /* Remove phone number */
1015     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1016       foreach ($_POST['phonenumber_list'] as $number){
1017         unset($this->phoneNumbers[$number]);
1018         $this->is_modified= TRUE;
1019       }
1020     }
1022     /* Assign acls */
1023     $tmp = $this->plInfo();
1024     foreach($tmp['plProvidedAcls'] as $name => $translation){
1025       $smarty->assign($name."ACL",$this->getacl($name));
1026     }
1028     /* Transfer ACL's */
1029     foreach($this->attributes as $val){
1030       if(isset($this->$val)){
1031         $smarty->assign($val,$this->$val);
1032       }else{
1033         $smarty->assign($val,"");
1034       }
1035     }
1037     /* Create home server array */
1038     $tmp = array();
1039     foreach($this->goFonHomeServers as $dn => $attrs){
1040       if(!is_numeric($dn)){
1041         $tmp[$dn] = $attrs['SERVER'];
1042       }
1043     }
1044     $smarty->assign("goFonHomeServers",$tmp);
1046     /* Fill arrays */
1047     $smarty->assign ("goFonHardware", $this->goFonHardware);
1048     if (!count($this->phoneNumbers)){
1049       $smarty->assign ("phoneNumbers", array());
1050     } else {
1051       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1052     }
1054     $dis = "";
1055     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1056       $dis= " disabled ";
1057     }
1058     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1059        _("Choose your private phone")."\">\n";
1061     foreach ($this->hardware_list as $cn => $description){
1062       if ($cn == $this->goFonHardware){
1063         $selected= "selected";
1064       } else {
1065         $selected= "";
1066       }
1067       if (isset($this->used_hardware[$cn])){
1068         $color= "style=\"color:#A0A0A0\"";
1069       } else {
1070         $color= "";
1071       }
1072       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1073     }
1074     $hl.= "</select>\n";
1075     $smarty->assign ("hardware_list", $hl);
1078     foreach($this->attributes as $attr){
1079       if(in_array($attr,$this->multi_boxes)){
1080         $smarty->assign("use_".$attr,TRUE);
1081       }else{
1082         $smarty->assign("use_".$attr,FALSE);
1083       }
1084     }
1086     /* Show main page */
1087     $this->lastmacro = $this->macro;
1088     $smarty->assign("multiple_support",$this->multiple_support_active);
1089     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1090     return($display);
1091   }
1094   function save_object()
1095   {
1096     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1097     if (isset($_POST["phoneTab"])){
1098     
1099       plugin::save_object();
1101       /* Save checkbox */
1102       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1103       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1104         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1105           $tmp .= "M";
1106         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1107           $tmp  = preg_replace ("/M/","",$tmp);
1108         }
1109       }
1110       $this->goFonDeliveryMode= "[".$tmp."]";
1113       /* Every macro in the select box are available */
1114       if((isset($_POST['macro']))){
1115         $this->macrostillavailable=true;
1116       }
1118       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1119         $this->is_modified =true;
1120       }
1122       if(is_array($this->phoneNumbers)){
1123         foreach($this->phoneNumbers as $telenumms) {
1124           $nummsinorder[]=$telenumms; 
1125         }
1126       }else{
1127         $nummsinorder=array("");
1128       }
1131       /* get all Postvars */
1132       if(isset($this->macroarray[$this->macro])){
1134         if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1135           foreach($this->macroarray[$this->macro] as $key => $paras){
1137             $backup = $this->macroarray[$this->macro][$key];
1139             if(isset($_POST[$paras['var']])){
1140               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1141             }
1143             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1144                We need this code below to read and save checkboxes correct
1145              */
1147             if(isset($_POST['post_success'])){
1148               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1149                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1150                   $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1151                 }else{
1152                   $this->macroarray[$this->macro][$key]['choosen']=false;
1153                 }
1154               }
1155             }
1156           }
1157           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1158             $this->modified = TRUE;
1159           }
1160         }
1161       }
1162     }
1163   }
1165   function check()
1166   {
1167     /* Call common method to give check the hook */
1168     $message= plugin::check();
1170     if(!count($this->goFonHomeServers)){
1171       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1172     }
1174     if(empty($this->goFonHomeServer)){
1175       $message[] = msgPool::invalid(_("Home server"));
1176     }
1178     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1179       $message[]= msgPool::invalid(_("Voicemail PIN"),"","",_("Between 1-4 charactes"));
1180     }else{
1181       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1182         $message[]= msgPool::invalid(_("Voicemail PIN"),preg_replace("/[0-9]/","X",$this->goFonVoicemailPIN),"/X/");
1183       }
1184     }
1186     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1187       $message[]= msgPool::invalid(_("Phone PIN"),preg_replace("/[0-9a-z]/i","X",$this->goFonPIN),"/X/");
1188     }
1190     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1191       if(!$this->generate_mysql_entension_entries()){
1192         $message[] = $this->generate_error;
1193       }
1194     }
1196     /* We need at least one phone number */
1197     if (count($this->phoneNumbers) == 0){
1198       $message[]= msgPool::required("Phone number");
1199     }
1201     /* check for ! in any parameter setting*/
1202     if(isset($this->macroarray[$this->macro])){
1203       foreach($this->macroarray[$this->macro] as $val){
1204         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1205           $message[] = msgPool::invalid(sprintf(_("macro parameter %s"),$val['name']),$val['choosen'],"/[^\#]/");
1206         }
1207       }
1208     }
1209     return ($message);
1210   }
1214   function save()
1215   {
1216     plugin::save();
1218     /* Force saving macro again 
1219      * This ensures that 
1220      *  - the macro is available on the destiantion server.
1221      *  - the macro saved is up to date on the destination server.
1222      */
1223     if(!empty($this->macro) && $this->macro != "none")  {
1224       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1225       $macro_tab -> save();
1226     }
1228     /* Save arrays */
1229     $tmp_numbers = array();
1230     foreach ($this->phoneNumbers as $number){
1231       $tmp_numbers[] = $number;
1232     }
1234     /* Save settings, or remove goFonMacro attribute*/
1235     if($this->macro!="none"){    
1236       $this->attrs['goFonMacro']=$this->macro;
1237       if(isset($this->macroarray[$this->macro])){
1238         foreach($this->macroarray[$this->macro] as $paras)  {
1239           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1240         }
1241       }
1242     }else{
1243       $this->attrs['goFonMacro']=array();
1244     }
1245     unset($this->attrs['macro'])  ;
1247     $this->attrs['goFonForwarding']=array();
1249     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1250       $str = $this->generate_mysql_entension_entries(true);
1251       if(empty($str)){
1252         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
1253       }
1254     }
1256     if($this->attrs['goFonMacro']==""){
1257       $this->attrs['goFonMacro']=array();
1258     }
1260     unset($this->attrs['cn']);
1262     /* Write back to ldap */
1263     $ldap= $this->config->get_ldap_link();
1264     $ldap->cd($this->dn);
1265     $this->cleanup();
1266     
1267     /* Force saving numbers, else it will be overwriten by user account. */
1268     $this->attrs['telephoneNumber'] =$tmp_numbers;
1269     $ldap->modify ($this->attrs); 
1271     /* Log last action */
1272     if($this->initially_was_account){
1273       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1274     }else{
1275       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1276     }
1278     if (!$ldap->success()){
1279       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
1280     }
1282     /* Optionally execute a command after we're done */
1284     if ($this->initially_was_account == $this->is_account){
1285       if ($this->is_modified){
1286         $this->handle_post_events("modify",array("uid" => $this->uid));
1287       }
1288     } else {
1289       $this->handle_post_events("add",array("uid" => $this->uid));
1290     }
1292   }
1295   function adapt_from_template($dn)
1296   {
1297     plugin::adapt_from_template($dn);
1299     /* Assemble phone numbers */
1300     if (isset($this->attrs['telephoneNumber'])){
1301       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1302         $number= $this->attrs['telephoneNumber'][$i];
1303         $this->phoneNumbers[$number]= $number;
1304       }
1305     }
1306   }
1309   function remove_from_parent()
1310   {
1311     if(!$this->initially_was_account) return;
1313     foreach($this->attributes as $key=>$val){
1314       if(in_array($val,array("uid","cn"))){
1315         unset($this->attributes[$key]);
1316         unset($this->$val);
1317       }
1318     }
1319     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1321       // Get Configuration for initial Mysql database Server
1322       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1323       $s_parameter  ="";
1325       // Connect to DB server
1326       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1328       // Check if we are  connected correctly
1329       if(!$r_con){
1330         msg_dialog::display(_("Error"), msgPool::dbconnect("GOfon",@mysql_error()), ERROR_DIALOG);
1331         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1332         return false;
1333       }
1335       // Select database for Extensions
1336       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1338       // Test if we have the database selected correctly
1339       if(!$db){
1340         msg_dialog::display(_("Error"), msgPool::dbselect("GOfon", @mysql_error()), ERROR_DIALOG);
1341         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1342         return false;
1343       }
1345       $SQL="";
1347       /* If deletion starts from userslist, cn uid are not set */
1348       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1349         $this->uid = $this->parent->by_object['user']->uid;
1350       }
1352       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1353         $this->cn  = $this->parent->by_object['user']->cn;
1354       }
1356       $first_num = false;
1357       // Delete old entries
1358       foreach($this->a_old_telenums as $s_telenums){
1359         if(!$first_num){
1360           $first_num = $s_telenums;
1361         }
1362         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1363       }
1365       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1366       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1367       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1369       foreach($SQL as $query){
1370         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1371         if(!@mysql_query($query,$r_con)){
1372           msg_dialog::display(_("Error"), msgPool::dbquery("GOfon",@mysql_error()), ERROR_DIALOG);
1373           return false;
1374         }
1375       }
1376     }else{
1377       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
1378       return false;
1379     }
1381     /* unset macro attr, it will cause an error */
1382     $tmp = array_flip($this->attributes);
1383     unset($tmp['macro']);
1384     $this->attributes=array_flip($tmp);
1386     /* Cancel if there's nothing to do here */
1387     if (!$this->initially_was_account){
1388       return;
1389     }
1391     plugin::remove_from_parent();
1393     /* Just keep one phone number */
1394     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1395       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1396     } else {
1397       $this->attrs['telephoneNumber']= array();
1398     }
1401     $ldap= $this->config->get_ldap_link();
1402     $ldap->cd($this->config->current['BASE']);
1403     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1404     while($attr = $ldap->fetch()){
1405       if(in_array($this->dn,$attr['member'])){
1406         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1407         unset($new->by_object['ogroup']->memberList[$this->dn]);
1408         unset($new->by_object['ogroup']->member[$this->dn]);
1409         $new->save();
1410         msg_dialog::display(_("Information"), sprintf(_("User '%s' has been removed from phone queue '%s'."), $this->cn, $new->by_object['ogroup']->cn), INFO_DIALOG);
1411       }
1412     }
1413     $ldap->cd($this->dn);
1414     $this->cleanup();
1415     $ldap->modify ($this->attrs); 
1417     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1418     if (!$ldap->success()){
1419       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1420     }
1422     /* Optionally execute a command after we're done */
1423     @mysql_close($r_con);
1424     $this->handle_post_events('remove',array("uid"=> $this->uid));
1425   }
1429   /* This function checks if the given phonenumbers are available or already in use*/
1430   function is_number_used()
1431   {
1432     $ldap= $this->config->get_ldap_link();
1433     $ldap->cd($this->config->current['BASE']);
1434     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1435     while($attrs = $ldap->fetch()) {
1436       unset($attrs['telephoneNumber']['count']);
1437       foreach($attrs['telephoneNumber'] as $tele){
1438         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1439         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1440         $numbers[$tele]=$attrs;
1441       }
1442     }
1444     foreach($this->phoneNumbers as $num){
1445       if(!isset($this->cn)) $this->cn = "";
1447       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1448         if(isset($numbers[$num]['uid'][0])){
1449           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1450         }else{
1451           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1452         }
1453       }
1454     }
1455   }
1458   /* Create phoneAccount part of copy & paste dialog */
1459   function getCopyDialog()
1460   { 
1461     if(!$this->is_account) return("");
1462     $smarty = get_smarty();
1463     if (!count($this->phoneNumbers)){
1464       $smarty->assign ("phoneNumbers", array(""));
1465     } else {
1466       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1467     }
1469     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1470     $smarty->assign("goFonPIN",$this->goFonPIN);
1472     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1473     $ret =array();
1474     $ret['string'] = $display;
1475     $ret['status'] = "";
1476     return($ret);
1477   }
1479   /* Save posts from copy & paste dialog dialog  */
1480   function saveCopyDialog()
1481   {
1482     if(!$this->is_account) return;
1483     $this->execute();
1484     if(isset($_POST['goFonVoicemailPIN'])) {
1485       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1486     }
1487     if(isset($_POST['goFonPIN'])){
1488       $this->goFonPIN = $_POST['goFonPIN'];
1489     }
1490   }
1493   function allow_remove()
1494   {
1495     /* Check if previously selected server is still available */
1496     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1497       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1498     }
1499   }
1501   /* Return plugin informations for acl handling */
1502   static function plInfo()
1503   {
1504     return (array(
1505           "plShortName"     => _("Phone"),
1506           "plDescription"   => _("Phone account settings"),
1507           "plSelfModify"    => TRUE,
1508           "plDepends"       => array("user"),
1509           "plPriority"      => 7,                                 // Position in tabs
1510           "plSection"       => "personal",                        // This belongs to personal
1511           "plCategory"      => array("gofonreport" => array("description" => _("GOfon reports"),
1512               "objectClass" => "")),
1514           "plOptions"       => array(),
1516           "plProvidedAcls"  => array(
1517             "telephoneNumber"     => _("Telephone number"),
1518             "goFonHomeServer"     => _("Home server"),
1519             "goFonMacro"          => _("Macro settings"),
1520             "goFonHardware"       => _("Phone hardware"),
1521             "goFonPIN"            => _("Telephone pin"),
1522             "goFonVoicemailPIN"   => _("Voicemail pin"))
1523           ));
1524   }
1528   function multiple_execute()
1529   {
1530     plugin::multiple_execute();
1531     return($this->execute());
1532   }
1534   function get_multi_init_values()
1535   {
1536     $ret = plugin::get_multi_init_values();
1537     $ret['phoneNumbers'] = array();
1538     foreach($this->phoneNumbers as $number){
1539       $ret['phoneNumbers'][] = $number."  [".$this->attrs['cn'][0]."]"; 
1540     }
1541     $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1542     return($ret);
1543   }
1545   function init_multiple_support($attrs,$all)
1546   {
1547     plugin::init_multiple_support($attrs,$all);
1549     $this->phoneNumbers = array();
1550     if(isset($all['phoneNumbers'])){
1551       for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1552         $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1553       }
1554     }
1555   }
1557   function multiple_save_object()
1558   {
1559     /* Simply call parents save_object */
1560     if (isset($_POST["phoneTab"])){
1562       plugin::save_object();
1563       plugin::multiple_save_object();
1565       /* Every macro in the select box are available */
1566       if((isset($_POST['macro']))){
1567         $this->macrostillavailable=true;
1568       }
1570       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1571         $this->is_modified =true;
1572       }
1574       /* get all Postvars */
1575       if(isset($this->macroarray[$this->macro])){
1576         foreach($this->macroarray[$this->macro] as $key => $paras){
1577           $backup = $this->macroarray[$this->macro][$key];
1578           if(isset($_POST[$paras['var']])){
1579             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1580           }
1581           if(isset($_POST['post_success'])){
1582             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1583               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1584                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1585               }else{
1586                 $this->macroarray[$this->macro][$key]['choosen']=false;
1587               }
1588             }
1589           }
1590         }
1591         if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1592           $this->modified = TRUE;
1593         }
1594       }
1595     }
1596   }
1598   function multiple_check()
1599   {
1600     $message = plugin::multiple_check();
1602     if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1603       $message[] = _("There is currently no asterisk server defined!");
1604     }
1606     if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1607       $message[] = _("Asterisk server is invalid!");
1608     }
1610     if(in_array("goFonVoicemailPIN",$this->multi_boxes) && 
1611         ( (strlen($this->goFonVoicemailPIN)==0)||
1612           (strlen($this->goFonVoicemailPIN)>4))){
1613       $message[]=(_("Voicemail PIN must be 4 characters long!"));
1614     }else{
1615       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1616         $message[]=(_("Voicemail PIN contains invalid characters!"));
1617       }
1618     }
1620     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1621       $message[]=(_("Phone pin contains invalid characters!"));
1622     }
1624     /* check for ! in any parameter setting*/
1625     if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1626       foreach($this->macroarray[$this->macro] as $val){
1627         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1628           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1629         }
1630       }
1631     }
1633     return($message);
1634   }
1636   function get_multi_edit_values()
1637   {
1638     $ret = plugin::get_multi_edit_values();
1639     if(in_array("macro",$this->multi_boxes)){
1640       $ret['macro'] = $this->macro;
1641       $ret['macroarray'] = $this->macroarray;
1642       $ret['macros'] = $this->macros;
1643     }
1644     return($ret);
1645   }
1648 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1649 ?>