Code

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