Code

Disabled goFonDeliveryMode Post checks - there is no delivery mode posted
[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 $sip_contexts           = "default";
36   var $voice_context          = "default";
37   var $voicemail_contexts     = "default";
39   /* attribute list for save action */
40   var $CopyPasteVars          = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
41                                       "hardware_list","used_hardware");
43   var $attributes             = array("goFonDeliveryMode", "goFonFormat","goFonHomeServer",
44       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
45   var $objectclasses= array("goFonAccount");
47   var $uid;
48   var $cn;
50   var $view_logged = FALSE;
51   var $multiple_support = TRUE;
52   var $mailAddress      = "";
53   var $has_mailAccount  = FALSE;
54   var $pager      = "";
56   function phoneAccount (&$config, $dn= NULL, $parent= NULL)
57   {
58     plugin::plugin ($config, $dn, $parent);
60     /* Assemble phone numbers */
61     if (isset($this->attrs['telephoneNumber'])){
62       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
63         $number= $this->attrs['telephoneNumber'][$i];
64         $this->phoneNumbers[$number]= $number;
65       }
66     }
68     $this->sip_contexts = $this->get_asterisk_sip_contexts();
69     $this->voicemail_contexts = $this->get_asterisk_voicemail_contexts();
71     /* Set parent object to tab object */
72     if(is_object($parent)){
73       $this->parent = $parent->parent;
74     }
76     /* Get current uid and cn 
77      */
78     if(isset($this->attrs['uid'][0])){
79       $this->uid = $this->attrs['uid'][0];
80     }
81     if(isset($this->attrs['cn'][0])){
82       $this->cn = $this->attrs['cn'][0];
83     }
84     if(isset($this->attrs['mail'][0])){
85       $this->mailAddress = $this->attrs['mail'][0];
86       $this->has_mailAccount = true;
87     }
88     if(isset($this->attrs['pager'][0])){
89       $this->pager = $this->attrs['pager'][0];
90     }
92     /* If there is a parent object present, use references 
93      */
94     if(isset($this->parent->by_object['user']->uid)){
95       $this->uid = &$this->parent->by_object['user']->uid;
96     }
97     if(isset($this->parent->by_object['user']->cn)){
98       $this->cn   =&$this->parent->by_object['user']->cn;
99     }
100     if(isset($this->parent->by_object['user']->pager)){
101       $this->pager   =&$this->parent->by_object['user']->pager;
102     }
103     if(isset($this->parent->by_object['mailAccount']->mail)){
104       $this->mailAddress      = &$this->parent->by_object['mailAccount']->mail;
105       $this->has_mailAccount  = &$this->parent->by_object['mailAccount']->is_account;
106     }
108     /* Check server configurations 
109      * Load all server configuration in $this->goFonHomeServers if available
110      *  and first server as default if necessary.
111      * Check if connection is successfull for the selected server $this->goFonHomeServer
112      */
114   
115     /* Set available server */
116     $config = session::get('config');
117     if(isset($config->data['SERVERS']['FON'])){
118       $this->goFonHomeServers = $config->data['SERVERS']['FON'];
119     }
121     $a_SETUP= array();
122     if($this->is_account && isset($config->data['SERVERS']['FON']) &&
123        array_key_exists('FON',$config->data['SERVERS']) &&
124        is_callable("mysql_connect")
125        ) {
127       /* Servers defined? Watch here... */
128       if (count($this->goFonHomeServers)){
130         /* Set default server */
131         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
132           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
133         }
135         /* Remember inital home server, to be able to remove old entries */
136         $this->init_HomeServer = $this->goFonHomeServer;
138         /* Get config */
139         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
140           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);
142           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
143           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
144         }    
145         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
147         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
148         if(!$r_con){
149           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
150         }
151         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
152         if(!$db){
153           new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
154         }
156         $first = false; 
157         foreach($this->phoneNumbers as $key => $val){
158           if(!$first){
159             $first = $key;
160           }
161         }
162       }
163     }
165     /* Get available phone hardware  
166      * Search for all available phone hardware  
167      */
168     $tmp = get_sub_list("(objectClass=goFonHardware)","phone",array(get_ou("phoneRDN")),
169                   $this->config->current['BASE'],array("cn","description"), GL_SUBSEARCH);
170     foreach($tmp as $attrs){
171       $cn= $attrs['cn'][0];
172       $description= "";
173       if (isset($attrs['description'])){
174         $description= " - ".$attrs['description'][0];
175       }
176       $this->hardware_list[$cn]= "$cn$description";
177     }
178     $this->hardware_list["automatic"]= _("automatic");
179     ksort($this->hardware_list);
182      /* Collect all usd phones 
183         goFonHardware set.
184      */
185     $deps_a = array(
186         get_people_ou(),
187         get_ou("ogroupRDN"),
188         get_ou("serverRDN"),
189         get_ou("terminalRDN"),
190         get_ou("workstationRDN"),
191         get_ou("printerRDN"),
192         get_ou("componentRDN"),
193         get_ou("phoneRDN"));
195     $tmp = get_sub_list("(goFonHardware=*)","phone",$deps_a,$this->config->current['BASE'],
196         array('cn','dn','goFonHardware'),GL_SUBSEARCH);
197     foreach($tmp as $attrs){
198       $cn = $attrs['goFonHardware'][0];
199       if(isset($this->hardware_list[$cn])){
200         $this->used_hardware[$cn]= $cn;
201       }
202     }
205     /* Get available Macros  
206      * Search for all Macros that are visible and create 
207      *  an array with name and parameters 
208      */
209     $tmp = get_sub_list("(&(objectClass=goFonMacro)(goFonMacroVisible=1))","gofonmacro",array(get_ou("phoneMacroRDN")),
210                   $this->config->current['BASE'],array("displayName","goFonMacroParameter","dn","cn"), GL_NO_ACL_CHECK | GL_SUBSEARCH );
211     
213     /* Add none for no macro*/
214     $this->macros['none']=_("no macro");    
215     $this->macro ="none";
217     /* Fetch all Macros*/
218     foreach($tmp as $attrs){
220       $ui = get_userinfo(); 
221       $acl = $ui->get_permissions($attrs['dn'],"gofonmacro/macro","");
223       /* Skip all macros we are not able to read 
224           execpt, the currently selected macro.
225        */
226       if(!preg_match("/r/",$acl) && !preg_match("/^".preg_quote($attrs['dn'], '/')."/",$this->goFonMacro)){
227         continue;
228       }
230       /* unset Count, we don't need that here */
231       unset($attrs['displayName']['count']);
233       /* Parse macro data, unset count for parameterarrays  */
234       if (isset($attrs['goFonMacroParameter']['count'])){
235         unset($attrs['goFonMacroParameter']['count']);
236       }
238       /* fill Selectfield variable with Macros */
239       if(isset($attrs['displayName'][0])){
240         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
241       }else{
242         $this->macros[$attrs['dn']] = _("undefined");
243       }
245       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
246       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
248         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
249           /* Split Data in readable values, by delimiter !  */
250           $data = explode("!",$attrs['goFonMacroParameter'][$pkey]);
252           /* Set all attrs */
253           $id = $data[0];
254           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
255           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
256           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
257           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
258           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
259           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
260           if($data[2] == "bool"){
261             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
262           }
263         }//foreach
264       }//is_array
265     }//while
268     /* Parse used Macro  
269      * If we have a macro selected, parse it and set values 
270      *  in $this->macroarray[$this->macro]. 
271      */
272     $tmp = explode("!",$this->goFonMacro);
273     if(is_array($tmp)){
275       /* First value is the macroname */
276       $this->macro = $tmp[0];
278       /* Macroname saved, delete that index */
279       unset($tmp[0]);
281       /* Check if makro has been removed */
282       if(!isset($this->macros[$this->macro])){
283         $this->macrostillavailable = false;
284       }else{
285         $this->macrostillavailable = true;
286       }
288       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
289       foreach($tmp as $var){
291         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
292         $varar = explode("#",$var);
294         /* Only insert if the parameter still exists */
295         if(isset($this->macroarray[$this->macro][$varar[0]])){
296           /* Assign value */
297           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
298         }
299       }
300     }
303     $this->a_old_telenums = $this->phoneNumbers;
306     /* Get voicemail PIN from MySQL DB 
307      * Because every user can change his PIN directly from the phone
308      *  without any update to the ldap
309      * This means, the PIN in the DB is up to date
310      */
311     // Connect to DB server
314     $num = key($this->phoneNumbers);
316     if( (is_callable("mysql_pconnect"))&&
317         (isset($cur_cfg))&&
318         (isset($cur_cfg['SERVER']))&&
319         (isset($cur_cfg['LOGIN']))&&
320         (isset($cur_cfg['PASSWORD']))){
322       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
323       if($r_con){
325         // Try to select the gophone database
326         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
327         if(!$r_db){
328           msg_dialog::display(_("Warning"), msgPool::dbselect($cur_cfg['DB'],mysql_error()), WARNING_DIALOG);
329         }
331         $query_tmp = "SELECT ".$cur_cfg['VOICE_TABLE'].".context as 'v_context', 
332                              ".$cur_cfg['SIP_TABLE'].".context, 
333                              ".$cur_cfg['VOICE_TABLE'].".password 
334                        FROM  ".$cur_cfg['VOICE_TABLE'].", 
335                              ".$cur_cfg['SIP_TABLE']." 
336                        WHERE ".$cur_cfg['VOICE_TABLE'].".mailbox = ".$num." 
337                           AND ".$cur_cfg['SIP_TABLE'].".name='".$this->uid."'";
338         $res = mysql_query($query_tmp);
339         $vp  = mysql_fetch_assoc($res);
340         if(!isset($vp['context'])){
341           $this->is_modified= TRUE;
342           msg_dialog::display(_("Warning"), sprintf(_("Cannot identify telephone extension in database, please try to save again.")), WARNING_DIALOG);
343         } 
344  
345         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
346         if((isset($vp['password']))&&(!empty($vp['password']))){
347           $this->goFonPINVoice = $vp['password'];
348         }
349         if((isset($vp['context']))&&(!empty($vp['context']))){
350           $this->context = $vp['context'];
351         }
352         if((isset($vp['v_context']))&&(!empty($vp['v_context']))){
353           $this->voice_context = $vp['v_context'];
354         }
355       }
356     }
357     $this->lastmacro=$this->macro;
359     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
360       @mysql_close($r_con) ;
361     }
362   }
365   /* Transaction will only work with InnoDB tables 
366    */
367   public static function checkRealtimeTables($config)
368   {
369     $ret =TRUE;
371     // Connect to DB server
372     if( (is_callable("mysql_pconnect"))&&
373         (isset($config))&&
374         (isset($config['SERVER']))&&
375         (isset($config['LOGIN']))&&
376         (isset($config['PASSWORD']))){
378       $r_con =  @mysql_pconnect($config['SERVER'],$config['LOGIN'],$config['PASSWORD']);
379       if($r_con){
380         $r_db  =  @mysql_select_db($config['DB'],$r_con);
382         /* Validate Table Type - it must be InnoDB to be able to use transactions 
383          */
384         $inno_tables = array("SIP_TABLE","EXT_TABLE","VOICE_TABLE","QUEUE_TABLE","QUEUE_MEMBER_TABLE"); 
385         foreach($inno_tables as $inno_table){
386           $sql = "show table status like '".$config[$inno_table]."';";
387           $res = mysql_query($sql);
388           $vp  = mysql_fetch_assoc($res);
389           if(!preg_match("/^InnoDB$/i",$vp['Engine'])){
391             /* Not an InnoDB Table type, try to modify type. 
392              */
393             $sql = "ALTER TABLE `".$config[$inno_table]."` ENGINE = INNODB; ";
394             $res = mysql_query($sql);
395             if(!$res){
396               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$sql."</b>", 
397                   "<b>FAILED!</b>. Transactions will not work!");
398               $ret = FALSE;
399             }else{
400               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$sql."</b>", 
401                   "<i>Table '".$config[$inno_table]."' is now of type InnoDB, this enables transactions.</i>");
402             }
403           }else{
404             @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"",
405                 "<i>Table type of '".$config[$inno_table]."' OK, using transactions!</i>");
406           }
407         }
408       }
409     }
410     return($ret);
411   }
413   function stripInvalidChars($tele){
414     /* Strip invalid chars, but maintain a leading + for international numbers */
415     $t_tele= preg_replace("/[^0-9]/","",$tele);
416     if (preg_match('/^\+/', $tele)) {
417       $t_tele= "+".$t_tele;
418     }
419     return($t_tele);
420   }
421     
425   /* This function generates the Database entries. 
426    * The Parameter 'save' could be true or false.
427    *  false - means only testing no database transactions.
428    *  true  - write database entries.
429    *
430    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
431    * 
432    * If the phone hardware is 'automatic' the table entries will only be removed
433    *  and not added. 
434    */
435   function generate_mysql_entension_entries($save = false)
436   {
437     /* Check if there is at least one server available 
438      * If not, return and tell the user that saving failed 
439      */
440     if(!count($this->goFonHomeServers)){
441       if($save){
442         msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
443       }
444       return(true);
445     }
447     /* Check if Mysql extension is available */
448     if(!is_callable("mysql_pconnect")){
449       if($save){
450         msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
451       }
452       return(true);
453     }
454  
455     /********************** 
456      * Attribute Initialisation
457      **********************/
459     $old_connection = false;
461     // Get Configuration for Mysql database Server
462     $s_parameter    = "";                                           // Contains paramter for selected Macro 
463     $r_con          = false;                                        // DB connection
464     $r_db           = false;                                        // Selected DB
465     $r_res          = false;                                        // Result resource
466     $a_ldap_attrs   = array();                                      //  
468     $s_ip           = NULL;                   // Contains ip for Sip entry
469     $s_host         = NULL;                   // Contains host for Sip entry
470     $s_qualify      = "yes";                  // Qualify entry
471     $s_pin          = NULL;                   // Entry for secret
472     $s_type         = "friend";               // Entry for phone type (friend , peer ..)
473                                               // Set the default to the default of the db
475     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
476     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
477     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
479     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
480     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
482     $s_sip_key      = "";     // Key for SIP entry index      
483     $s_sip_val      = "";     // Value for SIP entry index      
485     $b_first_deleted= false;  // Only delete first entry, 
486     $s_telenums     = "";     // for each value variable
488     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
490     /* Prepare some basic attributes */
491     $oldnums = array();
493     foreach($this->a_old_telenums as $tele){
494       $oldnums[]= $this->stripInvalidChars($tele);
495     }
496     foreach($this->phoneNumbers as $tele){
497       $newnums[]= $this->stripInvalidChars($tele);
498     }
500     if(empty($this->uid)) trigger_error("Uid is empty.");
503     /* Create voicemail entry 
504      */
505     if((!isset($this->cn))||(empty($this->cn))){
506       $CNname= $this->uid;
507     }else{
508       $CNname= $this->cn;
509     }
511     $s_mail = "";
512     if($this->has_mailAccount){
513       $s_mail = $this->mailAddress;;
514     }
516     /* Get phonehardware to setup sip entry  */
517     $ldap         = $this->config->get_ldap_link();
518     $ldap->cd ($this->config->current['BASE']);
519     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
520     $a_ldap_attrs = $ldap->fetch();
522     /* Check selected phone hardware, is a default IP set? */
523     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
524       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
525       $s_host     = $s_ip;
526     }else{
527       $s_ip       = NULL;
528       $s_host     = "dynamic";
529     }
531     // Attribute GoFonQualify set ?
532     if(isset($a_ldap_attrs['goFonQualify'])){
533       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
534     }
536     // Attribute GoFonPIN set ?
537     if(isset($this->goFonPIN)){
538       $s_pin      = $this->goFonPIN;
539     }
541     // Attribute GoFonType set ?
542     if(isset($a_ldap_attrs['goFonType'])){
543       $s_type = $a_ldap_attrs['goFonType'][0];
544     }
546     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
547       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
548     }else{
549       $sip_data_array['dtmfmode']     ="rfc2833";
550     }
552     /* Check if phone number is used */
553     if($this->is_number_used()){
554       $this->generate_error = $this->is_number_used(); 
555       return false;
556     }
560     /********************** 
561      * Check Server Connection Information
562      **********************/
563  
564     /* Create Mysql handle for the current goFonHomeServer, if possible  
565      * Get configuration to old asterisk home server 
566      */ 
567     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
568     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
569     if(!$new_connection){
570       $this->generate_error =  msgPool::dbconnect($a_New['SERVER'],@mysql_error($new_connection),
571           _("Abort saving entries to keep the database consistent."));
572       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
573       return false;
574     }
575     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
576     if(!$new_database){
577       $this->generate_error =  msgPool::dbselect($a_New['DB'],@mysql_error($new_connection),
578           _("Abort saving entries to keep the database consistent."));
579       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
580       return false;
581     }
583     /* If the home server has changed, we must remove entries from old 
584      *  server and add new entries in new server.  
585      */
586     if($this->init_HomeServer != $this->goFonHomeServer){
587     
588       /* Get configuration to old asterisk home server */ 
589       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
590  
591       /* Create connection to the database that contains the old entry. 
592        */
593       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
594       if(!$old_connection){
595         $this->generate_error =  msgPool::dbconnect($a_Remove['SERVER'],@mysql_error($old_connection),
596             _("Abort saving entries to keep the database consistent."));
597         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
598         return false;
599       }
600       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
601       if(!$old_database){
602         $this->generate_error =  msgPool::dbselect($a_Remove['DB'],@mysql_error($old_connection),
603             _("Abort saving entries to keep the database consistent."));
604         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
605         return false;
606       }
607     }
610     /* Save means that we must save changes, not only test  */
611     if($save == true){
612     
613       /********************** 
614        * Remove entries from old home server 
615        **********************/
617       /* Check if there is an old entry 
618        * If there is an old entry, get callerid and remove voicemail and extensions 
619        */
620       if($old_connection){
622         /* Check table definitions
623          */
624         if(!phoneAccount::checkRealtimeTables($a_Remove)){
625           msg_dialog::display(_("Warning"),
626               sprintf(_("GOsa identified problems with your MySQL table definition!")),
627               WARNING_DIALOG);
628         }
630         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
631         $rid    = mysql_query($query,$old_connection);
632         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, 
633             "<i>Reguest callerid to be able to identify the user.</i>");
635         /* Old entry found, remove it */
636         $query_a = array();
637         if(mysql_affected_rows($old_connection)){
638           $result = mysql_fetch_assoc($rid);
640           /* Set mode to strict
641              Strict disallows the addition of entries that do not match the targets field length.
642            */
643           $query_a[]= "SET @@sql_mode = STRICT_ALL_TABLES;";
644           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
645           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
646           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
647           foreach($oldnums as $s_telenums) {
648             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
649           }
651           /* Start transaction, to be able to rollback 
652            */
653           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Removing entry from old server---</b>","");
655           mysql_query("begin;",$old_connection);
656           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
658           foreach($query_a as $query){
659             @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
660             if(!mysql_query($query,$old_connection)){
661               $err = mysql_error($old_connection);
662               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
663               msg_dialog::display(_("Error"), 
664                   msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
665                   "\n<p>"._("Please activate debugging for details!")."</p>",
666                   ERROR_DIALOG);
668               mysql_query("rollback;",$old_connection);
669               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
670               @mysql_close($old_connection);
671               return(false);
672             } 
673           }
675           /* Let changes get active, everything was fine;
676            */ 
677           mysql_query("commit;",$old_connection);
678           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "");
679           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
680         }
681       }
684       /********************** 
685        * Update / Insert sip_users entry  
686        **********************/
688       /* Check table definitions
689        */
690       if(!phoneAccount::checkRealtimeTables($a_New)){
691         msg_dialog::display(_("Warning"),
692             sprintf(_("GOsa identified problems with your MySQL table definition!")),
693             WARNING_DIALOG);
694       }
697       /* Set the first given phone number as callerid */
698       reset($newnums);        
699       $i_new_key = key($newnums);
700       $sip_data_array['callerid']  =$newnums[$i_new_key];
701       $sip_data_array['mailbox']   =$newnums[$i_new_key]."@".$this->voice_context;
703       /* Check if there is already an entry in sip_users for this uid */
704       $SQL_query_array = array();
706       /* Enforce strict mode, ensures inout validation, e.g. target field length 
707        */
708       $SQL_query_array[] = "SET @@sql_mode = STRICT_ALL_TABLES;";
710       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
711       $rid = mysql_query($query,$new_connection);
712       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Receive current mysql entries.");
713       if(mysql_affected_rows($new_connection)){
715         /********************** 
716          * Update sip_users entry 
717          **********************/
718         $result                     = mysql_fetch_assoc($rid);
719         $sip_data_array['host']         = $s_host;
720         $sip_data_array['qualify']      = $s_qualify;
721         $sip_data_array['secret']       = $this->goFonPIN;
722         $sip_data_array['type']         = $s_type ;
723         $sip_data_array['username']     = $this->uid;
724         $sip_data_array['ipaddr']       = $s_ip;
725         $sip_data_array['context']      = $this->context;
727         /* Remove not changed attributes, to avoid updating table with same values */
728         foreach($sip_data_array as $name => $value){
729           if($result[$name] == $value){
730             unset($sip_data_array[$name]);
731           }
732         }
733         /* Only update entry if there is something to uopdate */
734         if(count($sip_data_array)){
735           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
736           foreach($sip_data_array as $key => $val){
737             $query.= "".$key."='".$val."',"; 
738           } 
739           $query = preg_replace("/,$/","",$query);
740           $query.= " WHERE name='".$this->uid."';";
741           $SQL_query_array[] = $query;
742         }
743       } else {
745         /********************** 
746          * Insert sip_users entry 
747          **********************/
748         //generate SIP entry
749         $sip_data_array['name']         = $this->uid;
750         $sip_data_array['accountcode']  = NULL;          
751         $sip_data_array['amaflags']     = NULL;
752         $sip_data_array['callgroup']    = NULL;
753         $sip_data_array['canreinvite']  = "no";
754         $sip_data_array['context']      = $this->context;
755         $sip_data_array['defaultip']    = NULL;
756         $sip_data_array['fromuser']     = NULL;
757         $sip_data_array['fromdomain']   = NULL;
758         $sip_data_array['host']         = $s_host;
759         $sip_data_array['insecure']     = NULL;
760         $sip_data_array['language']     = NULL;
761         $sip_data_array['mailbox']      = $newnums[$i_new_key]."@".$this->voice_context;
762         $sip_data_array['md5secret']    = NULL;
763         $sip_data_array['nat']          = "no";
764         $sip_data_array['permit']       = NULL;
765         $sip_data_array['deny']         = NULL;
766         $sip_data_array['mask']         = NULL;
767         $sip_data_array['pickupgroup']  = NULL;
768         $sip_data_array['port']         = NULL;
769         $sip_data_array['qualify']      = $s_qualify;
770         $sip_data_array['restrictcid']  = "n";
771         $sip_data_array['rtptimeout']   = NULL;
772         $sip_data_array['rtpholdtimeout']=NULL;
773         $sip_data_array['secret']       = $this->goFonPIN;
774         $sip_data_array['type']         = $s_type ;
775         $sip_data_array['username']     = $this->uid;
776         $sip_data_array['disallow']     = NULL;
777         $sip_data_array['allow']        = NULL;
778         $sip_data_array['musiconhold']  = NULL;
779         $sip_data_array['regseconds']   = NULL;
780         $sip_data_array['ipaddr']       = $s_ip;
781         $sip_data_array['regexten']     = NULL;
782         $sip_data_array['cancallforward']=NULL;
784         /* There is currently no entry for this user in the sip_users table. 
785          * We should create one i
786          */
787         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
788           if($s_sip_val === NULL) continue;
789           $s_sip_values.="'".$s_sip_val."',";
790           $s_sip_keys  .="`".$s_sip_key."`,";
791         }
792         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
793         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
795         /* Add sip entries to mysql queries */
796         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
797       }
800       /********************** 
801        * Update / Insert Voice mail entry  
802        **********************/
804       $customer_id = $newnums[$i_new_key];
805       $query  = "SELECT id,name,callerid FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';";
806       $rid    = mysql_query($query,$new_connection);
808       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Receive callerid");
809       $result = mysql_fetch_assoc($rid);
811       $old_customer_id = ""; 
812       if($result){
813         $old_customer_id = $result['callerid'];
814       }
816       $voice_data_array = array(
817           "customer_id" => $customer_id,
818           "mailbox"     => $customer_id,
819           "password"    => $this->goFonVoicemailPIN,
820           "fullname"    => $CNname,
821           "context"     => $this->voice_context,
822           "email"       => $s_mail);
824       $voice_data_array['pager']   = $this->pager;
826       /* Check if there is already an entry in sip_users for this uid */
827       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$old_customer_id."';\n";
828       $rid = mysql_query($query_tmp,$new_connection);
830       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Check if voicemail entry exists");
831       if(mysql_affected_rows($new_connection)){
833         /********************** 
834          * Update Voice mail entry  
835          **********************/
837         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"", "<i>Voicemail entry exists, adding updating to queue.</i>");
838         $result = mysql_fetch_assoc($rid)  ;
840         foreach($voice_data_array as $name => $value){
841           if($result[$name] == $value){
842             unset($voice_data_array[$name]);
843           }
844         }
846         /* Only update entry if there is something to update */
847         if(count($voice_data_array)){
848           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
849           foreach($voice_data_array as $key => $val){
850             $query.= "".$key."='".$val."',"; 
851           } 
852           $query = preg_replace("/,$/","",$query);
853           $query.= " WHERE customer_id='".$old_customer_id."';";
854           $SQL_query_array[] = $query;
855         }
856       }else{
858         /********************** 
859          * Insert Voice mail entry  
860          **********************/
861         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"", "<i>No voicemail entry found, add 'create' to queue.</i>");
862         $voice_data_array['context'] = $this->voice_context;
864         /* There is currently no voice mail entry for this user. 
865          * We should create one 
866          */
867         $s_voi_values = $s_voi_keys = "";
868         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
869           if($s_voi_val === NULL) continue;
870           $s_voi_values.="'".$s_voi_val."',";
871           $s_voi_keys  .="`".$s_voi_key."`,";
872         }
873         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
874         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
876         /* Add sip entries to mysql queries */
877         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
878       }
881       /********************** 
882        * Remove/Insert extension entries
883        **********************/
885       /* Initiate transaction 
886        */
887       $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
888       $oldnums= array();
889       foreach($oldnums as $s_telenums){
890         $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
891       }
892       foreach($newnums as $s_telenums){
893         $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
894       }
896       /********************** 
897        * Insert extension entries
898        **********************/
900       // Get selected Macro Parameter and create parameter entry 
901       if(isset($this->macroarray[$this->macro])){
902         foreach($this->macroarray[$this->macro] as $key => $val ){
903           $s_parameter .= $val['choosen']."|";
904         }
905         $s_parameter = preg_replace("/\|$/","",$s_parameter);
906       }
908       $i = 0; 
909       $EXT = array();
910       if(!is_numeric($this->uid)){
911         $EXT[$i]['context'] = 'GOsa';
912         $EXT[$i]['exten']   = $this->uid;
913         $EXT[$i]['priority']= 1;
914         $EXT[$i]['app']     = "Goto";
915         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
916         $i ++;
917       }
919       // Entension entries  Hint / Dial / Goto
920       foreach($newnums as $s_telenums){
922         /* Hint Entry */
923         $EXT[$i]['context'] = 'GOsa';
924         $EXT[$i]['exten']   = $s_telenums;
925         $EXT[$i]['priority']= 0;
926         $EXT[$i]['app']     = 'SIP/'.$this->uid;
927         $i ++;  
928         /* SetCID */
929         //$EXT[$i]['context'] = 'GOsa';
930         //$EXT[$i]['exten']   = $s_telenums;
931         //$EXT[$i]['priority']= 1;
932         //$EXT[$i]['app']     = "SetCIDName";
933         //$EXT[$i]['appdata'] = $CNname;
934         //$i ++;  
936         // If no macro is selected use Dial
937         if($this->macro!="none"){ 
938           $macroname = preg_replace("/,.*$/","",$this->macro);        
939           $macroname = preg_replace("/^.*=/","",$macroname);        
940           $s_app = "Macro";$macroname;
941           $s_par = $macroname."|".$s_parameter; 
942         }else{
943           $s_app = "Dial";
944           $s_par = 'SIP/'.$this->uid."|20|r";
945         }
947         $EXT[$i]['context'] = 'GOsa';
948         $EXT[$i]['exten']   = $s_telenums;
949         $EXT[$i]['priority']= 1;
950         $EXT[$i]['app']     = $s_app;
951         $EXT[$i]['appdata'] = $s_par;
952         $i ++;
953       }
955       // Append all these Entries 
956       foreach($EXT as $entr){
957         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
958         foreach($entr as $key2 => $val2){
959           $SQL_syn.= "`".$key2."`,";
960         }
961         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
962         $SQL_syn .= ") VALUES ("; 
963         foreach($entr as $key2 => $val2){
964           $SQL_syn .= "'".$val2."',";
965         }
966         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
967         $SQL_syn .=");\n";
969         $SQL_query_array[] =$SQL_syn;
970         $SQL_syn ="";
971       }
973       /* Start transaction, to be able to rollback 
974        */
975       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Insert/Update new entry---</b>","");
977       mysql_query("begin;",$new_connection);
978       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
980       foreach($SQL_query_array as $query){
981         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
982         if(!mysql_query($query,$new_connection)){
983           $err = mysql_error($new_connection);
984           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
985           msg_dialog::display(_("Error"), 
986               msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
987               "\n<p>"._("Please activate debugging for details!")."</p>",
988               ERROR_DIALOG);
990           mysql_query("rollback;",$new_connection);
991           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
992           @mysql_close($new_connection);
993           return(false);
994         } 
995       }
996      
997       /* Let changes get active, everything was fine;
998        */ 
999       mysql_query("commit;",$new_connection);
1000       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "Perform transaction!");
1001       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
1002     }
1003     @mysql_close($new_connection);
1004     return true;
1005   }
1008   function execute()
1009   {
1010     /* Call parent execute */
1011     plugin::execute();
1013     /* Log view */
1014     if($this->is_account && !$this->view_logged){
1015       $this->view_logged = TRUE;
1016       new log("view","users/".get_class($this),$this->dn);
1017     }
1019     $display = "";
1020     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1022     if(empty($this->macro)&&(!empty($this->goFonMacro))){
1024       /* Go through already saved values, for a parameter */
1025       $tmp = explode("!",$this->goFonMacro);
1027       /* it is possible that nothing has been saved yet */
1028       if(is_array($tmp)){
1030         /* First value is the macroname */
1031         $this->macro = $tmp[0];
1033         /* Macroname saved, delete that index */
1034         unset($tmp[0]);
1036         /* Check if macro has been removed */
1037         if(!isset($this->macroarray[$this->macro])){
1038           $this->macrostillavailable = false;
1039         }else{
1040           $this->macrostillavailable = true;
1041         }
1043         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
1044         foreach($tmp as $var){
1046           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
1047           $varar = explode("#",$var);
1049           /* Only insert if the parameter still exists */
1050           if(isset($this->macroarray[$this->macro][$varar[0]])){
1051             /* Assign value */
1052             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
1053           }
1054         }
1055       }
1056     }
1057     
1058     /* Do we represent a valid account? */
1059     if (!$this->is_account && $this->parent === NULL){
1060       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
1061         msgPool::noValidExtension(_("Phone"))."</b>";
1062       $display.= back_to_main();
1063       return ($display);
1064     }
1066     /* Do we need to flip is_account state? */
1067     if (isset($_POST['modify_state'])){
1068       $this->is_account= !$this->is_account;
1069     }
1071     /* Do we represent a valid account? */
1072     if (!$this->is_account && $this->parent === NULL){
1073       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
1074         msgPool::noValidExtension(_("Phone"))."</b>";
1075       $display.= back_to_main();
1076       return($display);
1077     }
1079     $display= "";
1081     /* Show tab dialog headers */
1082     
1083     if (!$this->multiple_support_active && $this->parent !== NULL){
1084       if ($this->is_account){
1085         $display= $this->show_disable_header(_("Remove phone account"),
1086             msgPool::featuresEnabled(_("Phone")));
1087       } else {
1088         if(empty($this->uid)){
1089           $display= $this->show_enable_header(_("Create phone account"),
1090             msgPool::featuresDisabled(_("Phone"),_("User uid")));
1091         }else{
1092           $display= $this->show_enable_header(_("Create phone account"),
1093             msgPool::featuresDisabled(_("Phone")));
1094         }
1095         return ($display);
1096       }
1097     }
1098     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
1099     if(empty($this->macro)){
1100       $this->macro ="none";
1101     }
1103     /* Prepare templating */
1104     $smarty= get_smarty();
1106     /* tell user that the selected plugin is no longer available */
1107     if((!$this->macrostillavailable)&&($this->macro!="none")){
1108       msg_dialog::display(_("Error"), _("Selected macro is not available anymore!"), ERROR_DIALOG);
1109     }
1111     /* Assing macroselectbox values  */
1112     $smarty->assign("macros",$this->macros);   
1113     $smarty->assign("macro", $this->macro);   
1115     /* Assign contexts */
1116     $smarty->assign("voicemail_contexts",$this->voicemail_contexts);
1117     $smarty->assign("sip_contexts",$this->sip_contexts);
1118     $smarty->assign("context" ,$this->context);
1119     $smarty->assign("voice_context" ,$this->voice_context);
1121     /* check if there is a FON server created */
1122     if(!count($this->goFonHomeServer)){
1123       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
1124     }
1126     /* Create html parameter table for selected macro parameters 
1127      *  skip if no parameters given 
1128      */
1129     if(!isset($this->macroarray[$this->macro])){
1130       $macrotab="";
1131     }else{
1133       $macrotab ="<table summary=\""._("Parameter")."\">";
1134       /* for every single parameter-> display textfile,combo, or true false switch*/
1136       foreach($this->phoneNumbers as $phonenum){
1137         $tmp[] = $phonenum;
1138       }
1139     
1140       if($this->macro != $this->lastmacro){
1141         /* Go through all params */
1142         foreach($this->macroarray[$this->macro] as $key => $paras){
1144           $string = $paras['default'];
1146           $string=preg_replace("/%uid/i",$this->uid,$string);
1148           if(isset($this->cn)){
1149             $string=preg_replace("/%cn/i",$this->cn,$string);
1150           }
1152           for($i = 0 ; $i < 10; $i++){
1153             if(isset($tmp[$i])){
1154               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
1155             }
1156           }
1157           if(isset($tmp[0])){
1158             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
1159           }
1160           $this->macroarray[$this->macro][$key]['choosen']=$string;
1161         }
1162       }
1164       foreach($this->macroarray[$this->macro] as $paras){
1166         /* get al vars */
1167         $var        = $paras['var'];           
1168         $name       = $paras['name'];           
1169         $default    = $paras['default'];
1170         $type       = $paras['type'];
1171         $choosen    = $paras['choosen'] ; 
1172         $str        = $default;
1174         $dis = "";
1175         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
1176           $dis = " disabled ";
1177         }
1179         /* in case of a combo box display a combobox with selected attr */
1180         $macrotab.= "<tr>";
1181         switch ($type){
1183           case "combo":
1184             $str= "<select name='".$var."' ".$dis." >";
1185           foreach(explode(":",$default) as $choice){
1186             if($choosen==$choice){
1187               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
1188             }else{
1189               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
1190             }
1191           }
1192           $str.="</select>";
1193           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1194           break;
1196           case "bool":
1197             if(!$choosen){
1198               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
1199             }else{
1200               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
1201             }
1202           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
1203           break;
1205           case "string":
1206             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
1207           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1208           break;
1210         }
1211         $macrotab.= "</td></tr>";
1213       }
1214       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1215     }//is_array()
1217     /* Give smarty the table */
1218     $smarty->assign("macrotab",$macrotab);
1221     /* Add phone number */
1222     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1224       if(strlen(trim($_POST["phonenumber"])) > 20 ){
1225         msg_dialog::display(_("Error"), msgPool::toobig("Phone number"), ERROR_DIALOG);
1226       }elseif (tests::is_phone_nr($_POST['phonenumber'])){
1227         $number= trim($_POST["phonenumber"]);
1228         $this->phoneNumbers[$number]= $number;
1229         $this->is_modified= TRUE;
1230       } else {
1231         msg_dialog::display(_("Error"), msgPool::invalid("Phone number"), ERROR_DIALOG);
1232       }
1233     }
1235     /* Remove phone number */
1236     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1237       foreach ($_POST['phonenumber_list'] as $number){
1238         unset($this->phoneNumbers[$number]);
1239         $this->is_modified= TRUE;
1240       }
1241     }
1243     /* Assign acls */
1244     $tmp = $this->plInfo();
1245     foreach($tmp['plProvidedAcls'] as $name => $translation){
1246       $smarty->assign($name."ACL",$this->getacl($name,$SkipWrite));
1247     }
1249     /* Transfer ACL's */
1250     foreach($this->attributes as $val){
1251       if(isset($this->$val)){
1252         $smarty->assign($val,$this->$val);
1253       }else{
1254         $smarty->assign($val,"");
1255       }
1256     }
1258     /* Create home server array */
1259     $tmp = array();
1260     foreach($this->goFonHomeServers as $dn => $attrs){
1261       if(!is_numeric($dn)){
1262         $tmp[$dn] = $attrs['SERVER'];
1263       }
1264     }
1265     $smarty->assign("goFonHomeServers",$tmp);
1267     /* Fill arrays */
1268     $smarty->assign ("goFonHardware", $this->goFonHardware);
1269     if (!count($this->phoneNumbers)){
1270       $smarty->assign ("phoneNumbers", array());
1271     } else {
1272       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1273     }
1275     $dis = "";
1276     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1277       $dis= " disabled ";
1278     }
1279     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1280        _("Choose your private phone")."\">\n";
1282     foreach ($this->hardware_list as $cn => $description){
1283       if ($cn == $this->goFonHardware){
1284         $selected= "selected";
1285       } else {
1286         $selected= "";
1287       }
1288       if (isset($this->used_hardware[$cn])){
1289         $color= "style=\"color:#A0A0A0\"";
1290       } else {
1291         $color= "";
1292       }
1293       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1294     }
1295     $hl.= "</select>\n";
1296     $smarty->assign ("hardware_list", $hl);
1299     foreach($this->attributes as $attr){
1300       if(in_array($attr,$this->multi_boxes)){
1301         $smarty->assign("use_".$attr,TRUE);
1302       }else{
1303         $smarty->assign("use_".$attr,FALSE);
1304       }
1305     }
1307     foreach(array("goFonVoiceMailContext","goFonContext") as $attr){
1308       if(in_array($attr,$this->multi_boxes)){
1309         $smarty->assign("use_".$attr,TRUE);
1310       }else{
1311         $smarty->assign("use_".$attr,FALSE);
1312       }
1313     }
1315     /* Show main page */
1316     $this->lastmacro = $this->macro;
1317     $smarty->assign("multiple_support",$this->multiple_support_active);
1318     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1319     return($display);
1320   }
1323   function save_object()
1324   {
1325     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1326     if (isset($_POST["phoneTab"])){
1327     
1328       plugin::save_object();
1330       /* Save checkbox */
1331       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1332 //     if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1333 //       if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1334 //         $tmp .= "M";
1335 //       }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1336 //         $tmp  = preg_replace ("/M/","",$tmp);
1337 //       }
1338 //     }
1339       $this->goFonDeliveryMode= "[".$tmp."]";
1342       /* Every macro in the select box are available */
1343       if((isset($_POST['macro']))){
1344         $this->macro = $_POST['macro'];
1345         $this->macrostillavailable=true;
1346       }
1348       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1349         $this->is_modified =true;
1350       }
1352       /* Save context */
1353       if(isset($_POST['context'])){
1354         if($this->context != $_POST['context']){
1355           $this->is_modified= TRUE;
1356         }
1357         $this->context= $_POST['context'];
1358       }
1360       /* Save voice context */
1361       if(isset($_POST['voice_context'])){
1362         if($this->voice_context != $_POST['voice_context']){
1363           $this->is_modified= TRUE;
1364         }
1365         $this->voice_context= $_POST['voice_context'];
1366       }
1368       if(is_array($this->phoneNumbers)){
1369         foreach($this->phoneNumbers as $telenumms) {
1370           $nummsinorder[]=$telenumms; 
1371         }
1372       }else{
1373         $nummsinorder=array("");
1374       }
1377       /* get all Postvars */
1378       if(isset($this->macroarray[$this->macro])){
1381         if($this->acl_is_writeable("goFonMacro",$SkipWrite)){
1382           foreach($this->macroarray[$this->macro] as $key => $paras){
1384             $old_macro_settings = $this->macroarray[$this->macro][$key]; 
1385             $backup = $this->macroarray[$this->macro][$key];
1387             if(isset($_POST[$paras['var']])){
1388               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1389             }
1391             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1392                We need this code below to read and save checkboxes correct
1393              */
1395             if(isset($_POST['post_success'])){
1396               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1397                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1398                   $this->macroarray[$this->macro][$key]['choosen']=1;
1399                 }else{
1400                   $this->macroarray[$this->macro][$key]['choosen']=0;
1401                 }
1402               }
1403             }
1404             if(array_differs($old_macro_settings,$this->macroarray[$this->macro][$key])){
1405               $this->is_modified = TRUE;
1406             }
1407           }
1409           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1410             $this->is_modified = TRUE;
1411           }
1412         }
1413       }
1414     }
1415   }
1417   function check()
1418   {
1419     /* Call common method to give check the hook */
1420     $message= plugin::check();
1422     if(!count($this->goFonHomeServers)){
1423       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1424     }
1426     if(empty($this->goFonHomeServer)){
1427       $message[] = msgPool::invalid(_("Home server"));
1428     }
1430     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1431       $message[]= msgPool::invalid(_("Voicemail PIN"),"","",_("Between 1-4 charactes"));
1432     }else{
1433       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1434         $message[]= msgPool::invalid(_("Voicemail PIN"),preg_replace("/[0-9]/","X",$this->goFonVoicemailPIN),"/X/");
1435       }
1436     }
1438     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1439       $message[]= msgPool::invalid(_("Phone PIN"),preg_replace("/[0-9a-z]/i","X",$this->goFonPIN),"/X/");
1440     }
1442     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1443       $str = $this->generate_mysql_entension_entries(false);
1444       if(empty($str)){
1445         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
1446       }
1447     }
1449     /* We need at least one phone number */
1450     if (count($this->phoneNumbers) == 0){
1451       $message[]= msgPool::required("Phone number");
1452     }
1454     /* Do not allow to save duplicate phone numbers 
1455      *  this may destroy the extensions table.
1456      */ 
1457     $ldap = $this->config->get_ldap_link();
1458     $ldap->cd($this->config->current['BASE']);  
1459     $numberFilter = "";
1460     foreach($this->phoneNumbers as $number){
1461       $numberFilter .= "(telephoneNumber={$number})";
1462     }
1463     $ldap->search("(&(!(uid=".$this->uid."))(objectClass=goFonAccount)(|{$numberFilter}))",array("dn","telephoneNumber"));
1464     $res = array();
1465     while($attrs = $ldap->fetch()){
1466       unset($attrs['telephoneNumber']['count']);
1467       $res = array_merge($res,array_intersect($attrs['telephoneNumber'], $this->phoneNumbers));
1468     }
1469     $res = array_unique($res);
1470     if(count($res)){
1471       $message[] = msgPool::duplicated(_("Phone number"))."&nbsp;<br>".
1472         implode(array_intersect($res, $this->phoneNumbers), ", ");
1473     }
1475     /* check for ! in any parameter setting*/
1476     if(isset($this->macroarray[$this->macro])){
1477       foreach($this->macroarray[$this->macro] as $val){
1478         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1479           $message[] = msgPool::invalid(sprintf(_("macro parameter %s"),$val['name']),$val['choosen'],"/[^\#]/");
1480         }
1481       }
1482     }
1483     return ($message);
1484   }
1488   function save()
1489   {
1490     plugin::save();
1492     /* Force saving macro again 
1493      * This ensures that 
1494      *  - the macro is available on the destiantion server.
1495      *  - the macro saved is up to date on the destination server.
1496      */
1497     if(!empty($this->macro) && $this->macro != "none")  {
1498       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1499       $macro_tab -> save();
1500     }
1502     /* Save arrays */
1503     $tmp_numbers = array();
1504     foreach ($this->phoneNumbers as $number){
1505       $tmp_numbers[] = $number;
1506     }
1508     /* Save settings, or remove goFonMacro attribute*/
1509     if($this->macro!="none"){    
1510       $this->attrs['goFonMacro']=$this->macro;
1511       if(isset($this->macroarray[$this->macro])){
1512         foreach($this->macroarray[$this->macro] as $paras)  {
1513           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1514         }
1515       }
1516     }else{
1517       $this->attrs['goFonMacro']=array();
1518     }
1519     unset($this->attrs['macro'])  ;
1521     $this->attrs['goFonForwarding']=array();
1523     /*
1524      */
1525     $str = $this->generate_mysql_entension_entries(true);
1526     if(!$str){
1527       msg_dialog::display(_("Error"),_("An error occured while updating the database entries!") , ERROR_DIALOG);
1528     }
1530     if($this->attrs['goFonMacro']==""){
1531       $this->attrs['goFonMacro']=array();
1532     }
1534     unset($this->attrs['cn']);
1536     /* Write back to ldap */
1537     $ldap= $this->config->get_ldap_link();
1538     $ldap->cd($this->dn);
1539     $this->cleanup();
1540     
1541     /* Force saving numbers, else it will be overwriten by user account. */
1542     $this->attrs['telephoneNumber'] =$tmp_numbers;
1543     $ldap->modify ($this->attrs); 
1545     /* Log last action */
1546     if($this->initially_was_account){
1547       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1548     }else{
1549       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1550     }
1552     if (!$ldap->success()){
1553       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
1554     }
1556     /* Optionally execute a command after we're done */
1558     if ($this->initially_was_account == $this->is_account){
1559       if ($this->is_modified){
1560         $this->handle_post_events("modify",array("uid" => $this->uid));
1561       }
1562     } else {
1563       $this->handle_post_events("add",array("uid" => $this->uid));
1564     }
1566   }
1569   function adapt_from_template($dn, $skip= array())
1570   {
1571     plugin::adapt_from_template($dn, $skip);
1573     /* Assemble phone numbers */
1574     if (isset($this->attrs['telephoneNumber']) && !in_array("telephoneNumber", $skip)){
1575       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1576         $number= $this->attrs['telephoneNumber'][$i];
1577         $this->phoneNumbers[$number]= $number;
1578       }
1579     }
1580   }
1583   function remove_from_parent()
1584   {
1585     if(!$this->initially_was_account) return;
1587     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1589       // Get Configuration for initial Mysql database Server
1590       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1591       $s_parameter  ="";
1593       /* Check table definitions
1594        */
1595       if(!phoneAccount::checkRealtimeTables($a_SETUP)){
1596         msg_dialog::display(_("Warning"),
1597             sprintf(_("GOsa identified problems with your MySQL table definition!")),
1598             WARNING_DIALOG);
1599       }
1601       // Connect to DB server
1602       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1604       // Check if we are  connected correctly
1605       if(!$r_con){
1606         msg_dialog::display(_("Error"), msgPool::dbconnect("GOfon",@mysql_error()), ERROR_DIALOG);
1607         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1608         return false;
1609       }
1611       // Select database for Extensions
1612       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1614       // Test if we have the database selected correctly
1615       if(!$db){
1616         msg_dialog::display(_("Error"), msgPool::dbselect("GOfon", @mysql_error()), ERROR_DIALOG);
1617         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1618         return false;
1619       }
1621       $SQL="";
1622       $SQL[]= "SET @@sql_mode = STRICT_ALL_TABLES;";
1624       $first_num = false;
1625       // Delete old entries
1626       foreach($this->a_old_telenums as $s_telenums){
1627         if(!$first_num){
1628           $first_num = $s_telenums;
1629         }
1630         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1631       }
1634       $query  = "SELECT id,name,callerid FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';";
1635       $rid    = mysql_query($query,$r_con);
1636       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1637       $result = mysql_fetch_assoc($rid);
1638       $callerid = $first_num;
1639       if($result){
1640         $callerid = $result['callerid'];
1641       }
1643       /* Set mode to strict
1644          Strict disallows the addition of entries that do not match the targets field length.
1645        */
1646       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$callerid."';";
1647       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1648       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1650       /* Start transaction, to be able to rollback
1651        */
1652       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Removing entry from server---</b>","");
1654       mysql_query("begin;",$r_con);
1655       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
1657       foreach($SQL as $query){
1658         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
1660         if(!mysql_query($query,$r_con)){
1661           $err = mysql_error($r_con);
1662           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
1663           msg_dialog::display(_("Error"),
1664               msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
1665               "\n<p>"._("Please activate debugging for details!")."</p>",
1666               ERROR_DIALOG);
1668           mysql_query("rollback;",$r_con);
1669           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
1670           @mysql_close($r_con);
1671           return(false);
1672         }
1673       }
1675       /* Let changes get active, everything was fine;
1676        */
1677       mysql_query("commit;",$r_con);
1678       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "");
1679       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
1681     }else{
1682       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
1683       return false;
1684     }
1686     /* unset macro attr, it will cause an error */
1687     $tmp = array_flip($this->attributes);
1688     unset($tmp['macro']);
1689     $this->attributes=array_flip($tmp);
1691     /* Cancel if there's nothing to do here */
1692     if (!$this->initially_was_account){
1693       return;
1694     }
1696     plugin::remove_from_parent();
1698     /* Just keep one phone number */
1699     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1700       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1701     } else {
1702       $this->attrs['telephoneNumber']= array();
1703     }
1706     $ldap= $this->config->get_ldap_link();
1707     $ldap->cd($this->config->current['BASE']);
1708     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1709     while($attr = $ldap->fetch()){
1710       if(in_array($this->dn,$attr['member'])){
1711         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1712         unset($new->by_object['ogroup']->memberList[$this->dn]);
1713         unset($new->by_object['ogroup']->member[$this->dn]);
1714         $new->save();
1715         msg_dialog::display(_("Information"), sprintf(_("User '%s' has been removed from phone queue '%s'."), $this->cn, $new->by_object['ogroup']->cn), INFO_DIALOG);
1716       }
1717     }
1718     $ldap->cd($this->dn);
1719     $this->cleanup();
1720     $ldap->modify ($this->attrs); 
1722     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1723     if (!$ldap->success()){
1724       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1725     }
1727     /* Optionally execute a command after we're done */
1728     @mysql_close($r_con);
1729     $this->handle_post_events('remove',array("uid"=> $this->uid));
1730   }
1734   /* This function checks if the given phonenumbers are available or already in use*/
1735   function is_number_used()
1736   {
1737     $ldap= $this->config->get_ldap_link();
1738     $ldap->cd($this->config->current['BASE']);
1739     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1740     while($attrs = $ldap->fetch()) {
1741       unset($attrs['telephoneNumber']['count']);
1742       foreach($attrs['telephoneNumber'] as $tele){
1743         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1744         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1745         $numbers[$tele]=$attrs;
1746       }
1747     }
1749     foreach($this->phoneNumbers as $num){
1750       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1751         if(isset($numbers[$num]['uid'][0])){
1752           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1753         }else{
1754           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1755         }
1756       }
1757     }
1758   }
1761   /* Create phoneAccount part of copy & paste dialog */
1762   function getCopyDialog()
1763   { 
1764     if(!$this->is_account) return("");
1765     $smarty = get_smarty();
1766     if (!count($this->phoneNumbers)){
1767       $smarty->assign ("phoneNumbers", array(""));
1768     } else {
1769       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1770     }
1772     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1773     $smarty->assign("goFonPIN",$this->goFonPIN);
1775     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1776     $ret =array();
1777     $ret['string'] = $display;
1778     $ret['status'] = "";
1779     return($ret);
1780   }
1782   /* Save posts from copy & paste dialog dialog  */
1783   function saveCopyDialog()
1784   {
1785     if(!$this->is_account) return;
1786     $this->execute();
1787     if(isset($_POST['goFonVoicemailPIN'])) {
1788       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1789     }
1790     if(isset($_POST['goFonPIN'])){
1791       $this->goFonPIN = $_POST['goFonPIN'];
1792     }
1793   }
1796   function allow_remove()
1797   {
1798     /* Check if previously selected server is still available */
1799     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1800       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1801     }
1802   }
1804   /* Return plugin informations for acl handling */
1805   static function plInfo()
1806   {
1807     return (array(
1808           "plShortName"     => _("Phone"),
1809           "plDescription"   => _("Phone account settings"),
1810           "plSelfModify"    => TRUE,
1811           "plDepends"       => array("user"),
1812           "plPriority"      => 7,                                 // Position in tabs
1813           "plSection"         => array("personal" => _("My account")),
1814           "plCategory"        => array("users"),
1817           "plOptions"       => array(),
1819           "plProvidedAcls"  => array(
1820             "telephoneNumber"     => _("Telephone number"),
1821             "goFonMacro"          => _("Macro settings"),
1822             "goFonHardware"       => _("Phone hardware"),
1823             "goFonHomeServer"     => _("Home server"),
1824             "goFonContext"          => _("Phone context"),
1825             "goFonVoiceMailContext" => _("Voice mail context"),
1826             "goFonPIN"            => _("Telephone pin"),
1827             "goFonVoicemailPIN"   => _("Voicemail pin"))
1828           ));
1829   }
1833   function multiple_execute()
1834   {
1835     plugin::multiple_execute();
1836     return($this->execute());
1837   }
1839   function get_multi_init_values()
1840   {
1841     $ret = plugin::get_multi_init_values();
1842     $ret['phoneNumbers'] = array();
1843     foreach($this->phoneNumbers as $number){
1844       $ret['phoneNumbers'][] = $number."  [".$this->attrs['cn'][0]."]"; 
1845     }
1846     $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1847     return($ret);
1848   }
1850   function init_multiple_support($attrs,$all)
1851   {
1852     plugin::init_multiple_support($attrs,$all);
1854     $this->phoneNumbers = array();
1855     if(isset($all['phoneNumbers'])){
1856       for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1857         $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1858       }
1859     }
1860   }
1862   function multiple_save_object()
1863   {
1864     /* Simply call parents save_object */
1865     if (isset($_POST["phoneTab"])){
1867       plugin::save_object();
1868       plugin::multiple_save_object();
1870       /* Every macro in the select box are available */
1871       if((isset($_POST['macro']))){
1872         $this->macrostillavailable=true;
1873       }
1875       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1876         $this->macro = $_POST['macro'];
1877         $this->is_modified =true;
1878       }
1880       /* get all Postvars */
1881       if(isset($this->macroarray[$this->macro])){
1882         foreach($this->macroarray[$this->macro] as $key => $paras){
1883           $backup = $this->macroarray[$this->macro][$key];
1884           if(isset($_POST[$paras['var']])){
1885             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1886           }
1887           if(isset($_POST['post_success'])){
1888             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1889               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1890                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1891               }else{
1892                 $this->macroarray[$this->macro][$key]['choosen']=false;
1893               }
1894             }
1895           }
1896         }
1897         if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1898           $this->is_modified = TRUE;
1899         }
1900       }
1901     }
1902   }
1904   function multiple_check()
1905   {
1906     $message = plugin::multiple_check();
1908     if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1909       $message[] = _("There is currently no asterisk server defined!");
1910     }
1912     if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1913       $message[] = _("Asterisk server is invalid!");
1914     }
1916     if(in_array("goFonVoicemailPIN",$this->multi_boxes) && 
1917         ( (strlen($this->goFonVoicemailPIN)==0)||
1918           (strlen($this->goFonVoicemailPIN)>4))){
1919       $message[]=(_("Voicemail PIN must be 4 characters long!"));
1920     }else{
1921       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1922         $message[]=(_("Voicemail PIN contains invalid characters!"));
1923       }
1924     }
1926     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1927       $message[]=(_("Phone pin contains invalid characters!"));
1928     }
1930     /* check for ! in any parameter setting*/
1931     if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1932       foreach($this->macroarray[$this->macro] as $val){
1933         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1934           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1935         }
1936       }
1937     }
1939     return($message);
1940   }
1942   function get_multi_edit_values()
1943   {
1944     $ret = plugin::get_multi_edit_values();
1945     if(in_array("macro",$this->multi_boxes)){
1946       $ret['macro'] = $this->macro;
1947       $ret['macroarray'] = $this->macroarray;
1948       $ret['macros'] = $this->macros;
1949     }
1950     return($ret);
1951   }
1954   /* Return asterisk contexts
1955    * Additionaly read contexts from file.
1956    */
1957   function get_asterisk_voicemail_contexts()
1958   {
1959     return($this->get_asterisk_contexts(CONFIG_DIR."/asterisk/voicemail_context.conf"));
1960   }
1961   function get_asterisk_sip_contexts()
1962   {
1963     return($this->get_asterisk_contexts(CONFIG_DIR."/asterisk/sip_context.conf"));
1964   }
1965   function get_asterisk_contexts($file)
1966   {
1967     $contexts = array();
1968     if(file_exists($file) && is_readable($file)){
1969       foreach(file($file) as $context){
1970         $contexts[] = trim($context);
1971       }
1972     }else{
1973       msg_dialog::display(_("Warning"), msgPool::cannotReadFile($file),WARNING_DIALOG);
1974       $contexts[] = "default";
1975     }
1976     array_unique($contexts);
1977     return($contexts);
1978   }
1981 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1982 ?>