Code

Added schema updated - homeServer for conferences
[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 
33     
35   /* CLI vars */
36   var $cli_summary            = "Manage users phone account";
37   var $cli_description        = "Some longer text\nfor help";
38   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
40   /* attribute list for save action */
41   var $CopyPasteVars          = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
42                                       "hardware_list","used_hardware");
44   var $attributes             = array("goFonDeliveryMode", "goFonFormat","uid","cn","goFonHomeServer",
45       "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
46   var $objectclasses= array("goFonAccount");
48   var $uid;
50   function phoneAccount ($config, $dn= NULL, $parent= NULL)
51   {
52     plugin::plugin ($config, $dn, $parent);
54     /* Assemble phone numbers */
55     if (isset($this->attrs['telephoneNumber'])){
56       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
57         $number= $this->attrs['telephoneNumber'][$i];
58         $this->phoneNumbers[$number]= $number;
59       }
60     }
62     /* Set up has_mailAccount */
63     if (isset($this->attrs['objectClass'])){
64       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
65         $this->has_mailAccount= TRUE;
66       }
67     }
70     /* Check server configurations 
71      * Load all server configuration in $this->goFonHomeServers if available
72      *  and first server as default if necessary.
73      * Check if connection is successfull for the selected server $this->goFonHomeServer
74      */
75     $a_SETUP= array();
76     if(array_key_exists('config',$_SESSION) &&
77        array_key_exists('SERVERS',$_SESSION['config']->data) &&
78        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
79        is_callable("mysql_connect")
80        ) {
82       /* Set available server */
83       $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
85       /* Servers defined? Watch here... */
86       if (count($this->goFonHomeServers)){
88         /* Set default server */
89         if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
90           $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
91         }
93         /* Remember inital home server, to be able to remove old entries */
94         $this->init_HomeServer = $this->goFonHomeServer;
96         /* Get config */
97         if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
98           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']));
100           $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
101           $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
102         }    
103         $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
105         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
106         if(!$r_con){
107           print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
108                 $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
109           gosa_log(mysql_error());
110         }
111         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
112         if(!$db){
113           print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
114           gosa_log(mysql_error());
115         }
117         $first = false; 
118         foreach($this->phoneNumbers as $key => $val){
119           if(!$first){
120             $first = $key;
121           }
122         }
123       }
124     }
126     /* Get available phone hardware  
127      * Search for all available phone hardware  
128      */
129     $ldap= $this->config->get_ldap_link();
130     $ldap->cd($this->config->current['BASE']);
131     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
132     while ($attrs= $ldap->fetch()){
133       $cn= $attrs['cn'][0];
134       if (isset($attrs['description'])){
135         $description= " - ".$attrs['description'][0];
136       } else {
137         $description= "";
138       }
139       $this->hardware_list[$cn]= "$cn$description";
140     }
143     /* Get available Macros  
144      * Search for all Marcos that are visible and create 
145      *  an array with name and parameters 
146      */
147     $ldap->search("(&(objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
149     /* Add none for no macro*/
150     $this->macros['none']=_("no macro");    
151     $this->macro ="none";
153     /* Fetch all Macros*/
154     while ($attrs= $ldap->fetch()){
156       /* unset Count, we don't need that here */
157       unset($attrs['displayName']['count']);
159       /* Parse macro data, unset count for parameterarrays  */
160       if (isset($attrs['goFonMacroParameter']['count'])){
161         unset($attrs['goFonMacroParameter']['count']);
162       }
164       /* fill Selectfield variable with Macros */
165       if(isset($attrs['displayName'][0])){
166         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
167       }else{
168         $this->macros[$attrs['dn']] = _("undefined");
169       }
171       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
172       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
174         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
175           /* Split Data in readable values, by delimiter !  */
176           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
178           /* Set all attrs */
179           $id = $data[0];
180           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
181           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
182           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
183           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
184           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
185           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
186           if($data[2] == "bool"){
187             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
188           }
189         }//foreach
190       }//is_array
191     }//while
194     /* Parse used Macro  
195      * If we have a macro selected, parse it and set values 
196      *  in $this->macroarray[$this->macro]. 
197      */
198     $tmp = split("!",$this->goFonMacro);
199     if(is_array($tmp)){
201       /* First value is the macroname */
202       $this->macro = $tmp[0];
204       /* Macroname saved, delete that index */
205       unset($tmp[0]);
207       /* Check if makro has been removed */
208       if(!isset($this->macros[$this->macro])){
209         $this->macrostillavailable = false;
210       }else{
211         $this->macrostillavailable = true;
212       }
214       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
215       foreach($tmp as $var){
217         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
218         $varar = split("#",$var);
220         /* Only insert if the parameter still exists */
221         if(isset($this->macroarray[$this->macro][$varar[0]])){
222           /* Assign value */
223           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
224         }
225       }
226     }
229     /* Colorize phones 
230      * Used phones will be colored in grey, 
231      *  so we must detect which phones are currently in use.
232      */
233     $ldap->cd($this->config->current['BASE']);
234     foreach ($this->hardware_list as $cn => $desc){
235       $ldap->search("(goFonHardware=$cn)", array('cn'));
236       if ($ldap->count() > 0){
237         $ldap->fetch();
238         if ($ldap->getDN() != $this->dn){
239           $this->used_hardware[$cn]= $ldap->getDN();
240         }
241       }
242     }
243     $this->hardware_list["automatic"]= _("automatic");
244     ksort($this->hardware_list);
245     $this->a_old_telenums = $this->phoneNumbers;
247     if($this->is_account){
248       $this->is_modified = true;
249     }
252     /* Get voicemail PIN from MySQL DB 
253      * Because every user can change his PIN directly from the phone
254      *  without any update to the ldap
255      * This means, the PIN in the DB is up to date
256      */
257     // Connect to DB server
258     if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
259       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
260       if($r_con){
261         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
262         $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."'"));
264         if((isset($vp[0]))&&(!empty($vp[0]))){
265           $this->goFonPINVoice = $vp[0];
266         }
267       }
268     }
269     $this->lastmacro=$this->macro;
271     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
272       @mysql_close($r_con) ;
273     }
274   }
277   /* This function generates the Database entries. 
278    * The Parameter 'save' could be true or false.
279    *  false - means only testing no database transactions.
280    *  true  - write database entries.
281    *
282    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
283    * 
284    * If the phone hardware is 'automatic' the table entries will only be removed
285    *  and not added. 
286    */
287   function generate_mysql_entension_entries($save = false)
288   {
289     /* Check if there is at least one server available 
290      * If not, return and tell the user that saving failed 
291      */
292     if(!count($this->goFonHomeServers)){
293       if($save){
294         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."));
295       }
296       return(true);
297     }
299     /* Check if Mysql extension is available */
300     if(!is_callable("mysql_pconnect")){
301       if($save)
302       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
303       return(true);
304     }
305  
306     /********************** 
307      * Attribute Initialisation
308      **********************/
310     $old_connection = false;
312     // Get Configuration for Mysql database Server
313     $s_parameter    = "";                                           // Contains paramter for selected Macro 
314     $r_con          = false;                                        // DB connection
315     $r_db           = false;                                        // Selected DB
316     $r_res          = false;                                        // Result resource
317     $a_ldap_attrs   = array();                                      //  
319     $s_ip           = NULL;                   // Contains ip for Sip entry
320     $s_host         = NULL;                   // Contains host for Sip entry
321     $s_qualify      = "yes";                  // Qualify entry
322     $s_pin          = NULL;                   // Entry for secret
323     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
325     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
326     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
327     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
329     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
330     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
332     $s_sip_key      = "";     // Key for SIP entry index      
333     $s_sip_val      = "";     // Value for SIP entry index      
335     $b_first_deleted= false;  // Only delete first entry, 
336     $s_telenums     = "";     // for each value variable
338     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
340     restore_error_handler();
342     /* Prepare some basic attributes */
343     foreach($this->a_old_telenums as $tele){
344       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
345     }
346     foreach($this->phoneNumbers as $tele){
347       $newnums[]= preg_replace("/[^0-9]/","",$tele);
348     }
350     /* If deletion starts from userslist, cn uid are not set */
351     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
352       $this->uid = $this->parent->by_object['user']->uid;
353     }
354     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
355       $this->cn  = $this->parent->by_object['user']->cn;
356     }
357     /* Create voicemail entry 
358      */
359     if((!isset($this->cn))||(empty($this->cn))){
360       $CNname= $this->uid;
361     }else{
362       $CNname= $this->cn;
363     }
365     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
366       $s_mail = $this->parent->by_object['mailAccount']->mail;
367     }else{
368       $s_mail = "";
369     }
370     /* Get phonehardware to setup sip entry  */
371     $ldap         = $this->config->get_ldap_link();
372     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
373     $a_ldap_attrs = $ldap->fetch();
375     /* Check selected phone hardware, is a default IP set? */
376     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
377       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
378       $s_host     = $s_ip;
379     }else{
380       $s_ip       = NULL;
381       $s_host     = "dynamic";
382     }
384     // Attribute GoFonQualify set ?
385     if(isset($a_ldap_attrs['goFonQualify'])){
386       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
387     }
389     // Attribute GoFonPIN set ?
390     if(isset($this->goFonPIN)){
391       $s_pin      = $this->goFonPIN;
392     }
394     // Attribute GoFonType set ?
395     if(isset($a_ldap_attrs['goFonType'])){
396       $s_type = $a_ldap_attrs['goFonType'][0];
397     }
399     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
400       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
401     }else{
402       $sip_data_array['dtmfmode']     ="rfc2833";
403     }
405     /* Check if phone number is used */
406     if($this->is_number_used()){
407       $this->generate_error = $this->is_number_used(); 
408       return false;
409     }
413     /********************** 
414      * Check Server Connection Information
415      **********************/
416  
417     /* Create Mysql handle for the current goFonHomeServer, if possible  
418      * Get configuration to old asterisk home server 
419      */ 
420     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
421     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
422     if(!$new_connection){
423       $this->generate_error = sprintf(
424           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
425           $a_New['SERVER'],$a_New['LOGIN']);
426       gosa_log(@mysql_error($new_connection));
427       return false;
428     }
429     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
430     if(!$new_database){
431       $this->generate_error = sprintf(
432           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
433           $a_New['DB'],$a_New['SERVER']);
434       gosa_log( @mysql_error($new_connection));
435       return false;
436     }
438     /* If the home server has changed, we must remove entries from old 
439      *  server and add new entries in new server.  
440      */
441     if($this->init_HomeServer != $this->goFonHomeServer){
442     
443       /* Get configuration to old asterisk home server */ 
444       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
445  
446       /* Create connection to the database that contains the old entry. 
447        */
448       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
449       if(!$old_connection){
450         $this->generate_error = sprintf(
451             _("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."),
452             $a_Remove['SERVER'],$a_Remove['LOGIN']);
453         gosa_log(@mysql_error($old_connection));
454         return false;
455       }
456       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
457       if(!$old_database){
458         $this->generate_error = sprintf(
459             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
460             $a_Remove['DB'],$a_Remove['SERVER']);
461         gosa_log(@mysql_error($old_connection));
462         return false;
463       }
464     }
466     /* Save means that we must save changes, not only test  */
467     if($save == true){
468     
469       /********************** 
470        * Remove entries from old home server 
471        **********************/
473       /* Check if there is an old entry 
474        * If there is en old entry, get callerid and remove voicemail and extensions too 
475        */
476       if($old_connection){
477         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
478         $rid    = mysql_query($query,$old_connection);
480         /* Old entry found, remove it */
481         $query_a = array();
482         if(mysql_affected_rows($old_connection)){
483           $result = mysql_fetch_assoc($rid);
484           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
485           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
486           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
487           foreach($oldnums as $s_telenums) {
488             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
489           }
491           foreach($query_a as $qry){
492             if(!mysql_query($qry,$old_connection)){
493               echo $qry;
494               echo mysql_error($old_connection);
495             } 
496           }
497         }
498       }
500       /********************** 
501        * Update / Insert sip_users entry  
502        **********************/
504       /* Set the first given phone number as callerid */
505       reset($newnums);        
506       $i_new_key = key($newnums);
507       $sip_data_array['callerid']  =$newnums[$i_new_key];
508       $sip_data_array['mailbox']   =$newnums[$i_new_key];
510       /* Check if there is already an entry in sip_users for this uid */
511       $SQL_query_array = array();
512       $rid = mysql_query("SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n",$new_connection);
513       if(mysql_affected_rows($new_connection)){
515         /********************** 
516          * Update sip_users entry 
517          **********************/
518         $result                     = mysql_fetch_assoc($rid);
519         $sip_data_array['host']         = $s_host;
520         $sip_data_array['qualify']      = $s_qualify;
521         $sip_data_array['secret']       = $this->goFonPIN;
522         $sip_data_array['type']         = $s_type ;
523         $sip_data_array['username']     = $this->uid;
524         $sip_data_array['ipaddr']       = $s_ip;
526         /* Remove not changed attributes, to avoid updating table with same values */
527         foreach($sip_data_array as $name => $value){
528           if($result[$name] == $value){
529             unset($sip_data_array[$name]);
530           }
531         }
532         /* Only update entry if there is something to uopdate */
533         if(count($sip_data_array)){
534           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
535           foreach($sip_data_array as $key => $val){
536             $query.= "".$key."='".$val."',"; 
537           } 
538           $query = preg_replace("/,$/","",$query);
539           $query.= " WHERE name='".$this->uid."';";
540           $SQL_query_array[] = $query;
541         }
542       } else {
543  
544         /********************** 
545          * Insert sip_users entry 
546          **********************/
547         //generate SIP entry
548         $sip_data_array['id']           = "";
549         $sip_data_array['name']         = $this->uid;
550         $sip_data_array['accountcode']  = NULL;          
551         $sip_data_array['amaflags']     = NULL;
552         $sip_data_array['callgroup']    = NULL;
553         $sip_data_array['canreinvite']  = "no";
554         $sip_data_array['context']      = "default";
555         $sip_data_array['defaultip']    = NULL;
556         $sip_data_array['fromuser']     = NULL;
557         $sip_data_array['fromdomain']   = NULL;
558         $sip_data_array['host']         = $s_host;
559         $sip_data_array['insecure']     = NULL;
560         $sip_data_array['language']     = NULL;
561         $sip_data_array['mailbox']      = $newnums[$i_new_key];
562         $sip_data_array['md5secret']    = NULL;
563         $sip_data_array['nat']          = "no";
564         $sip_data_array['permit']       = NULL;
565         $sip_data_array['deny']         = NULL;
566         $sip_data_array['mask']         = NULL;
567         $sip_data_array['pickupgroup']  = NULL;
568         $sip_data_array['port']         = NULL;
569         $sip_data_array['qualify']      = $s_qualify;
570         $sip_data_array['restrictcid']  = "n";
571         $sip_data_array['rtptimeout']   = NULL;
572         $sip_data_array['rtpholdtimeout']=NULL;
573         $sip_data_array['secret']       = $this->goFonPIN;
574         $sip_data_array['type']         = $s_type ;
575         $sip_data_array['username']     = $this->uid;
576         $sip_data_array['disallow']     = NULL;
577         $sip_data_array['allow']        = NULL;
578         $sip_data_array['musiconhold']  = NULL;
579         $sip_data_array['regseconds']   = NULL;
580         $sip_data_array['ipaddr']       = $s_ip;
581         $sip_data_array['regexten']     = NULL;
582         $sip_data_array['cancallforward']=NULL;
584         /* There is currently no entry for this user in the sip_users table. 
585          * We should create one i
586          */
587         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
588           if($s_sip_val == NULL) continue;
589           $s_sip_values.="'".$s_sip_val."',";
590           $s_sip_keys  .="`".$s_sip_key."`,";
591         }
592         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
593         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
595         /* Add sip entries to mysql queries */
596         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
597       }
600       /********************** 
601        * Update / Insert Voice mail entry  
602        **********************/
604       $customer_id = $newnums[$i_new_key];
606       $voice_data_array = array(
607           "customer_id" => $customer_id,
608           "mailbox"     => $customer_id,
609           "password"    => $this->goFonVoicemailPIN,
610           "fullname"    => $CNname,
611           "email"       => $s_mail);
613       /* Check if there is already an entry in sip_users for this uid */
614       $rid = mysql_query("SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n",$new_connection);
615       if(mysql_affected_rows($new_connection)){
617         /********************** 
618          * Update Voice mail entry  
619          **********************/
620         $result = mysql_fetch_assoc($rid)  ;
622         foreach($voice_data_array as $name => $value){
623           if($result[$name] == $value){
624             unset($voice_data_array[$name]);
625           }
626         }
628         /* Only update entry if there is something to uopdate */
629         if(count($voice_data_array)){
630           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
631           foreach($voice_data_array as $key => $val){
632             $query.= "".$key."='".$val."',"; 
633           } 
634           $query = preg_replace("/,$/","",$query);
635           $query.= " WHERE customer_id='".$customer_id."';";
636           $SQL_query_array[] = $query;
637         }
638       }else{
640         /********************** 
641          * Insert Voice mail entry  
642          **********************/
643         $voice_data_array['context'] = "default";
644         $voice_data_array['pager']   = "";
645   
646         /* There is currently no voice mail entry for this user. 
647          * We should create one 
648          */
649         $s_voi_values = $s_voi_keys = "";
650         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
651           if($s_voi_val == NULL) continue;
652           $s_voi_values.="'".$s_voi_val."',";
653           $s_voi_keys  .="`".$s_voi_key."`,";
654         }
655         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
656         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
658         /* Add sip entries to mysql queries */
659         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
660       }
662      
663       /********************** 
664        * Remove/Insert extension entries
665        **********************/
666       
667       /* Remove old entries */
668       $query = array();
669       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
670       foreach($newnums as $s_telenums){
671         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
672       }
673       foreach($query as $qry){
674         if(!mysql_query($qry,$new_connection)){
675           echo mysql_error($new_connection);
676         } 
677       }
678  
679       /********************** 
680        * Insert extension entries
681        **********************/
682  
683       // Get selected Macro Parameter and create parameter entry 
684       if(isset($this->macroarray[$this->macro])){
685         foreach($this->macroarray[$this->macro] as $key => $val ){
686           $s_parameter .= $val['choosen']."|";
687         }
688         $s_parameter = preg_replace("/\|$/","",$s_parameter);
689       }
690      
691       $i = 0; 
692       $EXT = array();
693       $EXT[$i]['context'] = 'GOsa';
694       $EXT[$i]['exten']   = $this->uid;
695       $EXT[$i]['priority']= 1;
696       $EXT[$i]['app']     = "Goto";
697       $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
698       $i ++;
700       // Entension entries  Hint / Dial / Goto
701       foreach($newnums as $s_telenums){
703         /* Hint Entry */
704         $EXT[$i]['context'] = 'GOsa';
705         $EXT[$i]['exten']   = $s_telenums;
706         $EXT[$i]['priority']= "Hint";
707         $EXT[$i]['app']     = 'SIP/'.$this->uid;
708         $i ++;  
709         /* SetCID */
710         //$EXT[$i]['context'] = 'GOsa';
711         //$EXT[$i]['exten']   = $s_telenums;
712         //$EXT[$i]['priority']= 1;
713         //$EXT[$i]['app']     = "SetCIDName";
714         //$EXT[$i]['appdata'] = $CNname;
715         //$i ++;  
717         // If no macro is selected use Dial
718         if($this->macro!="none"){ 
719           $macroname = preg_replace("/,.*$/","",$this->macro);        
720           $macroname = preg_replace("/^.*=/","",$macroname);        
721           $s_app = "Macro";$macroname;
722           $s_par = $macroname."|".$s_parameter; 
723         }else{
724           $s_app = "Dial";
725           $s_par = 'SIP/'.$this->uid."|20|r";
726         }
728         $EXT[$i]['context'] = 'GOsa';
729         $EXT[$i]['exten']   = $s_telenums;
730         $EXT[$i]['priority']= 1;
731         $EXT[$i]['app']     = $s_app;
732         $EXT[$i]['appdata'] = $s_par;
733         $i ++;
734       }
736       // Append all these Entries 
737       foreach($EXT as $entr){
738         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
739         foreach($entr as $key2 => $val2){
740           $SQL_syn.= "`".$key2."`,";
741         }
742         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
743         $SQL_syn .= ") VALUES ("; 
744         foreach($entr as $key2 => $val2){
745           $SQL_syn .= "'".$val2."',";
746         }
747         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
748         $SQL_syn .=");\n";
750         $SQL_query_array[] =$SQL_syn;
751         $SQL_syn ="";
752       }
754       // Perform queries ...
755       if($this->goFonHardware != "automatic"){
756         foreach($SQL_query_array as $query){
757           if(!@mysql_query($query,$new_connection)){
758             print_red(_("Error while performing query:")." ".mysql_error());
759             return false;
760           }
761         }
762       }
763     }
764     @mysql_close($new_connection);
765     return true;
766   }
769   function execute()
770   {
771     /* Call parent execute */
772     plugin::execute();
774     $display = "";
776     if(empty($this->macro)&&(!empty($this->goFonMacro))){
778       /* Go through already saved values, for a parameter */
779       $tmp = split("!",$this->goFonMacro);
781       /* it is possible that nothing has been saved yet */
782       if(is_array($tmp)){
784         /* First value is the macroname */
785         $this->macro = $tmp[0];
787         /* Macroname saved, delete that index */
788         unset($tmp[0]);
790         /* Check if macro has been removed */
791         if(!isset($this->macroarray[$this->macro])){
792           $this->macrostillavailable = false;
793         }else{
794           $this->macrostillavailable = true;
795         }
797         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
798         foreach($tmp as $var){
800           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
801           $varar = split("#",$var);
803           /* Only insert if the parameter still exists */
804           if(isset($this->macroarray[$this->macro][$varar[0]])){
805             /* Assign value */
806             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
807           }
808         }
809       }
810     }
811     
812     /* Do we represent a valid account? */
813     if (!$this->is_account && $this->parent == NULL){
814       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
815         _("This account has no phone extensions.")."</b>";
816       $display.= back_to_main();
817       return ($display);
818     }
820     /* Do we need to flip is_account state? */
821     if (isset($_POST['modify_state'])){
822       $this->is_account= !$this->is_account;
823     }
825     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
826     if(empty($this->macro)){
827       $this->macro ="none";
828     }
830     /* Prepare templating */
831     $smarty= get_smarty();
833     /* tell user that the selected plugin is no longer available */
834     if((!$this->macrostillavailable)&&($this->macro!="none")){
835       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
836     }
838     /* Assing macroselectbox values  */
839     $smarty->assign("macros",$this->macros);   
840     $smarty->assign("macro", $this->macro);   
842     /* check if there is a FON server created */
843     if(!count($this->goFonHomeServer)){
844       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."));
845     }
847     /* Create html parameter table for selected macro parameters 
848      *  skip if no parameters given 
849      */
850     if(!isset($this->macroarray[$this->macro])){
851       $macrotab="";
852     }else{
854       $macrotab ="<table summary=\""._("Parameter")."\">";
855       /* for every single parameter-> display textfile,combo, or true false switch*/
857       foreach($this->phoneNumbers as $phonenum){
858         $tmp[] = $phonenum;
859       }
860     
861       if($this->macro != $this->lastmacro){
862         /* Go through all params */
863         foreach($this->macroarray[$this->macro] as $key => $paras){
865           $string = $paras['default'];
867           $string=preg_replace("/%uid/i",$this->uid,$string);
869           if(isset($this->cn)){
870             $string=preg_replace("/%cn/i",$this->cn,$string);
871           }
873           for($i = 0 ; $i < 10; $i++){
874             if(isset($tmp[$i])){
875               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
876             }
877           }
878           if(isset($tmp[0])){
879             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
880           }
881           $this->macroarray[$this->macro][$key]['choosen']=$string;
882         }
883       }
885       foreach($this->macroarray[$this->macro] as $paras){
887         /* get al vars */
888         $var        = $paras['var'];           
889         $name       = $paras['name'];           
890         $default    = $paras['default'];
891         $type       = $paras['type'];
892         $choosen    = $paras['choosen'] ; 
893         $str        = $default;
895         /* in case of a combo box display a combobox with selected attr */
896         $macrotab.= "<tr>";
897         switch ($type){
899           case "combo":
900             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
901           foreach(split(":",$default) as $choice){
902             if($choosen==$choice){
903               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
904             }else{
905               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
906             }
907           }
908           $str.="</select>";
909           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
910           break;
912           case "bool":
913             if(!$choosen){
914               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
915             }else{
916               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
917             }
918           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
919           break;
921           case "string":
922             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
923           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
924           break;
926         }
927         $macrotab.= "</td></tr>";
929       }
930       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
931     }//is_array()
933     /* Give smarty the table */
934     $smarty->assign("macrotab",$macrotab);
937     /* Do we represent a valid account? */
938     if (!$this->is_account && $this->parent == NULL){
939       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
940         _("This account has no phone extensions.")."</b>";
941       $display.= back_to_main();
942       return($display);
943     }
945     $display= "";
947     /* Show tab dialog headers */
948     if ($this->parent != NULL){
949       if ($this->is_account){
950         $display= $this->show_header(_("Remove phone account"),
951             _("This account has phone features enabled. You can disable them by clicking below."));
952       } else {
953         if(empty($this->uid)){
954           $display= $this->show_header(_("Create phone account"),
955               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
956         }else{
957           $display= $this->show_header(_("Create phone account"),
958               _("This account has phone features disabled. You can enable them by clicking below."));
959         }
960         return ($display);
961       }
962     }
964     /* Add phone number */
965     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
966       if (is_phone_nr($_POST['phonenumber'])){
967         $number= $_POST["phonenumber"];
968         $this->phoneNumbers[$number]= $number;
969         $this->is_modified= TRUE;
970       } else {
971         print_red(_("Please enter a valid phone number!"));
972       }
973     }
975     /* Remove phone number */
976     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
977       foreach ($_POST['phonenumber_list'] as $number){
978         unset($this->phoneNumbers[$number]);
979         $this->is_modified= TRUE;
980       }
981     }
983     /* Transfer ACL's */
984     foreach($this->attributes as $val){
985       $smarty->assign($val."ACL", chkacl($this->acl,$val));
986       if(isset($this->$val)){
987         $smarty->assign($val,$this->$val);
988       }else{
989         $smarty->assign($val,"");
990       }
991     }
993     /* Create home server array */
994     $tmp = array();
995     foreach($this->goFonHomeServers as $dn => $attrs){
996       if(!is_numeric($dn)){
997         $tmp[$dn] = $attrs['SERVER'];
998       }
999     }
1000     $smarty->assign("goFonHomeServers",$tmp);
1002     /* Fill arrays */
1003     $smarty->assign ("goFonHardware", $this->goFonHardware);
1004     if (!count($this->phoneNumbers)){
1005       $smarty->assign ("phoneNumbers", array());
1006     } else {
1007       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1008     }
1009     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
1010       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
1011     foreach ($this->hardware_list as $cn => $description){
1012       if ($cn == $this->goFonHardware){
1013         $selected= "selected";
1014       } else {
1015         $selected= "";
1016       }
1017       if (isset($this->used_hardware[$cn])){
1018         $color= "style=\"color:#A0A0A0\"";
1019       } else {
1020         $color= "";
1021       }
1022       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1023     }
1024     $hl.= "</select>\n";
1025     $smarty->assign ("hardware_list", $hl);
1027     /* Show main page */
1028     $this->lastmacro = $this->macro;
1029     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1030     return($display);
1031   }
1034   function save_object()
1035   {
1036     if (isset($_POST["phoneTab"])){
1037       plugin::save_object();
1039       /* Save checkbox */
1040       if (isset($_POST['fon_to_mail'])){
1041         $tmp= "[M]";
1042       } else {
1043         $tmp= "[]";
1044       }
1045       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
1046         if ($this->goFonDeliveryMode != $tmp){
1047           $this->is_modified= TRUE;
1048         }
1049         $this->goFonDeliveryMode= $tmp;
1050       }
1052       /* Every macro in the select box are available */
1053       if((isset($_POST['macro']))){
1054         $this->macrostillavailable=true;
1055       }
1057       if(is_array($this->phoneNumbers)){
1058         foreach($this->phoneNumbers as $telenumms) {
1059           $nummsinorder[]=$telenumms; 
1060         }
1061       }else{
1062         $nummsinorder=array("");
1063       }
1065       /* get all Postvars */
1066       if(isset($this->macroarray[$this->macro])){ 
1067         foreach($this->macroarray[$this->macro] as $key => $paras){
1068           if(isset($_POST[$paras['var']])){
1069             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1070           }
1072           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
1073              We need this code below to read and save checkboxes correct
1074            */
1076           if(isset($_POST['post_success'])){
1077             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1078               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1079                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1080               }else{
1081                 $this->macroarray[$this->macro][$key]['choosen']=false;
1082               }
1083             }
1084           }
1085         }
1086       }
1087     }
1088   }
1090   function check()
1091   {
1092     /* Call common method to give check the hook */
1093     $message= plugin::check();
1095     if(!count($this->goFonHomeServers)){
1096       $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1097     }
1099     if(empty($this->goFonHomeServer)){
1100       $message[] = _("Please select a valid goFonHomeServer.");
1101     }
1103     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1104       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1105     }else{
1106       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1107         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1108       }
1109     }
1111     if((strlen($this->goFonPIN)<=0)){
1112       $message[]=(_("Phone PIN must be at least one character long."));
1113     }else{
1114       if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1115         $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1116       }
1117     }
1119     if(!$this->generate_mysql_entension_entries()){
1120       $message[] = $this->generate_error;
1121     }
1123     /* We need at least one phone number */
1124     if (count($this->phoneNumbers) == 0){
1125       $message[]= sprintf(_("You need to specify at least one phone number!"));
1126     }
1128     /* check for ! in any parameter setting*/
1129     if(isset($this->macroarray[$this->macro])){
1130       foreach($this->macroarray[$this->macro] as $val){
1131         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1132           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1133         }
1134       }
1135     }
1136     return ($message);
1137   }
1141   function save()
1142   {
1143     plugin::save();
1145     /* Force saving macro again 
1146      * This ensures that 
1147      *  - the macro is available on the destiantion server.
1148      *  - the macro saved is up to date on the destination server.
1149      */
1150     if(!empty($this->macro) && $this->macro != "none")  {
1151       $macro_tab = new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro);
1152       $macro_tab -> save();
1153     }
1155     /* Save arrays */
1156     $tmp_numbers = array();
1157     foreach ($this->phoneNumbers as $number){
1158       $tmp_numbers[] = $number;
1159     }
1161     /* Save settings, or remove goFonMacro attribute*/
1162     if($this->macro!="none"){    
1163       $this->attrs['goFonMacro']=$this->macro;
1164       if(isset($this->macroarray[$this->macro])){
1165         foreach($this->macroarray[$this->macro] as $paras)  {
1166           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1167         }
1168       }
1169     }else{
1170       $this->attrs['goFonMacro']=array();
1171     }
1172     unset($this->attrs['macro'])  ;
1174     $this->attrs['goFonForwarding']=array();
1176     $str = $this->generate_mysql_entension_entries(true);
1177     if(empty($str)){
1178       print_red($str);
1179     }
1181     if($this->attrs['goFonMacro']==""){
1182       $this->attrs['goFonMacro']=array();
1183     }
1185     unset($this->attrs['cn']);
1187     /* Write back to ldap */
1188     $ldap= $this->config->get_ldap_link();
1189     $ldap->cd($this->dn);
1190     $this->cleanup();
1191     
1192     /* Force saving numbers, else it will be overwriten by user account. */
1193     $this->attrs['telephoneNumber'] =$tmp_numbers;
1194     $ldap->modify ($this->attrs); 
1196     show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
1198     /* Optionally execute a command after we're done */
1200     if ($this->initially_was_account == $this->is_account){
1201       if ($this->is_modified){
1202         $this->handle_post_events("modify",array("uid" => $this->uid));
1203       }
1204     } else {
1205       $this->handle_post_events("add",array("uid" => $this->uid));
1206     }
1208   }
1211   function adapt_from_template($dn)
1212   {
1213     plugin::adapt_from_template($dn);
1215     /* Assemble phone numbers */
1216     if (isset($this->attrs['telephoneNumber'])){
1217       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1218         $number= $this->attrs['telephoneNumber'][$i];
1219         $this->phoneNumbers[$number]= $number;
1220       }
1221     }
1222   }
1225   function remove_from_parent()
1226   {
1227     if(!$this->initially_was_account) return;
1229     foreach($this->attributes as $key=>$val){
1230       if(in_array($val,array("uid","cn"))){
1231         unset($this->attributes[$key]);
1232         unset($this->$val);
1233       }
1234     }
1235     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1237       // Get Configuration for initial Mysql database Server
1238       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1239       $s_parameter  ="";
1241       // Connect to DB server
1242       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1244       // Check if we are  connected correctly
1245       if(!$r_con){
1246         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1247                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1248         gosa_log(@mysql_error());
1249         return false;
1250       }
1252       // Select database for Extensions
1253       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1255       // Test if we have the database selected correctly
1256       if(!$db){
1257         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1258         gosa_log(@mysql_error());
1259         return false;
1260       }
1262       $SQL="";
1264       /* If deletion starts from userslist, cn uid are not set */
1265       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1266         $this->uid = $this->parent->by_object['user']->uid;
1267       }
1269       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1270         $this->cn  = $this->parent->by_object['user']->cn;
1271       }
1273       $first_num = false;
1274       // Delete old entries
1275       foreach($this->a_old_telenums as $s_telenums){
1276         if(!$first_num){
1277           $first_num = $s_telenums;
1278         }
1279         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1280       }
1282       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1283       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1284       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1286       foreach($SQL as $query){
1287         if(!@mysql_query($query,$r_con)){
1288           print_red(_("Stop".mysql_error()));
1289           return false;
1290         }
1291       }
1292     }else{
1293       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1294       return false;
1295     }
1297     /* unset macro attr, it will cause an error */
1298     $tmp = array_flip($this->attributes);
1299     unset($tmp['macro']);
1300     $this->attributes=array_flip($tmp);
1302     /* Cancel if there's nothing to do here */
1303     if (!$this->initially_was_account){
1304       return;
1305     }
1307     plugin::remove_from_parent();
1309     /* Just keep one phone number */
1310     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1311       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1312     } else {
1313       $this->attrs['telephoneNumber']= array();
1314     }
1317     $ldap= $this->config->get_ldap_link();
1318     $ldap->cd($this->config->current['BASE']);
1319     $ldap->search("(objectClass=goFonQueue)", array("member"));
1320     while($attr = $ldap->fetch()){
1321       if(in_array($this->dn,$attr['member'])){
1322         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1323         unset($new->by_object['ogroup']->memberList[$this->dn]);
1324         unset($new->by_object['ogroup']->member[$this->dn]);
1325         $new->save();
1326         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1327       }
1328     }
1329     $ldap->cd($this->dn);
1330     $this->cleanup();
1331     $ldap->modify ($this->attrs); 
1333     show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1335     /* Optionally execute a command after we're done */
1336     @mysql_close($r_con);
1337     $this->handle_post_events('remove',array("uid"=> $this->uid));
1338   }
1342   /* This function checks if the given phonenumbers are available or already in use*/
1343   function is_number_used()
1344   {
1345     $ldap= $this->config->get_ldap_link();
1346     $ldap->cd($this->config->current['BASE']);
1347     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1348     while($attrs = $ldap->fetch()) {
1349       unset($attrs['telephoneNumber']['count']);
1350       foreach($attrs['telephoneNumber'] as $tele){
1351         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1352         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1353         $numbers[$tele]=$attrs;
1354       }
1355     }
1357     foreach($this->phoneNumbers as $num){
1358       if(!isset($this->cn)) $this->cn = "";
1360       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1361         if(isset($numbers[$num]['uid'][0])){
1362           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1363         }else{
1364           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1365         }
1366       }
1367     }
1368   }
1371   /* Create phoneAccount part of copy & paste dialog */
1372   function getCopyDialog()
1373   { 
1374     if(!$this->is_account) return("");
1375     $smarty = get_smarty();
1376     if (!count($this->phoneNumbers)){
1377       $smarty->assign ("phoneNumbers", array(""));
1378     } else {
1379       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1380     }
1382     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1383     $smarty->assign("goFonPIN",$this->goFonPIN);
1385     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1386     $ret =array();
1387     $ret['string'] = $display;
1388     $ret['status'] = "";
1389     return($ret);
1390   }
1392   /* Save posts from copy & paste dialog dialog  */
1393   function saveCopyDialog()
1394   {
1395     if(!$this->is_account) return;
1396     $this->execute();
1397     if(isset($_POST['goFonVoicemailPIN'])) {
1398       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1399     }
1400     if(isset($_POST['goFonPIN'])){
1401       $this->goFonPIN = $_POST['goFonPIN'];
1402     }
1403   }
1406   function allow_remove()
1407   {
1408     /* Check if previously selected server is still available */
1409     if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1410       return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1411     }
1412   }
1415 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1416 ?>