Code

Phone attribute can reinvite set to 'no'
[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        = "";
12   var $goFonHardware          = "";
13   var $goFonFormat            = "";
14   var $goFonPIN               = "";
15   var $goFonVoicePIN          = "";
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 Macro
23   var $macros                 = array();        // List of macros for smarty select box
24   var $macroarray             = array();        // All needed macro informations
25   var $macrostillavailable    = false;
26   var $generate_error         = "";
27   var $a_old_telenums         = array();
28   var $goFonPINVoice          = "";
30   /* CLI vars */
31   var $cli_summary            = "Manage users phone account";
32   var $cli_description        = "Some longer text\nfor help";
33   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
35   /* attribute list for save action */
36   var $attributes             = array("goFonDeliveryMode", "goFonFormat","uid","cn","mail",
37       "goFonHardware","goFonPIN", "telephoneNumber", "goFonMacro","macro");
38   var $objectclasses= array("goFonAccount");
40   function phoneAccount ($config, $dn= NULL)
41   {
42     plugin::plugin ($config, $dn);
44     /* Set phone hardware */
45     if (!isset($this->attrs['goFonHardware'])){
46       $this->goFonHardware= "automatic";
47     }
49     /* Preset voice format */
50     if (!isset($this->attrs['goFonFormat'])){
51       $this->goFonFormat= "wav";
52     }
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     }
69     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
70     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
71     if(!$r_con){
72       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
73           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
74       gosa_log(mysql_error());
75       return false;
76     }
77     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
78     if(!$db){
79       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
80       gosa_log(mysql_error());
81       return false;
82     }
83  
84     $first = false; 
85     foreach($this->phoneNumbers as $key => $val){
86       if(!$first){
87         $first = $key;
88       }
89     }
91     $attrs = @mysql_fetch_row(@mysql_query("SELECT *  FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$first].";"));
92     if($attrs){
93       $this->goFonPINVoice = $attrs[4];
94     }else{
95       $this->goFonPINVoice = false;
96     }
98     /* Load hardware list */
99     $ldap= $this->config->get_ldap_link();
100     $ldap->cd($this->config->current['BASE']);
101     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
102     while ($attrs= $ldap->fetch()){
103       $cn= $attrs['cn'][0];
104       if (isset($attrs['description'])){
105         $description= " - ".$attrs['description'][0];
106       } else {
107         $description= "";
108       }
109       $this->hardware_list[$cn]= "$cn$description";
111     }
113     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
114     $ldap->search("(objectClass=goFonMacro)", array("*"));
116     /* Add none for no macro*/
117     $this->macros['none']=_("no macro");    
118     $this->macro ="none";
121     /* Fetch all Macros*/
122     while ($attrs= $ldap->fetch()){
124       /* Only visisble */
125       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
127         /* unset Count, we don't need that here */
128         unset($attrs['displayName']['count']);
130         /* fill Selectfield variable with Macros */
131         if(isset($attrs['displayName'][0])){
132           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
133         }else{
134           $this->macros[$attrs['dn']] = _("undefined");
135         }
137         /* Parse macro data, unset count for parameterarrays  */
138         unset($attrs['goFonMacroParameter']['count']);
140         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
141         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
143           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
144             /* Split Data in readable values, by delimiter !  */
145             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
147             /* Set all attrs */
148             $id = $data[0];
149             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
150             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
151             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
152             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
153             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
154             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
155             if($data[2] == "bool"){
156               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
157             }
158           }//foreach
159         }//is_array
160       }//visible = 1
161     }//while
163     /* Go through already saved values, for a parameter */
164     $tmp = split("!",$this->goFonMacro);
166     /* it is possible that nothing has been saved yet */
167     if(is_array($tmp)){
169       /* First value is the macroname */
170       $this->macro = $tmp[0];
172       /* Macroname saved, delete that index */
173       unset($tmp[0]);
175       /* Check if makro has been removed */
176       if(!isset($this->macroarray[$this->macro])){
177         $this->macrostillavailable = false;
178       }else{
179         $this->macrostillavailable = true;
180       }
182       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
183       foreach($tmp as $var){
185         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
186         $varar = split("#",$var);
188         /* Only insert if the parameter still exists */
189         if(isset($this->macroarray[$this->macro][$varar[0]])){
190           /* Assign value */
191           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
192         }
193       }
194     }
197     /* Eventually colorize phones */
198     $ldap->cd($this->config->current['BASE']);
199     foreach ($this->hardware_list as $cn => $desc){
200       $ldap->search("(goFonHardware=$cn)", array('cn'));
201       if ($ldap->count() > 0){
202         $ldap->fetch();
203         if ($ldap->getDN() != $this->dn){
204           $this->used_hardware[$cn]= $ldap->getDN();
205         }
206       }
207     }
208     $this->hardware_list["automatic"]= _("automatic");
209     ksort($this->hardware_list);
210     $this->a_old_telenums = $this->phoneNumbers;
212     if($this->is_account){
213       $this->is_modified = true;
214     }
216     /* Set PINs to false, 
217      *  to avoid setting them before we explicitly 
218      *  pressed set voicemail PIN or Phone PIN  
219      */
221     if(count(split("\|",$this->goFonPIN))==2){
222       $tmp = split("\|",$this->goFonPIN);
223       $this->goFonPIN       = $tmp[0]; 
224       $this->goFonVoicePIN  = $tmp[1]; 
225     }else{
226       $this->goFonVoicePIN  = $this->goFonPIN;
227     }
228  
229     // Unset goFonPIN, to avoid save_object for this attribute 
230     foreach($this->attributes as $key=>$val){
231       if($val == "goFonPIN"){
232         unset($this->attributes[$key]);
233       }    
234     }
236   }
239   // Generate MySQL Syntax
240   function generate_mysql_entension_entries($save = false){
242     // Get Configuration for Mysql database Server
243     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
244     $s_parameter    = "";                                           // Contains paramter for selected Macro 
245     $r_con          = false;                                        // DB connection
246     $r_db           = false;                                        // Selected DB
247     $r_res          = false;                                        // Result resource
248     $a_ldap_attrs   = array();                                      //  
250     $s_ip           = NULL;                   // Contains ip for Sip entry
251     $s_host         = NULL;                   // Contains host for Sip entry
252     $s_qualify      = NULL;                   // Qualify entry
253     $s_pin          = NULL;                   // Entry for secret
254     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
256     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
257     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
258     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
260     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
261     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
263     $s_sip_key      = "";     // Key for SIP entry index      
264     $s_sip_val      = "";     // Value for SIP entry index      
266     $b_first_deleted= false;  // Only delete first entry, 
267     $s_telenums     = "";     // for each value variable
269     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
272     // Connect to DB server
273     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
275     // Check if we are  connected correctly
276     if(!$r_con){
277       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
278           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
279       gosa_log(mysql_error());
280       return false;
281     }
283     // Select database for Extensions
284     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
286     // Test if we have the database selected correctly
287     if(!$r_db){
288       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
289       gosa_log(mysql_error());
290       return false;
291     }
293     // Get phonehardware to setup sip entry
294     $ldap         = $this->config->get_ldap_link();
295     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
296     $a_ldap_attrs = $ldap->fetch();
298     if($this->is_number_used()){
299       $this->generate_error = $this->is_number_used(); 
300       return false;
301     }
303     $existence = @mysql_fetch_row(@mysql_query(  "SELECT * FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';"));
304     
305     if(!$existence&&((empty($this->goFonPIN))||(empty($this->goFonVoicePIN)))){
306       $this->generate_error = _("You are currently creating a new phone account, please specify a value for phone PIN and voice PIN.");  
307       return(false);
308     }
309   
310     if((empty($this->goFonPIN))&&(empty($existence[27]))){
311       $this->generate_error = _("The PIN attribute is missing in database entry. Please assign a valid phone PIN.");  
312       return(false);
313     }
314   
315     if(isset($existence[15])){
316       $voice = @mysql_fetch_row(@mysql_query("SELECT password FROM ".$a_SETUP['VOICE_TABLE']." where customer_id='".$existence[15]."'"));
317       if((empty($this->goFonVoicePIN))&&(empty($voice[0]))){
318         $this->generate_error = _("The voice PIN attribute is missing in database entry. Please assign a valid voice PIN.");
319         return(false);
320       }
321     }
322      
323     /* If Save == true, we should save something.
324      * Generate SQL, for drop of old entries
325      * Generate SQL, for insert new entries
326      */ 
327     if($save == true){
329       /* Get old voice passwword if no new isset */
330       if($this->goFonPIN==false){
331         $pin = @mysql_fetch_row(@mysql_query("SELECT secret FROM ".$a_SETUP['SIP_TABLE']." where name='".$this->uid."'"));
332         $this->goFonPIN = $pin[0];
333       }
335       // Attribute GoFonDefaultIP set ?
336       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
337         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
338         $s_host     = $s_ip;
339       }else{
340         $s_ip       = NULL;
341         $s_host     = "dynamic";
342       }
344       // Attribute GoFonQualify set ?
345       if(isset($a_ldap_attrs['goFonQualify'])){
346         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
347       }
349       // Attribute GoFonPIN set ?
350       if(isset($this->goFonPIN)){
351         $s_pin      = $this->goFonPIN;
352       }
354       // Attribute GoFonType set ?
355       if(isset($a_ldap_attrs['goFonType'])){
356         $s_type = $a_ldap_attrs['goFonType'][0];
357       }
359       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
360         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
361       }else{
362         $sip_data_array['dtmfmode']     ="rfc2833";
363       }
365       // generate SIP entry
366       $sip_data_array['id']           = "";
367       $sip_data_array['name']         = $this->uid;
368       $sip_data_array['accountcode']  = NULL;          
369       $sip_data_array['amaflags']     = NULL;
370       $sip_data_array['callgroup']    = NULL;
371       $sip_data_array['callerid']     = "";
372       $sip_data_array['canreinvite']  = "no";
373       $sip_data_array['context']      = "default";
374       $sip_data_array['defaultip']    = NULL;
375       $sip_data_array['fromuser']     = NULL;
376       $sip_data_array['fromdomain']   = NULL;
377       $sip_data_array['host']         = $s_host;
378       $sip_data_array['insecure']     = NULL;
379       $sip_data_array['language']     = NULL;
380       $sip_data_array['mailbox']      = "asterisk";
381       $sip_data_array['md5secret']    = NULL;
382       $sip_data_array['nat']          = "no";
383       $sip_data_array['permit']       = NULL;
384       $sip_data_array['deny']         = NULL;
385       $sip_data_array['mask']         = NULL;
386       $sip_data_array['pickupgroup']  = NULL;
387       $sip_data_array['port']         = NULL;
388       $sip_data_array['qualify']      = $s_qualify;
389       $sip_data_array['restrictcid']  = "n";
390       $sip_data_array['rtptimeout']   = NULL;
391       $sip_data_array['rtpholdtimeout']=NULL;
392       $sip_data_array['secret']       = $s_pin;
393       $sip_data_array['type']         = $s_type ;
394       $sip_data_array['username']     = $this->uid;
395       $sip_data_array['disallow']     = NULL;
396       $sip_data_array['allow']        = NULL;
397       $sip_data_array['musiconhold']  = NULL;
398       $sip_data_array['regseconds']   = NULL;
399       $sip_data_array['ipaddr']       = $s_ip;
400       $sip_data_array['regexten']     = NULL;
401       $sip_data_array['cancallforward']=NULL;
403       // Get selected Macro Parameter and create parameter entry 
404       if(isset($this->macroarray[$this->macro])){
405         foreach($this->macroarray[$this->macro] as $key => $val ){
406           $s_parameter .= $val['choosen']."|";
407         }
408         $s_parameter = preg_replace("/\|$/","",$s_parameter);
409       }
411       if($this->is_number_used()){
412         $this->generate_error = $this->is_number_used(); 
413         return false;
414       }
416       // Create new SIP entry ...
417       $sip_entry = $sip_data_array;
418       reset($this->phoneNumbers);
419       $i_new_key = key($this->phoneNumbers);
420       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
421       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
423       if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
424         $s_mail = $this->parent->by_object['mailAccount']->mail;
425       }else{
426         $s_mail = "";
427       }
430       /* Get old voice passwword if no new isset */
431       if($this->goFonVoicePIN==false){
432         $voice = @mysql_fetch_row(@mysql_query("SELECT password FROM ".$a_SETUP['VOICE_TABLE']." where customer_id=".$this->phoneNumbers[$i_new_key].""));
433         $this->goFonVoicePIN = $voice[0];
434       }
435       
436       /* Get old voice passwword if no new isset */
437       if($this->goFonPIN==false){
438         $pin = @mysql_fetch_row(@mysql_query("SELECT secret FROM ".$a_SETUP['SIP_TABLE']." where name='".$this->uid."'"));
439         $this->goFonPIN = $pin[0];
440       }
441     
442       // $SQL contains all queries
443       $SQL   = array();
444       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
445       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
446       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
448       // Generate Strings with keys and values 
449       foreach($sip_entry as $s_sip_key=>$s_sip_val){
450         if($s_sip_val == NULL) continue;
451         $s_sip_values.="'".$s_sip_val."',";
452         $s_sip_keys  .="`".$s_sip_key."`,";
453       }
454       // Remove last ,
455       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
456       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
458       // Append SIP Entry 
459       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
461       // Delete old entries
462       $b_first_deleted  =false;
463       foreach($this->a_old_telenums as $s_telenums){
464         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
465         if(!$b_first_deleted){
466           $b_first_deleted=true;
467           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
468         }
469       }
471       if(empty($this->goFonPINVoice)){
472         $this->goFonPINVoice = $this->goFonPIN;
473       } 
475       /* If deletion starts from userslist, cn uid are not set */
476       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
477         $this->uid = $this->parent->by_object['user']->uid;
478       }
480       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
481         $this->cn  = $this->parent->by_object['user']->cn;
482       }
484       if((!isset($this->cn))||(empty($this->cn))){
485         $CNname= $this->uid;
486       }else{
487         $CNname= $this->cn;
488       }
490       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
491           VALUES   ('".$this->phoneNumbers[$i_new_key]."',
492                     'default',
493                     '".$this->phoneNumbers[$i_new_key]."',
494                     '".$this->goFonVoicePIN."',
495                     '".$CNname."',
496                     '".$s_mail."',
497                     '');";
498       $i_is_accounted=false;
499     
500       $i = 0; 
501   
502       // Entension entries  Hint / Dial / Goto
503       foreach($this->phoneNumbers as $s_telenums){
505         /* Mapping : Name TO Number*/
506         $EXT[$i]['context'] = 'GOsa';
507         $EXT[$i]['exten']   = $this->uid;
508         $EXT[$i]['priority']= 1;
509         $EXT[$i]['app']     = "Goto";
510         $EXT[$i]['appdata'] = $s_telenums."|1";
511         $i ++;  
512         /* Hint Entry */
513         $EXT[$i]['context'] = 'GOsa';
514         $EXT[$i]['exten']   = $s_telenums;
515         $EXT[$i]['priority']= "Hint";
516         $EXT[$i]['app']     = 'SIP/'.$this->uid;
517         $i ++;  
518         /* SetCID */
519         $EXT[$i]['context'] = 'GOsa';
520         $EXT[$i]['exten']   = $s_telenums;
521         $EXT[$i]['priority']= 1;
522         $EXT[$i]['app']     = "SetCIDName";
523         $EXT[$i]['appdata'] = $CNname;
524         $i ++;  
526         // If no macro is selected use Dial
527         if($this->macro!="none"){ 
528           $macroname = preg_replace("/,.*$/","",$this->macro);        
529           $macroname = preg_replace("/^.*=/","",$macroname);        
530           $s_app = "Macro";$macroname;
531           $s_par = $macroname."|".$s_parameter; 
532         }else{
533           $s_app = "Dial";
534           $s_par = 'SIP/'.$this->uid;
535         }
537         $EXT[$i]['context'] = 'GOsa';
538         $EXT[$i]['exten']   = $s_telenums;
539         $EXT[$i]['priority']= 2;
540         $EXT[$i]['app']     = $s_app;
541         $EXT[$i]['appdata'] = $s_par;
542         $i ++;
544       }
546       // Append all these Entries 
547       foreach($EXT as $entr){
548         $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
549         foreach($entr as $key2 => $val2){
550           $SQL_syn.= "`".$key2."`,";
551         }
552         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
553         $SQL_syn .= ") VALUES ("; 
554         foreach($entr as $key2 => $val2){
555           $SQL_syn .= "'".$val2."',";
556         }
557         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
558         $SQL_syn .=");\n";
559         $SQL[] =$SQL_syn;
560         $SQL_syn ="";
561       }
563       // Perform queries ...
564       foreach($SQL as $query){
565         if(!@mysql_query($query,$r_con)){
566           print_red(_("Error while performing query ".mysql_error()));
567           return false;
568         }
569       }
570     }
571     return true;
572   }
575   function execute()
576   {
577     /* Do we represent a valid account? */
578     if (!$this->is_account && $this->parent == NULL){
579       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
580         _("This account has no phone extensions.")."</b>";
581       $display.= back_to_main();
582       return ($display);
583     }
585     /* Do we need to flip is_account state? */
586     if (isset($_POST['modify_state'])){
587       $this->is_account= !$this->is_account;
588     }
590     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
591     if(empty($this->macro)){
592       $this->macro ="none";
593     }
595     if(isset($_POST['goFonVoicePINSet'])){
596       if((strlen($_POST['goFonVoicePIN'])==0)||(strlen($_POST['goFonVoicePIN'])>4)){
597         print_red(_("Voicemail PIN must be between 1-4 characters."));
598       }else{
599         if(preg_match("/[^0-9]/",$_POST['goFonVoicePIN'])){
600           print_red(_("The specified oicemail PIN contains invalid characters, only numeric values are allowed here."));
601         }else{
602           $this->goFonVoicePIN=$_POST['goFonVoicePIN'];
603         }
604       }
605     }
607     if(isset($_POST['goFonPINSet'])){
608       if((strlen($_POST['goFonPIN'])!=4)){
609         print_red(_("Phone PIN must be 4 characters long."));
610       }else{
611         if(preg_match("/[^0-9]/",$_POST['goFonVoicePIN'])){
612           print_red(_("The specified phone PIN contains invalid characters, only numeric values are allowed here."));
613         }else{
614           $this->goFonPIN=$_POST['goFonPIN'];
615         }
616       }
617     }
619     /* tell user that the pluging selected is no longer available*/
620     if((!$this->macrostillavailable)&&($this->macro!="none")){
621       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
622     }
624     /* Prepare templating */
625     $smarty= get_smarty();
627     /* Assing macroselectbox values  */
628     $smarty->assign("macros",$this->macros);   
629     $smarty->assign("macro", $this->macro);   
631     /* Create parameter table, skip if no parameters given */
632     if(!isset($this->macroarray[$this->macro])){
633       $macrotab="";
634     }else{
636       $macrotab ="<table summary=\""._("Parameter")."\">";
637       /* for every single parameter-> display textfile,combo, or true false switch*/
640       /* Automatic fill out */
641       if(isset($_POST['fillout'])){
643         foreach($this->phoneNumbers as $phonenum){
644           $tmp[] = $phonenum;
645         }
647         /* Go through all params */
648         foreach($this->macroarray[$this->macro] as $key => $paras){
650           $string = $paras['default'];
652           $string=preg_replace("/%uid/i",$this->uid,$string);
653           
654           if(isset($this->cn)){
655             $string=preg_replace("/%cn/i",$this->cn,$string);
656           }
658           for($i = 0 ; $i < 10; $i++){
659             if(isset($tmp[$i])){
660               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
661             }
662           }
664           $this->macroarray[$this->macro][$key]['choosen']=$string;
665         }
666       }
668       foreach($this->macroarray[$this->macro] as $paras){
670         /* get al vars */
671         $var        = $paras['var'];           
672         $name       = $paras['name'];           
673         $default    = $paras['default'];
674         $type       = $paras['type'];
675         $choosen    = $paras['choosen'] ; 
676         $str        = $default;
678         /* in case of a combo box display a combobox with selected attr */
679         $macrotab.= "<tr>";
680         switch ($type){
682           case "combo":
683             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
684           foreach(split(":",$default) as $choice){
685             if($choosen==$choice){
686               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
687             }else{
688               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
689             }
690           }
691           $str.="</select>";
692           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
693           break;
695           case "bool":
696             if(!$choosen){
697               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
698             }else{
699               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
700             }
701           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
702           break;
704           case "string":
705             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
706           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
707           break;
709         }
710         $macrotab.= "</td></tr>";
712       }
713       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
714     }//is_array()
716     /* Give smarty the table */
717     $smarty->assign("macrotab",$macrotab);
719     /* Do we represent a valid account? */
720     if (!$this->is_account && $this->parent == NULL){
721       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
722         _("This account has no phone extensions.")."</b>";
723       $display.= back_to_main();
724       return($display);
725     }
727     $display= "";
729     /* Show tab dialog headers */
730     if ($this->parent != NULL){
731       if ($this->is_account){
732         $display= $this->show_header(_("Remove phone account"),
733             _("This account has phone features enabled. You can disable them by clicking below."));
734       } else {
735         if(empty($this->uid)){
736           $display= $this->show_header(_("Create phone account"),
737               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
738         }else{
739           $display= $this->show_header(_("Create phone account"),
740               _("This account has phone features disabled. You can enable them by clicking below."));
741         }
742         return ($display);
743       }
744     }
746     /* Add phone number */
747     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
748       if (is_phone_nr($_POST['phonenumber'])){
749         $number= $_POST["phonenumber"];
750         $this->phoneNumbers[$number]= $number;
751         $this->is_modified= TRUE;
752       } else {
753         print_red(_("Please enter a valid phone number!"));
754       }
755     }
757     /* Remove phone number */
758     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
759       foreach ($_POST['phonenumber_list'] as $number){
760         unset($this->phoneNumbers[$number]);
761         $this->is_modified= TRUE;
762       }
763     }
765     /* Transfer ACL's */
766     foreach($this->attributes as $val){
767       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
768       if(isset($this->$val)){
769         $smarty->assign($val,$this->$val);
770       }else{
771         $smarty->assign($val,"");
772       }
773     }
775     /* Fill arrays */
776     $smarty->assign ("goFonHardware", $this->goFonHardware);
777     if (!count($this->phoneNumbers)){
778       $smarty->assign ("phoneNumbers", array(""));
779     } else {
780       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
781     }
782     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
783       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
784     foreach ($this->hardware_list as $cn => $description){
785       if ($cn == $this->goFonHardware){
786         $selected= "selected";
787       } else {
788         $selected= "";
789       }
790       if (isset($this->used_hardware[$cn])){
791         $color= "style=\"color:#A0A0A0\"";
792       } else {
793         $color= "";
794       }
795       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
796     }
797     $hl.= "</select>\n";
798     $smarty->assign ("hardware_list", $hl);
800     /* Show main page */
802     foreach(array("goFonVoicePIN","goFonPIN") as $attrs ){
803       $smarty->assign($attrs,$this->$attrs);
804       $smarty->assign($attrs."ACL",chkacl($this->acl,$attrs));
805     }
808     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
809     return($display);
810   }
813   function save_object()
814   {
815     if (isset($_POST["phoneTab"])){
816       plugin::save_object();
818       /* Save checkbox */
819       if (isset($_POST['fon_to_mail'])){
820         $tmp= "[M]";
821       } else {
822         $tmp= "[]";
823       }
824       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
825         if ($this->goFonDeliveryMode != $tmp){
826           $this->is_modified= TRUE;
827         }
828         $this->goFonDeliveryMode= $tmp;
829       }
831       /* Every macro in the select box are available */
832       if((isset($_POST['macro']))){
833         $this->macrostillavailable=true;
834       }
836       if(is_array($this->phoneNumbers)){
837         foreach($this->phoneNumbers as $telenumms) {
838           $nummsinorder[]=$telenumms; 
839         }
840       }else{
841         $nummsinorder=array("");
842       }
844       /* get all Postvars */
845       if(isset($this->macroarray[$this->macro])){ 
846         foreach($this->macroarray[$this->macro] as $key => $paras){
847           if(isset($_POST[$paras['var']])){
848             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
849           }
851           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
852              We need this code below to read and save checkboxes correct
853            */
855           if(isset($_POST['post_success'])){
856             if($this->macroarray[$this->macro][$key]['type']=="bool"){
857               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
858                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
859               }else{
860                 $this->macroarray[$this->macro][$key]['choosen']=false;
861               }
862             }
863           }
864         }
865       }
866     }
867   }
869   function check()
870   {
871     /* Reset message array */
872     $message= array();
874     if(!$this->generate_mysql_entension_entries()){
875       $message[] = $this->generate_error;
876     }
878     /* We need at least one phone number */
879     if (count($this->phoneNumbers) == 0){
880       $message[]= sprintf(_("You need to specify at least one phone number!"));
881     }
883     /* check for ! in any parameter setting*/
884     if(isset($this->macroarray[$this->macro])){
885       foreach($this->macroarray[$this->macro] as $val){
886         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
887           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
888         }
889       }
890     }
891     return ($message);
892   }
896   function save()
897   {
898     plugin::save();
900     /* Save arrays */
901     $this->attrs['telephoneNumber']= array();
902     foreach ($this->phoneNumbers as $number){
903       $this->attrs['telephoneNumber'][]= $number;
904     }
906     /* Save settings, or remove goFonMacro attribute*/
907     if($this->macro!="none"){    
908       $this->attrs['goFonMacro']=$this->macro;
909       if(isset($this->macroarray[$this->macro])){
910         foreach($this->macroarray[$this->macro] as $paras)  {
911           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
912         }
913       }
914     }else{
915       $this->attrs['goFonMacro']=array();
916     }
917     unset($this->attrs['macro'])  ;
919     $this->attrs['goFonForwarding']=array();
921     $this->generate_mysql_entension_entries(true);
923     if($this->attrs['goFonMacro']==""){
924       $this->attrs['goFonMacro']=array();
925     }
927     /* Cahnged behavior for goFonPIN */
928     $this->attrs['goFonPIN'] = $this->goFonPIN."|".$this->goFonVoicePIN;
929   
930     unset($this->attrs['cn']);
932     /* Write back to ldap */
933     $ldap= $this->config->get_ldap_link();
934     $ldap->cd($this->dn);
935     $ldap->modify($this->attrs);
936     show_ldap_error($ldap->get_error());
938     /* Optionally execute a command after we're done */
940     if ($this->initially_was_account == $this->is_account){
941       if ($this->is_modified){
942         $this->handle_post_events("modify");
943       }
944     } else {
945       $this->handle_post_events("add");
946     }
948   }
951   function insert_after($entry, $nr, $list)
952   {
953     /* Is the entry free? No? Make it free... */
954     if (isset($list[$nr])) {
955       $dest= array();
956       $newidx= 0;
958       foreach ($list as $idx => $contents){
959         $dest[$newidx++]= $contents;
960         if ($idx == $nr){
961           $dest[$newidx++]= $entry;
962         }
963       }
964     } else {
965       $dest= $list;
966       $dest[$nr]= $entry;
967     }
969     return ($dest);
970   }
973   function adapt_from_template($dn)
974   {
975     plugin::adapt_from_template($dn);
977     /* Assemble phone numbers */
978     if (isset($this->attrs['telephoneNumber'])){
979       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
980         $number= $this->attrs['telephoneNumber'][$i];
981         $this->phoneNumbers[$number]= $number;
982       }
983     }
984   }
987   function remove_from_parent()
988   {
989   
990     foreach($this->attributes as $key=>$val){
991       if(in_array($val,array("uid","cn","mail"))){
992         unset($this->attributes[$key]);
993         unset($this->$val);
994       }
995     }
997     $this->attributes[]="goFonPIN";
999     // Get Configuration for Mysql database Server
1000     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
1001     $s_parameter  ="";
1003     // Connect to DB server
1004     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1006     // Check if we are  connected correctly
1007     if(!$r_con){
1008       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1009           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
1010       gosa_log(@mysql_error());
1011       return false;
1012     }
1014     // Select database for Extensions
1015     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
1017     // Test if we have the database selected correctly
1018     if(!$db){
1019       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
1020       gosa_log(@mysql_error());
1021       return false;
1022     }
1024     $SQL="";
1026     /* If deletion starts from userslist, cn uid are not set */
1027     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1028       $this->uid = $this->parent->by_object['user']->uid;
1029     }
1031     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1032       $this->cn  = $this->parent->by_object['user']->cn;
1033     }
1035     $first_num = false;
1036     // Delete old entries
1037     foreach($this->a_old_telenums as $s_telenums){
1038       if(!$first_num){
1039         $first_num = $s_telenums;
1040       }
1041       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1042     }
1044     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1045     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1046     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1049     foreach($SQL as $query){
1050       if(!@mysql_query($query,$r_con)){
1051         print_red(_("Stop".mysql_error()));
1052         return false;
1053       }
1054     }
1058     /* unset macro attr, it will cause an error */
1059     $tmp = array_flip($this->attributes);
1060     unset($tmp['macro']);
1061     $this->attributes=array_flip($tmp);
1063     /* Cancel if there's nothing to do here */
1064     if (!$this->initially_was_account){
1065       return;
1066     }
1068     plugin::remove_from_parent();
1070     /* Just keep one phone number */
1071     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1072       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1073     } else {
1074       $this->attrs['telephoneNumber']= array();
1075     }
1077     $ldap= $this->config->get_ldap_link();
1078     $ldap->cd($this->config->current['BASE']);
1079     $ldap->search("(objectClass=goFonQueue)", array("member"));
1080     while($attr = $ldap->fetch()){
1081       if(in_array($this->dn,$attr['member'])){
1082         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1083         unset($new->by_object['ogroup']->memberList[$this->dn]);
1084         unset($new->by_object['ogroup']->member[$this->dn]);
1085         $new->save();
1086         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1087       }
1088     }
1089     $ldap->cd($this->dn);
1090     $ldap->modify($this->attrs);
1091     show_ldap_error($ldap->get_error());
1093     /* Optionally execute a command after we're done */
1094     $this->handle_post_events('remove');
1095   }
1099   /* This function checks if the given phonenumbers are available or already in use*/
1100   function is_number_used()
1101   {
1102     $ldap= $this->config->get_ldap_link();
1103     $ldap->cd($this->config->current['BASE']);
1104     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1105     while($attrs = $ldap->fetch()) {
1106       unset($attrs['telephoneNumber']['count']);
1107       foreach($attrs['telephoneNumber'] as $tele){
1108         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1109         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1110         $numbers[$tele]=$attrs;
1111       }
1112     }
1114     foreach($this->phoneNumbers as $num){
1115       if(!isset($this->cn)) $this->cn = "";
1117       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1118         if(isset($numbers[$num]['uid'][0])){
1119           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1120         }else{
1121           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1122         }
1123       }
1124     }
1125   }
1128 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1129 ?>