Code

Fixed some error msgs
[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       /* Set default server */
86       if($this->dn == "new"){
87         $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
88       }
90       /* Remember inital home server, to be able to remove old entries */
91       $this->init_HomeServer = $this->goFonHomeServer;
93       /* get config */
94       if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
95         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']));
97         $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
98         $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
99       }    
100       $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
102       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
103       if(!$r_con){
104         print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
105             $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
106         gosa_log(mysql_error());
107         return false;
108       }
109       $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
110       if(!$db){
111         print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
112         gosa_log(mysql_error());
113         return false;
114       }
116       $first = false; 
117       foreach($this->phoneNumbers as $key => $val){
118         if(!$first){
119           $first = $key;
120         }
121       }
122     }
125     /* Get available phone hardware  
126      * Search for all available phone hardware  
127      */
128     $ldap= $this->config->get_ldap_link();
129     $ldap->cd($this->config->current['BASE']);
130     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
131     while ($attrs= $ldap->fetch()){
132       $cn= $attrs['cn'][0];
133       if (isset($attrs['description'])){
134         $description= " - ".$attrs['description'][0];
135       } else {
136         $description= "";
137       }
138       $this->hardware_list[$cn]= "$cn$description";
139     }
142     /* Get available Macros  
143      * Search for all Marcos that are visible and create 
144      *  an array with name and parameters 
145      */
146     $ldap->search("((objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
148     /* Add none for no macro*/
149     $this->macros['none']=_("no macro");    
150     $this->macro ="none";
152     /* Fetch all Macros*/
153     while ($attrs= $ldap->fetch()){
155       /* unset Count, we don't need that here */
156       unset($attrs['displayName']['count']);
158       /* Parse macro data, unset count for parameterarrays  */
159       if (isset($attrs['goFonMacroParameter']['count'])){
160         unset($attrs['goFonMacroParameter']['count']);
161       }
163       /* fill Selectfield variable with Macros */
164       if(isset($attrs['displayName'][0])){
165         $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
166       }else{
167         $this->macros[$attrs['dn']] = _("undefined");
168       }
170       /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
171       if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
173         foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
174           /* Split Data in readable values, by delimiter !  */
175           $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
177           /* Set all attrs */
178           $id = $data[0];
179           $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
180           $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
181           $this->macroarray[$attrs['dn']][$id]['id']     =$id;
182           $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
183           $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
184           $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
185           if($data[2] == "bool"){
186             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
187           }
188         }//foreach
189       }//is_array
190     }//while
193     /* Parse used Macro  
194      * If we have a macro selected, parse it and set values 
195      *  in $this->macroarray[$this->macro]. 
196      */
197     $tmp = split("!",$this->goFonMacro);
198     if(is_array($tmp)){
200       /* First value is the macroname */
201       $this->macro = $tmp[0];
203       /* Macroname saved, delete that index */
204       unset($tmp[0]);
206       /* Check if makro has been removed */
207       if(!isset($this->macroarray[$this->macro])){
208         $this->macrostillavailable = false;
209       }else{
210         $this->macrostillavailable = true;
211       }
213       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
214       foreach($tmp as $var){
216         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
217         $varar = split("#",$var);
219         /* Only insert if the parameter still exists */
220         if(isset($this->macroarray[$this->macro][$varar[0]])){
221           /* Assign value */
222           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
223         }
224       }
225     }
228     /* Colorize phones 
229      * Used phones will be colored in grey, 
230      *  so we must detect which phones are currently in use.
231      */
232     $ldap->cd($this->config->current['BASE']);
233     foreach ($this->hardware_list as $cn => $desc){
234       $ldap->search("(goFonHardware=$cn)", array('cn'));
235       if ($ldap->count() > 0){
236         $ldap->fetch();
237         if ($ldap->getDN() != $this->dn){
238           $this->used_hardware[$cn]= $ldap->getDN();
239         }
240       }
241     }
242     $this->hardware_list["automatic"]= _("automatic");
243     ksort($this->hardware_list);
244     $this->a_old_telenums = $this->phoneNumbers;
246     if($this->is_account){
247       $this->is_modified = true;
248     }
251     /* Get voicemail PIN from MySQL DB 
252      * Because every user can change his PIN directly from the phone
253      *  without any update to the ldap
254      * This means, the PIN in the DB is up to date
255      */
256     // Connect to DB server
257     if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
258       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
259       if($r_con){
260         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
261         $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."'"));
263         if((isset($vp[0]))&&(!empty($vp[0]))){
264           $this->goFonPINVoice = $vp[0];
265         }
266       }
267     }
268     $this->lastmacro=$this->macro;
270     if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
271       @mysql_close($r_con) ;
272     }
273   }
276   /* This function generates the Database entries. 
277    * The Parameter 'save' could be true or false.
278    *  false - means only testing no database transactions.
279    *  true  - write database entries.
280    *
281    * 'sip_users','voice_mail' and 'extensions' table entries will be created.
282    * 
283    * If the phone hardware is 'automatic' the table entries will only be removed
284    *  and not added. 
285    */
286   function generate_mysql_entension_entries($save = false)
287   {
288     /* Check if there is at least one server available 
289      * If not, return and tell the user that saving failed 
290      */
291     if(!count($this->goFonHomeServers)){
292       if($save){
293         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."));
294       }
295       return(true);
296     }
298     /* Check if Mysql extension is available */
299     if(!is_callable("mysql_pconnect")){
300       if($save)
301       print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
302       return(true);
303     }
304  
305     /********************** 
306      * Attribute Initialisation
307      **********************/
309     $old_connection = false;
311     // Get Configuration for Mysql database Server
312     $s_parameter    = "";                                           // Contains paramter for selected Macro 
313     $r_con          = false;                                        // DB connection
314     $r_db           = false;                                        // Selected DB
315     $r_res          = false;                                        // Result resource
316     $a_ldap_attrs   = array();                                      //  
318     $s_ip           = NULL;                   // Contains ip for Sip entry
319     $s_host         = NULL;                   // Contains host for Sip entry
320     $s_qualify      = "yes";                  // Qualify entry
321     $s_pin          = NULL;                   // Entry for secret
322     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
324     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
325     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
326     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
328     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
329     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
331     $s_sip_key      = "";     // Key for SIP entry index      
332     $s_sip_val      = "";     // Value for SIP entry index      
334     $b_first_deleted= false;  // Only delete first entry, 
335     $s_telenums     = "";     // for each value variable
337     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
339     restore_error_handler();
341     /* Prepare some basic attributes */
342     foreach($this->a_old_telenums as $tele){
343       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
344     }
345     foreach($this->phoneNumbers as $tele){
346       $newnums[]= preg_replace("/[^0-9]/","",$tele);
347     }
349     /* If deletion starts from userslist, cn uid are not set */
350     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
351       $this->uid = $this->parent->by_object['user']->uid;
352     }
353     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
354       $this->cn  = $this->parent->by_object['user']->cn;
355     }
356     /* Create voicemail entry 
357      */
358     if((!isset($this->cn))||(empty($this->cn))){
359       $CNname= $this->uid;
360     }else{
361       $CNname= $this->cn;
362     }
364     if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
365       $s_mail = $this->parent->by_object['mailAccount']->mail;
366     }else{
367       $s_mail = "";
368     }
369     /* Get phonehardware to setup sip entry  */
370     $ldap         = $this->config->get_ldap_link();
371     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
372     $a_ldap_attrs = $ldap->fetch();
374     /* Check selected phone hardware, is a default IP set? */
375     if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
376       $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
377       $s_host     = $s_ip;
378     }else{
379       $s_ip       = NULL;
380       $s_host     = "dynamic";
381     }
383     // Attribute GoFonQualify set ?
384     if(isset($a_ldap_attrs['goFonQualify'])){
385       $s_qualify = $a_ldap_attrs['goFonQualify'][0];
386     }
388     // Attribute GoFonPIN set ?
389     if(isset($this->goFonPIN)){
390       $s_pin      = $this->goFonPIN;
391     }
393     // Attribute GoFonType set ?
394     if(isset($a_ldap_attrs['goFonType'])){
395       $s_type = $a_ldap_attrs['goFonType'][0];
396     }
398     if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
399       $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
400     }else{
401       $sip_data_array['dtmfmode']     ="rfc2833";
402     }
404     /* Check if phone number is used */
405     if($this->is_number_used()){
406       $this->generate_error = $this->is_number_used(); 
407       return false;
408     }
412     /********************** 
413      * Check Server Connection Information
414      **********************/
415  
416     /* Create Mysql handle for the current goFonHomeServer, if possible  
417      * Get configuration to old asterisk home server 
418      */ 
419     $a_New = $this->goFonHomeServers[$this->goFonHomeServer];  // DB Configuration
420     $new_connection =  @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
421     if(!$new_connection){
422       $this->generate_error = sprintf(
423           _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
424           $a_New['SERVER'],$a_New['LOGIN']);
425       gosa_log(@mysql_error($new_connection));
426       return false;
427     }
428     $new_database  =  @mysql_select_db($a_New['DB'],$new_connection);
429     if(!$new_database){
430       $this->generate_error = sprintf(
431           _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
432           $a_New['DB'],$a_New['SERVER']);
433       gosa_log( @mysql_error($new_connection));
434       return false;
435     }
437     /* If the home server has changed, we must remove entries from old 
438      *  server and add new entries in new server.  
439      */
440     if($this->init_HomeServer != $this->goFonHomeServer){
441     
442       /* Get configuration to old asterisk home server */ 
443       $a_Remove = $this->goFonHomeServers[$this->init_HomeServer];  // DB Configuration
444  
445       /* Create connection to the database that contains the old entry. 
446        */
447       $old_connection =  @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
448       if(!$old_connection){
449         $this->generate_error = sprintf(
450             _("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."),
451             $a_Remove['SERVER'],$a_Remove['LOGIN']);
452         gosa_log(@mysql_error($old_connection));
453         return false;
454       }
455       $old_database  =  @mysql_select_db($a_Remove['DB'],$old_connection);
456       if(!$old_database){
457         $this->generate_error = sprintf(
458             _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
459             $a_Remove['DB'],$a_Remove['SERVER']);
460         gosa_log(@mysql_error($old_connection));
461         return false;
462       }
463     }
465     /* Save means that we must save changes, not only test  */
466     if($save == true){
467     
468       /********************** 
469        * Remove entries from old home server 
470        **********************/
472       /* Check if there is an old entry 
473        * If there is en old entry, get callerid and remove voicemail and extensions too 
474        */
475       if($old_connection){
476         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
477         $rid    = mysql_query($query,$old_connection);
479         /* Old entry found, remove it */
480         $query_a = array();
481         if(mysql_affected_rows($old_connection)){
482           $result = mysql_fetch_assoc($rid);
483           $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
484           $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
485           $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
486           foreach($oldnums as $s_telenums) {
487             $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
488           }
490           foreach($query_a as $qry){
491             if(!mysql_query($qry,$old_connection)){
492               echo $qry;
493               echo mysql_error($old_connection);
494             } 
495           }
496         }
497       }
499       /********************** 
500        * Update / Insert sip_users entry  
501        **********************/
503       /* Set the first given phone number as callerid */
504       reset($newnums);        
505       $i_new_key = key($newnums);
506       $sip_data_array['callerid']  =$newnums[$i_new_key];
507       $sip_data_array['mailbox']   =$newnums[$i_new_key];
509       /* Check if there is already an entry in sip_users for this uid */
510       $SQL_query_array = array();
511       $rid = mysql_query("SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n",$new_connection);
512       if(mysql_affected_rows($new_connection)){
514         /********************** 
515          * Update sip_users entry 
516          **********************/
517         $result                     = mysql_fetch_assoc($rid);
518         $sip_data_array['host']         = $s_host;
519         $sip_data_array['qualify']      = $s_qualify;
520         $sip_data_array['secret']       = $this->goFonPIN;
521         $sip_data_array['type']         = $s_type ;
522         $sip_data_array['username']     = $this->uid;
523         $sip_data_array['ipaddr']       = $s_ip;
525         /* Remove not changed attributes, to avoid updating table with same values */
526         foreach($sip_data_array as $name => $value){
527           if($result[$name] == $value){
528             unset($sip_data_array[$name]);
529           }
530         }
531         /* Only update entry if there is something to uopdate */
532         if(count($sip_data_array)){
533           $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
534           foreach($sip_data_array as $key => $val){
535             $query.= "".$key."='".$val."',"; 
536           } 
537           $query = preg_replace("/,$/","",$query);
538           $query.= " WHERE name='".$this->uid."';";
539           $SQL_query_array[] = $query;
540         }
541       } else {
542  
543         /********************** 
544          * Insert sip_users entry 
545          **********************/
546         //generate SIP entry
547         $sip_data_array['id']           = "";
548         $sip_data_array['name']         = $this->uid;
549         $sip_data_array['accountcode']  = NULL;          
550         $sip_data_array['amaflags']     = NULL;
551         $sip_data_array['callgroup']    = NULL;
552         $sip_data_array['canreinvite']  = "no";
553         $sip_data_array['context']      = "default";
554         $sip_data_array['defaultip']    = NULL;
555         $sip_data_array['fromuser']     = NULL;
556         $sip_data_array['fromdomain']   = NULL;
557         $sip_data_array['host']         = $s_host;
558         $sip_data_array['insecure']     = NULL;
559         $sip_data_array['language']     = NULL;
560         $sip_data_array['mailbox']      = "asterisk";
561         $sip_data_array['md5secret']    = NULL;
562         $sip_data_array['nat']          = "no";
563         $sip_data_array['permit']       = NULL;
564         $sip_data_array['deny']         = NULL;
565         $sip_data_array['mask']         = NULL;
566         $sip_data_array['pickupgroup']  = NULL;
567         $sip_data_array['port']         = NULL;
568         $sip_data_array['qualify']      = $s_qualify;
569         $sip_data_array['restrictcid']  = "n";
570         $sip_data_array['rtptimeout']   = NULL;
571         $sip_data_array['rtpholdtimeout']=NULL;
572         $sip_data_array['secret']       = $this->goFonPIN;
573         $sip_data_array['type']         = $s_type ;
574         $sip_data_array['username']     = $this->uid;
575         $sip_data_array['disallow']     = NULL;
576         $sip_data_array['allow']        = NULL;
577         $sip_data_array['musiconhold']  = NULL;
578         $sip_data_array['regseconds']   = NULL;
579         $sip_data_array['ipaddr']       = $s_ip;
580         $sip_data_array['regexten']     = NULL;
581         $sip_data_array['cancallforward']=NULL;
583         /* There is currently no entry for this user in the sip_users table. 
584          * We should create one i
585          */
586         foreach($sip_data_array as $s_sip_key=>$s_sip_val){
587           if($s_sip_val == NULL) continue;
588           $s_sip_values.="'".$s_sip_val."',";
589           $s_sip_keys  .="`".$s_sip_key."`,";
590         }
591         $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
592         $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
594         /* Add sip entries to mysql queries */
595         $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
596       }
599       /********************** 
600        * Update / Insert Voice mail entry  
601        **********************/
603       $customer_id = $newnums[$i_new_key];
605       $voice_data_array = array(
606           "customer_id" => $customer_id,
607           "mailbox"     => $customer_id,
608           "password"    => $this->goFonVoicemailPIN,
609           "fullname"    => $CNname,
610           "email"       => $s_mail);
612       /* Check if there is already an entry in sip_users for this uid */
613       $rid = mysql_query("SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n",$new_connection);
614       if(mysql_affected_rows($new_connection)){
616         /********************** 
617          * Update Voice mail entry  
618          **********************/
619         $result = mysql_fetch_assoc($rid)  ;
621         foreach($voice_data_array as $name => $value){
622           if($result[$name] == $value){
623             unset($voice_data_array[$name]);
624           }
625         }
627         /* Only update entry if there is something to uopdate */
628         if(count($voice_data_array)){
629           $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
630           foreach($voice_data_array as $key => $val){
631             $query.= "".$key."='".$val."',"; 
632           } 
633           $query = preg_replace("/,$/","",$query);
634           $query.= " WHERE customer_id='".$customer_id."';";
635           $SQL_query_array[] = $query;
636         }
637       }else{
639         /********************** 
640          * Insert Voice mail entry  
641          **********************/
642         $voice_data_array['context'] = "default";
643         $voice_data_array['pager']   = "";
644   
645         /* There is currently no voice mail entry for this user. 
646          * We should create one 
647          */
648         $s_voi_values = $s_voi_keys = "";
649         foreach($voice_data_array as $s_voi_key=>$s_voi_val){
650           if($s_voi_val == NULL) continue;
651           $s_voi_values.="'".$s_voi_val."',";
652           $s_voi_keys  .="`".$s_voi_key."`,";
653         }
654         $s_voi_values =  preg_replace("/,$/","",$s_voi_values);
655         $s_voi_keys   =  preg_replace("/,$/","",$s_voi_keys);
657         /* Add sip entries to mysql queries */
658         $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
659       }
661      
662       /********************** 
663        * Remove/Insert extension entries
664        **********************/
665       
666       /* Remove old entries */
667       $query = array();
668       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
669       foreach($newnums as $s_telenums){
670         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
671       }
672       foreach($query as $qry){
673         if(!mysql_query($qry,$new_connection)){
674           echo mysql_error($new_connection);
675         } 
676       }
677  
678       /********************** 
679        * Insert extension entries
680        **********************/
681  
682       // Get selected Macro Parameter and create parameter entry 
683       if(isset($this->macroarray[$this->macro])){
684         foreach($this->macroarray[$this->macro] as $key => $val ){
685           $s_parameter .= $val['choosen']."|";
686         }
687         $s_parameter = preg_replace("/\|$/","",$s_parameter);
688       }
689      
690       $i = 0; 
691       $EXT = array();
692       $EXT[$i]['context'] = 'GOsa';
693       $EXT[$i]['exten']   = $this->uid;
694       $EXT[$i]['priority']= 1;
695       $EXT[$i]['app']     = "Goto";
696       $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
697       $i ++;
699       // Entension entries  Hint / Dial / Goto
700       foreach($newnums as $s_telenums){
702         /* Hint Entry */
703         $EXT[$i]['context'] = 'GOsa';
704         $EXT[$i]['exten']   = $s_telenums;
705         $EXT[$i]['priority']= "Hint";
706         $EXT[$i]['app']     = 'SIP/'.$this->uid;
707         $i ++;  
708         /* SetCID */
709         //$EXT[$i]['context'] = 'GOsa';
710         //$EXT[$i]['exten']   = $s_telenums;
711         //$EXT[$i]['priority']= 1;
712         //$EXT[$i]['app']     = "SetCIDName";
713         //$EXT[$i]['appdata'] = $CNname;
714         //$i ++;  
716         // If no macro is selected use Dial
717         if($this->macro!="none"){ 
718           $macroname = preg_replace("/,.*$/","",$this->macro);        
719           $macroname = preg_replace("/^.*=/","",$macroname);        
720           $s_app = "Macro";$macroname;
721           $s_par = $macroname."|".$s_parameter; 
722         }else{
723           $s_app = "Dial";
724           $s_par = 'SIP/'.$this->uid."|20|r";
725         }
727         $EXT[$i]['context'] = 'GOsa';
728         $EXT[$i]['exten']   = $s_telenums;
729         $EXT[$i]['priority']= 1;
730         $EXT[$i]['app']     = $s_app;
731         $EXT[$i]['appdata'] = $s_par;
732         $i ++;
733       }
735       // Append all these Entries 
736       foreach($EXT as $entr){
737         $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
738         foreach($entr as $key2 => $val2){
739           $SQL_syn.= "`".$key2."`,";
740         }
741         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
742         $SQL_syn .= ") VALUES ("; 
743         foreach($entr as $key2 => $val2){
744           $SQL_syn .= "'".$val2."',";
745         }
746         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
747         $SQL_syn .=");\n";
749         $SQL_query_array[] =$SQL_syn;
750         $SQL_syn ="";
751       }
753       // Perform queries ...
754       foreach($SQL_query_array as $query){
755         if(!@mysql_query($query,$new_connection)){
756           print_red(_("Error while performing query:")." ".mysql_error());
757           return false;
758         }
759       }
760     }
761     @mysql_close($new_connection);
762     return true;
763   }
766   function execute()
767   {
768     /* Call parent execute */
769     plugin::execute();
771     $display = "";
773     if(empty($this->macro)&&(!empty($this->goFonMacro))){
775       /* Go through already saved values, for a parameter */
776       $tmp = split("!",$this->goFonMacro);
778       /* it is possible that nothing has been saved yet */
779       if(is_array($tmp)){
781         /* First value is the macroname */
782         $this->macro = $tmp[0];
784         /* Macroname saved, delete that index */
785         unset($tmp[0]);
787         /* Check if macro has been removed */
788         if(!isset($this->macroarray[$this->macro])){
789           $this->macrostillavailable = false;
790         }else{
791           $this->macrostillavailable = true;
792         }
794         /* for each parametervalues ( parameterID#value like 25#twentyfive) */
795         foreach($tmp as $var){
797           /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
798           $varar = split("#",$var);
800           /* Only insert if the parameter still exists */
801           if(isset($this->macroarray[$this->macro][$varar[0]])){
802             /* Assign value */
803             $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
804           }
805         }
806       }
807     }
808     
809     /* Do we represent a valid account? */
810     if (!$this->is_account && $this->parent == NULL){
811       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
812         _("This account has no phone extensions.")."</b>";
813       $display.= back_to_main();
814       return ($display);
815     }
817     /* Do we need to flip is_account state? */
818     if (isset($_POST['modify_state'])){
819       $this->is_account= !$this->is_account;
820     }
822     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
823     if(empty($this->macro)){
824       $this->macro ="none";
825     }
827     /* Prepare templating */
828     $smarty= get_smarty();
830     /* tell user that the selected plugin is no longer available */
831     if((!$this->macrostillavailable)&&($this->macro!="none")){
832       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
833     }
835     /* Assing macroselectbox values  */
836     $smarty->assign("macros",$this->macros);   
837     $smarty->assign("macro", $this->macro);   
839     /* check if there is a FON server created */
840     if(!count($this->goFonHomeServer)){
841       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."));
842     }
844     /* Create html parameter table for selected macro parameters 
845      *  skip if no parameters given 
846      */
847     if(!isset($this->macroarray[$this->macro])){
848       $macrotab="";
849     }else{
851       $macrotab ="<table summary=\""._("Parameter")."\">";
852       /* for every single parameter-> display textfile,combo, or true false switch*/
854       foreach($this->phoneNumbers as $phonenum){
855         $tmp[] = $phonenum;
856       }
857     
858       if($this->macro != $this->lastmacro){
859         /* Go through all params */
860         foreach($this->macroarray[$this->macro] as $key => $paras){
862           $string = $paras['default'];
864           $string=preg_replace("/%uid/i",$this->uid,$string);
866           if(isset($this->cn)){
867             $string=preg_replace("/%cn/i",$this->cn,$string);
868           }
870           for($i = 0 ; $i < 10; $i++){
871             if(isset($tmp[$i])){
872               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
873             }
874           }
875           if(isset($tmp[0])){
876             $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
877           }
878           $this->macroarray[$this->macro][$key]['choosen']=$string;
879         }
880       }
882       foreach($this->macroarray[$this->macro] as $paras){
884         /* get al vars */
885         $var        = $paras['var'];           
886         $name       = $paras['name'];           
887         $default    = $paras['default'];
888         $type       = $paras['type'];
889         $choosen    = $paras['choosen'] ; 
890         $str        = $default;
892         /* in case of a combo box display a combobox with selected attr */
893         $macrotab.= "<tr>";
894         switch ($type){
896           case "combo":
897             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
898           foreach(split(":",$default) as $choice){
899             if($choosen==$choice){
900               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
901             }else{
902               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
903             }
904           }
905           $str.="</select>";
906           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
907           break;
909           case "bool":
910             if(!$choosen){
911               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
912             }else{
913               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
914             }
915           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
916           break;
918           case "string":
919             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
920           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
921           break;
923         }
924         $macrotab.= "</td></tr>";
926       }
927       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
928     }//is_array()
930     /* Give smarty the table */
931     $smarty->assign("macrotab",$macrotab);
934     /* Do we represent a valid account? */
935     if (!$this->is_account && $this->parent == NULL){
936       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
937         _("This account has no phone extensions.")."</b>";
938       $display.= back_to_main();
939       return($display);
940     }
942     $display= "";
944     /* Show tab dialog headers */
945     if ($this->parent != NULL){
946       if ($this->is_account){
947         $display= $this->show_header(_("Remove phone account"),
948             _("This account has phone features enabled. You can disable them by clicking below."));
949       } else {
950         if(empty($this->uid)){
951           $display= $this->show_header(_("Create phone account"),
952               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
953         }else{
954           $display= $this->show_header(_("Create phone account"),
955               _("This account has phone features disabled. You can enable them by clicking below."));
956         }
957         return ($display);
958       }
959     }
961     /* Add phone number */
962     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
963       if (is_phone_nr($_POST['phonenumber'])){
964         $number= $_POST["phonenumber"];
965         $this->phoneNumbers[$number]= $number;
966         $this->is_modified= TRUE;
967       } else {
968         print_red(_("Please enter a valid phone number!"));
969       }
970     }
972     /* Remove phone number */
973     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
974       foreach ($_POST['phonenumber_list'] as $number){
975         unset($this->phoneNumbers[$number]);
976         $this->is_modified= TRUE;
977       }
978     }
980     /* Transfer ACL's */
981     foreach($this->attributes as $val){
982       $smarty->assign($val."ACL", chkacl($this->acl,$val));
983       if(isset($this->$val)){
984         $smarty->assign($val,$this->$val);
985       }else{
986         $smarty->assign($val,"");
987       }
988     }
990     /* Create home server array */
991     $tmp = array();
992     foreach($this->goFonHomeServers as $dn => $attrs){
993       if(!is_numeric($dn)){
994         $tmp[$dn] = $attrs['SERVER'];
995       }
996     }
997     $smarty->assign("goFonHomeServers",$tmp);
999     /* Fill arrays */
1000     $smarty->assign ("goFonHardware", $this->goFonHardware);
1001     if (!count($this->phoneNumbers)){
1002       $smarty->assign ("phoneNumbers", array());
1003     } else {
1004       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1005     }
1006     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
1007       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
1008     foreach ($this->hardware_list as $cn => $description){
1009       if ($cn == $this->goFonHardware){
1010         $selected= "selected";
1011       } else {
1012         $selected= "";
1013       }
1014       if (isset($this->used_hardware[$cn])){
1015         $color= "style=\"color:#A0A0A0\"";
1016       } else {
1017         $color= "";
1018       }
1019       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
1020     }
1021     $hl.= "</select>\n";
1022     $smarty->assign ("hardware_list", $hl);
1024     /* Show main page */
1025     $this->lastmacro = $this->macro;
1026     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1027     return($display);
1028   }
1031   function save_object()
1032   {
1033     if (isset($_POST["phoneTab"])){
1034       plugin::save_object();
1036       /* Save checkbox */
1037       if (isset($_POST['fon_to_mail'])){
1038         $tmp= "[M]";
1039       } else {
1040         $tmp= "[]";
1041       }
1042       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
1043         if ($this->goFonDeliveryMode != $tmp){
1044           $this->is_modified= TRUE;
1045         }
1046         $this->goFonDeliveryMode= $tmp;
1047       }
1049       /* Every macro in the select box are available */
1050       if((isset($_POST['macro']))){
1051         $this->macrostillavailable=true;
1052       }
1054       if(is_array($this->phoneNumbers)){
1055         foreach($this->phoneNumbers as $telenumms) {
1056           $nummsinorder[]=$telenumms; 
1057         }
1058       }else{
1059         $nummsinorder=array("");
1060       }
1062       /* get all Postvars */
1063       if(isset($this->macroarray[$this->macro])){ 
1064         foreach($this->macroarray[$this->macro] as $key => $paras){
1065           if(isset($_POST[$paras['var']])){
1066             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1067           }
1069           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
1070              We need this code below to read and save checkboxes correct
1071            */
1073           if(isset($_POST['post_success'])){
1074             if($this->macroarray[$this->macro][$key]['type']=="bool"){
1075               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1076                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1077               }else{
1078                 $this->macroarray[$this->macro][$key]['choosen']=false;
1079               }
1080             }
1081           }
1082         }
1083       }
1084     }
1085   }
1087   function check()
1088   {
1089     /* Call common method to give check the hook */
1090     $message= plugin::check();
1092     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1093       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1094     }else{
1095       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1096         $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1097       }
1098     }
1100     if((strlen($this->goFonPIN)<=0)){
1101       $message[]=(_("Phone PIN must be at least one character long."));
1102     }else{
1103       if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1104         $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1105       }
1106     }
1108     if(!$this->generate_mysql_entension_entries()){
1109       $message[] = $this->generate_error;
1110     }
1112     /* We need at least one phone number */
1113     if (count($this->phoneNumbers) == 0){
1114       $message[]= sprintf(_("You need to specify at least one phone number!"));
1115     }
1117     /* check for ! in any parameter setting*/
1118     if(isset($this->macroarray[$this->macro])){
1119       foreach($this->macroarray[$this->macro] as $val){
1120         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1121           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1122         }
1123       }
1124     }
1125     return ($message);
1126   }
1130   function save()
1131   {
1132     plugin::save();
1134     /* Save arrays */
1135     $tmp_numbers = array();
1136     foreach ($this->phoneNumbers as $number){
1137       $tmp_numbers[] = $number;
1138     }
1140     /* Save settings, or remove goFonMacro attribute*/
1141     if($this->macro!="none"){    
1142       $this->attrs['goFonMacro']=$this->macro;
1143       if(isset($this->macroarray[$this->macro])){
1144         foreach($this->macroarray[$this->macro] as $paras)  {
1145           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1146         }
1147       }
1148     }else{
1149       $this->attrs['goFonMacro']=array();
1150     }
1151     unset($this->attrs['macro'])  ;
1153     $this->attrs['goFonForwarding']=array();
1155     $this->generate_mysql_entension_entries(true);
1157     if($this->attrs['goFonMacro']==""){
1158       $this->attrs['goFonMacro']=array();
1159     }
1161     unset($this->attrs['cn']);
1163     /* Write back to ldap */
1164     $ldap= $this->config->get_ldap_link();
1165     $ldap->cd($this->dn);
1166     $this->cleanup();
1167     
1168     /* Force saving numbers, else it will be overwriten by user account. */
1169     $this->attrs['telephoneNumber'] =$tmp_numbers;
1170     $ldap->modify ($this->attrs); 
1172     show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
1174     /* Optionally execute a command after we're done */
1176     if ($this->initially_was_account == $this->is_account){
1177       if ($this->is_modified){
1178         $this->handle_post_events("modify",array("uid" => $this->uid));
1179       }
1180     } else {
1181       $this->handle_post_events("add",array("uid" => $this->uid));
1182     }
1184   }
1187   function adapt_from_template($dn)
1188   {
1189     plugin::adapt_from_template($dn);
1191     /* Assemble phone numbers */
1192     if (isset($this->attrs['telephoneNumber'])){
1193       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1194         $number= $this->attrs['telephoneNumber'][$i];
1195         $this->phoneNumbers[$number]= $number;
1196       }
1197     }
1198   }
1201   function remove_from_parent()
1202   {
1203     if(!$this->initially_was_account) return;
1205     foreach($this->attributes as $key=>$val){
1206       if(in_array($val,array("uid","cn"))){
1207         unset($this->attributes[$key]);
1208         unset($this->$val);
1209       }
1210     }
1211     if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1213       // Get Configuration for initial Mysql database Server
1214       $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1215       $s_parameter  ="";
1217       // Connect to DB server
1218       $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1220       // Check if we are  connected correctly
1221       if(!$r_con){
1222         print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1223                     $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1224         gosa_log(@mysql_error());
1225         return false;
1226       }
1228       // Select database for Extensions
1229       $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1231       // Test if we have the database selected correctly
1232       if(!$db){
1233         print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1234         gosa_log(@mysql_error());
1235         return false;
1236       }
1238       $SQL="";
1240       /* If deletion starts from userslist, cn uid are not set */
1241       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1242         $this->uid = $this->parent->by_object['user']->uid;
1243       }
1245       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1246         $this->cn  = $this->parent->by_object['user']->cn;
1247       }
1249       $first_num = false;
1250       // Delete old entries
1251       foreach($this->a_old_telenums as $s_telenums){
1252         if(!$first_num){
1253           $first_num = $s_telenums;
1254         }
1255         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1256       }
1258       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1259       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1260       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1262       foreach($SQL as $query){
1263         if(!@mysql_query($query,$r_con)){
1264           print_red(_("Stop".mysql_error()));
1265           return false;
1266         }
1267       }
1268     }else{
1269       print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1270       return false;
1271     }
1273     /* unset macro attr, it will cause an error */
1274     $tmp = array_flip($this->attributes);
1275     unset($tmp['macro']);
1276     $this->attributes=array_flip($tmp);
1278     /* Cancel if there's nothing to do here */
1279     if (!$this->initially_was_account){
1280       return;
1281     }
1283     plugin::remove_from_parent();
1285     /* Just keep one phone number */
1286     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1287       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1288     } else {
1289       $this->attrs['telephoneNumber']= array();
1290     }
1293     $ldap= $this->config->get_ldap_link();
1294     $ldap->cd($this->config->current['BASE']);
1295     $ldap->search("(objectClass=goFonQueue)", array("member"));
1296     while($attr = $ldap->fetch()){
1297       if(in_array($this->dn,$attr['member'])){
1298         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1299         unset($new->by_object['ogroup']->memberList[$this->dn]);
1300         unset($new->by_object['ogroup']->member[$this->dn]);
1301         $new->save();
1302         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1303       }
1304     }
1305     $ldap->cd($this->dn);
1306     $this->cleanup();
1307     $ldap->modify ($this->attrs); 
1309     show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1311     /* Optionally execute a command after we're done */
1312     @mysql_close($r_con);
1313     $this->handle_post_events('remove',array("uid"=> $this->uid));
1314   }
1318   /* This function checks if the given phonenumbers are available or already in use*/
1319   function is_number_used()
1320   {
1321     $ldap= $this->config->get_ldap_link();
1322     $ldap->cd($this->config->current['BASE']);
1323     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1324     while($attrs = $ldap->fetch()) {
1325       unset($attrs['telephoneNumber']['count']);
1326       foreach($attrs['telephoneNumber'] as $tele){
1327         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1328         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1329         $numbers[$tele]=$attrs;
1330       }
1331     }
1333     foreach($this->phoneNumbers as $num){
1334       if(!isset($this->cn)) $this->cn = "";
1336       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1337         if(isset($numbers[$num]['uid'][0])){
1338           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1339         }else{
1340           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1341         }
1342       }
1343     }
1344   }
1347   /* Create phoneAccount part of copy & paste dialog */
1348   function getCopyDialog()
1349   { 
1350     if(!$this->is_account) return("");
1351     $smarty = get_smarty();
1352     if (!count($this->phoneNumbers)){
1353       $smarty->assign ("phoneNumbers", array(""));
1354     } else {
1355       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1356     }
1358     $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1359     $smarty->assign("goFonPIN",$this->goFonPIN);
1361     $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1362     $ret =array();
1363     $ret['string'] = $display;
1364     $ret['status'] = "";
1365     return($ret);
1366   }
1368   /* Save posts from copy & paste dialog dialog  */
1369   function saveCopyDialog()
1370   {
1371     if(!$this->is_account) return;
1372     $this->execute();
1373     if(isset($_POST['goFonVoicemailPIN'])) {
1374       $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1375     }
1376     if(isset($_POST['goFonPIN'])){
1377       $this->goFonPIN = $_POST['goFonPIN'];
1378     }
1379   }
1382 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1383 ?>