Code

Created trunk inside of 2.6-lhm
[gosa.git] / trunk / 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 $plIcon       = "plugins/gofon/images/phoneAccount.png";
10   /* Attributes */
11   var $telephoneNumber        = array();
12   var $goFonHardware          = "automatic";
13   var $goFonFormat            = "wav";
14   var $goFonPIN               = "";
15   var $goFonVoicemailPIN      = "";
16   var $goFonDeliveryMode      = "";
17   var $phoneNumbers           = array();
18   var $mail                   = "";
19   var $hardware_list          = array();
20   var $used_hardware          = array();
21   var $goFonMacro             = "";
22   var $macro                  = 0;              // Selected Macroi
23   var $lastmacro              = "";
24   var $macros                 = array();        // List of macros for smarty select box
25   var $macroarray             = array();        // All needed macro informations
26   var $macrostillavailable    = false;
27   var $generate_error         = "";
28   var $a_old_telenums         = array();
29   var $goFonPINVoice          = "";
30   var $goFonHomeServer        = "0";            // Contains the dn of the server that manage this account 
31   var $init_HomeServer        = "0";            // Contains the dn of the server that manage this account 
32   var $goFonHomeServers       = array();        // Contains all available server configurations 
34   var $context                = "default";
35   var $voice_context          = "default";
37   /* attribute list for save action */
38   var $CopyPasteVars          = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
39                                       "hardware_list","used_hardware");
41   var $attributes             = array("goFonDeliveryMode", "goFonFormat","goFonHomeServer",
42       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
43   var $objectclasses= array("goFonAccount");
45   var $uid;
46   var $cn;
48   var $view_logged = FALSE;
49   var $multiple_support = TRUE;
50   var $mailAddress      = "";
51   var $has_mailAccount  = FALSE;
52   var $pager      = "";
54   function phoneAccount (&$config, $dn= NULL, $parent= NULL)
55   {
56     plugin::plugin ($config, $dn, $parent);
58     /* Assemble phone numbers */
59     if (isset($this->attrs['telephoneNumber'])){
60       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
61         $number= $this->attrs['telephoneNumber'][$i];
62         $this->phoneNumbers[$number]= $number;
63       }
64     }
66     /* Set parent object to tab object */
67     if(is_object($parent)){
68       $this->parent = $parent->parent;
69     }
71     /* Get current uid and cn 
72      */
73     if(isset($this->attrs['uid'][0])){
74       $this->uid = $this->attrs['uid'][0];
75     }
76     if(isset($this->attrs['cn'][0])){
77       $this->cn = $this->attrs['cn'][0];
78     }
79     if(isset($this->attrs['mail'][0])){
80       $this->mailAddress = $this->attrs['mail'][0];
81       $this->has_mailAccount = true;
82     }
83     if(isset($this->attrs['pager'][0])){
84       $this->pager = $this->attrs['pager'][0];
85     }
87     /* If there is a parent object present, use references 
88      */
89     if(isset($this->parent->by_object['user']->uid)){
90       $this->uid = &$this->parent->by_object['user']->uid;
91     }
92     if(isset($this->parent->by_object['user']->cn)){
93       $this->cn   =&$this->parent->by_object['user']->cn;
94     }
95     if(isset($this->parent->by_object['user']->pager)){
96       $this->pager   =&$this->parent->by_object['user']->pager;
97     }
98     if(isset($this->parent->by_object['mailAccount']->mail)){
99       $this->mailAddress      = &$this->parent->by_object['mailAccount']->mail;
100       $this->has_mailAccount  = &$this->parent->by_object['mailAccount']->is_account;
101     }
103     /* Check server configurations 
104      * Load all server configuration in $this->goFonHomeServers if available
105      *  and first server as default if necessary.
106      * Check if connection is successfull for the selected server $this->goFonHomeServer
107      */
109   
110     /* Set available server */
111     $config = session::get('config');
112     if(isset($config->data['SERVERS']['FON'])){
113       $this->goFonHomeServers = $config->data['SERVERS']['FON'];
114     }
116     $a_SETUP= array();
117     if($this->is_account && isset($config->data['SERVERS']['FON']) &&
118        array_key_exists('FON',$config->data['SERVERS']) &&
119        is_callable("mysql_connect")
120        ) {
122       /* Servers defined? Watch here... */
123       if (count($this->goFonHomeServers)){
125         /* Set default server */
126         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
127           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
128         }
130         /* Remember inital home server, to be able to remove old entries */
131         $this->init_HomeServer = $this->goFonHomeServer;
133         /* Get config */
134         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
135           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);
137           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
138           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
139         }    
140         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
142         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
143         if(!$r_con){
144           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
145         }
146         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
147         if(!$db){
148           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
149         }
151         $first = false; 
152         foreach($this->phoneNumbers as $key => $val){
153           if(!$first){
154             $first = $key;
155           }
156         }
157       }
158     }
160     /* Get available phone hardware  
161      * Search for all available phone hardware  
162      */
163     $tmp = get_sub_list("(objectClass=goFonHardware)","phone",array(get_ou("phoneRDN")),
164                   $this->config->current['BASE'],array("cn","description"), GL_SUBSEARCH);
165     foreach($tmp as $attrs){
166       $cn= $attrs['cn'][0];
167       $description= "";
168       if (isset($attrs['description'])){
169         $description= " - ".$attrs['description'][0];
170       }
171       $this->hardware_list[$cn]= "$cn$description";
172     }
173     $this->hardware_list["automatic"]= _("automatic");
174     ksort($this->hardware_list);
177      /* Collect all usd phones 
178         goFonHardware set.
179      */
180     $deps_a = array(
181         get_people_ou(),
182         get_ou("ogroupRDN"),
183         get_ou("serverRDN"),
184         get_ou("terminalRDN"),
185         get_ou("workstationRDN"),
186         get_ou("printerRDN"),
187         get_ou("componentRDN"),
188         get_ou("phoneRDN"));
190     $tmp = get_sub_list("(goFonHardware=*)","phone",$deps_a,$this->config->current['BASE'],
191         array('cn','dn','goFonHardware'),GL_SUBSEARCH);
192     foreach($tmp as $attrs){
193       $cn = $attrs['goFonHardware'][0];
194       if(isset($this->hardware_list[$cn])){
195         $this->used_hardware[$cn]= $cn;
196       }
197     }
200     /* Get available Macros  
201      * Search for all Macros that are visible and create 
202      *  an array with name and parameters 
203      */
204     $tmp = get_sub_list("(&(objectClass=goFonMacro)(goFonMacroVisible=1))","gofonmacro",array(get_ou("phoneMacroRDN")),
205                   $this->config->current['BASE'],array("displayName","goFonMacroParameter","dn","cn"), GL_NO_ACL_CHECK | GL_SUBSEARCH );
206     
208     /* Add none for no macro*/
209     $this->macros['none']=_("no macro");    
210     $this->macro ="none";
212     /* Fetch all Macros*/
213     foreach($tmp as $attrs){
215       $ui = get_userinfo(); 
216       $acl = $ui->get_permissions($attrs['dn'],"gofonmacro/macro","");
218       /* Skip all macros we are not able to read 
219           execpt, the currently selected macro.
220        */
221       if(!preg_match("/r/",$acl) && !preg_match("/^".preg_quote($attrs['dn'], '/')."/",$this->goFonMacro)){
222         continue;
223       }
225       /* unset Count, we don't need that here */
226       unset($attrs['displayName']['count']);
228       /* Parse macro data, unset count for parameterarrays  */
229       if (isset($attrs['goFonMacroParameter']['count'])){
230         unset($attrs['goFonMacroParameter']['count']);
231       }
233       /* fill Selectfield variable with Macros */
234       if(isset($attrs['displayName'][0])){
235         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
236       }else{
237         $this->macros[$attrs['dn']] = _("undefined");
238       }
240       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
241       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
243         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
244           /* Split Data in readable values, by delimiter !  */
245           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
247           /* Set all attrs */
248           $id = $data[0];
249           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
250           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
251           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
252           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
253           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
254           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
255           if($data[2] == "bool"){
256             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
257           }
258         }//foreach
259       }//is_array
260     }//while
263     /* Parse used Macro  
264      * If we have a macro selected, parse it and set values 
265      *  in $this->macroarray[$this->macro]. 
266      */
267     $tmp = split("!",$this->goFonMacro);
268     if(is_array($tmp)){
270       /* First value is the macroname */
271       $this->macro = $tmp[0];
273       /* Macroname saved, delete that index */
274       unset($tmp[0]);
276       /* Check if makro has been removed */
277       if(!isset($this->macros[$this->macro])){
278         $this->macrostillavailable = false;
279       }else{
280         $this->macrostillavailable = true;
281       }
283       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
284       foreach($tmp as $var){
286         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
287         $varar = split("#",$var);
289         /* Only insert if the parameter still exists */
290         if(isset($this->macroarray[$this->macro][$varar[0]])){
291           /* Assign value */
292           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
293         }
294       }
295     }
298     $this->a_old_telenums = $this->phoneNumbers;
300     /* Get voicemail PIN from MySQL DB 
301      * Because every user can change his PIN directly from the phone
302      *  without any update to the ldap
303      * This means, the PIN in the DB is up to date
304      */
305     // Connect to DB server
306     if( (is_callable("mysql_pconnect"))&&
307         (isset($cur_cfg))&&
308         (isset($cur_cfg['SERVER']))&&
309         (isset($cur_cfg['LOGIN']))&&
310         (isset($cur_cfg['PASSWORD']))){
312       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
313       if($r_con){
314         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
315   
316         $query_tmp = "SELECT ".$cur_cfg['VOICE_TABLE'].".context as 'v_context', 
317                              ".$cur_cfg['SIP_TABLE'].".context, 
318                              ".$cur_cfg['VOICE_TABLE'].".password 
319                        FROM  ".$cur_cfg['VOICE_TABLE'].", 
320                              ".$cur_cfg['SIP_TABLE']." 
321                        WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'";
324         $res = mysql_query($query_tmp);
325         $vp  = mysql_fetch_assoc($res);
326   
327         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
328         if((isset($vp['password']))&&(!empty($vp['password']))){
329           $this->goFonPINVoice = $vp['password'];
330         }
331         if((isset($vp['context']))&&(!empty($vp['context']))){
332           $this->context = $vp['context'];
333         }
334         if((isset($vp['v_context']))&&(!empty($vp['v_context']))){
335           $this->voice_context = $vp['v_context'];
336         }
337       }
338     }
339     $this->lastmacro=$this->macro;
341     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
342       @mysql_close($r_con) ;
343     }
344   }
347   /* This function generates the Database entries. 
348    * The Parameter 'save' could be true or false.
349    *  false - means only testing no database transactions.
350    *  true  - write database entries.
351    *
352    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
353    * 
354    * If the phone hardware is 'automatic' the table entries will only be removed
355    *  and not added. 
356    */
357   function generate_mysql_entension_entries($save = false)
358   {
359     /* Check if there is at least one server available 
360      * If not, return and tell the user that saving failed 
361      */
362     if(!count($this->goFonHomeServers)){
363       if($save){
364         msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
365       }
366       return(true);
367     }
369     /* Check if Mysql extension is available */
370     if(!is_callable("mysql_pconnect")){
371       if($save){
372         msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
373       }
374       return(true);
375     }
376  
377     /********************** 
378      * Attribute Initialisation
379      **********************/
381     $old_connection = false;
383     // Get Configuration for Mysql database Server
384     $s_parameter    = "";                                           // Contains paramter for selected Macro 
385     $r_con          = false;                                        // DB connection
386     $r_db           = false;                                        // Selected DB
387     $r_res          = false;                                        // Result resource
388     $a_ldap_attrs   = array();                                      //  
390     $s_ip           = NULL;                   // Contains ip for Sip entry
391     $s_host         = NULL;                   // Contains host for Sip entry
392     $s_qualify      = "yes";                  // Qualify entry
393     $s_pin          = NULL;                   // Entry for secret
394     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
396     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
397     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
398     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
400     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
401     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
403     $s_sip_key      = "";     // Key for SIP entry index      
404     $s_sip_val      = "";     // Value for SIP entry index      
406     $b_first_deleted= false;  // Only delete first entry, 
407     $s_telenums     = "";     // for each value variable
409     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
411     /* Prepare some basic attributes */
412     $oldnums = array();
413     foreach($this->a_old_telenums as $tele){
414       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
415     }
416     foreach($this->phoneNumbers as $tele){
417       $newnums[]= preg_replace("/[^0-9]/","",$tele);
418     }
420     if(empty($this->uid)) trigger_error("Uid is empty.");
423     /* Create voicemail entry 
424      */
425     if((!isset($this->cn))||(empty($this->cn))){
426       $CNname= $this->uid;
427     }else{
428       $CNname= $this->cn;
429     }
431     $s_mail = "";
432     if($this->has_mailAccount){
433       $s_mail = $this->mailAddress;;
434     }
436     /* Get phonehardware to setup sip entry  */
437     $ldap         = $this->config->get_ldap_link();
438     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
439     $a_ldap_attrs = $ldap->fetch();
441     /* Check selected phone hardware, is a default IP set? */
442     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
443       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
444       $s_host     = $s_ip;
445     }else{
446       $s_ip       = NULL;
447       $s_host     = "dynamic";
448     }
450     // Attribute GoFonQualify set ?
451     if(isset($a_ldap_attrs['goFonQualify'])){
452       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
453     }
455     // Attribute GoFonPIN set ?
456     if(isset($this->goFonPIN)){
457       $s_pin      = $this->goFonPIN;
458     }
460     // Attribute GoFonType set ?
461     if(isset($a_ldap_attrs['goFonType'])){
462       $s_type = $a_ldap_attrs['goFonType'][0];
463     }
465     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
466       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
467     }else{
468       $sip_data_array['dtmfmode']     ="rfc2833";
469     }
471     /* Check if phone number is used */
472     if($this->is_number_used()){
473       $this->generate_error = $this->is_number_used(); 
474       return false;
475     }
479     /********************** 
480      * Check Server Connection Information
481      **********************/
482  
483     /* Create Mysql handle for the current goFonHomeServer, if possible  
484      * Get configuration to old asterisk home server 
485      */ 
486     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
487     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
488     if(!$new_connection){
489       $this->generate_error =  msgPool::dbconnect($a_New['SERVER'],@mysql_error($new_connection),
490           _("Abort saving entries to keep the database consistent."));
491       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
492       return false;
493     }
494     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
495     if(!$new_database){
496       $this->generate_error =  msgPool::dbselect($a_New['DB'],@mysql_error($new_connection),
497           _("Abort saving entries to keep the database consistent."));
498       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
499       return false;
500     }
502     /* If the home server has changed, we must remove entries from old 
503      *  server and add new entries in new server.  
504      */
505     if($this->init_HomeServer != $this->goFonHomeServer){
506     
507       /* Get configuration to old asterisk home server */ 
508       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
509  
510       /* Create connection to the database that contains the old entry. 
511        */
512       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
513       if(!$old_connection){
514         $this->generate_error =  msgPool::dbconnect($a_Remove['SERVER'],@mysql_error($old_connection),
515             _("Abort saving entries to keep the database consistent."));
516         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
517         return false;
518       }
519       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
520       if(!$old_database){
521         $this->generate_error =  msgPool::dbselect($a_Remove['DB'],@mysql_error($old_connection),
522             _("Abort saving entries to keep the database consistent."));
523         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
524         return false;
525       }
526     }
528     /* Save means that we must save changes, not only test  */
529     if($save == true){
530     
531       /********************** 
532        * Remove entries from old home server 
533        **********************/
535       /* Check if there is an old entry 
536        * If there is an old entry, get callerid and remove voicemail and extensions 
537        */
538       if($old_connection){
539         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
540         $rid    = mysql_query($query,$old_connection);
541         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
543         /* Old entry found, remove it */
544         $query_a = array();
545         if(mysql_affected_rows($old_connection)){
546           $result = mysql_fetch_assoc($rid);
547           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
548           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
549           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
550           foreach($oldnums as $s_telenums) {
551             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
552           }
554           foreach($query_a as $qry){
555                   @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
556             if(!mysql_query($qry,$old_connection)){
557               trigger_error(mysql_error($old_connection));
558             } 
559           }
560         }
561       }
563       /********************** 
564        * Update / Insert sip_users entry  
565        **********************/
567       /* Set the first given phone number as callerid */
568       reset($newnums);        
569       $i_new_key = key($newnums);
570       $sip_data_array['callerid']  =$newnums[$i_new_key];
571       $sip_data_array['mailbox']   =$newnums[$i_new_key];
573       /* Check if there is already an entry in sip_users for this uid */
574       $SQL_query_array = array();
575       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
576       $rid = mysql_query($query,$new_connection);
577       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
578       if(mysql_affected_rows($new_connection)){
580         /********************** 
581          * Update sip_users entry 
582          **********************/
583         $result                     = mysql_fetch_assoc($rid);
584         $sip_data_array['host']         = $s_host;
585         $sip_data_array['qualify']      = $s_qualify;
586         $sip_data_array['secret']       = $this->goFonPIN;
587         $sip_data_array['type']         = $s_type ;
588         $sip_data_array['username']     = $this->uid;
589         $sip_data_array['ipaddr']       = $s_ip;
590         $sip_data_array['context']      = $this->context;
592         /* Remove not changed attributes, to avoid updating table with same values */
593         foreach($sip_data_array as $name => $value){
594           if($result[$name] == $value){
595             unset($sip_data_array[$name]);
596           }
597         }
598         /* Only update entry if there is something to uopdate */
599         if(count($sip_data_array)){
600           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
601           foreach($sip_data_array as $key => $val){
602             $query.= "".$key."='".$val."',"; 
603           } 
604           $query = preg_replace("/,$/","",$query);
605           $query.= " WHERE name='".$this->uid."';";
606           $SQL_query_array[] = $query;
607         }
608       } else {
609  
610         /********************** 
611          * Insert sip_users entry 
612          **********************/
613         //generate SIP entry
614         $sip_data_array['id']           = "";
615         $sip_data_array['name']         = $this->uid;
616         $sip_data_array['accountcode']  = NULL;          
617         $sip_data_array['amaflags']     = NULL;
618         $sip_data_array['callgroup']    = NULL;
619         $sip_data_array['canreinvite']  = "no";
620         $sip_data_array['context']      = $this->context;
621         $sip_data_array['defaultip']    = NULL;
622         $sip_data_array['fromuser']     = NULL;
623         $sip_data_array['fromdomain']   = NULL;
624         $sip_data_array['host']         = $s_host;
625         $sip_data_array['insecure']     = NULL;
626         $sip_data_array['language']     = NULL;
627         $sip_data_array['mailbox']      = $newnums[$i_new_key];
628         $sip_data_array['md5secret']    = NULL;
629         $sip_data_array['nat']          = "no";
630         $sip_data_array['permit']       = NULL;
631         $sip_data_array['deny']         = NULL;
632         $sip_data_array['mask']         = NULL;
633         $sip_data_array['pickupgroup']  = NULL;
634         $sip_data_array['port']         = NULL;
635         $sip_data_array['qualify']      = $s_qualify;
636         $sip_data_array['restrictcid']  = "n";
637         $sip_data_array['rtptimeout']   = NULL;
638         $sip_data_array['rtpholdtimeout']=NULL;
639         $sip_data_array['secret']       = $this->goFonPIN;
640         $sip_data_array['type']         = $s_type ;
641         $sip_data_array['username']     = $this->uid;
642         $sip_data_array['disallow']     = NULL;
643         $sip_data_array['allow']        = NULL;
644         $sip_data_array['musiconhold']  = NULL;
645         $sip_data_array['regseconds']   = NULL;
646         $sip_data_array['ipaddr']       = $s_ip;
647         $sip_data_array['regexten']     = NULL;
648         $sip_data_array['cancallforward']=NULL;
650         /* There is currently no entry for this user in the sip_users table. 
651          * We should create one i
652          */
653         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
654           if($s_sip_val === NULL) continue;
655           $s_sip_values.="'".$s_sip_val."',";
656           $s_sip_keys  .="`".$s_sip_key."`,";
657         }
658         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
659         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
661         /* Add sip entries to mysql queries */
662         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
663       }
666       /********************** 
667        * Update / Insert Voice mail entry  
668        **********************/
670       $customer_id = $newnums[$i_new_key];
672       $query  = "SELECT id,name,callerid FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';";
674       $rid    = mysql_query($query,$new_connection);
675       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
676       $result = mysql_fetch_assoc($rid);
677   
678       $old_customer_id = ""; 
679       if($result){
680         $old_customer_id = $result['callerid'];
681       }
683       $voice_data_array = array(
684           "customer_id" => $customer_id,
685           "mailbox"     => $customer_id,
686           "password"    => $this->goFonVoicemailPIN,
687           "fullname"    => $CNname,
688           "context"     => $this->voice_context,
689           "email"       => $s_mail);
691       $voice_data_array['pager']   = $this->pager;
693       /* Check if there is already an entry in sip_users for this uid */
694       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$old_customer_id."';\n";
697       $rid = mysql_query($query_tmp,$new_connection);
698       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
699       if(mysql_affected_rows($new_connection)){
701         /********************** 
702          * Update Voice mail entry  
703          **********************/
705         $result = mysql_fetch_assoc($rid)  ;
707         foreach($voice_data_array as $name => $value){
708           if($result[$name] == $value){
709             unset($voice_data_array[$name]);
710           }
711         }
713         /* Only update entry if there is something to update */
714         if(count($voice_data_array)){
715           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
716           foreach($voice_data_array as $key => $val){
717             $query.= "".$key."='".$val."',"; 
718           } 
719           $query = preg_replace("/,$/","",$query);
720           $query.= " WHERE customer_id='".$old_customer_id."';";
721           $SQL_query_array[] = $query;
722         }
723       }else{
725         /********************** 
726          * Insert Voice mail entry  
727          **********************/
728         $voice_data_array['context'] = $this->voice_context;
729   
730         /* There is currently no voice mail entry for this user. 
731          * We should create one 
732          */
733         $s_voi_values = $s_voi_keys = "";
734         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
735           if($s_voi_val === NULL) continue;
736           $s_voi_values.="'".$s_voi_val."',";
737           $s_voi_keys  .="`".$s_voi_key."`,";
738         }
739         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
740         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
742         /* Add sip entries to mysql queries */
743         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
744       }
746      
747       /********************** 
748        * Remove/Insert extension entries
749        **********************/
750       
751       /* Remove old entries */
752       $query = array();
753       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
754       $oldnums= array();
755       foreach($oldnums as $s_telenums){
756         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
757       }
758       foreach($newnums as $s_telenums){
759         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
760       }
761       foreach($query as $qry){
762         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
763         if(!mysql_query($qry,$new_connection)){
764           trigger_error(mysql_error($new_connection));
765         } 
766       }
767  
768       /********************** 
769        * Insert extension entries
770        **********************/
771  
772       // Get selected Macro Parameter and create parameter entry 
773       if(isset($this->macroarray[$this->macro])){
774         foreach($this->macroarray[$this->macro] as $key => $val ){
775           $s_parameter .= $val['choosen']."|";
776         }
777         $s_parameter = preg_replace("/\|$/","",$s_parameter);
778       }
779      
780       $i = 0; 
781       $EXT = array();
782       if(!is_numeric($this->uid)){
783         $EXT[$i]['context'] = 'GOsa';
784         $EXT[$i]['exten']   = $this->uid;
785         $EXT[$i]['priority']= 1;
786         $EXT[$i]['app']     = "Goto";
787         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
788         $i ++;
789       }
791       // Entension entries  Hint / Dial / Goto
792       foreach($newnums as $s_telenums){
794         /* Hint Entry */
795         $EXT[$i]['context'] = 'GOsa';
796         $EXT[$i]['exten']   = $s_telenums;
797         $EXT[$i]['priority']= "Hint";
798         $EXT[$i]['app']     = 'SIP/'.$this->uid;
799         $i ++;  
800         /* SetCID */
801         //$EXT[$i]['context'] = 'GOsa';
802         //$EXT[$i]['exten']   = $s_telenums;
803         //$EXT[$i]['priority']= 1;
804         //$EXT[$i]['app']     = "SetCIDName";
805         //$EXT[$i]['appdata'] = $CNname;
806         //$i ++;  
808         // If no macro is selected use Dial
809         if($this->macro!="none"){ 
810           $macroname = preg_replace("/,.*$/","",$this->macro);        
811           $macroname = preg_replace("/^.*=/","",$macroname);        
812           $s_app = "Macro";$macroname;
813           $s_par = $macroname."|".$s_parameter; 
814         }else{
815           $s_app = "Dial";
816           $s_par = 'SIP/'.$this->uid."|20|r";
817         }
819         $EXT[$i]['context'] = 'GOsa';
820         $EXT[$i]['exten']   = $s_telenums;
821         $EXT[$i]['priority']= 1;
822         $EXT[$i]['app']     = $s_app;
823         $EXT[$i]['appdata'] = $s_par;
824         $i ++;
825       }
827       // Append all these Entries 
828       foreach($EXT as $entr){
829         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
830         foreach($entr as $key2 => $val2){
831           $SQL_syn.= "`".$key2."`,";
832         }
833         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
834         $SQL_syn .= ") VALUES ("; 
835         foreach($entr as $key2 => $val2){
836           $SQL_syn .= "'".$val2."',";
837         }
838         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
839         $SQL_syn .=");\n";
841         $SQL_query_array[] =$SQL_syn;
842         $SQL_syn ="";
843       }
845       // Perform queries ...
846       foreach($SQL_query_array as $query){
847         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
848         if(!@mysql_query($query,$new_connection)){
849           $this->generate_error =  msgPool::dbquery("GOfon",@mysql_error($old_connection));
850           return false;
851         }
852       }
853     }
854     @mysql_close($new_connection);
855     return true;
856   }
859   function execute()
860   {
861     /* Call parent execute */
862     plugin::execute();
864     /* Log view */
865     if($this->is_account && !$this->view_logged){
866       $this->view_logged = TRUE;
867       new log("view","users/".get_class($this),$this->dn);
868     }
870     $display = "";
871     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
873     if(empty($this->macro)&&(!empty($this->goFonMacro))){
875       /* Go through already saved values, for a parameter */
876       $tmp = split("!",$this->goFonMacro);
878       /* it is possible that nothing has been saved yet */
879       if(is_array($tmp)){
881         /* First value is the macroname */
882         $this->macro = $tmp[0];
884         /* Macroname saved, delete that index */
885         unset($tmp[0]);
887         /* Check if macro has been removed */
888         if(!isset($this->macroarray[$this->macro])){
889           $this->macrostillavailable = false;
890         }else{
891           $this->macrostillavailable = true;
892         }
894         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
895         foreach($tmp as $var){
897           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
898           $varar = split("#",$var);
900           /* Only insert if the parameter still exists */
901           if(isset($this->macroarray[$this->macro][$varar[0]])){
902             /* Assign value */
903             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
904           }
905         }
906       }
907     }
908     
909     /* Do we represent a valid account? */
910     if (!$this->is_account && $this->parent === NULL){
911       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
912         msgPool::noValidExtension(_("Phone"))."</b>";
913       $display.= back_to_main();
914       return ($display);
915     }
917     /* Do we need to flip is_account state? */
918     if (isset($_POST['modify_state'])){
919       $this->is_account= !$this->is_account;
920     }
922     /* Do we represent a valid account? */
923     if (!$this->is_account && $this->parent === NULL){
924       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
925         msgPool::noValidExtension(_("Phone"))."</b>";
926       $display.= back_to_main();
927       return($display);
928     }
930     $display= "";
932     /* Show tab dialog headers */
933     
934     if (!$this->multiple_support_active && $this->parent !== NULL){
935       if ($this->is_account){
936         $display= $this->show_disable_header(_("Remove phone account"),
937             msgPool::featuresEnabled(_("Phone")));
938       } else {
939         if(empty($this->uid)){
940           $display= $this->show_enable_header(_("Create phone account"),
941             msgPool::featuresDisabled(_("Phone"),_("User uid")));
942         }else{
943           $display= $this->show_enable_header(_("Create phone account"),
944             msgPool::featuresDisabled(_("Phone")));
945         }
946         return ($display);
947       }
948     }
949     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
950     if(empty($this->macro)){
951       $this->macro ="none";
952     }
954     /* Prepare templating */
955     $smarty= get_smarty();
957     /* tell user that the selected plugin is no longer available */
958     if((!$this->macrostillavailable)&&($this->macro!="none")){
959       msg_dialog::display(_("Error"), _("Selected macro is not available anymore!"), ERROR_DIALOG);
960     }
962     /* Assing macroselectbox values  */
963     $smarty->assign("macros",$this->macros);   
964     $smarty->assign("macro", $this->macro);   
966     /* Assign contexts */
967     $smarty->assign("contexts",$this->get_asterisk_contexts());
968     $smarty->assign("context" ,$this->context);
969     $smarty->assign("voice_context" ,$this->voice_context);
971     /* check if there is a FON server created */
972     if(!count($this->goFonHomeServer)){
973       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
974     }
976     /* Create html parameter table for selected macro parameters 
977      *  skip if no parameters given 
978      */
979     if(!isset($this->macroarray[$this->macro])){
980       $macrotab="";
981     }else{
983       $macrotab ="<table summary=\""._("Parameter")."\">";
984       /* for every single parameter-> display textfile,combo, or true false switch*/
986       foreach($this->phoneNumbers as $phonenum){
987         $tmp[] = $phonenum;
988       }
989     
990       if($this->macro != $this->lastmacro){
991         /* Go through all params */
992         foreach($this->macroarray[$this->macro] as $key => $paras){
994           $string = $paras['default'];
996           $string=preg_replace("/%uid/i",$this->uid,$string);
998           if(isset($this->cn)){
999             $string=preg_replace("/%cn/i",$this->cn,$string);
1000           }
1002           for($i = 0 ; $i < 10; $i++){
1003             if(isset($tmp[$i])){
1004               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
1005             }
1006           }
1007           if(isset($tmp[0])){
1008             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
1009           }
1010           $this->macroarray[$this->macro][$key]['choosen']=$string;
1011         }
1012       }
1014       foreach($this->macroarray[$this->macro] as $paras){
1016         /* get al vars */
1017         $var        = $paras['var'];           
1018         $name       = $paras['name'];           
1019         $default    = $paras['default'];
1020         $type       = $paras['type'];
1021         $choosen    = $paras['choosen'] ; 
1022         $str        = $default;
1024         $dis = "";
1025         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
1026           $dis = " disabled ";
1027         }
1029         /* in case of a combo box display a combobox with selected attr */
1030         $macrotab.= "<tr>";
1031         switch ($type){
1033           case "combo":
1034             $str= "<select name='".$var."' ".$dis." >";
1035           foreach(split(":",$default) as $choice){
1036             if($choosen==$choice){
1037               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
1038             }else{
1039               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
1040             }
1041           }
1042           $str.="</select>";
1043           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1044           break;
1046           case "bool":
1047             if(!$choosen){
1048               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
1049             }else{
1050               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
1051             }
1052           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
1053           break;
1055           case "string":
1056             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
1057           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1058           break;
1060         }
1061         $macrotab.= "</td></tr>";
1063       }
1064       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1065     }//is_array()
1067     /* Give smarty the table */
1068     $smarty->assign("macrotab",$macrotab);
1071     /* Add phone number */
1072     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1074       if(strlen(trim($_POST["phonenumber"])) > 5 ){
1075         msg_dialog::display(_("Error"), msgPool::toobig("Phone number",99999), ERROR_DIALOG);
1076       }elseif (tests::is_phone_nr($_POST['phonenumber'])){
1077         $number= trim($_POST["phonenumber"]);
1078         $this->phoneNumbers[$number]= $number;
1079         $this->is_modified= TRUE;
1080       } else {
1081         msg_dialog::display(_("Error"), msgPool::invalid("Phone number"), ERROR_DIALOG);
1082       }
1083     }
1085     /* Remove phone number */
1086     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1087       foreach ($_POST['phonenumber_list'] as $number){
1088         unset($this->phoneNumbers[$number]);
1089         $this->is_modified= TRUE;
1090       }
1091     }
1093     /* Assign acls */
1094     $tmp = $this->plInfo();
1095     foreach($tmp['plProvidedAcls'] as $name => $translation){
1096       $smarty->assign($name."ACL",$this->getacl($name,$SkipWrite));
1097     }
1099     /* Transfer ACL's */
1100     foreach($this->attributes as $val){
1101       if(isset($this->$val)){
1102         $smarty->assign($val,$this->$val);
1103       }else{
1104         $smarty->assign($val,"");
1105       }
1106     }
1108     /* Create home server array */
1109     $tmp = array();
1110     foreach($this->goFonHomeServers as $dn => $attrs){
1111       if(!is_numeric($dn)){
1112         $tmp[$dn] = $attrs['SERVER'];
1113       }
1114     }
1115     $smarty->assign("goFonHomeServers",$tmp);
1117     /* Fill arrays */
1118     $smarty->assign ("goFonHardware", $this->goFonHardware);
1119     if (!count($this->phoneNumbers)){
1120       $smarty->assign ("phoneNumbers", array());
1121     } else {
1122       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1123     }
1125     $dis = "";
1126     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1127       $dis= " disabled ";
1128     }
1129     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1130        _("Choose your private phone")."\">\n";
1132     foreach ($this->hardware_list as $cn => $description){
1133       if ($cn == $this->goFonHardware){
1134         $selected= "selected";
1135       } else {
1136         $selected= "";
1137       }
1138       if (isset($this->used_hardware[$cn])){
1139         $color= "style=\"color:#A0A0A0\"";
1140       } else {
1141         $color= "";
1142       }
1143       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1144     }
1145     $hl.= "</select>\n";
1146     $smarty->assign ("hardware_list", $hl);
1149     foreach($this->attributes as $attr){
1150       if(in_array($attr,$this->multi_boxes)){
1151         $smarty->assign("use_".$attr,TRUE);
1152       }else{
1153         $smarty->assign("use_".$attr,FALSE);
1154       }
1155     }
1157     foreach(array("goFonVoiceMailContext","goFonContext") as $attr){
1158       if(in_array($attr,$this->multi_boxes)){
1159         $smarty->assign("use_".$attr,TRUE);
1160       }else{
1161         $smarty->assign("use_".$attr,FALSE);
1162       }
1163     }
1165     /* Show main page */
1166     $this->lastmacro = $this->macro;
1167     $smarty->assign("multiple_support",$this->multiple_support_active);
1168     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1169     return($display);
1170   }
1173   function save_object()
1174   {
1175     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1176     if (isset($_POST["phoneTab"])){
1177     
1178       plugin::save_object();
1180       /* Save checkbox */
1181       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1182       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1183         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1184           $tmp .= "M";
1185         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1186           $tmp  = preg_replace ("/M/","",$tmp);
1187         }
1188       }
1189       $this->goFonDeliveryMode= "[".$tmp."]";
1192       /* Every macro in the select box are available */
1193       if((isset($_POST['macro']))){
1194         $this->macro = $_POST['macro'];
1195         $this->macrostillavailable=true;
1196       }
1198       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1199         $this->is_modified =true;
1200       }
1202       /* Save context */
1203       if(isset($_POST['context'])){
1204         if($this->context != $_POST['context']){
1205           $this->is_modified= TRUE;
1206         }
1207         $this->context= $_POST['context'];
1208       }
1210       /* Save voice context */
1211       if(isset($_POST['voice_context'])){
1212         if($this->voice_context != $_POST['voice_context']){
1213           $this->is_modified= TRUE;
1214         }
1215         $this->voice_context= $_POST['voice_context'];
1216       }
1218       if(is_array($this->phoneNumbers)){
1219         foreach($this->phoneNumbers as $telenumms) {
1220           $nummsinorder[]=$telenumms; 
1221         }
1222       }else{
1223         $nummsinorder=array("");
1224       }
1227       /* get all Postvars */
1228       if(isset($this->macroarray[$this->macro])){
1231         if($this->acl_is_writeable("goFonMacro",$SkipWrite)){
1232           foreach($this->macroarray[$this->macro] as $key => $paras){
1234             $old_macro_settings = $this->macroarray[$this->macro][$key]; 
1235             $backup = $this->macroarray[$this->macro][$key];
1237             if(isset($_POST[$paras['var']])){
1238               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1239             }
1241             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1242                We need this code below to read and save checkboxes correct
1243              */
1245             if(isset($_POST['post_success'])){
1246               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1247                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1248                   $this->macroarray[$this->macro][$key]['choosen']=1;
1249                 }else{
1250                   $this->macroarray[$this->macro][$key]['choosen']=0;
1251                 }
1252               }
1253             }
1254             if(array_differs($old_macro_settings,$this->macroarray[$this->macro][$key])){
1255               $this->is_modified = TRUE;
1256             }
1257           }
1259           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1260             $this->is_modified = TRUE;
1261           }
1262         }
1263       }
1264     }
1265   }
1267   function check()
1268   {
1269     /* Call common method to give check the hook */
1270     $message= plugin::check();
1272     if(!count($this->goFonHomeServers)){
1273       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1274     }
1276     if(empty($this->goFonHomeServer)){
1277       $message[] = msgPool::invalid(_("Home server"));
1278     }
1280     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1281       $message[]= msgPool::invalid(_("Voicemail PIN"),"","",_("Between 1-4 charactes"));
1282     }else{
1283       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1284         $message[]= msgPool::invalid(_("Voicemail PIN"),preg_replace("/[0-9]/","X",$this->goFonVoicemailPIN),"/X/");
1285       }
1286     }
1288     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1289       $message[]= msgPool::invalid(_("Phone PIN"),preg_replace("/[0-9a-z]/i","X",$this->goFonPIN),"/X/");
1290     }
1292     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1293       if(!$this->generate_mysql_entension_entries()){
1294         $message[] = $this->generate_error;
1295       }
1296     }
1298     /* We need at least one phone number */
1299     if (count($this->phoneNumbers) == 0){
1300       $message[]= msgPool::required("Phone number");
1301     }
1303     /* check for ! in any parameter setting*/
1304     if(isset($this->macroarray[$this->macro])){
1305       foreach($this->macroarray[$this->macro] as $val){
1306         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1307           $message[] = msgPool::invalid(sprintf(_("macro parameter %s"),$val['name']),$val['choosen'],"/[^\#]/");
1308         }
1309       }
1310     }
1311     return ($message);
1312   }
1316   function save()
1317   {
1318     plugin::save();
1320     /* Force saving macro again 
1321      * This ensures that 
1322      *  - the macro is available on the destiantion server.
1323      *  - the macro saved is up to date on the destination server.
1324      */
1325     if(!empty($this->macro) && $this->macro != "none")  {
1326       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1327       $macro_tab -> save();
1328     }
1330     /* Save arrays */
1331     $tmp_numbers = array();
1332     foreach ($this->phoneNumbers as $number){
1333       $tmp_numbers[] = $number;
1334     }
1336     /* Save settings, or remove goFonMacro attribute*/
1337     if($this->macro!="none"){    
1338       $this->attrs['goFonMacro']=$this->macro;
1339       if(isset($this->macroarray[$this->macro])){
1340         foreach($this->macroarray[$this->macro] as $paras)  {
1341           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1342         }
1343       }
1344     }else{
1345       $this->attrs['goFonMacro']=array();
1346     }
1347     unset($this->attrs['macro'])  ;
1349     $this->attrs['goFonForwarding']=array();
1351     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1352       $str = $this->generate_mysql_entension_entries(true);
1353       if(empty($str)){
1354         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
1355       }
1356     }
1358     if($this->attrs['goFonMacro']==""){
1359       $this->attrs['goFonMacro']=array();
1360     }
1362     unset($this->attrs['cn']);
1364     /* Write back to ldap */
1365     $ldap= $this->config->get_ldap_link();
1366     $ldap->cd($this->dn);
1367     $this->cleanup();
1368     
1369     /* Force saving numbers, else it will be overwriten by user account. */
1370     $this->attrs['telephoneNumber'] =$tmp_numbers;
1371     $ldap->modify ($this->attrs); 
1373     /* Log last action */
1374     if($this->initially_was_account){
1375       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1376     }else{
1377       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1378     }
1380     if (!$ldap->success()){
1381       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
1382     }
1384     /* Optionally execute a command after we're done */
1386     if ($this->initially_was_account == $this->is_account){
1387       if ($this->is_modified){
1388         $this->handle_post_events("modify",array("uid" => $this->uid));
1389       }
1390     } else {
1391       $this->handle_post_events("add",array("uid" => $this->uid));
1392     }
1394   }
1397   function adapt_from_template($dn, $skip= array())
1398   {
1399     plugin::adapt_from_template($dn, $skip);
1401     /* Assemble phone numbers */
1402     if (isset($this->attrs['telephoneNumber']) && !in_array("telephoneNumber", $skip)){
1403       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1404         $number= $this->attrs['telephoneNumber'][$i];
1405         $this->phoneNumbers[$number]= $number;
1406       }
1407     }
1408   }
1411   function remove_from_parent()
1412   {
1413     if(!$this->initially_was_account) return;
1415     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1417       // Get Configuration for initial Mysql database Server
1418       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1419       $s_parameter  ="";
1421       // Connect to DB server
1422       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1424       // Check if we are  connected correctly
1425       if(!$r_con){
1426         msg_dialog::display(_("Error"), msgPool::dbconnect("GOfon",@mysql_error()), ERROR_DIALOG);
1427         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1428         return false;
1429       }
1431       // Select database for Extensions
1432       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1434       // Test if we have the database selected correctly
1435       if(!$db){
1436         msg_dialog::display(_("Error"), msgPool::dbselect("GOfon", @mysql_error()), ERROR_DIALOG);
1437         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1438         return false;
1439       }
1441       $SQL="";
1444       $first_num = false;
1445       // Delete old entries
1446       foreach($this->a_old_telenums as $s_telenums){
1447         if(!$first_num){
1448           $first_num = $s_telenums;
1449         }
1450         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1451       }
1454       $query  = "SELECT id,name,callerid FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';";
1455       $rid    = mysql_query($query,$r_con);
1456       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1457       $result = mysql_fetch_assoc($rid);
1458       $callerid = $first_num;
1459       if($result){
1460         $callerid = $result['callerid'];
1461       }
1463       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$callerid."';";
1464       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1465       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1467       foreach($SQL as $query){
1468         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1469         if(!@mysql_query($query,$r_con)){
1470           msg_dialog::display(_("Error"), msgPool::dbquery("GOfon",@mysql_error()), ERROR_DIALOG);
1471           return false;
1472         }
1473       }
1474     }else{
1475       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
1476       return false;
1477     }
1479     /* unset macro attr, it will cause an error */
1480     $tmp = array_flip($this->attributes);
1481     unset($tmp['macro']);
1482     $this->attributes=array_flip($tmp);
1484     /* Cancel if there's nothing to do here */
1485     if (!$this->initially_was_account){
1486       return;
1487     }
1489     plugin::remove_from_parent();
1491     /* Just keep one phone number */
1492     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1493       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1494     } else {
1495       $this->attrs['telephoneNumber']= array();
1496     }
1499     $ldap= $this->config->get_ldap_link();
1500     $ldap->cd($this->config->current['BASE']);
1501     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1502     while($attr = $ldap->fetch()){
1503       if(in_array($this->dn,$attr['member'])){
1504         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1505         unset($new->by_object['ogroup']->memberList[$this->dn]);
1506         unset($new->by_object['ogroup']->member[$this->dn]);
1507         $new->save();
1508         msg_dialog::display(_("Information"), sprintf(_("User '%s' has been removed from phone queue '%s'."), $this->cn, $new->by_object['ogroup']->cn), INFO_DIALOG);
1509       }
1510     }
1511     $ldap->cd($this->dn);
1512     $this->cleanup();
1513     $ldap->modify ($this->attrs); 
1515     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1516     if (!$ldap->success()){
1517       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1518     }
1520     /* Optionally execute a command after we're done */
1521     @mysql_close($r_con);
1522     $this->handle_post_events('remove',array("uid"=> $this->uid));
1523   }
1527   /* This function checks if the given phonenumbers are available or already in use*/
1528   function is_number_used()
1529   {
1530     $ldap= $this->config->get_ldap_link();
1531     $ldap->cd($this->config->current['BASE']);
1532     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1533     while($attrs = $ldap->fetch()) {
1534       unset($attrs['telephoneNumber']['count']);
1535       foreach($attrs['telephoneNumber'] as $tele){
1536         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1537         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1538         $numbers[$tele]=$attrs;
1539       }
1540     }
1542     foreach($this->phoneNumbers as $num){
1543       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1544         if(isset($numbers[$num]['uid'][0])){
1545           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1546         }else{
1547           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1548         }
1549       }
1550     }
1551   }
1554   /* Create phoneAccount part of copy & paste dialog */
1555   function getCopyDialog()
1556   { 
1557     if(!$this->is_account) return("");
1558     $smarty = get_smarty();
1559     if (!count($this->phoneNumbers)){
1560       $smarty->assign ("phoneNumbers", array(""));
1561     } else {
1562       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1563     }
1565     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1566     $smarty->assign("goFonPIN",$this->goFonPIN);
1568     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1569     $ret =array();
1570     $ret['string'] = $display;
1571     $ret['status'] = "";
1572     return($ret);
1573   }
1575   /* Save posts from copy & paste dialog dialog  */
1576   function saveCopyDialog()
1577   {
1578     if(!$this->is_account) return;
1579     $this->execute();
1580     if(isset($_POST['goFonVoicemailPIN'])) {
1581       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1582     }
1583     if(isset($_POST['goFonPIN'])){
1584       $this->goFonPIN = $_POST['goFonPIN'];
1585     }
1586   }
1589   function allow_remove()
1590   {
1591     /* Check if previously selected server is still available */
1592     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1593       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1594     }
1595   }
1597   /* Return plugin informations for acl handling */
1598   static function plInfo()
1599   {
1600     return (array(
1601           "plShortName"     => _("Phone"),
1602           "plDescription"   => _("Phone account settings"),
1603           "plSelfModify"    => TRUE,
1604           "plDepends"       => array("user"),
1605           "plPriority"      => 7,                                 // Position in tabs
1606           "plSection"         => array("personal" => _("My account")),
1607           "plCategory"        => array("users"),
1610           "plOptions"       => array(),
1612           "plProvidedAcls"  => array(
1613             "telephoneNumber"     => _("Telephone number"),
1614             "goFonMacro"          => _("Macro settings"),
1615             "goFonHardware"       => _("Phone hardware"),
1616             "goFonHomeServer"     => _("Home server"),
1617             "goFonContext"          => _("Phone context"),
1618             "goFonVoiceMailContext" => _("Voice mail context"),
1619             "goFonPIN"            => _("Telephone pin"),
1620             "goFonVoicemailPIN"   => _("Voicemail pin"))
1621           ));
1622   }
1626   function multiple_execute()
1627   {
1628     plugin::multiple_execute();
1629     return($this->execute());
1630   }
1632   function get_multi_init_values()
1633   {
1634     $ret = plugin::get_multi_init_values();
1635     $ret['phoneNumbers'] = array();
1636     foreach($this->phoneNumbers as $number){
1637       $ret['phoneNumbers'][] = $number."  [".$this->attrs['cn'][0]."]"; 
1638     }
1639     $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1640     return($ret);
1641   }
1643   function init_multiple_support($attrs,$all)
1644   {
1645     plugin::init_multiple_support($attrs,$all);
1647     $this->phoneNumbers = array();
1648     if(isset($all['phoneNumbers'])){
1649       for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1650         $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1651       }
1652     }
1653   }
1655   function multiple_save_object()
1656   {
1657     /* Simply call parents save_object */
1658     if (isset($_POST["phoneTab"])){
1660       plugin::save_object();
1661       plugin::multiple_save_object();
1663       /* Every macro in the select box are available */
1664       if((isset($_POST['macro']))){
1665         $this->macrostillavailable=true;
1666       }
1668       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1669         $this->macro = $_POST['macro'];
1670         $this->is_modified =true;
1671       }
1673       /* get all Postvars */
1674       if(isset($this->macroarray[$this->macro])){
1675         foreach($this->macroarray[$this->macro] as $key => $paras){
1676           $backup = $this->macroarray[$this->macro][$key];
1677           if(isset($_POST[$paras['var']])){
1678             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1679           }
1680           if(isset($_POST['post_success'])){
1681             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1682               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1683                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1684               }else{
1685                 $this->macroarray[$this->macro][$key]['choosen']=false;
1686               }
1687             }
1688           }
1689         }
1690         if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1691           $this->is_modified = TRUE;
1692         }
1693       }
1694     }
1695   }
1697   function multiple_check()
1698   {
1699     $message = plugin::multiple_check();
1701     if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1702       $message[] = _("There is currently no asterisk server defined!");
1703     }
1705     if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1706       $message[] = _("Asterisk server is invalid!");
1707     }
1709     if(in_array("goFonVoicemailPIN",$this->multi_boxes) && 
1710         ( (strlen($this->goFonVoicemailPIN)==0)||
1711           (strlen($this->goFonVoicemailPIN)>4))){
1712       $message[]=(_("Voicemail PIN must be 4 characters long!"));
1713     }else{
1714       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1715         $message[]=(_("Voicemail PIN contains invalid characters!"));
1716       }
1717     }
1719     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1720       $message[]=(_("Phone pin contains invalid characters!"));
1721     }
1723     /* check for ! in any parameter setting*/
1724     if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1725       foreach($this->macroarray[$this->macro] as $val){
1726         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1727           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1728         }
1729       }
1730     }
1732     return($message);
1733   }
1735   function get_multi_edit_values()
1736   {
1737     $ret = plugin::get_multi_edit_values();
1738     if(in_array("macro",$this->multi_boxes)){
1739       $ret['macro'] = $this->macro;
1740       $ret['macroarray'] = $this->macroarray;
1741       $ret['macros'] = $this->macros;
1742     }
1743     return($ret);
1744   }
1747   /* Return asterisk contexts
1748    * Additionaly read contexts from file.
1749    */
1750   function get_asterisk_contexts()
1751   {
1752     $contexts = array();
1753     $contexts[] = "default";
1754     $contexts[] = "parkedcalls";
1755     $contexts[] = "from-sip";
1756     $contexts[] = "from-capi";
1757     $file = "/etc/gosa/asterisk_contexts.conf";
1758     if(file_exists($file) && is_readable($file)){
1759       foreach(file($file) as $context){
1760         $contexts[] = trim($context);
1761       }
1762     }
1763     array_unique($contexts);
1764     return($contexts);
1765   }
1768 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1769 ?>