Code

Updated gofon
[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 $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;
301     /* Get voicemail PIN from MySQL DB 
302      * Because every user can change his PIN directly from the phone
303      *  without any update to the ldap
304      * This means, the PIN in the DB is up to date
305      */
306     // Connect to DB server
309     $num = key($this->phoneNumbers);
311     if( (is_callable("mysql_pconnect"))&&
312         (isset($cur_cfg))&&
313         (isset($cur_cfg['SERVER']))&&
314         (isset($cur_cfg['LOGIN']))&&
315         (isset($cur_cfg['PASSWORD']))){
317       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
318       if($r_con){
320         // Try to select the gophone database
321         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
322         if(!$r_db){
323           msg_dialog::display(_("Warning"), msgPool::dbselect($cur_cfg['DB'],mysql_error()), WARNING_DIALOG);
324         }
326         $query_tmp = "SELECT ".$cur_cfg['VOICE_TABLE'].".context as 'v_context', 
327                              ".$cur_cfg['SIP_TABLE'].".context, 
328                              ".$cur_cfg['VOICE_TABLE'].".password 
329                        FROM  ".$cur_cfg['VOICE_TABLE'].", 
330                              ".$cur_cfg['SIP_TABLE']." 
331                        WHERE ".$cur_cfg['VOICE_TABLE'].".mailbox = ".$num." 
332                           AND ".$cur_cfg['SIP_TABLE'].".name='".$this->uid."'";
333         $res = mysql_query($query_tmp);
334         $vp  = mysql_fetch_assoc($res);
335         if(!isset($vp['context'])){
336           $this->is_modified= TRUE;
337           msg_dialog::display(_("Warning"), sprintf(_("Could not identify telephone extension in database, please try to save again. Activate debugging if error remains.")), WARNING_DIALOG);
338         } 
339  
340         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
341         if((isset($vp['password']))&&(!empty($vp['password']))){
342           $this->goFonPINVoice = $vp['password'];
343         }
344         if((isset($vp['context']))&&(!empty($vp['context']))){
345           $this->context = $vp['context'];
346         }
347         if((isset($vp['v_context']))&&(!empty($vp['v_context']))){
348           $this->voice_context = $vp['v_context'];
349         }
350       }
351     }
352     $this->lastmacro=$this->macro;
354     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
355       @mysql_close($r_con) ;
356     }
357   }
360   /* Transaction will only work with InnoDB tables 
361    */
362   public static function checkRealtimeTables($config)
363   {
364     $ret =TRUE;
366     // Connect to DB server
367     if( (is_callable("mysql_pconnect"))&&
368         (isset($config))&&
369         (isset($config['SERVER']))&&
370         (isset($config['LOGIN']))&&
371         (isset($config['PASSWORD']))){
373       $r_con =  @mysql_pconnect($config['SERVER'],$config['LOGIN'],$config['PASSWORD']);
374       if($r_con){
375         $r_db  =  @mysql_select_db($config['DB'],$r_con);
377         /* Validate Table Type - it must be InnoDB to be able to use transactions 
378          */
379         $inno_tables = array("SIP_TABLE","EXT_TABLE","VOICE_TABLE","QUEUE_TABLE","QUEUE_MEMBER_TABLE"); 
380         foreach($inno_tables as $inno_table){
381           $sql = "show table status like '".$config[$inno_table]."';";
382           $res = mysql_query($sql);
383           $vp  = mysql_fetch_assoc($res);
384           if(!preg_match("/^InnoDB$/i",$vp['Engine'])){
386             /* Not an InnoDB Table type, try to modify type. 
387              */
388             $sql = "ALTER TABLE `".$config[$inno_table]."` ENGINE = INNODB; ";
389             $res = mysql_query($sql);
390             if(!$res){
391               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$sql."</b>", 
392                   "<b>FAILED!</b>. Transactions will not work!");
393               $ret = FALSE;
394             }else{
395               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$sql."</b>", 
396                   "<i>Table '".$config[$inno_table]."' is now of type InnoDB, this enables transactions.</i>");
397             }
398           }else{
399             @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"",
400                 "<i>Table type of '".$config[$inno_table]."' OK, using transactions!</i>");
401           }
402         }
403       }
404     }
405     return($ret);
406   }
409   /* This function generates the Database entries. 
410    * The Parameter 'save' could be true or false.
411    *  false - means only testing no database transactions.
412    *  true  - write database entries.
413    *
414    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
415    * 
416    * If the phone hardware is 'automatic' the table entries will only be removed
417    *  and not added. 
418    */
419   function generate_mysql_entension_entries($save = false)
420   {
421     /* Check if there is at least one server available 
422      * If not, return and tell the user that saving failed 
423      */
424     if(!count($this->goFonHomeServers)){
425       if($save){
426         msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
427       }
428       return(true);
429     }
431     /* Check if Mysql extension is available */
432     if(!is_callable("mysql_pconnect")){
433       if($save){
434         msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
435       }
436       return(true);
437     }
438  
439     /********************** 
440      * Attribute Initialisation
441      **********************/
443     $old_connection = false;
445     // Get Configuration for Mysql database Server
446     $s_parameter    = "";                                           // Contains paramter for selected Macro 
447     $r_con          = false;                                        // DB connection
448     $r_db           = false;                                        // Selected DB
449     $r_res          = false;                                        // Result resource
450     $a_ldap_attrs   = array();                                      //  
452     $s_ip           = NULL;                   // Contains ip for Sip entry
453     $s_host         = NULL;                   // Contains host for Sip entry
454     $s_qualify      = "yes";                  // Qualify entry
455     $s_pin          = NULL;                   // Entry for secret
456     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
458     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
459     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
460     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
462     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
463     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
465     $s_sip_key      = "";     // Key for SIP entry index      
466     $s_sip_val      = "";     // Value for SIP entry index      
468     $b_first_deleted= false;  // Only delete first entry, 
469     $s_telenums     = "";     // for each value variable
471     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
473     /* Prepare some basic attributes */
474     $oldnums = array();
475     foreach($this->a_old_telenums as $tele){
476       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
477     }
478     foreach($this->phoneNumbers as $tele){
479       $newnums[]= preg_replace("/[^0-9]/","",$tele);
480     }
482     if(empty($this->uid)) trigger_error("Uid is empty.");
485     /* Create voicemail entry 
486      */
487     if((!isset($this->cn))||(empty($this->cn))){
488       $CNname= $this->uid;
489     }else{
490       $CNname= $this->cn;
491     }
493     $s_mail = "";
494     if($this->has_mailAccount){
495       $s_mail = $this->mailAddress;;
496     }
498     /* Get phonehardware to setup sip entry  */
499     $ldap         = $this->config->get_ldap_link();
500     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
501     $a_ldap_attrs = $ldap->fetch();
503     /* Check selected phone hardware, is a default IP set? */
504     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
505       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
506       $s_host     = $s_ip;
507     }else{
508       $s_ip       = NULL;
509       $s_host     = "dynamic";
510     }
512     // Attribute GoFonQualify set ?
513     if(isset($a_ldap_attrs['goFonQualify'])){
514       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
515     }
517     // Attribute GoFonPIN set ?
518     if(isset($this->goFonPIN)){
519       $s_pin      = $this->goFonPIN;
520     }
522     // Attribute GoFonType set ?
523     if(isset($a_ldap_attrs['goFonType'])){
524       $s_type = $a_ldap_attrs['goFonType'][0];
525     }
527     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
528       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
529     }else{
530       $sip_data_array['dtmfmode']     ="rfc2833";
531     }
533     /* Check if phone number is used */
534     if($this->is_number_used()){
535       $this->generate_error = $this->is_number_used(); 
536       return false;
537     }
541     /********************** 
542      * Check Server Connection Information
543      **********************/
544  
545     /* Create Mysql handle for the current goFonHomeServer, if possible  
546      * Get configuration to old asterisk home server 
547      */ 
548     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
549     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
550     if(!$new_connection){
551       $this->generate_error =  msgPool::dbconnect($a_New['SERVER'],@mysql_error($new_connection),
552           _("Abort saving entries to keep the database consistent."));
553       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
554       return false;
555     }
556     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
557     if(!$new_database){
558       $this->generate_error =  msgPool::dbselect($a_New['DB'],@mysql_error($new_connection),
559           _("Abort saving entries to keep the database consistent."));
560       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
561       return false;
562     }
564     /* If the home server has changed, we must remove entries from old 
565      *  server and add new entries in new server.  
566      */
567     if($this->init_HomeServer != $this->goFonHomeServer){
568     
569       /* Get configuration to old asterisk home server */ 
570       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
571  
572       /* Create connection to the database that contains the old entry. 
573        */
574       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
575       if(!$old_connection){
576         $this->generate_error =  msgPool::dbconnect($a_Remove['SERVER'],@mysql_error($old_connection),
577             _("Abort saving entries to keep the database consistent."));
578         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
579         return false;
580       }
581       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
582       if(!$old_database){
583         $this->generate_error =  msgPool::dbselect($a_Remove['DB'],@mysql_error($old_connection),
584             _("Abort saving entries to keep the database consistent."));
585         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
586         return false;
587       }
588     }
591     /* Save means that we must save changes, not only test  */
592     if($save == true){
593     
594       /********************** 
595        * Remove entries from old home server 
596        **********************/
598       /* Check if there is an old entry 
599        * If there is an old entry, get callerid and remove voicemail and extensions 
600        */
601       if($old_connection){
603         /* Check table definitions
604          */
605         if(!phoneAccount::checkRealtimeTables($a_Remove)){
606           msg_dialog::display(_("Warning"),
607               sprintf(_("GOsa identified problems with your MySQL table definition, please activate debugging for details.")),
608               WARNING_DIALOG);
609         }
611         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
612         $rid    = mysql_query($query,$old_connection);
613         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, 
614             "<i>Reguest callerid to be able to identify the user.</i>");
616         /* Old entry found, remove it */
617         $query_a = array();
618         if(mysql_affected_rows($old_connection)){
619           $result = mysql_fetch_assoc($rid);
621           /* Set mode to strict
622              Strict disallows the addition of entries that do not match the targets field length.
623            */
624           $query_a[]= "SET @@sql_mode = STRICT_ALL_TABLES;";
625           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
626           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
627           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
628           foreach($oldnums as $s_telenums) {
629             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
630           }
632           /* Start transaction, to be able to rollback 
633            */
634           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Removing entry from old server---</b>","");
636           mysql_query("begin;",$old_connection);
637           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
639           foreach($query_a as $query){
640             @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
641             if(!mysql_query($query,$old_connection)){
642               $err = mysql_error($old_connection);
643               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
644               msg_dialog::display(_("Error"), 
645                   msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
646                   "\n<p>"._("Please activate debugging for details!")."</p>",
647                   ERROR_DIALOG);
649               mysql_query("rollback;",$old_connection);
650               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
651               @mysql_close($old_connection);
652               return(false);
653             } 
654           }
656           /* Let changes get active, everything was fine;
657            */ 
658           mysql_query("commit;",$old_connection);
659           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "");
660           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
661         }
662       }
665       /********************** 
666        * Update / Insert sip_users entry  
667        **********************/
669       /* Check table definitions
670        */
671       if(!phoneAccount::checkRealtimeTables($a_New)){
672         msg_dialog::display(_("Warning"),
673             sprintf(_("GOsa identified problems with your MySQL table definition, please activate debugging for details.")),
674             WARNING_DIALOG);
675       }
678       /* Set the first given phone number as callerid */
679       reset($newnums);        
680       $i_new_key = key($newnums);
681       $sip_data_array['callerid']  =$newnums[$i_new_key];
682       $sip_data_array['mailbox']   =$newnums[$i_new_key]."@".$this->voice_context;
684       /* Check if there is already an entry in sip_users for this uid */
685       $SQL_query_array = array();
687       /* Enforce strict mode, ensures inout validation, e.g. target field length 
688        */
689       $SQL_query_array[] = "SET @@sql_mode = STRICT_ALL_TABLES;";
691       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
692       $rid = mysql_query($query,$new_connection);
693       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Receive current mysql entries.");
694       if(mysql_affected_rows($new_connection)){
696         /********************** 
697          * Update sip_users entry 
698          **********************/
699         $result                     = mysql_fetch_assoc($rid);
700         $sip_data_array['host']         = $s_host;
701         $sip_data_array['qualify']      = $s_qualify;
702         $sip_data_array['secret']       = $this->goFonPIN;
703         $sip_data_array['type']         = $s_type ;
704         $sip_data_array['username']     = $this->uid;
705         $sip_data_array['ipaddr']       = $s_ip;
706         $sip_data_array['context']      = $this->context;
708         /* Remove not changed attributes, to avoid updating table with same values */
709         foreach($sip_data_array as $name => $value){
710           if($result[$name] == $value){
711             unset($sip_data_array[$name]);
712           }
713         }
714         /* Only update entry if there is something to uopdate */
715         if(count($sip_data_array)){
716           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
717           foreach($sip_data_array as $key => $val){
718             $query.= "".$key."='".$val."',"; 
719           } 
720           $query = preg_replace("/,$/","",$query);
721           $query.= " WHERE name='".$this->uid."';";
722           $SQL_query_array[] = $query;
723         }
724       } else {
726         /********************** 
727          * Insert sip_users entry 
728          **********************/
729         //generate SIP entry
730         $sip_data_array['name']         = $this->uid;
731         $sip_data_array['accountcode']  = NULL;          
732         $sip_data_array['amaflags']     = NULL;
733         $sip_data_array['callgroup']    = NULL;
734         $sip_data_array['canreinvite']  = "no";
735         $sip_data_array['context']      = $this->context;
736         $sip_data_array['defaultip']    = NULL;
737         $sip_data_array['fromuser']     = NULL;
738         $sip_data_array['fromdomain']   = NULL;
739         $sip_data_array['host']         = $s_host;
740         $sip_data_array['insecure']     = NULL;
741         $sip_data_array['language']     = NULL;
742         $sip_data_array['mailbox']      = $newnums[$i_new_key]."@".$this->voice_context;
743         $sip_data_array['md5secret']    = NULL;
744         $sip_data_array['nat']          = "no";
745         $sip_data_array['permit']       = NULL;
746         $sip_data_array['deny']         = NULL;
747         $sip_data_array['mask']         = NULL;
748         $sip_data_array['pickupgroup']  = NULL;
749         $sip_data_array['port']         = NULL;
750         $sip_data_array['qualify']      = $s_qualify;
751         $sip_data_array['restrictcid']  = "n";
752         $sip_data_array['rtptimeout']   = NULL;
753         $sip_data_array['rtpholdtimeout']=NULL;
754         $sip_data_array['secret']       = $this->goFonPIN;
755         $sip_data_array['type']         = $s_type ;
756         $sip_data_array['username']     = $this->uid;
757         $sip_data_array['disallow']     = NULL;
758         $sip_data_array['allow']        = NULL;
759         $sip_data_array['musiconhold']  = NULL;
760         $sip_data_array['regseconds']   = NULL;
761         $sip_data_array['ipaddr']       = $s_ip;
762         $sip_data_array['regexten']     = NULL;
763         $sip_data_array['cancallforward']=NULL;
765         /* There is currently no entry for this user in the sip_users table. 
766          * We should create one i
767          */
768         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
769           if($s_sip_val === NULL) continue;
770           $s_sip_values.="'".$s_sip_val."',";
771           $s_sip_keys  .="`".$s_sip_key."`,";
772         }
773         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
774         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
776         /* Add sip entries to mysql queries */
777         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
778       }
781       /********************** 
782        * Update / Insert Voice mail entry  
783        **********************/
785       $customer_id = $newnums[$i_new_key];
786       $query  = "SELECT id,name,callerid FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';";
787       $rid    = mysql_query($query,$new_connection);
789       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Receive callerid");
790       $result = mysql_fetch_assoc($rid);
792       $old_customer_id = ""; 
793       if($result){
794         $old_customer_id = $result['callerid'];
795       }
797       $voice_data_array = array(
798           "customer_id" => $customer_id,
799           "mailbox"     => $customer_id,
800           "password"    => $this->goFonVoicemailPIN,
801           "fullname"    => $CNname,
802           "context"     => $this->voice_context,
803           "email"       => $s_mail);
805       $voice_data_array['pager']   = $this->pager;
807       /* Check if there is already an entry in sip_users for this uid */
808       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$old_customer_id."';\n";
809       $rid = mysql_query($query_tmp,$new_connection);
811       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Check if voicemail entry exists");
812       if(mysql_affected_rows($new_connection)){
814         /********************** 
815          * Update Voice mail entry  
816          **********************/
818         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"", "<i>Voicemail entry exists, adding updating to queue.</i>");
819         $result = mysql_fetch_assoc($rid)  ;
821         foreach($voice_data_array as $name => $value){
822           if($result[$name] == $value){
823             unset($voice_data_array[$name]);
824           }
825         }
827         /* Only update entry if there is something to update */
828         if(count($voice_data_array)){
829           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
830           foreach($voice_data_array as $key => $val){
831             $query.= "".$key."='".$val."',"; 
832           } 
833           $query = preg_replace("/,$/","",$query);
834           $query.= " WHERE customer_id='".$old_customer_id."';";
835           $SQL_query_array[] = $query;
836         }
837       }else{
839         /********************** 
840          * Insert Voice mail entry  
841          **********************/
842         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"", "<i>No voicemail entry found, add 'create' to queue.</i>");
843         $voice_data_array['context'] = $this->voice_context;
845         /* There is currently no voice mail entry for this user. 
846          * We should create one 
847          */
848         $s_voi_values = $s_voi_keys = "";
849         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
850           if($s_voi_val === NULL) continue;
851           $s_voi_values.="'".$s_voi_val."',";
852           $s_voi_keys  .="`".$s_voi_key."`,";
853         }
854         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
855         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
857         /* Add sip entries to mysql queries */
858         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
859       }
862       /********************** 
863        * Remove/Insert extension entries
864        **********************/
866       /* Initiate transaction 
867        */
868       $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
869       $oldnums= array();
870       foreach($oldnums as $s_telenums){
871         $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
872       }
873       foreach($newnums as $s_telenums){
874         $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
875       }
877       /********************** 
878        * Insert extension entries
879        **********************/
881       // Get selected Macro Parameter and create parameter entry 
882       if(isset($this->macroarray[$this->macro])){
883         foreach($this->macroarray[$this->macro] as $key => $val ){
884           $s_parameter .= $val['choosen']."|";
885         }
886         $s_parameter = preg_replace("/\|$/","",$s_parameter);
887       }
889       $i = 0; 
890       $EXT = array();
891       if(!is_numeric($this->uid)){
892         $EXT[$i]['context'] = 'GOsa';
893         $EXT[$i]['exten']   = $this->uid;
894         $EXT[$i]['priority']= 1;
895         $EXT[$i]['app']     = "Goto";
896         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
897         $i ++;
898       }
900       // Entension entries  Hint / Dial / Goto
901       foreach($newnums as $s_telenums){
903         /* Hint Entry */
904         $EXT[$i]['context'] = 'GOsa';
905         $EXT[$i]['exten']   = $s_telenums;
906         $EXT[$i]['priority']= 0;
907         $EXT[$i]['app']     = 'SIP/'.$this->uid;
908         $i ++;  
909         /* SetCID */
910         //$EXT[$i]['context'] = 'GOsa';
911         //$EXT[$i]['exten']   = $s_telenums;
912         //$EXT[$i]['priority']= 1;
913         //$EXT[$i]['app']     = "SetCIDName";
914         //$EXT[$i]['appdata'] = $CNname;
915         //$i ++;  
917         // If no macro is selected use Dial
918         if($this->macro!="none"){ 
919           $macroname = preg_replace("/,.*$/","",$this->macro);        
920           $macroname = preg_replace("/^.*=/","",$macroname);        
921           $s_app = "Macro";$macroname;
922           $s_par = $macroname."|".$s_parameter; 
923         }else{
924           $s_app = "Dial";
925           $s_par = 'SIP/'.$this->uid."|20|r";
926         }
928         $EXT[$i]['context'] = 'GOsa';
929         $EXT[$i]['exten']   = $s_telenums;
930         $EXT[$i]['priority']= 1;
931         $EXT[$i]['app']     = $s_app;
932         $EXT[$i]['appdata'] = $s_par;
933         $i ++;
934       }
936       // Append all these Entries 
937       foreach($EXT as $entr){
938         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
939         foreach($entr as $key2 => $val2){
940           $SQL_syn.= "`".$key2."`,";
941         }
942         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
943         $SQL_syn .= ") VALUES ("; 
944         foreach($entr as $key2 => $val2){
945           $SQL_syn .= "'".$val2."',";
946         }
947         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
948         $SQL_syn .=");\n";
950         $SQL_query_array[] =$SQL_syn;
951         $SQL_syn ="";
952       }
954       /* Start transaction, to be able to rollback 
955        */
956       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Insert/Update new entry---</b>","");
958       mysql_query("begin;",$new_connection);
959       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
961       foreach($SQL_query_array as $query){
962         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
963         if(!mysql_query($query,$new_connection)){
964           $err = mysql_error($new_connection);
965           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
966           msg_dialog::display(_("Error"), 
967               msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
968               "\n<p>"._("Please activate debugging for details!")."</p>",
969               ERROR_DIALOG);
971           mysql_query("rollback;",$new_connection);
972           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
973           @mysql_close($new_connection);
974           return(false);
975         } 
976       }
977      
978       /* Let changes get active, everything was fine;
979        */ 
980       mysql_query("commit;",$new_connection);
981       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "Perform transaction!");
982       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
983     }
984     @mysql_close($new_connection);
985     return true;
986   }
989   function execute()
990   {
991     /* Call parent execute */
992     plugin::execute();
994     /* Log view */
995     if($this->is_account && !$this->view_logged){
996       $this->view_logged = TRUE;
997       new log("view","users/".get_class($this),$this->dn);
998     }
1000     $display = "";
1001     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1003     if(empty($this->macro)&&(!empty($this->goFonMacro))){
1005       /* Go through already saved values, for a parameter */
1006       $tmp = split("!",$this->goFonMacro);
1008       /* it is possible that nothing has been saved yet */
1009       if(is_array($tmp)){
1011         /* First value is the macroname */
1012         $this->macro = $tmp[0];
1014         /* Macroname saved, delete that index */
1015         unset($tmp[0]);
1017         /* Check if macro has been removed */
1018         if(!isset($this->macroarray[$this->macro])){
1019           $this->macrostillavailable = false;
1020         }else{
1021           $this->macrostillavailable = true;
1022         }
1024         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
1025         foreach($tmp as $var){
1027           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
1028           $varar = split("#",$var);
1030           /* Only insert if the parameter still exists */
1031           if(isset($this->macroarray[$this->macro][$varar[0]])){
1032             /* Assign value */
1033             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
1034           }
1035         }
1036       }
1037     }
1038     
1039     /* Do we represent a valid account? */
1040     if (!$this->is_account && $this->parent === NULL){
1041       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
1042         msgPool::noValidExtension(_("Phone"))."</b>";
1043       $display.= back_to_main();
1044       return ($display);
1045     }
1047     /* Do we need to flip is_account state? */
1048     if (isset($_POST['modify_state'])){
1049       $this->is_account= !$this->is_account;
1050     }
1052     /* Do we represent a valid account? */
1053     if (!$this->is_account && $this->parent === NULL){
1054       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
1055         msgPool::noValidExtension(_("Phone"))."</b>";
1056       $display.= back_to_main();
1057       return($display);
1058     }
1060     $display= "";
1062     /* Show tab dialog headers */
1063     
1064     if (!$this->multiple_support_active && $this->parent !== NULL){
1065       if ($this->is_account){
1066         $display= $this->show_disable_header(_("Remove phone account"),
1067             msgPool::featuresEnabled(_("Phone")));
1068       } else {
1069         if(empty($this->uid)){
1070           $display= $this->show_enable_header(_("Create phone account"),
1071             msgPool::featuresDisabled(_("Phone"),_("User uid")));
1072         }else{
1073           $display= $this->show_enable_header(_("Create phone account"),
1074             msgPool::featuresDisabled(_("Phone")));
1075         }
1076         return ($display);
1077       }
1078     }
1079     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
1080     if(empty($this->macro)){
1081       $this->macro ="none";
1082     }
1084     /* Prepare templating */
1085     $smarty= get_smarty();
1087     /* tell user that the selected plugin is no longer available */
1088     if((!$this->macrostillavailable)&&($this->macro!="none")){
1089       msg_dialog::display(_("Error"), _("Selected macro is not available anymore!"), ERROR_DIALOG);
1090     }
1092     /* Assing macroselectbox values  */
1093     $smarty->assign("macros",$this->macros);   
1094     $smarty->assign("macro", $this->macro);   
1096     /* Assign contexts */
1097     $smarty->assign("contexts",$this->get_asterisk_contexts());
1098     $smarty->assign("context" ,$this->context);
1099     $smarty->assign("voice_context" ,$this->voice_context);
1101     /* check if there is a FON server created */
1102     if(!count($this->goFonHomeServer)){
1103       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
1104     }
1106     /* Create html parameter table for selected macro parameters 
1107      *  skip if no parameters given 
1108      */
1109     if(!isset($this->macroarray[$this->macro])){
1110       $macrotab="";
1111     }else{
1113       $macrotab ="<table summary=\""._("Parameter")."\">";
1114       /* for every single parameter-> display textfile,combo, or true false switch*/
1116       foreach($this->phoneNumbers as $phonenum){
1117         $tmp[] = $phonenum;
1118       }
1119     
1120       if($this->macro != $this->lastmacro){
1121         /* Go through all params */
1122         foreach($this->macroarray[$this->macro] as $key => $paras){
1124           $string = $paras['default'];
1126           $string=preg_replace("/%uid/i",$this->uid,$string);
1128           if(isset($this->cn)){
1129             $string=preg_replace("/%cn/i",$this->cn,$string);
1130           }
1132           for($i = 0 ; $i < 10; $i++){
1133             if(isset($tmp[$i])){
1134               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
1135             }
1136           }
1137           if(isset($tmp[0])){
1138             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
1139           }
1140           $this->macroarray[$this->macro][$key]['choosen']=$string;
1141         }
1142       }
1144       foreach($this->macroarray[$this->macro] as $paras){
1146         /* get al vars */
1147         $var        = $paras['var'];           
1148         $name       = $paras['name'];           
1149         $default    = $paras['default'];
1150         $type       = $paras['type'];
1151         $choosen    = $paras['choosen'] ; 
1152         $str        = $default;
1154         $dis = "";
1155         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
1156           $dis = " disabled ";
1157         }
1159         /* in case of a combo box display a combobox with selected attr */
1160         $macrotab.= "<tr>";
1161         switch ($type){
1163           case "combo":
1164             $str= "<select name='".$var."' ".$dis." >";
1165           foreach(split(":",$default) as $choice){
1166             if($choosen==$choice){
1167               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
1168             }else{
1169               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
1170             }
1171           }
1172           $str.="</select>";
1173           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1174           break;
1176           case "bool":
1177             if(!$choosen){
1178               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
1179             }else{
1180               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
1181             }
1182           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
1183           break;
1185           case "string":
1186             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
1187           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1188           break;
1190         }
1191         $macrotab.= "</td></tr>";
1193       }
1194       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1195     }//is_array()
1197     /* Give smarty the table */
1198     $smarty->assign("macrotab",$macrotab);
1201     /* Add phone number */
1202     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1204       if(strlen(trim($_POST["phonenumber"])) > 5 ){
1205         msg_dialog::display(_("Error"), msgPool::toobig("Phone number",99999), ERROR_DIALOG);
1206       }elseif (tests::is_phone_nr($_POST['phonenumber'])){
1207         $number= trim($_POST["phonenumber"]);
1208         $this->phoneNumbers[$number]= $number;
1209         $this->is_modified= TRUE;
1210       } else {
1211         msg_dialog::display(_("Error"), msgPool::invalid("Phone number"), ERROR_DIALOG);
1212       }
1213     }
1215     /* Remove phone number */
1216     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1217       foreach ($_POST['phonenumber_list'] as $number){
1218         unset($this->phoneNumbers[$number]);
1219         $this->is_modified= TRUE;
1220       }
1221     }
1223     /* Assign acls */
1224     $tmp = $this->plInfo();
1225     foreach($tmp['plProvidedAcls'] as $name => $translation){
1226       $smarty->assign($name."ACL",$this->getacl($name,$SkipWrite));
1227     }
1229     /* Transfer ACL's */
1230     foreach($this->attributes as $val){
1231       if(isset($this->$val)){
1232         $smarty->assign($val,$this->$val);
1233       }else{
1234         $smarty->assign($val,"");
1235       }
1236     }
1238     /* Create home server array */
1239     $tmp = array();
1240     foreach($this->goFonHomeServers as $dn => $attrs){
1241       if(!is_numeric($dn)){
1242         $tmp[$dn] = $attrs['SERVER'];
1243       }
1244     }
1245     $smarty->assign("goFonHomeServers",$tmp);
1247     /* Fill arrays */
1248     $smarty->assign ("goFonHardware", $this->goFonHardware);
1249     if (!count($this->phoneNumbers)){
1250       $smarty->assign ("phoneNumbers", array());
1251     } else {
1252       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1253     }
1255     $dis = "";
1256     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1257       $dis= " disabled ";
1258     }
1259     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1260        _("Choose your private phone")."\">\n";
1262     foreach ($this->hardware_list as $cn => $description){
1263       if ($cn == $this->goFonHardware){
1264         $selected= "selected";
1265       } else {
1266         $selected= "";
1267       }
1268       if (isset($this->used_hardware[$cn])){
1269         $color= "style=\"color:#A0A0A0\"";
1270       } else {
1271         $color= "";
1272       }
1273       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1274     }
1275     $hl.= "</select>\n";
1276     $smarty->assign ("hardware_list", $hl);
1279     foreach($this->attributes as $attr){
1280       if(in_array($attr,$this->multi_boxes)){
1281         $smarty->assign("use_".$attr,TRUE);
1282       }else{
1283         $smarty->assign("use_".$attr,FALSE);
1284       }
1285     }
1287     foreach(array("goFonVoiceMailContext","goFonContext") as $attr){
1288       if(in_array($attr,$this->multi_boxes)){
1289         $smarty->assign("use_".$attr,TRUE);
1290       }else{
1291         $smarty->assign("use_".$attr,FALSE);
1292       }
1293     }
1295     /* Show main page */
1296     $this->lastmacro = $this->macro;
1297     $smarty->assign("multiple_support",$this->multiple_support_active);
1298     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1299     return($display);
1300   }
1303   function save_object()
1304   {
1305     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1306     if (isset($_POST["phoneTab"])){
1307     
1308       plugin::save_object();
1310       /* Save checkbox */
1311       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1312       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1313         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1314           $tmp .= "M";
1315         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1316           $tmp  = preg_replace ("/M/","",$tmp);
1317         }
1318       }
1319       $this->goFonDeliveryMode= "[".$tmp."]";
1322       /* Every macro in the select box are available */
1323       if((isset($_POST['macro']))){
1324         $this->macro = $_POST['macro'];
1325         $this->macrostillavailable=true;
1326       }
1328       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1329         $this->is_modified =true;
1330       }
1332       /* Save context */
1333       if(isset($_POST['context'])){
1334         if($this->context != $_POST['context']){
1335           $this->is_modified= TRUE;
1336         }
1337         $this->context= $_POST['context'];
1338       }
1340       /* Save voice context */
1341       if(isset($_POST['voice_context'])){
1342         if($this->voice_context != $_POST['voice_context']){
1343           $this->is_modified= TRUE;
1344         }
1345         $this->voice_context= $_POST['voice_context'];
1346       }
1348       if(is_array($this->phoneNumbers)){
1349         foreach($this->phoneNumbers as $telenumms) {
1350           $nummsinorder[]=$telenumms; 
1351         }
1352       }else{
1353         $nummsinorder=array("");
1354       }
1357       /* get all Postvars */
1358       if(isset($this->macroarray[$this->macro])){
1361         if($this->acl_is_writeable("goFonMacro",$SkipWrite)){
1362           foreach($this->macroarray[$this->macro] as $key => $paras){
1364             $old_macro_settings = $this->macroarray[$this->macro][$key]; 
1365             $backup = $this->macroarray[$this->macro][$key];
1367             if(isset($_POST[$paras['var']])){
1368               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1369             }
1371             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1372                We need this code below to read and save checkboxes correct
1373              */
1375             if(isset($_POST['post_success'])){
1376               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1377                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1378                   $this->macroarray[$this->macro][$key]['choosen']=1;
1379                 }else{
1380                   $this->macroarray[$this->macro][$key]['choosen']=0;
1381                 }
1382               }
1383             }
1384             if(array_differs($old_macro_settings,$this->macroarray[$this->macro][$key])){
1385               $this->is_modified = TRUE;
1386             }
1387           }
1389           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1390             $this->is_modified = TRUE;
1391           }
1392         }
1393       }
1394     }
1395   }
1397   function check()
1398   {
1399     /* Call common method to give check the hook */
1400     $message= plugin::check();
1402     if(!count($this->goFonHomeServers)){
1403       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1404     }
1406     if(empty($this->goFonHomeServer)){
1407       $message[] = msgPool::invalid(_("Home server"));
1408     }
1410     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1411       $message[]= msgPool::invalid(_("Voicemail PIN"),"","",_("Between 1-4 charactes"));
1412     }else{
1413       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1414         $message[]= msgPool::invalid(_("Voicemail PIN"),preg_replace("/[0-9]/","X",$this->goFonVoicemailPIN),"/X/");
1415       }
1416     }
1418     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1419       $message[]= msgPool::invalid(_("Phone PIN"),preg_replace("/[0-9a-z]/i","X",$this->goFonPIN),"/X/");
1420     }
1422     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1423       $str = $this->generate_mysql_entension_entries(true);
1424       if(empty($str)){
1425         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
1426       }
1427     }
1429     /* We need at least one phone number */
1430     if (count($this->phoneNumbers) == 0){
1431       $message[]= msgPool::required("Phone number");
1432     }
1434     /* check for ! in any parameter setting*/
1435     if(isset($this->macroarray[$this->macro])){
1436       foreach($this->macroarray[$this->macro] as $val){
1437         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1438           $message[] = msgPool::invalid(sprintf(_("macro parameter %s"),$val['name']),$val['choosen'],"/[^\#]/");
1439         }
1440       }
1441     }
1442     return ($message);
1443   }
1447   function save()
1448   {
1449     plugin::save();
1451     /* Force saving macro again 
1452      * This ensures that 
1453      *  - the macro is available on the destiantion server.
1454      *  - the macro saved is up to date on the destination server.
1455      */
1456     if(!empty($this->macro) && $this->macro != "none")  {
1457       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1458       $macro_tab -> save();
1459     }
1461     /* Save arrays */
1462     $tmp_numbers = array();
1463     foreach ($this->phoneNumbers as $number){
1464       $tmp_numbers[] = $number;
1465     }
1467     /* Save settings, or remove goFonMacro attribute*/
1468     if($this->macro!="none"){    
1469       $this->attrs['goFonMacro']=$this->macro;
1470       if(isset($this->macroarray[$this->macro])){
1471         foreach($this->macroarray[$this->macro] as $paras)  {
1472           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1473         }
1474       }
1475     }else{
1476       $this->attrs['goFonMacro']=array();
1477     }
1478     unset($this->attrs['macro'])  ;
1480     $this->attrs['goFonForwarding']=array();
1482     /*
1483      */
1484     $str = $this->generate_mysql_entension_entries(true);
1485     if(!$str){
1486       msg_dialog::display(_("Error"),_("An error occured while updating the database entries, activate debugging for details.") , ERROR_DIALOG);
1487     }
1489     if($this->attrs['goFonMacro']==""){
1490       $this->attrs['goFonMacro']=array();
1491     }
1493     unset($this->attrs['cn']);
1495     /* Write back to ldap */
1496     $ldap= $this->config->get_ldap_link();
1497     $ldap->cd($this->dn);
1498     $this->cleanup();
1499     
1500     /* Force saving numbers, else it will be overwriten by user account. */
1501     $this->attrs['telephoneNumber'] =$tmp_numbers;
1502     $ldap->modify ($this->attrs); 
1504     /* Log last action */
1505     if($this->initially_was_account){
1506       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1507     }else{
1508       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1509     }
1511     if (!$ldap->success()){
1512       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
1513     }
1515     /* Optionally execute a command after we're done */
1517     if ($this->initially_was_account == $this->is_account){
1518       if ($this->is_modified){
1519         $this->handle_post_events("modify",array("uid" => $this->uid));
1520       }
1521     } else {
1522       $this->handle_post_events("add",array("uid" => $this->uid));
1523     }
1525   }
1528   function adapt_from_template($dn, $skip= array())
1529   {
1530     plugin::adapt_from_template($dn, $skip);
1532     /* Assemble phone numbers */
1533     if (isset($this->attrs['telephoneNumber']) && !in_array("telephoneNumber", $skip)){
1534       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1535         $number= $this->attrs['telephoneNumber'][$i];
1536         $this->phoneNumbers[$number]= $number;
1537       }
1538     }
1539   }
1542   function remove_from_parent()
1543   {
1544     if(!$this->initially_was_account) return;
1546     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1548       // Get Configuration for initial Mysql database Server
1549       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1550       $s_parameter  ="";
1552       /* Check table definitions
1553        */
1554       if(!phoneAccount::checkRealtimeTables($a_SETUP)){
1555         msg_dialog::display(_("Warning"),
1556             sprintf(_("GOsa identified problems with your MySQL table definition, please activate debugging for details.")),
1557             WARNING_DIALOG);
1558       }
1560       // Connect to DB server
1561       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1563       // Check if we are  connected correctly
1564       if(!$r_con){
1565         msg_dialog::display(_("Error"), msgPool::dbconnect("GOfon",@mysql_error()), ERROR_DIALOG);
1566         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1567         return false;
1568       }
1570       // Select database for Extensions
1571       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1573       // Test if we have the database selected correctly
1574       if(!$db){
1575         msg_dialog::display(_("Error"), msgPool::dbselect("GOfon", @mysql_error()), ERROR_DIALOG);
1576         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1577         return false;
1578       }
1580       $SQL="";
1581       $SQL[]= "SET @@sql_mode = STRICT_ALL_TABLES;";
1583       $first_num = false;
1584       // Delete old entries
1585       foreach($this->a_old_telenums as $s_telenums){
1586         if(!$first_num){
1587           $first_num = $s_telenums;
1588         }
1589         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1590       }
1593       $query  = "SELECT id,name,callerid FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';";
1594       $rid    = mysql_query($query,$r_con);
1595       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1596       $result = mysql_fetch_assoc($rid);
1597       $callerid = $first_num;
1598       if($result){
1599         $callerid = $result['callerid'];
1600       }
1602       /* Set mode to strict
1603          Strict disallows the addition of entries that do not match the targets field length.
1604        */
1605       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$callerid."';";
1606       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1607       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1609       /* Start transaction, to be able to rollback
1610        */
1611       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Removing entry from server---</b>","");
1613       mysql_query("begin;",$r_con);
1614       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
1616       foreach($SQL as $query){
1617         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
1619         if(!mysql_query($query,$r_con)){
1620           $err = mysql_error($r_con);
1621           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
1622           msg_dialog::display(_("Error"),
1623               msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
1624               "\n<p>"._("Please activate debugging for details!")."</p>",
1625               ERROR_DIALOG);
1627           mysql_query("rollback;",$r_con);
1628           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
1629           @mysql_close($r_con);
1630           return(false);
1631         }
1632       }
1634       /* Let changes get active, everything was fine;
1635        */
1636       mysql_query("commit;",$r_con);
1637       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "");
1638       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
1640     }else{
1641       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
1642       return false;
1643     }
1645     /* unset macro attr, it will cause an error */
1646     $tmp = array_flip($this->attributes);
1647     unset($tmp['macro']);
1648     $this->attributes=array_flip($tmp);
1650     /* Cancel if there's nothing to do here */
1651     if (!$this->initially_was_account){
1652       return;
1653     }
1655     plugin::remove_from_parent();
1657     /* Just keep one phone number */
1658     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1659       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1660     } else {
1661       $this->attrs['telephoneNumber']= array();
1662     }
1665     $ldap= $this->config->get_ldap_link();
1666     $ldap->cd($this->config->current['BASE']);
1667     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1668     while($attr = $ldap->fetch()){
1669       if(in_array($this->dn,$attr['member'])){
1670         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1671         unset($new->by_object['ogroup']->memberList[$this->dn]);
1672         unset($new->by_object['ogroup']->member[$this->dn]);
1673         $new->save();
1674         msg_dialog::display(_("Information"), sprintf(_("User '%s' has been removed from phone queue '%s'."), $this->cn, $new->by_object['ogroup']->cn), INFO_DIALOG);
1675       }
1676     }
1677     $ldap->cd($this->dn);
1678     $this->cleanup();
1679     $ldap->modify ($this->attrs); 
1681     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1682     if (!$ldap->success()){
1683       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1684     }
1686     /* Optionally execute a command after we're done */
1687     @mysql_close($r_con);
1688     $this->handle_post_events('remove',array("uid"=> $this->uid));
1689   }
1693   /* This function checks if the given phonenumbers are available or already in use*/
1694   function is_number_used()
1695   {
1696     $ldap= $this->config->get_ldap_link();
1697     $ldap->cd($this->config->current['BASE']);
1698     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1699     while($attrs = $ldap->fetch()) {
1700       unset($attrs['telephoneNumber']['count']);
1701       foreach($attrs['telephoneNumber'] as $tele){
1702         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1703         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1704         $numbers[$tele]=$attrs;
1705       }
1706     }
1708     foreach($this->phoneNumbers as $num){
1709       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1710         if(isset($numbers[$num]['uid'][0])){
1711           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1712         }else{
1713           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1714         }
1715       }
1716     }
1717   }
1720   /* Create phoneAccount part of copy & paste dialog */
1721   function getCopyDialog()
1722   { 
1723     if(!$this->is_account) return("");
1724     $smarty = get_smarty();
1725     if (!count($this->phoneNumbers)){
1726       $smarty->assign ("phoneNumbers", array(""));
1727     } else {
1728       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1729     }
1731     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1732     $smarty->assign("goFonPIN",$this->goFonPIN);
1734     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1735     $ret =array();
1736     $ret['string'] = $display;
1737     $ret['status'] = "";
1738     return($ret);
1739   }
1741   /* Save posts from copy & paste dialog dialog  */
1742   function saveCopyDialog()
1743   {
1744     if(!$this->is_account) return;
1745     $this->execute();
1746     if(isset($_POST['goFonVoicemailPIN'])) {
1747       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1748     }
1749     if(isset($_POST['goFonPIN'])){
1750       $this->goFonPIN = $_POST['goFonPIN'];
1751     }
1752   }
1755   function allow_remove()
1756   {
1757     /* Check if previously selected server is still available */
1758     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1759       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1760     }
1761   }
1763   /* Return plugin informations for acl handling */
1764   static function plInfo()
1765   {
1766     return (array(
1767           "plShortName"     => _("Phone"),
1768           "plDescription"   => _("Phone account settings"),
1769           "plSelfModify"    => TRUE,
1770           "plDepends"       => array("user"),
1771           "plPriority"      => 7,                                 // Position in tabs
1772           "plSection"         => array("personal" => _("My account")),
1773           "plCategory"        => array("users"),
1776           "plOptions"       => array(),
1778           "plProvidedAcls"  => array(
1779             "telephoneNumber"     => _("Telephone number"),
1780             "goFonMacro"          => _("Macro settings"),
1781             "goFonHardware"       => _("Phone hardware"),
1782             "goFonHomeServer"     => _("Home server"),
1783             "goFonContext"          => _("Phone context"),
1784             "goFonVoiceMailContext" => _("Voice mail context"),
1785             "goFonPIN"            => _("Telephone pin"),
1786             "goFonVoicemailPIN"   => _("Voicemail pin"))
1787           ));
1788   }
1792   function multiple_execute()
1793   {
1794     plugin::multiple_execute();
1795     return($this->execute());
1796   }
1798   function get_multi_init_values()
1799   {
1800     $ret = plugin::get_multi_init_values();
1801     $ret['phoneNumbers'] = array();
1802     foreach($this->phoneNumbers as $number){
1803       $ret['phoneNumbers'][] = $number."  [".$this->attrs['cn'][0]."]"; 
1804     }
1805     $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1806     return($ret);
1807   }
1809   function init_multiple_support($attrs,$all)
1810   {
1811     plugin::init_multiple_support($attrs,$all);
1813     $this->phoneNumbers = array();
1814     if(isset($all['phoneNumbers'])){
1815       for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1816         $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1817       }
1818     }
1819   }
1821   function multiple_save_object()
1822   {
1823     /* Simply call parents save_object */
1824     if (isset($_POST["phoneTab"])){
1826       plugin::save_object();
1827       plugin::multiple_save_object();
1829       /* Every macro in the select box are available */
1830       if((isset($_POST['macro']))){
1831         $this->macrostillavailable=true;
1832       }
1834       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1835         $this->macro = $_POST['macro'];
1836         $this->is_modified =true;
1837       }
1839       /* get all Postvars */
1840       if(isset($this->macroarray[$this->macro])){
1841         foreach($this->macroarray[$this->macro] as $key => $paras){
1842           $backup = $this->macroarray[$this->macro][$key];
1843           if(isset($_POST[$paras['var']])){
1844             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1845           }
1846           if(isset($_POST['post_success'])){
1847             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1848               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1849                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1850               }else{
1851                 $this->macroarray[$this->macro][$key]['choosen']=false;
1852               }
1853             }
1854           }
1855         }
1856         if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1857           $this->is_modified = TRUE;
1858         }
1859       }
1860     }
1861   }
1863   function multiple_check()
1864   {
1865     $message = plugin::multiple_check();
1867     if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1868       $message[] = _("There is currently no asterisk server defined!");
1869     }
1871     if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1872       $message[] = _("Asterisk server is invalid!");
1873     }
1875     if(in_array("goFonVoicemailPIN",$this->multi_boxes) && 
1876         ( (strlen($this->goFonVoicemailPIN)==0)||
1877           (strlen($this->goFonVoicemailPIN)>4))){
1878       $message[]=(_("Voicemail PIN must be 4 characters long!"));
1879     }else{
1880       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1881         $message[]=(_("Voicemail PIN contains invalid characters!"));
1882       }
1883     }
1885     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1886       $message[]=(_("Phone pin contains invalid characters!"));
1887     }
1889     /* check for ! in any parameter setting*/
1890     if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1891       foreach($this->macroarray[$this->macro] as $val){
1892         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1893           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1894         }
1895       }
1896     }
1898     return($message);
1899   }
1901   function get_multi_edit_values()
1902   {
1903     $ret = plugin::get_multi_edit_values();
1904     if(in_array("macro",$this->multi_boxes)){
1905       $ret['macro'] = $this->macro;
1906       $ret['macroarray'] = $this->macroarray;
1907       $ret['macros'] = $this->macros;
1908     }
1909     return($ret);
1910   }
1913   /* Return asterisk contexts
1914    * Additionaly read contexts from file.
1915    */
1916   function get_asterisk_contexts()
1917   {
1918     $contexts = array();
1919     $contexts[] = "default";
1920     $contexts[] = "parkedcalls";
1921     $contexts[] = "from-sip";
1922     $contexts[] = "from-capi";
1923     $file = "/etc/gosa/asterisk_contexts.conf";
1924     if(file_exists($file) && is_readable($file)){
1925       foreach(file($file) as $context){
1926         $contexts[] = trim($context);
1927       }
1928     }
1929     array_unique($contexts);
1930     return($contexts);
1931   }
1934 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1935 ?>