Code

Updated repository template
[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   }
414   /* This function generates the Database entries. 
415    * The Parameter 'save' could be true or false.
416    *  false - means only testing no database transactions.
417    *  true  - write database entries.
418    *
419    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
420    * 
421    * If the phone hardware is 'automatic' the table entries will only be removed
422    *  and not added. 
423    */
424   function generate_mysql_entension_entries($save = false)
425   {
426     /* Check if there is at least one server available 
427      * If not, return and tell the user that saving failed 
428      */
429     if(!count($this->goFonHomeServers)){
430       if($save){
431         msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
432       }
433       return(true);
434     }
436     /* Check if Mysql extension is available */
437     if(!is_callable("mysql_pconnect")){
438       if($save){
439         msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
440       }
441       return(true);
442     }
443  
444     /********************** 
445      * Attribute Initialisation
446      **********************/
448     $old_connection = false;
450     // Get Configuration for Mysql database Server
451     $s_parameter    = "";                                           // Contains paramter for selected Macro 
452     $r_con          = false;                                        // DB connection
453     $r_db           = false;                                        // Selected DB
454     $r_res          = false;                                        // Result resource
455     $a_ldap_attrs   = array();                                      //  
457     $s_ip           = NULL;                   // Contains ip for Sip entry
458     $s_host         = NULL;                   // Contains host for Sip entry
459     $s_qualify      = "yes";                  // Qualify entry
460     $s_pin          = NULL;                   // Entry for secret
461     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
463     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
464     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
465     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
467     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
468     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
470     $s_sip_key      = "";     // Key for SIP entry index      
471     $s_sip_val      = "";     // Value for SIP entry index      
473     $b_first_deleted= false;  // Only delete first entry, 
474     $s_telenums     = "";     // for each value variable
476     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
478     /* Prepare some basic attributes */
479     $oldnums = array();
480     foreach($this->a_old_telenums as $tele){
481       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
482     }
483     foreach($this->phoneNumbers as $tele){
484       $newnums[]= preg_replace("/[^0-9]/","",$tele);
485     }
487     if(empty($this->uid)) trigger_error("Uid is empty.");
490     /* Create voicemail entry 
491      */
492     if((!isset($this->cn))||(empty($this->cn))){
493       $CNname= $this->uid;
494     }else{
495       $CNname= $this->cn;
496     }
498     $s_mail = "";
499     if($this->has_mailAccount){
500       $s_mail = $this->mailAddress;;
501     }
503     /* Get phonehardware to setup sip entry  */
504     $ldap         = $this->config->get_ldap_link();
505     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
506     $a_ldap_attrs = $ldap->fetch();
508     /* Check selected phone hardware, is a default IP set? */
509     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
510       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
511       $s_host     = $s_ip;
512     }else{
513       $s_ip       = NULL;
514       $s_host     = "dynamic";
515     }
517     // Attribute GoFonQualify set ?
518     if(isset($a_ldap_attrs['goFonQualify'])){
519       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
520     }
522     // Attribute GoFonPIN set ?
523     if(isset($this->goFonPIN)){
524       $s_pin      = $this->goFonPIN;
525     }
527     // Attribute GoFonType set ?
528     if(isset($a_ldap_attrs['goFonType'])){
529       $s_type = $a_ldap_attrs['goFonType'][0];
530     }
532     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
533       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
534     }else{
535       $sip_data_array['dtmfmode']     ="rfc2833";
536     }
538     /* Check if phone number is used */
539     if($this->is_number_used()){
540       $this->generate_error = $this->is_number_used(); 
541       return false;
542     }
546     /********************** 
547      * Check Server Connection Information
548      **********************/
549  
550     /* Create Mysql handle for the current goFonHomeServer, if possible  
551      * Get configuration to old asterisk home server 
552      */ 
553     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
554     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
555     if(!$new_connection){
556       $this->generate_error =  msgPool::dbconnect($a_New['SERVER'],@mysql_error($new_connection),
557           _("Abort saving entries to keep the database consistent."));
558       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
559       return false;
560     }
561     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
562     if(!$new_database){
563       $this->generate_error =  msgPool::dbselect($a_New['DB'],@mysql_error($new_connection),
564           _("Abort saving entries to keep the database consistent."));
565       new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
566       return false;
567     }
569     /* If the home server has changed, we must remove entries from old 
570      *  server and add new entries in new server.  
571      */
572     if($this->init_HomeServer != $this->goFonHomeServer){
573     
574       /* Get configuration to old asterisk home server */ 
575       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
576  
577       /* Create connection to the database that contains the old entry. 
578        */
579       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
580       if(!$old_connection){
581         $this->generate_error =  msgPool::dbconnect($a_Remove['SERVER'],@mysql_error($old_connection),
582             _("Abort saving entries to keep the database consistent."));
583         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
584         return false;
585       }
586       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
587       if(!$old_database){
588         $this->generate_error =  msgPool::dbselect($a_Remove['DB'],@mysql_error($old_connection),
589             _("Abort saving entries to keep the database consistent."));
590         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
591         return false;
592       }
593     }
596     /* Save means that we must save changes, not only test  */
597     if($save == true){
598     
599       /********************** 
600        * Remove entries from old home server 
601        **********************/
603       /* Check if there is an old entry 
604        * If there is an old entry, get callerid and remove voicemail and extensions 
605        */
606       if($old_connection){
608         /* Check table definitions
609          */
610         if(!phoneAccount::checkRealtimeTables($a_Remove)){
611           msg_dialog::display(_("Warning"),
612               sprintf(_("GOsa identified problems with your MySQL table definition!")),
613               WARNING_DIALOG);
614         }
616         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
617         $rid    = mysql_query($query,$old_connection);
618         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, 
619             "<i>Reguest callerid to be able to identify the user.</i>");
621         /* Old entry found, remove it */
622         $query_a = array();
623         if(mysql_affected_rows($old_connection)){
624           $result = mysql_fetch_assoc($rid);
626           /* Set mode to strict
627              Strict disallows the addition of entries that do not match the targets field length.
628            */
629           $query_a[]= "SET @@sql_mode = STRICT_ALL_TABLES;";
630           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
631           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
632           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
633           foreach($oldnums as $s_telenums) {
634             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
635           }
637           /* Start transaction, to be able to rollback 
638            */
639           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Removing entry from old server---</b>","");
641           mysql_query("begin;",$old_connection);
642           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
644           foreach($query_a as $query){
645             @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
646             if(!mysql_query($query,$old_connection)){
647               $err = mysql_error($old_connection);
648               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
649               msg_dialog::display(_("Error"), 
650                   msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
651                   "\n<p>"._("Please activate debugging for details!")."</p>",
652                   ERROR_DIALOG);
654               mysql_query("rollback;",$old_connection);
655               @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
656               @mysql_close($old_connection);
657               return(false);
658             } 
659           }
661           /* Let changes get active, everything was fine;
662            */ 
663           mysql_query("commit;",$old_connection);
664           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "");
665           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
666         }
667       }
670       /********************** 
671        * Update / Insert sip_users entry  
672        **********************/
674       /* Check table definitions
675        */
676       if(!phoneAccount::checkRealtimeTables($a_New)){
677         msg_dialog::display(_("Warning"),
678             sprintf(_("GOsa identified problems with your MySQL table definition!")),
679             WARNING_DIALOG);
680       }
683       /* Set the first given phone number as callerid */
684       reset($newnums);        
685       $i_new_key = key($newnums);
686       $sip_data_array['callerid']  =$newnums[$i_new_key];
687       $sip_data_array['mailbox']   =$newnums[$i_new_key]."@".$this->voice_context;
689       /* Check if there is already an entry in sip_users for this uid */
690       $SQL_query_array = array();
692       /* Enforce strict mode, ensures inout validation, e.g. target field length 
693        */
694       $SQL_query_array[] = "SET @@sql_mode = STRICT_ALL_TABLES;";
696       $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
697       $rid = mysql_query($query,$new_connection);
698       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Receive current mysql entries.");
699       if(mysql_affected_rows($new_connection)){
701         /********************** 
702          * Update sip_users entry 
703          **********************/
704         $result                     = mysql_fetch_assoc($rid);
705         $sip_data_array['host']         = $s_host;
706         $sip_data_array['qualify']      = $s_qualify;
707         $sip_data_array['secret']       = $this->goFonPIN;
708         $sip_data_array['type']         = $s_type ;
709         $sip_data_array['username']     = $this->uid;
710         $sip_data_array['ipaddr']       = $s_ip;
711         $sip_data_array['context']      = $this->context;
713         /* Remove not changed attributes, to avoid updating table with same values */
714         foreach($sip_data_array as $name => $value){
715           if($result[$name] == $value){
716             unset($sip_data_array[$name]);
717           }
718         }
719         /* Only update entry if there is something to uopdate */
720         if(count($sip_data_array)){
721           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
722           foreach($sip_data_array as $key => $val){
723             $query.= "".$key."='".$val."',"; 
724           } 
725           $query = preg_replace("/,$/","",$query);
726           $query.= " WHERE name='".$this->uid."';";
727           $SQL_query_array[] = $query;
728         }
729       } else {
731         /********************** 
732          * Insert sip_users entry 
733          **********************/
734         //generate SIP entry
735         $sip_data_array['name']         = $this->uid;
736         $sip_data_array['accountcode']  = NULL;          
737         $sip_data_array['amaflags']     = NULL;
738         $sip_data_array['callgroup']    = NULL;
739         $sip_data_array['canreinvite']  = "no";
740         $sip_data_array['context']      = $this->context;
741         $sip_data_array['defaultip']    = NULL;
742         $sip_data_array['fromuser']     = NULL;
743         $sip_data_array['fromdomain']   = NULL;
744         $sip_data_array['host']         = $s_host;
745         $sip_data_array['insecure']     = NULL;
746         $sip_data_array['language']     = NULL;
747         $sip_data_array['mailbox']      = $newnums[$i_new_key]."@".$this->voice_context;
748         $sip_data_array['md5secret']    = NULL;
749         $sip_data_array['nat']          = "no";
750         $sip_data_array['permit']       = NULL;
751         $sip_data_array['deny']         = NULL;
752         $sip_data_array['mask']         = NULL;
753         $sip_data_array['pickupgroup']  = NULL;
754         $sip_data_array['port']         = NULL;
755         $sip_data_array['qualify']      = $s_qualify;
756         $sip_data_array['restrictcid']  = "n";
757         $sip_data_array['rtptimeout']   = NULL;
758         $sip_data_array['rtpholdtimeout']=NULL;
759         $sip_data_array['secret']       = $this->goFonPIN;
760         $sip_data_array['type']         = $s_type ;
761         $sip_data_array['username']     = $this->uid;
762         $sip_data_array['disallow']     = NULL;
763         $sip_data_array['allow']        = NULL;
764         $sip_data_array['musiconhold']  = NULL;
765         $sip_data_array['regseconds']   = NULL;
766         $sip_data_array['ipaddr']       = $s_ip;
767         $sip_data_array['regexten']     = NULL;
768         $sip_data_array['cancallforward']=NULL;
770         /* There is currently no entry for this user in the sip_users table. 
771          * We should create one i
772          */
773         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
774           if($s_sip_val === NULL) continue;
775           $s_sip_values.="'".$s_sip_val."',";
776           $s_sip_keys  .="`".$s_sip_key."`,";
777         }
778         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
779         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
781         /* Add sip entries to mysql queries */
782         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
783       }
786       /********************** 
787        * Update / Insert Voice mail entry  
788        **********************/
790       $customer_id = $newnums[$i_new_key];
791       $query  = "SELECT id,name,callerid FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';";
792       $rid    = mysql_query($query,$new_connection);
794       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Receive callerid");
795       $result = mysql_fetch_assoc($rid);
797       $old_customer_id = ""; 
798       if($result){
799         $old_customer_id = $result['callerid'];
800       }
802       $voice_data_array = array(
803           "customer_id" => $customer_id,
804           "mailbox"     => $customer_id,
805           "password"    => $this->goFonVoicemailPIN,
806           "fullname"    => $CNname,
807           "context"     => $this->voice_context,
808           "email"       => $s_mail);
810       $voice_data_array['pager']   = $this->pager;
812       /* Check if there is already an entry in sip_users for this uid */
813       $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$old_customer_id."';\n";
814       $rid = mysql_query($query_tmp,$new_connection);
816       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Check if voicemail entry exists");
817       if(mysql_affected_rows($new_connection)){
819         /********************** 
820          * Update Voice mail entry  
821          **********************/
823         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"", "<i>Voicemail entry exists, adding updating to queue.</i>");
824         $result = mysql_fetch_assoc($rid)  ;
826         foreach($voice_data_array as $name => $value){
827           if($result[$name] == $value){
828             unset($voice_data_array[$name]);
829           }
830         }
832         /* Only update entry if there is something to update */
833         if(count($voice_data_array)){
834           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
835           foreach($voice_data_array as $key => $val){
836             $query.= "".$key."='".$val."',"; 
837           } 
838           $query = preg_replace("/,$/","",$query);
839           $query.= " WHERE customer_id='".$old_customer_id."';";
840           $SQL_query_array[] = $query;
841         }
842       }else{
844         /********************** 
845          * Insert Voice mail entry  
846          **********************/
847         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"", "<i>No voicemail entry found, add 'create' to queue.</i>");
848         $voice_data_array['context'] = $this->voice_context;
850         /* There is currently no voice mail entry for this user. 
851          * We should create one 
852          */
853         $s_voi_values = $s_voi_keys = "";
854         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
855           if($s_voi_val === NULL) continue;
856           $s_voi_values.="'".$s_voi_val."',";
857           $s_voi_keys  .="`".$s_voi_key."`,";
858         }
859         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
860         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
862         /* Add sip entries to mysql queries */
863         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
864       }
867       /********************** 
868        * Remove/Insert extension entries
869        **********************/
871       /* Initiate transaction 
872        */
873       $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
874       $oldnums= array();
875       foreach($oldnums as $s_telenums){
876         $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
877       }
878       foreach($newnums as $s_telenums){
879         $SQL_query_array[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
880       }
882       /********************** 
883        * Insert extension entries
884        **********************/
886       // Get selected Macro Parameter and create parameter entry 
887       if(isset($this->macroarray[$this->macro])){
888         foreach($this->macroarray[$this->macro] as $key => $val ){
889           $s_parameter .= $val['choosen']."|";
890         }
891         $s_parameter = preg_replace("/\|$/","",$s_parameter);
892       }
894       $i = 0; 
895       $EXT = array();
896       if(!is_numeric($this->uid)){
897         $EXT[$i]['context'] = 'GOsa';
898         $EXT[$i]['exten']   = $this->uid;
899         $EXT[$i]['priority']= 1;
900         $EXT[$i]['app']     = "Goto";
901         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
902         $i ++;
903       }
905       // Entension entries  Hint / Dial / Goto
906       foreach($newnums as $s_telenums){
908         /* Hint Entry */
909         $EXT[$i]['context'] = 'GOsa';
910         $EXT[$i]['exten']   = $s_telenums;
911         $EXT[$i]['priority']= 0;
912         $EXT[$i]['app']     = 'SIP/'.$this->uid;
913         $i ++;  
914         /* SetCID */
915         //$EXT[$i]['context'] = 'GOsa';
916         //$EXT[$i]['exten']   = $s_telenums;
917         //$EXT[$i]['priority']= 1;
918         //$EXT[$i]['app']     = "SetCIDName";
919         //$EXT[$i]['appdata'] = $CNname;
920         //$i ++;  
922         // If no macro is selected use Dial
923         if($this->macro!="none"){ 
924           $macroname = preg_replace("/,.*$/","",$this->macro);        
925           $macroname = preg_replace("/^.*=/","",$macroname);        
926           $s_app = "Macro";$macroname;
927           $s_par = $macroname."|".$s_parameter; 
928         }else{
929           $s_app = "Dial";
930           $s_par = 'SIP/'.$this->uid."|20|r";
931         }
933         $EXT[$i]['context'] = 'GOsa';
934         $EXT[$i]['exten']   = $s_telenums;
935         $EXT[$i]['priority']= 1;
936         $EXT[$i]['app']     = $s_app;
937         $EXT[$i]['appdata'] = $s_par;
938         $i ++;
939       }
941       // Append all these Entries 
942       foreach($EXT as $entr){
943         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
944         foreach($entr as $key2 => $val2){
945           $SQL_syn.= "`".$key2."`,";
946         }
947         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
948         $SQL_syn .= ") VALUES ("; 
949         foreach($entr as $key2 => $val2){
950           $SQL_syn .= "'".$val2."',";
951         }
952         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
953         $SQL_syn .=");\n";
955         $SQL_query_array[] =$SQL_syn;
956         $SQL_syn ="";
957       }
959       /* Start transaction, to be able to rollback 
960        */
961       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Insert/Update new entry---</b>","");
963       mysql_query("begin;",$new_connection);
964       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
966       foreach($SQL_query_array as $query){
967         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
968         if(!mysql_query($query,$new_connection)){
969           $err = mysql_error($new_connection);
970           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
971           msg_dialog::display(_("Error"), 
972               msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
973               "\n<p>"._("Please activate debugging for details!")."</p>",
974               ERROR_DIALOG);
976           mysql_query("rollback;",$new_connection);
977           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
978           @mysql_close($new_connection);
979           return(false);
980         } 
981       }
982      
983       /* Let changes get active, everything was fine;
984        */ 
985       mysql_query("commit;",$new_connection);
986       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "Perform transaction!");
987       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
988     }
989     @mysql_close($new_connection);
990     return true;
991   }
994   function execute()
995   {
996     /* Call parent execute */
997     plugin::execute();
999     /* Log view */
1000     if($this->is_account && !$this->view_logged){
1001       $this->view_logged = TRUE;
1002       new log("view","users/".get_class($this),$this->dn);
1003     }
1005     $display = "";
1006     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1008     if(empty($this->macro)&&(!empty($this->goFonMacro))){
1010       /* Go through already saved values, for a parameter */
1011       $tmp = explode("!",$this->goFonMacro);
1013       /* it is possible that nothing has been saved yet */
1014       if(is_array($tmp)){
1016         /* First value is the macroname */
1017         $this->macro = $tmp[0];
1019         /* Macroname saved, delete that index */
1020         unset($tmp[0]);
1022         /* Check if macro has been removed */
1023         if(!isset($this->macroarray[$this->macro])){
1024           $this->macrostillavailable = false;
1025         }else{
1026           $this->macrostillavailable = true;
1027         }
1029         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
1030         foreach($tmp as $var){
1032           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
1033           $varar = explode("#",$var);
1035           /* Only insert if the parameter still exists */
1036           if(isset($this->macroarray[$this->macro][$varar[0]])){
1037             /* Assign value */
1038             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
1039           }
1040         }
1041       }
1042     }
1043     
1044     /* Do we represent a valid account? */
1045     if (!$this->is_account && $this->parent === NULL){
1046       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
1047         msgPool::noValidExtension(_("Phone"))."</b>";
1048       $display.= back_to_main();
1049       return ($display);
1050     }
1052     /* Do we need to flip is_account state? */
1053     if (isset($_POST['modify_state'])){
1054       $this->is_account= !$this->is_account;
1055     }
1057     /* Do we represent a valid account? */
1058     if (!$this->is_account && $this->parent === NULL){
1059       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
1060         msgPool::noValidExtension(_("Phone"))."</b>";
1061       $display.= back_to_main();
1062       return($display);
1063     }
1065     $display= "";
1067     /* Show tab dialog headers */
1068     
1069     if (!$this->multiple_support_active && $this->parent !== NULL){
1070       if ($this->is_account){
1071         $display= $this->show_disable_header(_("Remove phone account"),
1072             msgPool::featuresEnabled(_("Phone")));
1073       } else {
1074         if(empty($this->uid)){
1075           $display= $this->show_enable_header(_("Create phone account"),
1076             msgPool::featuresDisabled(_("Phone"),_("User uid")));
1077         }else{
1078           $display= $this->show_enable_header(_("Create phone account"),
1079             msgPool::featuresDisabled(_("Phone")));
1080         }
1081         return ($display);
1082       }
1083     }
1084     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
1085     if(empty($this->macro)){
1086       $this->macro ="none";
1087     }
1089     /* Prepare templating */
1090     $smarty= get_smarty();
1092     /* tell user that the selected plugin is no longer available */
1093     if((!$this->macrostillavailable)&&($this->macro!="none")){
1094       msg_dialog::display(_("Error"), _("Selected macro is not available anymore!"), ERROR_DIALOG);
1095     }
1097     /* Assing macroselectbox values  */
1098     $smarty->assign("macros",$this->macros);   
1099     $smarty->assign("macro", $this->macro);   
1101     /* Assign contexts */
1102     $smarty->assign("voicemail_contexts",$this->voicemail_contexts);
1103     $smarty->assign("sip_contexts",$this->sip_contexts);
1104     $smarty->assign("context" ,$this->context);
1105     $smarty->assign("voice_context" ,$this->voice_context);
1107     /* check if there is a FON server created */
1108     if(!count($this->goFonHomeServer)){
1109       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
1110     }
1112     /* Create html parameter table for selected macro parameters 
1113      *  skip if no parameters given 
1114      */
1115     if(!isset($this->macroarray[$this->macro])){
1116       $macrotab="";
1117     }else{
1119       $macrotab ="<table summary=\""._("Parameter")."\">";
1120       /* for every single parameter-> display textfile,combo, or true false switch*/
1122       foreach($this->phoneNumbers as $phonenum){
1123         $tmp[] = $phonenum;
1124       }
1125     
1126       if($this->macro != $this->lastmacro){
1127         /* Go through all params */
1128         foreach($this->macroarray[$this->macro] as $key => $paras){
1130           $string = $paras['default'];
1132           $string=preg_replace("/%uid/i",$this->uid,$string);
1134           if(isset($this->cn)){
1135             $string=preg_replace("/%cn/i",$this->cn,$string);
1136           }
1138           for($i = 0 ; $i < 10; $i++){
1139             if(isset($tmp[$i])){
1140               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
1141             }
1142           }
1143           if(isset($tmp[0])){
1144             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
1145           }
1146           $this->macroarray[$this->macro][$key]['choosen']=$string;
1147         }
1148       }
1150       foreach($this->macroarray[$this->macro] as $paras){
1152         /* get al vars */
1153         $var        = $paras['var'];           
1154         $name       = $paras['name'];           
1155         $default    = $paras['default'];
1156         $type       = $paras['type'];
1157         $choosen    = $paras['choosen'] ; 
1158         $str        = $default;
1160         $dis = "";
1161         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
1162           $dis = " disabled ";
1163         }
1165         /* in case of a combo box display a combobox with selected attr */
1166         $macrotab.= "<tr>";
1167         switch ($type){
1169           case "combo":
1170             $str= "<select name='".$var."' ".$dis." >";
1171           foreach(explode(":",$default) as $choice){
1172             if($choosen==$choice){
1173               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
1174             }else{
1175               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
1176             }
1177           }
1178           $str.="</select>";
1179           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1180           break;
1182           case "bool":
1183             if(!$choosen){
1184               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
1185             }else{
1186               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
1187             }
1188           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
1189           break;
1191           case "string":
1192             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
1193           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1194           break;
1196         }
1197         $macrotab.= "</td></tr>";
1199       }
1200       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1201     }//is_array()
1203     /* Give smarty the table */
1204     $smarty->assign("macrotab",$macrotab);
1207     /* Add phone number */
1208     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1210       if(strlen(trim($_POST["phonenumber"])) > 20 ){
1211         msg_dialog::display(_("Error"), msgPool::toobig("Phone number"), ERROR_DIALOG);
1212       }elseif (tests::is_phone_nr($_POST['phonenumber'])){
1213         $number= trim($_POST["phonenumber"]);
1214         $this->phoneNumbers[$number]= $number;
1215         $this->is_modified= TRUE;
1216       } else {
1217         msg_dialog::display(_("Error"), msgPool::invalid("Phone number"), ERROR_DIALOG);
1218       }
1219     }
1221     /* Remove phone number */
1222     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1223       foreach ($_POST['phonenumber_list'] as $number){
1224         unset($this->phoneNumbers[$number]);
1225         $this->is_modified= TRUE;
1226       }
1227     }
1229     /* Assign acls */
1230     $tmp = $this->plInfo();
1231     foreach($tmp['plProvidedAcls'] as $name => $translation){
1232       $smarty->assign($name."ACL",$this->getacl($name,$SkipWrite));
1233     }
1235     /* Transfer ACL's */
1236     foreach($this->attributes as $val){
1237       if(isset($this->$val)){
1238         $smarty->assign($val,$this->$val);
1239       }else{
1240         $smarty->assign($val,"");
1241       }
1242     }
1244     /* Create home server array */
1245     $tmp = array();
1246     foreach($this->goFonHomeServers as $dn => $attrs){
1247       if(!is_numeric($dn)){
1248         $tmp[$dn] = $attrs['SERVER'];
1249       }
1250     }
1251     $smarty->assign("goFonHomeServers",$tmp);
1253     /* Fill arrays */
1254     $smarty->assign ("goFonHardware", $this->goFonHardware);
1255     if (!count($this->phoneNumbers)){
1256       $smarty->assign ("phoneNumbers", array());
1257     } else {
1258       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1259     }
1261     $dis = "";
1262     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1263       $dis= " disabled ";
1264     }
1265     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1266        _("Choose your private phone")."\">\n";
1268     foreach ($this->hardware_list as $cn => $description){
1269       if ($cn == $this->goFonHardware){
1270         $selected= "selected";
1271       } else {
1272         $selected= "";
1273       }
1274       if (isset($this->used_hardware[$cn])){
1275         $color= "style=\"color:#A0A0A0\"";
1276       } else {
1277         $color= "";
1278       }
1279       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1280     }
1281     $hl.= "</select>\n";
1282     $smarty->assign ("hardware_list", $hl);
1285     foreach($this->attributes as $attr){
1286       if(in_array($attr,$this->multi_boxes)){
1287         $smarty->assign("use_".$attr,TRUE);
1288       }else{
1289         $smarty->assign("use_".$attr,FALSE);
1290       }
1291     }
1293     foreach(array("goFonVoiceMailContext","goFonContext") as $attr){
1294       if(in_array($attr,$this->multi_boxes)){
1295         $smarty->assign("use_".$attr,TRUE);
1296       }else{
1297         $smarty->assign("use_".$attr,FALSE);
1298       }
1299     }
1301     /* Show main page */
1302     $this->lastmacro = $this->macro;
1303     $smarty->assign("multiple_support",$this->multiple_support_active);
1304     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1305     return($display);
1306   }
1309   function save_object()
1310   {
1311     $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1312     if (isset($_POST["phoneTab"])){
1313     
1314       plugin::save_object();
1316       /* Save checkbox */
1317       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1318       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1319         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1320           $tmp .= "M";
1321         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1322           $tmp  = preg_replace ("/M/","",$tmp);
1323         }
1324       }
1325       $this->goFonDeliveryMode= "[".$tmp."]";
1328       /* Every macro in the select box are available */
1329       if((isset($_POST['macro']))){
1330         $this->macro = $_POST['macro'];
1331         $this->macrostillavailable=true;
1332       }
1334       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1335         $this->is_modified =true;
1336       }
1338       /* Save context */
1339       if(isset($_POST['context'])){
1340         if($this->context != $_POST['context']){
1341           $this->is_modified= TRUE;
1342         }
1343         $this->context= $_POST['context'];
1344       }
1346       /* Save voice context */
1347       if(isset($_POST['voice_context'])){
1348         if($this->voice_context != $_POST['voice_context']){
1349           $this->is_modified= TRUE;
1350         }
1351         $this->voice_context= $_POST['voice_context'];
1352       }
1354       if(is_array($this->phoneNumbers)){
1355         foreach($this->phoneNumbers as $telenumms) {
1356           $nummsinorder[]=$telenumms; 
1357         }
1358       }else{
1359         $nummsinorder=array("");
1360       }
1363       /* get all Postvars */
1364       if(isset($this->macroarray[$this->macro])){
1367         if($this->acl_is_writeable("goFonMacro",$SkipWrite)){
1368           foreach($this->macroarray[$this->macro] as $key => $paras){
1370             $old_macro_settings = $this->macroarray[$this->macro][$key]; 
1371             $backup = $this->macroarray[$this->macro][$key];
1373             if(isset($_POST[$paras['var']])){
1374               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1375             }
1377             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1378                We need this code below to read and save checkboxes correct
1379              */
1381             if(isset($_POST['post_success'])){
1382               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1383                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1384                   $this->macroarray[$this->macro][$key]['choosen']=1;
1385                 }else{
1386                   $this->macroarray[$this->macro][$key]['choosen']=0;
1387                 }
1388               }
1389             }
1390             if(array_differs($old_macro_settings,$this->macroarray[$this->macro][$key])){
1391               $this->is_modified = TRUE;
1392             }
1393           }
1395           if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1396             $this->is_modified = TRUE;
1397           }
1398         }
1399       }
1400     }
1401   }
1403   function check()
1404   {
1405     /* Call common method to give check the hook */
1406     $message= plugin::check();
1408     if(!count($this->goFonHomeServers)){
1409       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1410     }
1412     if(empty($this->goFonHomeServer)){
1413       $message[] = msgPool::invalid(_("Home server"));
1414     }
1416     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1417       $message[]= msgPool::invalid(_("Voicemail PIN"),"","",_("Between 1-4 charactes"));
1418     }else{
1419       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1420         $message[]= msgPool::invalid(_("Voicemail PIN"),preg_replace("/[0-9]/","X",$this->goFonVoicemailPIN),"/X/");
1421       }
1422     }
1424     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1425       $message[]= msgPool::invalid(_("Phone PIN"),preg_replace("/[0-9a-z]/i","X",$this->goFonPIN),"/X/");
1426     }
1428     if ($this->initially_was_account != $this->is_account || $this->is_modified){
1429       $str = $this->generate_mysql_entension_entries(true);
1430       if(empty($str)){
1431         msg_dialog::display(_("Error"), $str, ERROR_DIALOG);
1432       }
1433     }
1435     /* We need at least one phone number */
1436     if (count($this->phoneNumbers) == 0){
1437       $message[]= msgPool::required("Phone number");
1438     }
1440     /* Do not allow to save duplicate phone numbers 
1441      *  this may destroy the extensions table.
1442      */ 
1443     $ldap = $this->config->get_ldap_link();
1444     $ldap->cd($this->config->current['BASE']);  
1445     $numberFilter = "";
1446     foreach($this->phoneNumbers as $number){
1447       $numberFilter .= "(telephoneNumber={$number})";
1448     }
1449     $ldap->search("(&(!(uid=".$this->uid."))(objectClass=goFonAccount)(|{$numberFilter}))",array("dn","telephoneNumber"));
1450     $res = array();
1451     while($attrs = $ldap->fetch()){
1452       unset($attrs['telephoneNumber']['count']);
1453       $res = array_merge($res,array_intersect($attrs['telephoneNumber'], $this->phoneNumbers));
1454     }
1455     $res = array_unique($res);
1456     if(count($res)){
1457       $message[] = msgPool::duplicated(_("Phone number"))."&nbsp;<br>".
1458         implode(array_intersect($res, $this->phoneNumbers), ", ");
1459     }
1461     /* check for ! in any parameter setting*/
1462     if(isset($this->macroarray[$this->macro])){
1463       foreach($this->macroarray[$this->macro] as $val){
1464         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1465           $message[] = msgPool::invalid(sprintf(_("macro parameter %s"),$val['name']),$val['choosen'],"/[^\#]/");
1466         }
1467       }
1468     }
1469     return ($message);
1470   }
1474   function save()
1475   {
1476     plugin::save();
1478     /* Force saving macro again 
1479      * This ensures that 
1480      *  - the macro is available on the destiantion server.
1481      *  - the macro saved is up to date on the destination server.
1482      */
1483     if(!empty($this->macro) && $this->macro != "none")  {
1484       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1485       $macro_tab -> save();
1486     }
1488     /* Save arrays */
1489     $tmp_numbers = array();
1490     foreach ($this->phoneNumbers as $number){
1491       $tmp_numbers[] = $number;
1492     }
1494     /* Save settings, or remove goFonMacro attribute*/
1495     if($this->macro!="none"){    
1496       $this->attrs['goFonMacro']=$this->macro;
1497       if(isset($this->macroarray[$this->macro])){
1498         foreach($this->macroarray[$this->macro] as $paras)  {
1499           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1500         }
1501       }
1502     }else{
1503       $this->attrs['goFonMacro']=array();
1504     }
1505     unset($this->attrs['macro'])  ;
1507     $this->attrs['goFonForwarding']=array();
1509     /*
1510      */
1511     $str = $this->generate_mysql_entension_entries(true);
1512     if(!$str){
1513       msg_dialog::display(_("Error"),_("An error occured while updating the database entries!") , ERROR_DIALOG);
1514     }
1516     if($this->attrs['goFonMacro']==""){
1517       $this->attrs['goFonMacro']=array();
1518     }
1520     unset($this->attrs['cn']);
1522     /* Write back to ldap */
1523     $ldap= $this->config->get_ldap_link();
1524     $ldap->cd($this->dn);
1525     $this->cleanup();
1526     
1527     /* Force saving numbers, else it will be overwriten by user account. */
1528     $this->attrs['telephoneNumber'] =$tmp_numbers;
1529     $ldap->modify ($this->attrs); 
1531     /* Log last action */
1532     if($this->initially_was_account){
1533       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1534     }else{
1535       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1536     }
1538     if (!$ldap->success()){
1539       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()));
1540     }
1542     /* Optionally execute a command after we're done */
1544     if ($this->initially_was_account == $this->is_account){
1545       if ($this->is_modified){
1546         $this->handle_post_events("modify",array("uid" => $this->uid));
1547       }
1548     } else {
1549       $this->handle_post_events("add",array("uid" => $this->uid));
1550     }
1552   }
1555   function adapt_from_template($dn, $skip= array())
1556   {
1557     plugin::adapt_from_template($dn, $skip);
1559     /* Assemble phone numbers */
1560     if (isset($this->attrs['telephoneNumber']) && !in_array("telephoneNumber", $skip)){
1561       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1562         $number= $this->attrs['telephoneNumber'][$i];
1563         $this->phoneNumbers[$number]= $number;
1564       }
1565     }
1566   }
1569   function remove_from_parent()
1570   {
1571     if(!$this->initially_was_account) return;
1573     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1575       // Get Configuration for initial Mysql database Server
1576       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1577       $s_parameter  ="";
1579       /* Check table definitions
1580        */
1581       if(!phoneAccount::checkRealtimeTables($a_SETUP)){
1582         msg_dialog::display(_("Warning"),
1583             sprintf(_("GOsa identified problems with your MySQL table definition!")),
1584             WARNING_DIALOG);
1585       }
1587       // Connect to DB server
1588       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1590       // Check if we are  connected correctly
1591       if(!$r_con){
1592         msg_dialog::display(_("Error"), msgPool::dbconnect("GOfon",@mysql_error()), ERROR_DIALOG);
1593         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1594         return false;
1595       }
1597       // Select database for Extensions
1598       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1600       // Test if we have the database selected correctly
1601       if(!$db){
1602         msg_dialog::display(_("Error"), msgPool::dbselect("GOfon", @mysql_error()), ERROR_DIALOG);
1603         new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1604         return false;
1605       }
1607       $SQL="";
1608       $SQL[]= "SET @@sql_mode = STRICT_ALL_TABLES;";
1610       $first_num = false;
1611       // Delete old entries
1612       foreach($this->a_old_telenums as $s_telenums){
1613         if(!$first_num){
1614           $first_num = $s_telenums;
1615         }
1616         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1617       }
1620       $query  = "SELECT id,name,callerid FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';";
1621       $rid    = mysql_query($query,$r_con);
1622       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1623       $result = mysql_fetch_assoc($rid);
1624       $callerid = $first_num;
1625       if($result){
1626         $callerid = $result['callerid'];
1627       }
1629       /* Set mode to strict
1630          Strict disallows the addition of entries that do not match the targets field length.
1631        */
1632       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$callerid."';";
1633       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1634       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1636       /* Start transaction, to be able to rollback
1637        */
1638       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Removing entry from server---</b>","");
1640       mysql_query("begin;",$r_con);
1641       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>begin;</b>","<i>Starting transaction!</i>");
1643       foreach($SQL as $query){
1644         @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>".$query."</b>", "");
1646         if(!mysql_query($query,$r_con)){
1647           $err = mysql_error($r_con);
1648           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"\n".$err, "<b>FAILED</b>");
1649           msg_dialog::display(_("Error"),
1650               msgPool::mysqlerror($err,__CLASS__)."&nbsp;".
1651               "\n<p>"._("Please activate debugging for details!")."</p>",
1652               ERROR_DIALOG);
1654           mysql_query("rollback;",$r_con);
1655           @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>rollback;</b>", "<b>ERROR</b> Rollback transaction!");
1656           @mysql_close($r_con);
1657           return(false);
1658         }
1659       }
1661       /* Let changes get active, everything was fine;
1662        */
1663       mysql_query("commit;",$r_con);
1664       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>commit;</b>", "");
1665       @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,"<b>---Transaction sucessful!---</b>", "");
1667     }else{
1668       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
1669       return false;
1670     }
1672     /* unset macro attr, it will cause an error */
1673     $tmp = array_flip($this->attributes);
1674     unset($tmp['macro']);
1675     $this->attributes=array_flip($tmp);
1677     /* Cancel if there's nothing to do here */
1678     if (!$this->initially_was_account){
1679       return;
1680     }
1682     plugin::remove_from_parent();
1684     /* Just keep one phone number */
1685     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1686       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1687     } else {
1688       $this->attrs['telephoneNumber']= array();
1689     }
1692     $ldap= $this->config->get_ldap_link();
1693     $ldap->cd($this->config->current['BASE']);
1694     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1695     while($attr = $ldap->fetch()){
1696       if(in_array($this->dn,$attr['member'])){
1697         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1698         unset($new->by_object['ogroup']->memberList[$this->dn]);
1699         unset($new->by_object['ogroup']->member[$this->dn]);
1700         $new->save();
1701         msg_dialog::display(_("Information"), sprintf(_("User '%s' has been removed from phone queue '%s'."), $this->cn, $new->by_object['ogroup']->cn), INFO_DIALOG);
1702       }
1703     }
1704     $ldap->cd($this->dn);
1705     $this->cleanup();
1706     $ldap->modify ($this->attrs); 
1708     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1709     if (!$ldap->success()){
1710       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
1711     }
1713     /* Optionally execute a command after we're done */
1714     @mysql_close($r_con);
1715     $this->handle_post_events('remove',array("uid"=> $this->uid));
1716   }
1720   /* This function checks if the given phonenumbers are available or already in use*/
1721   function is_number_used()
1722   {
1723     $ldap= $this->config->get_ldap_link();
1724     $ldap->cd($this->config->current['BASE']);
1725     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1726     while($attrs = $ldap->fetch()) {
1727       unset($attrs['telephoneNumber']['count']);
1728       foreach($attrs['telephoneNumber'] as $tele){
1729         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1730         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1731         $numbers[$tele]=$attrs;
1732       }
1733     }
1735     foreach($this->phoneNumbers as $num){
1736       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1737         if(isset($numbers[$num]['uid'][0])){
1738           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1739         }else{
1740           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1741         }
1742       }
1743     }
1744   }
1747   /* Create phoneAccount part of copy & paste dialog */
1748   function getCopyDialog()
1749   { 
1750     if(!$this->is_account) return("");
1751     $smarty = get_smarty();
1752     if (!count($this->phoneNumbers)){
1753       $smarty->assign ("phoneNumbers", array(""));
1754     } else {
1755       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1756     }
1758     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1759     $smarty->assign("goFonPIN",$this->goFonPIN);
1761     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1762     $ret =array();
1763     $ret['string'] = $display;
1764     $ret['status'] = "";
1765     return($ret);
1766   }
1768   /* Save posts from copy & paste dialog dialog  */
1769   function saveCopyDialog()
1770   {
1771     if(!$this->is_account) return;
1772     $this->execute();
1773     if(isset($_POST['goFonVoicemailPIN'])) {
1774       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1775     }
1776     if(isset($_POST['goFonPIN'])){
1777       $this->goFonPIN = $_POST['goFonPIN'];
1778     }
1779   }
1782   function allow_remove()
1783   {
1784     /* Check if previously selected server is still available */
1785     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1786       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1787     }
1788   }
1790   /* Return plugin informations for acl handling */
1791   static function plInfo()
1792   {
1793     return (array(
1794           "plShortName"     => _("Phone"),
1795           "plDescription"   => _("Phone account settings"),
1796           "plSelfModify"    => TRUE,
1797           "plDepends"       => array("user"),
1798           "plPriority"      => 7,                                 // Position in tabs
1799           "plSection"         => array("personal" => _("My account")),
1800           "plCategory"        => array("users"),
1803           "plOptions"       => array(),
1805           "plProvidedAcls"  => array(
1806             "telephoneNumber"     => _("Telephone number"),
1807             "goFonMacro"          => _("Macro settings"),
1808             "goFonHardware"       => _("Phone hardware"),
1809             "goFonHomeServer"     => _("Home server"),
1810             "goFonContext"          => _("Phone context"),
1811             "goFonVoiceMailContext" => _("Voice mail context"),
1812             "goFonPIN"            => _("Telephone pin"),
1813             "goFonVoicemailPIN"   => _("Voicemail pin"))
1814           ));
1815   }
1819   function multiple_execute()
1820   {
1821     plugin::multiple_execute();
1822     return($this->execute());
1823   }
1825   function get_multi_init_values()
1826   {
1827     $ret = plugin::get_multi_init_values();
1828     $ret['phoneNumbers'] = array();
1829     foreach($this->phoneNumbers as $number){
1830       $ret['phoneNumbers'][] = $number."  [".$this->attrs['cn'][0]."]"; 
1831     }
1832     $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1833     return($ret);
1834   }
1836   function init_multiple_support($attrs,$all)
1837   {
1838     plugin::init_multiple_support($attrs,$all);
1840     $this->phoneNumbers = array();
1841     if(isset($all['phoneNumbers'])){
1842       for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1843         $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1844       }
1845     }
1846   }
1848   function multiple_save_object()
1849   {
1850     /* Simply call parents save_object */
1851     if (isset($_POST["phoneTab"])){
1853       plugin::save_object();
1854       plugin::multiple_save_object();
1856       /* Every macro in the select box are available */
1857       if((isset($_POST['macro']))){
1858         $this->macrostillavailable=true;
1859       }
1861       if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1862         $this->macro = $_POST['macro'];
1863         $this->is_modified =true;
1864       }
1866       /* get all Postvars */
1867       if(isset($this->macroarray[$this->macro])){
1868         foreach($this->macroarray[$this->macro] as $key => $paras){
1869           $backup = $this->macroarray[$this->macro][$key];
1870           if(isset($_POST[$paras['var']])){
1871             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1872           }
1873           if(isset($_POST['post_success'])){
1874             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1875               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1876                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1877               }else{
1878                 $this->macroarray[$this->macro][$key]['choosen']=false;
1879               }
1880             }
1881           }
1882         }
1883         if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1884           $this->is_modified = TRUE;
1885         }
1886       }
1887     }
1888   }
1890   function multiple_check()
1891   {
1892     $message = plugin::multiple_check();
1894     if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1895       $message[] = _("There is currently no asterisk server defined!");
1896     }
1898     if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1899       $message[] = _("Asterisk server is invalid!");
1900     }
1902     if(in_array("goFonVoicemailPIN",$this->multi_boxes) && 
1903         ( (strlen($this->goFonVoicemailPIN)==0)||
1904           (strlen($this->goFonVoicemailPIN)>4))){
1905       $message[]=(_("Voicemail PIN must be 4 characters long!"));
1906     }else{
1907       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1908         $message[]=(_("Voicemail PIN contains invalid characters!"));
1909       }
1910     }
1912     if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1913       $message[]=(_("Phone pin contains invalid characters!"));
1914     }
1916     /* check for ! in any parameter setting*/
1917     if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1918       foreach($this->macroarray[$this->macro] as $val){
1919         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1920           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1921         }
1922       }
1923     }
1925     return($message);
1926   }
1928   function get_multi_edit_values()
1929   {
1930     $ret = plugin::get_multi_edit_values();
1931     if(in_array("macro",$this->multi_boxes)){
1932       $ret['macro'] = $this->macro;
1933       $ret['macroarray'] = $this->macroarray;
1934       $ret['macros'] = $this->macros;
1935     }
1936     return($ret);
1937   }
1940   /* Return asterisk contexts
1941    * Additionaly read contexts from file.
1942    */
1943   function get_asterisk_voicemail_contexts()
1944   {
1945     return($this->get_asterisk_contexts(CONFIG_DIR."/asterisk/voicemail_context.conf"));
1946   }
1947   function get_asterisk_sip_contexts()
1948   {
1949     return($this->get_asterisk_contexts(CONFIG_DIR."/asterisk/sip_context.conf"));
1950   }
1951   function get_asterisk_contexts($file)
1952   {
1953     $contexts = array();
1954     if(file_exists($file) && is_readable($file)){
1955       foreach(file($file) as $context){
1956         $contexts[] = trim($context);
1957       }
1958     }else{
1959       msg_dialog::display(_("Warning"), msgPool::cannotReadFile($file),WARNING_DIALOG);
1960       $contexts[] = "default";
1961     }
1962     array_unique($contexts);
1963     return($contexts);
1964   }
1967 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1968 ?>