Code

Added remove multiple entries to macro list
[gosa.git] / plugins / gofon / phoneaccount / class_phoneAccount.inc
1 <?php
3 class phoneAccount extends plugin
4 {
5   /* Definitions */
6   var $plHeadline= "Phone";
7   var $plDescription= "This does something";
8   var $has_mailAccount= FALSE;
10   /* Attributes */
11   var $telephoneNumber        = array();
12   var $goFonHardware          = "automatic";
13   var $goFonFormat            = "wav";
14   var $goFonPIN               = "";
15   var $goFonVoicemailPIN      = "";
16   var $goFonDeliveryMode      = "";
17   var $phoneNumbers           = array();
18   var $mail                   = "";
19   var $hardware_list          = array();
20   var $used_hardware          = array();
21   var $goFonMacro             = "";
22   var $macro                  = 0;              // Selected Macroi
23   var $lastmacro              = "";
24   var $macros                 = array();        // List of macros for smarty select box
25   var $macroarray             = array();        // All needed macro informations
26   var $macrostillavailable    = false;
27   var $generate_error         = "";
28   var $a_old_telenums         = array();
29   var $goFonPINVoice          = "";
30   var $goFonHomeServer        = "0";            // Contains the dn of the server that manage this account 
31   var $init_HomeServer        = "0";            // Contains the dn of the server that manage this account 
32   var $goFonHomeServers       = array();        // Contains all available server configurations 
34   /* CLI vars */
35   var $cli_summary            = "Manage users phone account";
36   var $cli_description        = "Some longer text\nfor help";
37   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
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","cn","goFonHomeServer",
44       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
45   var $objectclasses= array("goFonAccount");
47   var $uid;
49   function phoneAccount ($config, $dn= NULL, $parent= NULL)
50   {
51     plugin::plugin ($config, $dn, $parent);
53     /* Assemble phone numbers */
54     if (isset($this->attrs['telephoneNumber'])){
55       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
56         $number= $this->attrs['telephoneNumber'][$i];
57         $this->phoneNumbers[$number]= $number;
58       }
59     }
61     /* Set up has_mailAccount */
62     if (isset($this->attrs['objectClass'])){
63       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
64         $this->has_mailAccount= TRUE;
65       }
66     }
68     /* Set uid */
69     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
70       $this->uid = $this->parent->by_object['user']->uid;
71     }
72     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
73       $this->cn  = $this->parent->by_object['user']->cn;
74     }
76     /* Check server configurations 
77      * Load all server configuration in $this->goFonHomeServers if available
78      *  and first server as default if necessary.
79      * Check if connection is successfull for the selected server $this->goFonHomeServer
80      */
82   
83     /* Set available server */
84     if(isset($_SESSION['config']->data['SERVERS']['FON'])){
85       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
86     }
88     $a_SETUP= array();
89     if($this->is_account &&
90        array_key_exists('config',$_SESSION) &&
91        array_key_exists('SERVERS',$_SESSION['config']->data) &&
92        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
93        is_callable("mysql_connect")
94        ) {
96       /* Servers defined? Watch here... */
97       if (count($this->goFonHomeServers)){
99         /* Set default server */
100         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
101           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
102         }
104         /* Remember inital home server, to be able to remove old entries */
105         $this->init_HomeServer = $this->goFonHomeServer;
107         /* Get config */
108         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
109           print_red(sprintf(_("The specified goFonHomeServer '%s' is not available in GOsa server configuration. Saving this account will create a new entry on the server '%s'. Use cancel if you do not want to create a new entry ignoring old accounts."),$this->goFonHomeServer, $this->goFonHomeServers[0]['DN']));
111           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
112           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
113         }    
114         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
116         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
117         if(!$r_con){
118           print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
119                 $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
120           gosa_log(mysql_error());
121         }
122         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
123         if(!$db){
124           print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
125           gosa_log(mysql_error());
126         }
128         $first = false; 
129         foreach($this->phoneNumbers as $key => $val){
130           if(!$first){
131             $first = $key;
132           }
133         }
134       }
135     }
137     /* Get available phone hardware  
138      * Search for all available phone hardware  
139      */
140     $ldap= $this->config->get_ldap_link();
141     $ldap->cd($this->config->current['BASE']);
142     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
143     while ($attrs= $ldap->fetch()){
144       $cn= $attrs['cn'][0];
145       if (isset($attrs['description'])){
146         $description= " - ".$attrs['description'][0];
147       } else {
148         $description= "";
149       }
150       $this->hardware_list[$cn]= "$cn$description";
151     }
154     /* Get available Macros  
155      * Search for all Marcos that are visible and create 
156      *  an array with name and parameters 
157      */
158     $ldap->search("(&(objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
160     /* Add none for no macro*/
161     $this->macros['none']=_("no macro");    
162     $this->macro ="none";
164     /* Fetch all Macros*/
165     while ($attrs= $ldap->fetch()){
167       /* unset Count, we don't need that here */
168       unset($attrs['displayName']['count']);
170       /* Parse macro data, unset count for parameterarrays  */
171       if (isset($attrs['goFonMacroParameter']['count'])){
172         unset($attrs['goFonMacroParameter']['count']);
173       }
175       /* fill Selectfield variable with Macros */
176       if(isset($attrs['displayName'][0])){
177         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
178       }else{
179         $this->macros[$attrs['dn']] = _("undefined");
180       }
182       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
183       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
185         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
186           /* Split Data in readable values, by delimiter !  */
187           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
189           /* Set all attrs */
190           $id = $data[0];
191           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
192           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
193           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
194           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
195           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
196           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
197           if($data[2] == "bool"){
198             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
199           }
200         }//foreach
201       }//is_array
202     }//while
205     /* Parse used Macro  
206      * If we have a macro selected, parse it and set values 
207      *  in $this->macroarray[$this->macro]. 
208      */
209     $tmp = split("!",$this->goFonMacro);
210     if(is_array($tmp)){
212       /* First value is the macroname */
213       $this->macro = $tmp[0];
215       /* Macroname saved, delete that index */
216       unset($tmp[0]);
218       /* Check if makro has been removed */
219       if(!isset($this->macros[$this->macro])){
220         $this->macrostillavailable = false;
221       }else{
222         $this->macrostillavailable = true;
223       }
225       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
226       foreach($tmp as $var){
228         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
229         $varar = split("#",$var);
231         /* Only insert if the parameter still exists */
232         if(isset($this->macroarray[$this->macro][$varar[0]])){
233           /* Assign value */
234           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
235         }
236       }
237     }
240     /* Colorize phones 
241      * Used phones will be colored in grey, 
242      *  so we must detect which phones are currently in use.
243      */
244     $ldap->cd($this->config->current['BASE']);
245     foreach ($this->hardware_list as $cn => $desc){
246       $ldap->search("(goFonHardware=$cn)", array('cn'));
247       if ($ldap->count() > 0){
248         $ldap->fetch();
249         if ($ldap->getDN() != $this->dn){
250           $this->used_hardware[$cn]= $ldap->getDN();
251         }
252       }
253     }
254     $this->hardware_list["automatic"]= _("automatic");
255     ksort($this->hardware_list);
256     $this->a_old_telenums = $this->phoneNumbers;
258     if($this->is_account){
259       $this->is_modified = true;
260     }
263     /* Get voicemail PIN from MySQL DB 
264      * Because every user can change his PIN directly from the phone
265      *  without any update to the ldap
266      * This means, the PIN in the DB is up to date
267      */
268     // Connect to DB server
269     if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
270       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
271       if($r_con){
272         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
273         $vp = mysql_fetch_row(mysql_query("SELECT ".$cur_cfg['VOICE_TABLE'].".password FROM  ".$cur_cfg['VOICE_TABLE'].", ".$cur_cfg['SIP_TABLE']."  WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'"));
275         if((isset($vp[0]))&&(!empty($vp[0]))){
276           $this->goFonPINVoice = $vp[0];
277         }
278       }
279     }
280     $this->lastmacro=$this->macro;
282     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
283       @mysql_close($r_con) ;
284     }
285   }
288   /* This function generates the Database entries. 
289    * The Parameter 'save' could be true or false.
290    *  false - means only testing no database transactions.
291    *  true  - write database entries.
292    *
293    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
294    * 
295    * If the phone hardware is 'automatic' the table entries will only be removed
296    *  and not added. 
297    */
298   function generate_mysql_entension_entries($save = false)
299   {
300     /* Check if there is at least one server available 
301      * If not, return and tell the user that saving failed 
302      */
303     if(!count($this->goFonHomeServers)){
304       if($save){
305         print_red(_("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer). Your settings can't be saved to asterisk database."));
306       }
307       return(true);
308     }
310     /* Check if Mysql extension is available */
311     if(!is_callable("mysql_pconnect")){
312       if($save)
313       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
314       return(true);
315     }
316  
317     /********************** 
318      * Attribute Initialisation
319      **********************/
321     $old_connection = false;
323     // Get Configuration for Mysql database Server
324     $s_parameter    = "";                                           // Contains paramter for selected Macro 
325     $r_con          = false;                                        // DB connection
326     $r_db           = false;                                        // Selected DB
327     $r_res          = false;                                        // Result resource
328     $a_ldap_attrs   = array();                                      //  
330     $s_ip           = NULL;                   // Contains ip for Sip entry
331     $s_host         = NULL;                   // Contains host for Sip entry
332     $s_qualify      = "yes";                  // Qualify entry
333     $s_pin          = NULL;                   // Entry for secret
334     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
336     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
337     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
338     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
340     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
341     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
343     $s_sip_key      = "";     // Key for SIP entry index      
344     $s_sip_val      = "";     // Value for SIP entry index      
346     $b_first_deleted= false;  // Only delete first entry, 
347     $s_telenums     = "";     // for each value variable
349     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
351     restore_error_handler();
353     /* Prepare some basic attributes */
354     foreach($this->a_old_telenums as $tele){
355       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
356     }
357     foreach($this->phoneNumbers as $tele){
358       $newnums[]= preg_replace("/[^0-9]/","",$tele);
359     }
361     /* If deletion starts from userslist, cn uid are not set */
362     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
363       $this->uid = $this->parent->by_object['user']->uid;
364     }
365     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
366       $this->cn  = $this->parent->by_object['user']->cn;
367     }
368     /* Create voicemail entry 
369      */
370     if((!isset($this->cn))||(empty($this->cn))){
371       $CNname= $this->uid;
372     }else{
373       $CNname= $this->cn;
374     }
376     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
377       $s_mail = $this->parent->by_object['mailAccount']->mail;
378     }else{
379       $s_mail = "";
380     }
381     /* Get phonehardware to setup sip entry  */
382     $ldap         = $this->config->get_ldap_link();
383     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
384     $a_ldap_attrs = $ldap->fetch();
386     /* Check selected phone hardware, is a default IP set? */
387     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
388       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
389       $s_host     = $s_ip;
390     }else{
391       $s_ip       = NULL;
392       $s_host     = "dynamic";
393     }
395     // Attribute GoFonQualify set ?
396     if(isset($a_ldap_attrs['goFonQualify'])){
397       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
398     }
400     // Attribute GoFonPIN set ?
401     if(isset($this->goFonPIN)){
402       $s_pin      = $this->goFonPIN;
403     }
405     // Attribute GoFonType set ?
406     if(isset($a_ldap_attrs['goFonType'])){
407       $s_type = $a_ldap_attrs['goFonType'][0];
408     }
410     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
411       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
412     }else{
413       $sip_data_array['dtmfmode']     ="rfc2833";
414     }
416     /* Check if phone number is used */
417     if($this->is_number_used()){
418       $this->generate_error = $this->is_number_used(); 
419       return false;
420     }
424     /********************** 
425      * Check Server Connection Information
426      **********************/
427  
428     /* Create Mysql handle for the current goFonHomeServer, if possible  
429      * Get configuration to old asterisk home server 
430      */ 
431     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
432     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
433     if(!$new_connection){
434       $this->generate_error = sprintf(
435           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
436           $a_New['SERVER'],$a_New['LOGIN']);
437       gosa_log(@mysql_error($new_connection));
438       return false;
439     }
440     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
441     if(!$new_database){
442       $this->generate_error = sprintf(
443           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
444           $a_New['DB'],$a_New['SERVER']);
445       gosa_log( @mysql_error($new_connection));
446       return false;
447     }
449     /* If the home server has changed, we must remove entries from old 
450      *  server and add new entries in new server.  
451      */
452     if($this->init_HomeServer != $this->goFonHomeServer){
453     
454       /* Get configuration to old asterisk home server */ 
455       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
456  
457       /* Create connection to the database that contains the old entry. 
458        */
459       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
460       if(!$old_connection){
461         $this->generate_error = sprintf(
462             _("The old MySQL home server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
463             $a_Remove['SERVER'],$a_Remove['LOGIN']);
464         gosa_log(@mysql_error($old_connection));
465         return false;
466       }
467       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
468       if(!$old_database){
469         $this->generate_error = sprintf(
470             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
471             $a_Remove['DB'],$a_Remove['SERVER']);
472         gosa_log(@mysql_error($old_connection));
473         return false;
474       }
475     }
477     /* Save means that we must save changes, not only test  */
478     if($save == true){
479     
480       /********************** 
481        * Remove entries from old home server 
482        **********************/
484       /* Check if there is an old entry 
485        * If there is en old entry, get callerid and remove voicemail and extensions too 
486        */
487       if($old_connection){
488         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
489         $rid    = mysql_query($query,$old_connection);
491         /* Old entry found, remove it */
492         $query_a = array();
493         if(mysql_affected_rows($old_connection)){
494           $result = mysql_fetch_assoc($rid);
495           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
496           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
497           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
498           foreach($oldnums as $s_telenums) {
499             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
500           }
502           foreach($query_a as $qry){
503             if(!mysql_query($qry,$old_connection)){
504               echo $qry;
505               echo mysql_error($old_connection);
506             } 
507           }
508         }
509       }
511       /********************** 
512        * Update / Insert sip_users entry  
513        **********************/
515       /* Set the first given phone number as callerid */
516       reset($newnums);        
517       $i_new_key = key($newnums);
518       $sip_data_array['callerid']  =$newnums[$i_new_key];
519       $sip_data_array['mailbox']   =$newnums[$i_new_key];
521       /* Check if there is already an entry in sip_users for this uid */
522       $SQL_query_array = array();
523       $rid = mysql_query("SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n",$new_connection);
524       if(mysql_affected_rows($new_connection)){
526         /********************** 
527          * Update sip_users entry 
528          **********************/
529         $result                     = mysql_fetch_assoc($rid);
530         $sip_data_array['host']         = $s_host;
531         $sip_data_array['qualify']      = $s_qualify;
532         $sip_data_array['secret']       = $this->goFonPIN;
533         $sip_data_array['type']         = $s_type ;
534         $sip_data_array['username']     = $this->uid;
535         $sip_data_array['ipaddr']       = $s_ip;
537         /* Remove not changed attributes, to avoid updating table with same values */
538         foreach($sip_data_array as $name => $value){
539           if($result[$name] == $value){
540             unset($sip_data_array[$name]);
541           }
542         }
543         /* Only update entry if there is something to uopdate */
544         if(count($sip_data_array)){
545           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
546           foreach($sip_data_array as $key => $val){
547             $query.= "".$key."='".$val."',"; 
548           } 
549           $query = preg_replace("/,$/","",$query);
550           $query.= " WHERE name='".$this->uid."';";
551           $SQL_query_array[] = $query;
552         }
553       } else {
554  
555         /********************** 
556          * Insert sip_users entry 
557          **********************/
558         //generate SIP entry
559         $sip_data_array['id']           = "";
560         $sip_data_array['name']         = $this->uid;
561         $sip_data_array['accountcode']  = NULL;          
562         $sip_data_array['amaflags']     = NULL;
563         $sip_data_array['callgroup']    = NULL;
564         $sip_data_array['canreinvite']  = "no";
565         $sip_data_array['context']      = "default";
566         $sip_data_array['defaultip']    = NULL;
567         $sip_data_array['fromuser']     = NULL;
568         $sip_data_array['fromdomain']   = NULL;
569         $sip_data_array['host']         = $s_host;
570         $sip_data_array['insecure']     = NULL;
571         $sip_data_array['language']     = NULL;
572         $sip_data_array['mailbox']      = $newnums[$i_new_key];
573         $sip_data_array['md5secret']    = NULL;
574         $sip_data_array['nat']          = "no";
575         $sip_data_array['permit']       = NULL;
576         $sip_data_array['deny']         = NULL;
577         $sip_data_array['mask']         = NULL;
578         $sip_data_array['pickupgroup']  = NULL;
579         $sip_data_array['port']         = NULL;
580         $sip_data_array['qualify']      = $s_qualify;
581         $sip_data_array['restrictcid']  = "n";
582         $sip_data_array['rtptimeout']   = NULL;
583         $sip_data_array['rtpholdtimeout']=NULL;
584         $sip_data_array['secret']       = $this->goFonPIN;
585         $sip_data_array['type']         = $s_type ;
586         $sip_data_array['username']     = $this->uid;
587         $sip_data_array['disallow']     = NULL;
588         $sip_data_array['allow']        = NULL;
589         $sip_data_array['musiconhold']  = NULL;
590         $sip_data_array['regseconds']   = NULL;
591         $sip_data_array['ipaddr']       = $s_ip;
592         $sip_data_array['regexten']     = NULL;
593         $sip_data_array['cancallforward']=NULL;
595         /* There is currently no entry for this user in the sip_users table. 
596          * We should create one i
597          */
598         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
599           if($s_sip_val == NULL) continue;
600           $s_sip_values.="'".$s_sip_val."',";
601           $s_sip_keys  .="`".$s_sip_key."`,";
602         }
603         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
604         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
606         /* Add sip entries to mysql queries */
607         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
608       }
611       /********************** 
612        * Update / Insert Voice mail entry  
613        **********************/
615       $customer_id = $newnums[$i_new_key];
617       $voice_data_array = array(
618           "customer_id" => $customer_id,
619           "mailbox"     => $customer_id,
620           "password"    => $this->goFonVoicemailPIN,
621           "fullname"    => $CNname,
622           "email"       => $s_mail);
624       /* Set pager number if available */
625       if(isset($this->parent->by_object['user']->pager)){
626         $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
627       }
629       /* Check if there is already an entry in sip_users for this uid */
630       $rid = mysql_query("SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n",$new_connection);
631       if(mysql_affected_rows($new_connection)){
633         /********************** 
634          * Update Voice mail entry  
635          **********************/
636         $result = mysql_fetch_assoc($rid)  ;
638         foreach($voice_data_array as $name => $value){
639           if($result[$name] == $value){
640             unset($voice_data_array[$name]);
641           }
642         }
644         /* Only update entry if there is something to uopdate */
645         if(count($voice_data_array)){
646           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
647           foreach($voice_data_array as $key => $val){
648             $query.= "".$key."='".$val."',"; 
649           } 
650           $query = preg_replace("/,$/","",$query);
651           $query.= " WHERE customer_id='".$customer_id."';";
652           $SQL_query_array[] = $query;
653         }
654       }else{
656         /********************** 
657          * Insert Voice mail entry  
658          **********************/
659         $voice_data_array['context'] = "default";
660   
661         /* There is currently no voice mail entry for this user. 
662          * We should create one 
663          */
664         $s_voi_values = $s_voi_keys = "";
665         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
666           if($s_voi_val == NULL) continue;
667           $s_voi_values.="'".$s_voi_val."',";
668           $s_voi_keys  .="`".$s_voi_key."`,";
669         }
670         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
671         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
673         /* Add sip entries to mysql queries */
674         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
675       }
677      
678       /********************** 
679        * Remove/Insert extension entries
680        **********************/
681       
682       /* Remove old entries */
683       $query = array();
684       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
685       foreach($newnums as $s_telenums){
686         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
687       }
688       foreach($query as $qry){
689         if(!mysql_query($qry,$new_connection)){
690           echo mysql_error($new_connection);
691         } 
692       }
693  
694       /********************** 
695        * Insert extension entries
696        **********************/
697  
698       // Get selected Macro Parameter and create parameter entry 
699       if(isset($this->macroarray[$this->macro])){
700         foreach($this->macroarray[$this->macro] as $key => $val ){
701           $s_parameter .= $val['choosen']."|";
702         }
703         $s_parameter = preg_replace("/\|$/","",$s_parameter);
704       }
705      
706       $i = 0; 
707       $EXT = array();
708       if(!is_numeric($this->uid)){
709         $EXT[$i]['context'] = 'GOsa';
710         $EXT[$i]['exten']   = $this->uid;
711         $EXT[$i]['priority']= 1;
712         $EXT[$i]['app']     = "Goto";
713         $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
714         $i ++;
715       }
717       // Entension entries  Hint / Dial / Goto
718       foreach($newnums as $s_telenums){
720         /* Hint Entry */
721         $EXT[$i]['context'] = 'GOsa';
722         $EXT[$i]['exten']   = $s_telenums;
723         $EXT[$i]['priority']= "Hint";
724         $EXT[$i]['app']     = 'SIP/'.$this->uid;
725         $i ++;  
726         /* SetCID */
727         //$EXT[$i]['context'] = 'GOsa';
728         //$EXT[$i]['exten']   = $s_telenums;
729         //$EXT[$i]['priority']= 1;
730         //$EXT[$i]['app']     = "SetCIDName";
731         //$EXT[$i]['appdata'] = $CNname;
732         //$i ++;  
734         // If no macro is selected use Dial
735         if($this->macro!="none"){ 
736           $macroname = preg_replace("/,.*$/","",$this->macro);        
737           $macroname = preg_replace("/^.*=/","",$macroname);        
738           $s_app = "Macro";$macroname;
739           $s_par = $macroname."|".$s_parameter; 
740         }else{
741           $s_app = "Dial";
742           $s_par = 'SIP/'.$this->uid."|20|r";
743         }
745         $EXT[$i]['context'] = 'GOsa';
746         $EXT[$i]['exten']   = $s_telenums;
747         $EXT[$i]['priority']= 1;
748         $EXT[$i]['app']     = $s_app;
749         $EXT[$i]['appdata'] = $s_par;
750         $i ++;
751       }
753       // Append all these Entries 
754       foreach($EXT as $entr){
755         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
756         foreach($entr as $key2 => $val2){
757           $SQL_syn.= "`".$key2."`,";
758         }
759         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
760         $SQL_syn .= ") VALUES ("; 
761         foreach($entr as $key2 => $val2){
762           $SQL_syn .= "'".$val2."',";
763         }
764         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
765         $SQL_syn .=");\n";
767         $SQL_query_array[] =$SQL_syn;
768         $SQL_syn ="";
769       }
771       // Perform queries ...
772       if($this->goFonHardware != "automatic"){
773         foreach($SQL_query_array as $query){
774           if(!@mysql_query($query,$new_connection)){
775             print_red(_("Error while performing query:")." ".mysql_error());
776             return false;
777           }
778         }
779       }
780     }
781     @mysql_close($new_connection);
782     return true;
783   }
786   function execute()
787   {
788     /* Call parent execute */
789     plugin::execute();
791     $display = "";
793     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
795     if(empty($this->macro)&&(!empty($this->goFonMacro))){
797       /* Go through already saved values, for a parameter */
798       $tmp = split("!",$this->goFonMacro);
800       /* it is possible that nothing has been saved yet */
801       if(is_array($tmp)){
803         /* First value is the macroname */
804         $this->macro = $tmp[0];
806         /* Macroname saved, delete that index */
807         unset($tmp[0]);
809         /* Check if macro has been removed */
810         if(!isset($this->macroarray[$this->macro])){
811           $this->macrostillavailable = false;
812         }else{
813           $this->macrostillavailable = true;
814         }
816         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
817         foreach($tmp as $var){
819           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
820           $varar = split("#",$var);
822           /* Only insert if the parameter still exists */
823           if(isset($this->macroarray[$this->macro][$varar[0]])){
824             /* Assign value */
825             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
826           }
827         }
828       }
829     }
830     
831     /* Do we represent a valid account? */
832     if (!$this->is_account && $this->parent == NULL){
833       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
834         _("This account has no phone extensions.")."</b>";
835       $display.= back_to_main();
836       return ($display);
837     }
839     /* Do we need to flip is_account state? */
840     if (isset($_POST['modify_state'])){
841       $this->is_account= !$this->is_account;
842     }
844     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
845     if(empty($this->macro)){
846       $this->macro ="none";
847     }
849     /* Prepare templating */
850     $smarty= get_smarty();
852     /* tell user that the selected plugin is no longer available */
853     if((!$this->macrostillavailable)&&($this->macro!="none")){
854       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
855     }
857     /* Assing macroselectbox values  */
858     $smarty->assign("macros",$this->macros);   
859     $smarty->assign("macro", $this->macro);   
861     /* check if there is a FON server created */
862     if(!count($this->goFonHomeServer)){
863       print_red(_("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer). Your settings can't be saved to asterisk database."));
864     }
866     /* Create html parameter table for selected macro parameters 
867      *  skip if no parameters given 
868      */
869     if(!isset($this->macroarray[$this->macro])){
870       $macrotab="";
871     }else{
873       $macrotab ="<table summary=\""._("Parameter")."\">";
874       /* for every single parameter-> display textfile,combo, or true false switch*/
876       foreach($this->phoneNumbers as $phonenum){
877         $tmp[] = $phonenum;
878       }
879     
880       if($this->macro != $this->lastmacro){
881         /* Go through all params */
882         foreach($this->macroarray[$this->macro] as $key => $paras){
884           $string = $paras['default'];
886           $string=preg_replace("/%uid/i",$this->uid,$string);
888           if(isset($this->cn)){
889             $string=preg_replace("/%cn/i",$this->cn,$string);
890           }
892           for($i = 0 ; $i < 10; $i++){
893             if(isset($tmp[$i])){
894               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
895             }
896           }
897           if(isset($tmp[0])){
898             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
899           }
900           $this->macroarray[$this->macro][$key]['choosen']=$string;
901         }
902       }
904       foreach($this->macroarray[$this->macro] as $paras){
906         /* get al vars */
907         $var        = $paras['var'];           
908         $name       = $paras['name'];           
909         $default    = $paras['default'];
910         $type       = $paras['type'];
911         $choosen    = $paras['choosen'] ; 
912         $str        = $default;
914         $dis = "";
915         if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
916           $dis = " disabled ";
917         }
919         /* in case of a combo box display a combobox with selected attr */
920         $macrotab.= "<tr>";
921         switch ($type){
923           case "combo":
924             $str= "<select name='".$var."' ".$dis." >";
925           foreach(split(":",$default) as $choice){
926             if($choosen==$choice){
927               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
928             }else{
929               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
930             }
931           }
932           $str.="</select>";
933           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
934           break;
936           case "bool":
937             if(!$choosen){
938               $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
939             }else{
940               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".$dis.">";
941             }
942           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
943           break;
945           case "string":
946             $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
947           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
948           break;
950         }
951         $macrotab.= "</td></tr>";
953       }
954       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
955     }//is_array()
957     /* Give smarty the table */
958     $smarty->assign("macrotab",$macrotab);
961     /* Do we represent a valid account? */
962     if (!$this->is_account && $this->parent == NULL){
963       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
964         _("This account has no phone extensions.")."</b>";
965       $display.= back_to_main();
966       return($display);
967     }
969     $display= "";
970  /* Show tab dialog headers */
971     if ($this->parent != NULL){
972       if ($this->is_account){
973         $display= $this->show_disable_header(_("Remove phone account"),
974             _("This account has phone features enabled. You can disable them by clicking below."));
975       } else {
976         if(empty($this->uid)){
977           $display= $this->show_enable_header(_("Create phone account"),
978               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
979         }else{
980           $display= $this->show_enable_header(_("Create phone account"),
981               _("This account has phone features disabled. You can enable them by clicking below."));
982         }
983         return ($display);
984       }
985     }
987     /* Add phone number */
988     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
989       if (is_phone_nr($_POST['phonenumber'])){
990         $number= $_POST["phonenumber"];
991         $this->phoneNumbers[$number]= $number;
992         $this->is_modified= TRUE;
993       } else {
994         print_red(_("Please enter a valid phone number!"));
995       }
996     }
998     /* Remove phone number */
999     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1000       foreach ($_POST['phonenumber_list'] as $number){
1001         unset($this->phoneNumbers[$number]);
1002         $this->is_modified= TRUE;
1003       }
1004     }
1006     /* Assign acls */
1007     $tmp = $this->plInfo();
1008     foreach($tmp['plProvidedAcls'] as $name => $translation){
1009       $smarty->assign($name."ACL",$this->getacl($name));
1010     }
1012     /* Transfer ACL's */
1013     foreach($this->attributes as $val){
1014       if(isset($this->$val)){
1015         $smarty->assign($val,$this->$val);
1016       }else{
1017         $smarty->assign($val,"");
1018       }
1019     }
1021     /* Create home server array */
1022     $tmp = array();
1023     foreach($this->goFonHomeServers as $dn => $attrs){
1024       if(!is_numeric($dn)){
1025         $tmp[$dn] = $attrs['SERVER'];
1026       }
1027     }
1028     $smarty->assign("goFonHomeServers",$tmp);
1030     /* Fill arrays */
1031     $smarty->assign ("goFonHardware", $this->goFonHardware);
1032     if (!count($this->phoneNumbers)){
1033       $smarty->assign ("phoneNumbers", array());
1034     } else {
1035       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1036     }
1038     $dis = "";
1039     if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1040       $dis= " disabled ";
1041     }
1042     $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1043        _("Choose your private phone")."\">\n";
1045     foreach ($this->hardware_list as $cn => $description){
1046       if ($cn == $this->goFonHardware){
1047         $selected= "selected";
1048       } else {
1049         $selected= "";
1050       }
1051       if (isset($this->used_hardware[$cn])){
1052         $color= "style=\"color:#A0A0A0\"";
1053       } else {
1054         $color= "";
1055       }
1056       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1057     }
1058     $hl.= "</select>\n";
1059     $smarty->assign ("hardware_list", $hl);
1061     /* Show main page */
1062     $this->lastmacro = $this->macro;
1063     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1064     return($display);
1065   }
1068   function save_object()
1069   {
1070     $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
1071     if (isset($_POST["phoneTab"])){
1072       plugin::save_object();
1074       /* Save checkbox */
1075       $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1076       if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1077         if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1078           $tmp .= "M";
1079         }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1080           $tmp  = preg_replace ("/M/","",$tmp);
1081         }
1082       }
1083       $this->goFonDeliveryMode= "[".$tmp."]";
1086       /* Every macro in the select box are available */
1087       if((isset($_POST['macro']))){
1088         $this->macrostillavailable=true;
1089       }
1091       if(is_array($this->phoneNumbers)){
1092         foreach($this->phoneNumbers as $telenumms) {
1093           $nummsinorder[]=$telenumms; 
1094         }
1095       }else{
1096         $nummsinorder=array("");
1097       }
1100       /* get all Postvars */
1101       if(isset($this->macroarray[$this->macro])){
1102         if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1103           foreach($this->macroarray[$this->macro] as $key => $paras){
1104             if(isset($_POST[$paras['var']])){
1105               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1106             }
1108             /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1109                We need this code below to read and save checkboxes correct
1110              */
1112             if(isset($_POST['post_success'])){
1113               if($this->macroarray[$this->macro][$key]['type']=="bool"){
1114                 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1115                   $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1116                 }else{
1117                   $this->macroarray[$this->macro][$key]['choosen']=false;
1118                 }
1119               }
1120             }
1121           }
1122         }
1123       }
1124     }
1125   }
1127   function check()
1128   {
1129     /* Call common method to give check the hook */
1130     $message= plugin::check();
1132     if(!count($this->goFonHomeServers)){
1133       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1134     }
1136     if(empty($this->goFonHomeServer)){
1137       $message[] = _("Please select a valid goFonHomeServer.");
1138     }
1140     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1141       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1142     }else{
1143       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1144         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1145       }
1146     }
1148     if((strlen($this->goFonPIN)<=0)){
1149       $message[]=(_("Phone PIN must be at least one character long."));
1150     }else{
1151       if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1152         $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1153       }
1154     }
1156     if(!$this->generate_mysql_entension_entries()){
1157       $message[] = $this->generate_error;
1158     }
1160     /* We need at least one phone number */
1161     if (count($this->phoneNumbers) == 0){
1162       $message[]= sprintf(_("You need to specify at least one phone number!"));
1163     }
1165     /* check for ! in any parameter setting*/
1166     if(isset($this->macroarray[$this->macro])){
1167       foreach($this->macroarray[$this->macro] as $val){
1168         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1169           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1170         }
1171       }
1172     }
1173     return ($message);
1174   }
1178   function save()
1179   {
1180     plugin::save();
1182     /* Force saving macro again 
1183      * This ensures that 
1184      *  - the macro is available on the destiantion server.
1185      *  - the macro saved is up to date on the destination server.
1186      */
1187     if(!empty($this->macro) && $this->macro != "none")  {
1188       $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1189       $macro_tab -> save();
1190     }
1192     /* Save arrays */
1193     $tmp_numbers = array();
1194     foreach ($this->phoneNumbers as $number){
1195       $tmp_numbers[] = $number;
1196     }
1198     /* Save settings, or remove goFonMacro attribute*/
1199     if($this->macro!="none"){    
1200       $this->attrs['goFonMacro']=$this->macro;
1201       if(isset($this->macroarray[$this->macro])){
1202         foreach($this->macroarray[$this->macro] as $paras)  {
1203           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1204         }
1205       }
1206     }else{
1207       $this->attrs['goFonMacro']=array();
1208     }
1209     unset($this->attrs['macro'])  ;
1211     $this->attrs['goFonForwarding']=array();
1213     $str = $this->generate_mysql_entension_entries(true);
1214     if(empty($str)){
1215       print_red($str);
1216     }
1218     if($this->attrs['goFonMacro']==""){
1219       $this->attrs['goFonMacro']=array();
1220     }
1222     unset($this->attrs['cn']);
1224     /* Write back to ldap */
1225     $ldap= $this->config->get_ldap_link();
1226     $ldap->cd($this->dn);
1227     $this->cleanup();
1228     
1229     /* Force saving numbers, else it will be overwriten by user account. */
1230     $this->attrs['telephoneNumber'] =$tmp_numbers;
1231     $ldap->modify ($this->attrs); 
1233     show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/phone account with dn '%s' failed."),$this->dn));
1235     /* Optionally execute a command after we're done */
1237     if ($this->initially_was_account == $this->is_account){
1238       if ($this->is_modified){
1239         $this->handle_post_events("modify",array("uid" => $this->uid));
1240       }
1241     } else {
1242       $this->handle_post_events("add",array("uid" => $this->uid));
1243     }
1245   }
1248   function adapt_from_template($dn)
1249   {
1250     plugin::adapt_from_template($dn);
1252     /* Assemble phone numbers */
1253     if (isset($this->attrs['telephoneNumber'])){
1254       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1255         $number= $this->attrs['telephoneNumber'][$i];
1256         $this->phoneNumbers[$number]= $number;
1257       }
1258     }
1259   }
1262   function remove_from_parent()
1263   {
1264     if(!$this->initially_was_account) return;
1266     foreach($this->attributes as $key=>$val){
1267       if(in_array($val,array("uid","cn"))){
1268         unset($this->attributes[$key]);
1269         unset($this->$val);
1270       }
1271     }
1272     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1274       // Get Configuration for initial Mysql database Server
1275       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1276       $s_parameter  ="";
1278       // Connect to DB server
1279       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1281       // Check if we are  connected correctly
1282       if(!$r_con){
1283         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1284                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1285         gosa_log(@mysql_error());
1286         return false;
1287       }
1289       // Select database for Extensions
1290       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1292       // Test if we have the database selected correctly
1293       if(!$db){
1294         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1295         gosa_log(@mysql_error());
1296         return false;
1297       }
1299       $SQL="";
1301       /* If deletion starts from userslist, cn uid are not set */
1302       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1303         $this->uid = $this->parent->by_object['user']->uid;
1304       }
1306       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1307         $this->cn  = $this->parent->by_object['user']->cn;
1308       }
1310       $first_num = false;
1311       // Delete old entries
1312       foreach($this->a_old_telenums as $s_telenums){
1313         if(!$first_num){
1314           $first_num = $s_telenums;
1315         }
1316         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1317       }
1319       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1320       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1321       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1323       foreach($SQL as $query){
1324         if(!@mysql_query($query,$r_con)){
1325           print_red(_("Stop".mysql_error()));
1326           return false;
1327         }
1328       }
1329     }else{
1330       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1331       return false;
1332     }
1334     /* unset macro attr, it will cause an error */
1335     $tmp = array_flip($this->attributes);
1336     unset($tmp['macro']);
1337     $this->attributes=array_flip($tmp);
1339     /* Cancel if there's nothing to do here */
1340     if (!$this->initially_was_account){
1341       return;
1342     }
1344     plugin::remove_from_parent();
1346     /* Just keep one phone number */
1347     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1348       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1349     } else {
1350       $this->attrs['telephoneNumber']= array();
1351     }
1354     $ldap= $this->config->get_ldap_link();
1355     $ldap->cd($this->config->current['BASE']);
1356     $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1357     while($attr = $ldap->fetch()){
1358       if(in_array($this->dn,$attr['member'])){
1359         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1360         unset($new->by_object['ogroup']->memberList[$this->dn]);
1361         unset($new->by_object['ogroup']->member[$this->dn]);
1362         $new->save();
1363         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1364       }
1365     }
1366     $ldap->cd($this->dn);
1367     $this->cleanup();
1368     $ldap->modify ($this->attrs); 
1370     show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/phone account with dn '%s' failed."),$this->dn));
1372     /* Optionally execute a command after we're done */
1373     @mysql_close($r_con);
1374     $this->handle_post_events('remove',array("uid"=> $this->uid));
1375   }
1379   /* This function checks if the given phonenumbers are available or already in use*/
1380   function is_number_used()
1381   {
1382     $ldap= $this->config->get_ldap_link();
1383     $ldap->cd($this->config->current['BASE']);
1384     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1385     while($attrs = $ldap->fetch()) {
1386       unset($attrs['telephoneNumber']['count']);
1387       foreach($attrs['telephoneNumber'] as $tele){
1388         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1389         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1390         $numbers[$tele]=$attrs;
1391       }
1392     }
1394     foreach($this->phoneNumbers as $num){
1395       if(!isset($this->cn)) $this->cn = "";
1397       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1398         if(isset($numbers[$num]['uid'][0])){
1399           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1400         }else{
1401           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1402         }
1403       }
1404     }
1405   }
1408   /* Create phoneAccount part of copy & paste dialog */
1409   function getCopyDialog()
1410   { 
1411     if(!$this->is_account) return("");
1412     $smarty = get_smarty();
1413     if (!count($this->phoneNumbers)){
1414       $smarty->assign ("phoneNumbers", array(""));
1415     } else {
1416       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1417     }
1419     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1420     $smarty->assign("goFonPIN",$this->goFonPIN);
1422     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1423     $ret =array();
1424     $ret['string'] = $display;
1425     $ret['status'] = "";
1426     return($ret);
1427   }
1429   /* Save posts from copy & paste dialog dialog  */
1430   function saveCopyDialog()
1431   {
1432     if(!$this->is_account) return;
1433     $this->execute();
1434     if(isset($_POST['goFonVoicemailPIN'])) {
1435       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1436     }
1437     if(isset($_POST['goFonPIN'])){
1438       $this->goFonPIN = $_POST['goFonPIN'];
1439     }
1440   }
1443   function allow_remove()
1444   {
1445     /* Check if previously selected server is still available */
1446     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1447       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1448     }
1449   }
1451   /* Return plugin informations for acl handling */
1452   function plInfo()
1453   {
1454     return (array(
1455           "plShortName"     => _("Phone"),
1456           "plDescription"   => _("Phone account settings"),
1457           "plSelfModify"    => TRUE,
1458           "plDepends"       => array("user"),
1459           "plPriority"      => 7,                                 // Position in tabs
1460           "plSection"       => "personal",                        // This belongs to personal
1461           "plCategory"      => array("gofonreport" => array("description" => _("GOfon reports"),
1462               "objectClass" => "")),
1464           "plOptions"       => array(),
1466           "plProvidedAcls"  => array(
1467             "telephoneNumber"     => _("Telephone number"),
1468             "goFonHomeServer"     => _("Home server"),
1469             "goFonMacro"          => _("Macro settings"),
1470             "goFonHardware"       => _("Phone hardware"),
1471             "goFonPIN"            => _("Telephone pin"),
1472             "goFonVoicemailPIN"   => _("Voicemail pin"))
1473           ));
1474   }
1477 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1478 ?>