Code

Fixed macro listing.
[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))","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       foreach($oldnums as $s_telenums){
691         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
692       }
693       foreach($newnums as $s_telenums){
694         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
695       }
696       foreach($query as $qry){
697         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
698         if(!mysql_query($qry,$new_connection)){
699           trigger_error(mysql_error($new_connection));
700         } 
701       }
702  
703       /********************** 
704        * Insert extension entries
705        **********************/
706  
707       // Get selected Macro Parameter and create parameter entry 
708       if(isset($this->macroarray[$this->macro])){
709         foreach($this->macroarray[$this->macro] as $key => $val ){
710           $s_parameter .= $val['choosen']."|";
711         }
712         $s_parameter = preg_replace("/\|$/","",$s_parameter);
713       }
714      
715       $i = 0; 
716       $EXT = array();
717       if(!is_numeric($this->uid)){
718         $EXT[$i]['context'] = 'GOsa';
719         $EXT[$i]['exten']   = $this->uid;
720         $EXT[$i]['priority']= 1;
721         $EXT[$i]['app']     = "Goto";
722         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
723         $i ++;
724       }
726       // Entension entries  Hint / Dial / Goto
727       foreach($newnums as $s_telenums){
729         /* Hint Entry */
730         $EXT[$i]['context'] = 'GOsa';
731         $EXT[$i]['exten']   = $s_telenums;
732         $EXT[$i]['priority']= "Hint";
733         $EXT[$i]['app']     = 'SIP/'.$this->uid;
734         $i ++;  
735         /* SetCID */
736         //$EXT[$i]['context'] = 'GOsa';
737         //$EXT[$i]['exten']   = $s_telenums;
738         //$EXT[$i]['priority']= 1;
739         //$EXT[$i]['app']     = "SetCIDName";
740         //$EXT[$i]['appdata'] = $CNname;
741         //$i ++;  
743         // If no macro is selected use Dial
744         if($this->macro!="none"){ 
745           $macroname = preg_replace("/,.*$/","",$this->macro);        
746           $macroname = preg_replace("/^.*=/","",$macroname);        
747           $s_app = "Macro";$macroname;
748           $s_par = $macroname."|".$s_parameter; 
749         }else{
750           $s_app = "Dial";
751           $s_par = 'SIP/'.$this->uid."|20|r";
752         }
754         $EXT[$i]['context'] = 'GOsa';
755         $EXT[$i]['exten']   = $s_telenums;
756         $EXT[$i]['priority']= 1;
757         $EXT[$i]['app']     = $s_app;
758         $EXT[$i]['appdata'] = $s_par;
759         $i ++;
760       }
762       // Append all these Entries 
763       foreach($EXT as $entr){
764         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
765         foreach($entr as $key2 => $val2){
766           $SQL_syn.= "`".$key2."`,";
767         }
768         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
769         $SQL_syn .= ") VALUES ("; 
770         foreach($entr as $key2 => $val2){
771           $SQL_syn .= "'".$val2."',";
772         }
773         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
774         $SQL_syn .=");\n";
776         $SQL_query_array[] =$SQL_syn;
777         $SQL_syn ="";
778       }
780       // Perform queries ...
781       if($this->goFonHardware != "automatic"){
782         foreach($SQL_query_array as $query){
783           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
784           if(!@mysql_query($query,$new_connection)){
785             $this->generate_error =  msgPool::dbquery("GOfon",@mysql_error($old_connection));
786             return false;
787           }
788         }
789       }
790     }
791     @mysql_close($new_connection);
792     return true;
793   }
796   function execute()
797   {
798     /* Call parent execute */
799     plugin::execute();
801     /* Log view */
802     if($this->is_account && !$this->view_logged){
803       $this->view_logged = TRUE;
804       new log("view","users/".get_class($this),$this->dn);
805     }
807     $display = "";
808     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
809     if(empty($this->macro)&&(!empty($this->goFonMacro))){
811       /* Go through already saved values, for a parameter */
812       $tmp = split("!",$this->goFonMacro);
814       /* it is possible that nothing has been saved yet */
815       if(is_array($tmp)){
817         /* First value is the macroname */
818         $this->macro = $tmp[0];
820         /* Macroname saved, delete that index */
821         unset($tmp[0]);
823         /* Check if macro has been removed */
824         if(!isset($this->macroarray[$this->macro])){
825           $this->macrostillavailable = false;
826         }else{
827           $this->macrostillavailable = true;
828         }
830         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
831         foreach($tmp as $var){
833           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
834           $varar = split("#",$var);
836           /* Only insert if the parameter still exists */
837           if(isset($this->macroarray[$this->macro][$varar[0]])){
838             /* Assign value */
839             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
840           }
841         }
842       }
843     }
844     
845     /* Do we represent a valid account? */
846     if (!$this->is_account && $this->parent === NULL){
847       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
848         msgPool::noValidExtension(_("Phone"))."</b>";
849       $display.= back_to_main();
850       return ($display);
851     }
853     /* Do we need to flip is_account state? */
854     if (isset($_POST['modify_state'])){
855       $this->is_account= !$this->is_account;
856     }
858     /* Do we represent a valid account? */
859     if (!$this->is_account && $this->parent === NULL){
860       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
861         msgPool::noValidExtension(_("Phone"))."</b>";
862       $display.= back_to_main();
863       return($display);
864     }
866     $display= "";
868     /* Show tab dialog headers */
869     
870     if (!$this->multiple_support_active && $this->parent !== NULL){
871       if ($this->is_account){
872         $display= $this->show_disable_header(_("Remove phone account"),
873             msgPool::featuresEnabled(_("Phone")));
874       } else {
875         if(empty($this->uid)){
876           $display= $this->show_enable_header(_("Create phone account"),
877             msgPool::featuresDisabled(_("Phone"),_("User uid")));
878         }else{
879           $display= $this->show_enable_header(_("Create phone account"),
880             msgPool::featuresDisabled(_("Phone")));
881         }
882         return ($display);
883       }
884     }
885     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
886     if(empty($this->macro)){
887       $this->macro ="none";
888     }
890     /* Prepare templating */
891     $smarty= get_smarty();
893     /* tell user that the selected plugin is no longer available */
894     if((!$this->macrostillavailable)&&($this->macro!="none")){
895       msg_dialog::display(_("Error"), _("Selected macro is not available anymore!"), ERROR_DIALOG);
896     }
898     /* Assing macroselectbox values  */
899     $smarty->assign("macros",$this->macros);   
900     $smarty->assign("macro", $this->macro);   
902     /* check if there is a FON server created */
903     if(!count($this->goFonHomeServer)){
904       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
905     }
907     /* Create html parameter table for selected macro parameters 
908      *  skip if no parameters given 
909      */
910     if(!isset($this->macroarray[$this->macro])){
911       $macrotab="";
912     }else{
914       $macrotab ="<table summary=\""._("Parameter")."\">";
915       /* for every single parameter-> display textfile,combo, or true false switch*/
917       foreach($this->phoneNumbers as $phonenum){
918         $tmp[] = $phonenum;
919       }
920     
921       if($this->macro != $this->lastmacro){
922         /* Go through all params */
923         foreach($this->macroarray[$this->macro] as $key => $paras){
925           $string = $paras['default'];
927           $string=preg_replace("/%uid/i",$this->uid,$string);
929           if(isset($this->cn)){
930             $string=preg_replace("/%cn/i",$this->cn,$string);
931           }
933           for($i = 0 ; $i < 10; $i++){
934             if(isset($tmp[$i])){
935               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
936             }
937           }
938           if(isset($tmp[0])){
939             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
940           }
941           $this->macroarray[$this->macro][$key]['choosen']=$string;
942         }
943       }
945       foreach($this->macroarray[$this->macro] as $paras){
947         /* get al vars */
948         $var        = $paras['var'];           
949         $name       = $paras['name'];           
950         $default    = $paras['default'];
951         $type       = $paras['type'];
952         $choosen    = $paras['choosen'] ; 
953         $str        = $default;
955         $dis = "";
956         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
957           $dis = " disabled ";
958         }
960         /* in case of a combo box display a combobox with selected attr */
961         $macrotab.= "<tr>";
962         switch ($type){
964           case "combo":
965             $str= "<select name='".$var."' ".$dis." >";
966           foreach(split(":",$default) as $choice){
967             if($choosen==$choice){
968               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
969             }else{
970               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
971             }
972           }
973           $str.="</select>";
974           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
975           break;
977           case "bool":
978             if(!$choosen){
979               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
980             }else{
981               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
982             }
983           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
984           break;
986           case "string":
987             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
988           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
989           break;
991         }
992         $macrotab.= "</td></tr>";
994       }
995       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
996     }//is_array()
998     /* Give smarty the table */
999     $smarty->assign("macrotab",$macrotab);
1002     /* Add phone number */
1003     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1004       if (tests::is_phone_nr($_POST['phonenumber'])){
1005         $number= $_POST["phonenumber"];
1006         $this->phoneNumbers[$number]= $number;
1007         $this->is_modified= TRUE;
1008       } else {
1009         msg_dialog::display(_("Error"), msgPool::invalid("Phone number"), ERROR_DIALOG);
1010       }
1011     }
1013     /* Remove phone number */
1014     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1015       foreach ($_POST['phonenumber_list'] as $number){
1016         unset($this->phoneNumbers[$number]);
1017         $this->is_modified= TRUE;
1018       }
1019     }
1021     /* Assign acls */
1022     $tmp = $this->plInfo();
1023     foreach($tmp['plProvidedAcls'] as $name => $translation){
1024       $smarty->assign($name."ACL",$this->getacl($name));
1025     }
1027     /* Transfer ACL's */
1028     foreach($this->attributes as $val){
1029       if(isset($this->$val)){
1030         $smarty->assign($val,$this->$val);
1031       }else{
1032         $smarty->assign($val,"");
1033       }
1034     }
1036     /* Create home server array */
1037     $tmp = array();
1038     foreach($this->goFonHomeServers as $dn => $attrs){
1039       if(!is_numeric($dn)){
1040         $tmp[$dn] = $attrs['SERVER'];
1041       }
1042     }
1043     $smarty->assign("goFonHomeServers",$tmp);
1045     /* Fill arrays */
1046     $smarty->assign ("goFonHardware", $this->goFonHardware);
1047     if (!count($this->phoneNumbers)){
1048       $smarty->assign ("phoneNumbers", array());
1049     } else {
1050       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1051     }
1053     $dis = "";
1054     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1055       $dis= " disabled ";
1056     }
1057     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1058        _("Choose your private phone")."\">\n";
1060     foreach ($this->hardware_list as $cn => $description){
1061       if ($cn == $this->goFonHardware){
1062         $selected= "selected";
1063       } else {
1064         $selected= "";
1065       }
1066       if (isset($this->used_hardware[$cn])){
1067         $color= "style=\"color:#A0A0A0\"";
1068       } else {
1069         $color= "";
1070       }
1071       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1072     }
1073     $hl.= "</select>\n";
1074     $smarty->assign ("hardware_list", $hl);
1077     foreach($this->attributes as $attr){
1078       if(in_array($attr,$this->multi_boxes)){
1079         $smarty->assign("use_".$attr,TRUE);
1080       }else{
1081         $smarty->assign("use_".$attr,FALSE);
1082       }
1083     }
1085     /* Show main page */
1086     $this->lastmacro = $this->macro;
1087     $smarty->assign("multiple_support",$this->multiple_support_active);
1088     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1089     return($display);
1090   }
1093   function save_object()
1094   {
1095     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1096     if (isset($_POST["phoneTab"])){
1097     
1098       plugin::save_object();
1100       /* Save checkbox */
1101       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1102       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1103         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1104           $tmp .= "M";
1105         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1106           $tmp  = preg_replace ("/M/","",$tmp);
1107         }
1108       }
1109       $this->goFonDeliveryMode= "[".$tmp."]";
1112       /* Every macro in the select box are available */
1113       if((isset($_POST['macro']))){
1114         $this->macrostillavailable=true;
1115       }
1117       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1118         $this->is_modified =true;
1119       }
1121       if(is_array($this->phoneNumbers)){
1122         foreach($this->phoneNumbers as $telenumms) {
1123           $nummsinorder[]=$telenumms; 
1124         }
1125       }else{
1126         $nummsinorder=array("");
1127       }
1130       /* get all Postvars */
1131       if(isset($this->macroarray[$this->macro])){
1133         if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1134           foreach($this->macroarray[$this->macro] as $key => $paras){
1136             $backup = $this->macroarray[$this->macro][$key];
1138             if(isset($_POST[$paras['var']])){
1139               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1140             }
1142             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1143                We need this code below to read and save checkboxes correct
1144              */
1146             if(isset($_POST['post_success'])){
1147               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1148                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1149                   $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1150                 }else{
1151                   $this->macroarray[$this->macro][$key]['choosen']=false;
1152                 }
1153               }
1154             }
1155           }
1156           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1157             $this->modified = TRUE;
1158           }
1159         }
1160       }
1161     }
1162   }
1164   function check()
1165   {
1166     /* Call common method to give check the hook */
1167     $message= plugin::check();
1169     if(!count($this->goFonHomeServers)){
1170       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1171     }
1173     if(empty($this->goFonHomeServer)){
1174       $message[] = msgPool::invalid(_("Home server"));
1175     }
1177     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1178       $message[]= msgPool::invalid(_("Voicemail PIN"),"","",_("Between 1-4 charactes"));
1179     }else{
1180       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1181         $message[]= msgPool::invalid(_("Voicemail PIN"),preg_replace("/[0-9]/","X",$this->goFonVoicemailPIN),"/X/");
1182       }
1183     }
1185     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1186       $message[]= msgPool::invalid(_("Phone PIN"),preg_replace("/[0-9a-z]/i","X",$this->goFonPIN),"/X/");
1187     }
1189     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1190       if(!$this->generate_mysql_entension_entries()){
1191         $message[] = $this->generate_error;
1192       }
1193     }
1195     /* We need at least one phone number */
1196     if (count($this->phoneNumbers) == 0){
1197       $message[]= msgPool::required("Phone number");
1198     }
1200     /* check for ! in any parameter setting*/
1201     if(isset($this->macroarray[$this->macro])){
1202       foreach($this->macroarray[$this->macro] as $val){
1203         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1204           $message[] = msgPool::invalid(sprintf(_("macro parameter %s"),$val['name']),$val['choosen'],"/[^\#]/");
1205         }
1206       }
1207     }
1208     return ($message);
1209   }
1213   function save()
1214   {
1215     plugin::save();
1217     /* Force saving macro again 
1218      * This ensures that 
1219      *  - the macro is available on the destiantion server.
1220      *  - the macro saved is up to date on the destination server.
1221      */
1222     if(!empty($this->macro) && $this->macro != "none")  {
1223       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1224       $macro_tab -> save();
1225     }
1227     /* Save arrays */
1228     $tmp_numbers = array();
1229     foreach ($this->phoneNumbers as $number){
1230       $tmp_numbers[] = $number;
1231     }
1233     /* Save settings, or remove goFonMacro attribute*/
1234     if($this->macro!="none"){    
1235       $this->attrs['goFonMacro']=$this->macro;
1236       if(isset($this->macroarray[$this->macro])){
1237         foreach($this->macroarray[$this->macro] as $paras)  {
1238           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1239         }
1240       }
1241     }else{
1242       $this->attrs['goFonMacro']=array();
1243     }
1244     unset($this->attrs['macro'])  ;
1246     $this->attrs['goFonForwarding']=array();
1248     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1249       $str = $this->generate_mysql_entension_entries(true);
1250       if(empty($str)){
1251         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
1252       }
1253     }
1255     if($this->attrs['goFonMacro']==""){
1256       $this->attrs['goFonMacro']=array();
1257     }
1259     unset($this->attrs['cn']);
1261     /* Write back to ldap */
1262     $ldap= $this->config->get_ldap_link();
1263     $ldap->cd($this->dn);
1264     $this->cleanup();
1265     
1266     /* Force saving numbers, else it will be overwriten by user account. */
1267     $this->attrs['telephoneNumber'] =$tmp_numbers;
1268     $ldap->modify ($this->attrs); 
1270     /* Log last action */
1271     if($this->initially_was_account){
1272       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1273     }else{
1274       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1275     }
1277     if (!$ldap->success()){
1278       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
1279     }
1281     /* Optionally execute a command after we're done */
1283     if ($this->initially_was_account == $this->is_account){
1284       if ($this->is_modified){
1285         $this->handle_post_events("modify",array("uid" => $this->uid));
1286       }
1287     } else {
1288       $this->handle_post_events("add",array("uid" => $this->uid));
1289     }
1291   }
1294   function adapt_from_template($dn)
1295   {
1296     plugin::adapt_from_template($dn);
1298     /* Assemble phone numbers */
1299     if (isset($this->attrs['telephoneNumber'])){
1300       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1301         $number= $this->attrs['telephoneNumber'][$i];
1302         $this->phoneNumbers[$number]= $number;
1303       }
1304     }
1305   }
1308   function remove_from_parent()
1309   {
1310     if(!$this->initially_was_account) return;
1312     foreach($this->attributes as $key=>$val){
1313       if(in_array($val,array("uid","cn"))){
1314         unset($this->attributes[$key]);
1315         unset($this->$val);
1316       }
1317     }
1318     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1320       // Get Configuration for initial Mysql database Server
1321       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1322       $s_parameter  ="";
1324       // Connect to DB server
1325       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1327       // Check if we are  connected correctly
1328       if(!$r_con){
1329         msg_dialog::display(_("Error"), msgPool::dbconnect("GOfon",@mysql_error()), ERROR_DIALOG);
1330         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1331         return false;
1332       }
1334       // Select database for Extensions
1335       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1337       // Test if we have the database selected correctly
1338       if(!$db){
1339         msg_dialog::display(_("Error"), msgPool::dbselect("GOfon", @mysql_error()), ERROR_DIALOG);
1340         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1341         return false;
1342       }
1344       $SQL="";
1346       /* If deletion starts from userslist, cn uid are not set */
1347       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1348         $this->uid = $this->parent->by_object['user']->uid;
1349       }
1351       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1352         $this->cn  = $this->parent->by_object['user']->cn;
1353       }
1355       $first_num = false;
1356       // Delete old entries
1357       foreach($this->a_old_telenums as $s_telenums){
1358         if(!$first_num){
1359           $first_num = $s_telenums;
1360         }
1361         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1362       }
1364       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1365       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1366       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1368       foreach($SQL as $query){
1369         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1370         if(!@mysql_query($query,$r_con)){
1371           msg_dialog::display(_("Error"), msgPool::dbquery("GOfon",@mysql_error()), ERROR_DIALOG);
1372           return false;
1373         }
1374       }
1375     }else{
1376       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
1377       return false;
1378     }
1380     /* unset macro attr, it will cause an error */
1381     $tmp = array_flip($this->attributes);
1382     unset($tmp['macro']);
1383     $this->attributes=array_flip($tmp);
1385     /* Cancel if there's nothing to do here */
1386     if (!$this->initially_was_account){
1387       return;
1388     }
1390     plugin::remove_from_parent();
1392     /* Just keep one phone number */
1393     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1394       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1395     } else {
1396       $this->attrs['telephoneNumber']= array();
1397     }
1400     $ldap= $this->config->get_ldap_link();
1401     $ldap->cd($this->config->current['BASE']);
1402     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1403     while($attr = $ldap->fetch()){
1404       if(in_array($this->dn,$attr['member'])){
1405         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1406         unset($new->by_object['ogroup']->memberList[$this->dn]);
1407         unset($new->by_object['ogroup']->member[$this->dn]);
1408         $new->save();
1409         msg_dialog::display(_("Information"), sprintf(_("User '%s' has been removed from phone queue '%s'."), $this->cn, $new->by_object['ogroup']->cn), INFO_DIALOG);
1410       }
1411     }
1412     $ldap->cd($this->dn);
1413     $this->cleanup();
1414     $ldap->modify ($this->attrs); 
1416     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1417     if (!$ldap->success()){
1418       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1419     }
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 ?>