Code

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