Code

parent / voicemail PIN fixes
[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 $goFonDeliveryMode      = "";
16   var $phoneNumbers           = array();
17   var $mail                   = "";
18   var $hardware_list          = array();
19   var $used_hardware          = array();
20   var $goFonMacro             = "";
21   var $macro                  = 0;              // Selected Macro
22   var $macros                 = array();        // List of macros for smarty select box
23   var $macroarray             = array();        // All needed macro informations
24   var $macrostillavailable    = false;
25   var $generate_error         = "";
26   var $a_old_telenums         = array();
27   var $goFonPINVoice          = "";
29   /* CLI vars */
30   var $cli_summary            = "Manage users phone account";
31   var $cli_description        = "Some longer text\nfor help";
32   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
34   /* attribute list for save action */
35   var $attributes             = array("goFonDeliveryMode", "goFonFormat","uid","cn","mail",
36       "goFonHardware", "goFonPIN", "telephoneNumber", "goFonMacro","macro");
37   var $objectclasses= array("goFonAccount");
39   function phoneAccount ($config, $dn= NULL)
40   {
41     plugin::plugin ($config, $dn);
43     /* Set phone hardware */
44     if (!isset($this->attrs['goFonHardware'])){
45       $this->goFonHardware= "automatic";
46     }
48     /* Preset voice format */
49     if (!isset($this->attrs['goFonFormat'])){
50       $this->goFonFormat= "wav";
51     }
53     /* Assemble phone numbers */
54     if (isset($this->attrs['telephoneNumber'])){
55       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
56         $number= $this->attrs['telephoneNumber'][$i];
57         $this->phoneNumbers[$number]= $number;
58       }
59     }
61     /* Set up has_mailAccount */
62     if (isset($this->attrs['objectClass'])){
63       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
64         $this->has_mailAccount= TRUE;
65       }
66     }
68     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
69     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
70     if(!$r_con){
71       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
72           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
73       gosa_log(mysql_error());
74       return false;
75     }
76     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
77     if(!$db){
78       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
79       gosa_log(mysql_error());
80       return false;
81     }
82  
83     $first = false; 
84     foreach($this->phoneNumbers as $key => $val){
85       if(!$first){
86         $first = $key;
87       }
88     }
90     $attrs = mysql_fetch_row(mysql_query("SELECT *  FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$first].";"));
91     if($attrs){
92       $this->goFonPINVoice = $attrs[4];
93     }else{
94       $this->goFonPINVoice = false;
95     }
97     /* Load hardware list */
98     $ldap= $this->config->get_ldap_link();
99     $ldap->cd($this->config->current['BASE']);
100     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
101     while ($attrs= $ldap->fetch()){
102       $cn= $attrs['cn'][0];
103       if (isset($attrs['description'])){
104         $description= " - ".$attrs['description'][0];
105       } else {
106         $description= "";
107       }
108       $this->hardware_list[$cn]= "$cn$description";
110     }
112     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
113     $ldap->search("(objectClass=goFonMacro)", array("*"));
115     /* Add none for no macro*/
116     $this->macros['none']=_("no macro");    
117     $this->macro ="none";
120     /* Fetch all Macros*/
121     while ($attrs= $ldap->fetch()){
123       /* Only visisble */
124       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
126         /* unset Count, we don't need that here */
127         unset($attrs['displayName']['count']);
129         /* fill Selectfield variable with Macros */
130         if(isset($attrs['displayName'][0])){
131           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
132         }else{
133           $this->macros[$attrs['dn']] = _("undefined");
134         }
136         /* Parse macro data, unset count for parameterarrays  */
137         unset($attrs['goFonMacroParameter']['count']);
139         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
140         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
142           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
143             /* Split Data in readable values, by delimiter !  */
144             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
146             /* Set all attrs */
147             $id = $data[0];
148             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
149             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
150             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
151             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
152             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
153             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
154             if($data[2] == "bool"){
155               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
156             }
157           }//foreach
158         }//is_array
159       }//visible = 1
160     }//while
162     /* Go through already saved values, for a parameter */
163     $tmp = split("!",$this->goFonMacro);
165     /* it is possible that nothing has been saved yet */
166     if(is_array($tmp)){
168       /* First value is the macroname */
169       $this->macro = $tmp[0];
171       /* Macroname saved, delete that index */
172       unset($tmp[0]);
174       /* Check if makro has been removed */
175       if(!isset($this->macroarray[$this->macro])){
176         $this->macrostillavailable = false;
177       }else{
178         $this->macrostillavailable = true;
179       }
181       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
182       foreach($tmp as $var){
184         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
185         $varar = split("#",$var);
187         /* Only insert if the parameter still exists */
188         if(isset($this->macroarray[$this->macro][$varar[0]])){
189           /* Assign value */
190           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
191         }
192       }
193     }
196     /* Eventually colorize phones */
197     $ldap->cd($this->config->current['BASE']);
198     foreach ($this->hardware_list as $cn => $desc){
199       $ldap->search("(goFonHardware=$cn)", array('cn'));
200       if ($ldap->count() > 0){
201         $ldap->fetch();
202         if ($ldap->getDN() != $this->dn){
203           $this->used_hardware[$cn]= $ldap->getDN();
204         }
205       }
206     }
207     $this->hardware_list["automatic"]= _("automatic");
208     ksort($this->hardware_list);
209     $this->a_old_telenums = $this->phoneNumbers;
210   }
213   // Generate MySQL Syntax
214   function generate_mysql_entension_entries($save = false){
216     // Get Configuration for Mysql database Server
217     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
218     $s_parameter    = "";                                           // Contains paramter for selected Macro 
219     $r_con          = false;                                        // DB connection
220     $r_db           = false;                                        // Selected DB
221     $r_res          = false;                                        // Result resource
222     $a_ldap_attrs   = array();                                      //  
224     $s_ip           = NULL;                   // Contains ip for Sip entry
225     $s_host         = NULL;                   // Contains host for Sip entry
226     $s_qualify      = NULL;                   // Qualify entry
227     $s_pin          = NULL;                   // Entry for secret
228     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
230     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
231     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
232     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
234     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
235     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
237     $s_sip_key      = "";     // Key for SIP entry index      
238     $s_sip_val      = "";     // Value for SIP entry index      
240     $b_first_deleted= false;  // Only delete first entry, 
241     $s_telenums     = "";     // for each value variable
243     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
246     // Connect to DB server
247     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
249     // Check if we are  connected correctly
250     if(!$r_con){
251       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
252           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
253       gosa_log(mysql_error());
254       return false;
255     }
257     // Select database for Extensions
258     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
260     // Test if we have the database selected correctly
261     if(!$r_db){
262       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
263       gosa_log(mysql_error());
264       return false;
265     }
267     // Get phonehardware to setup sip entry
268     $ldap         = $this->config->get_ldap_link();
269     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
270     $a_ldap_attrs = $ldap->fetch();
272     if($this->is_number_used()){
273       $this->generate_error = $this->is_number_used(); 
274       return false;
275     }
277     /* If Save == true, we should save something.
278      * Generate SQL, for drop of old entries
279      * Generate SQL, for insert new entries
280      */ 
281     if($save == true){
282       // Attribute GoFonDefaultIP set ?
283       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
284         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
285         $s_host     = $s_ip;
286       }else{
287         $s_ip       = NULL;
288         $s_host     = "dynamic";
289       }
291       // Attribute GoFonQualify set ?
292       if(isset($a_ldap_attrs['goFonQualify'])){
293         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
294       }
296       // Attribute GoFonPIN set ?
297       if(isset($this->goFonPIN)){
298         $s_pin      = $this->goFonPIN;
299       }
301       // Attribute GoFonType set ?
302       if(isset($a_ldap_attrs['goFonType'])){
303         $s_type = $a_ldap_attrs['goFonType'][0];
304       }
306       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
307         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
308       }else{
309         $sip_data_array['dtmfmode']     ="rfc2833";
310       }
312       // generate SIP entry
313       $sip_data_array['id']           = "";
314       $sip_data_array['name']         = $this->uid;
315       $sip_data_array['accountcode']  = NULL;          
316       $sip_data_array['amaflags']     = NULL;
317       $sip_data_array['callgroup']    = NULL;
318       $sip_data_array['callerid']     = "";
319       $sip_data_array['canreinvite']  = "yes";
320       $sip_data_array['context']      = "default";
321       $sip_data_array['defaultip']    = NULL;
322       $sip_data_array['fromuser']     = NULL;
323       $sip_data_array['fromdomain']   = NULL;
324       $sip_data_array['host']         = $s_host;
325       $sip_data_array['insecure']     = NULL;
326       $sip_data_array['language']     = NULL;
327       $sip_data_array['mailbox']      = "asterisk";
328       $sip_data_array['md5secret']    = NULL;
329       $sip_data_array['nat']          = "no";
330       $sip_data_array['permit']       = NULL;
331       $sip_data_array['deny']         = NULL;
332       $sip_data_array['mask']         = NULL;
333       $sip_data_array['pickupgroup']  = NULL;
334       $sip_data_array['port']         = NULL;
335       $sip_data_array['qualify']      = $s_qualify;
336       $sip_data_array['restrictcid']  = "n";
337       $sip_data_array['rtptimeout']   = NULL;
338       $sip_data_array['rtpholdtimeout']=NULL;
339       $sip_data_array['secret']       = $s_pin;
340       $sip_data_array['type']         = $s_type ;
341       $sip_data_array['username']     = $this->uid;
342       $sip_data_array['disallow']     = NULL;
343       $sip_data_array['allow']        = NULL;
344       $sip_data_array['musiconhold']  = NULL;
345       $sip_data_array['regseconds']   = NULL;
346       $sip_data_array['ipaddr']       = $s_ip;
347       $sip_data_array['regexten']     = NULL;
348       $sip_data_array['cancallforward']=NULL;
350       // Get selected Macro Parameter and create parameter entry 
351       if(isset($this->macroarray[$this->macro])){
352         foreach($this->macroarray[$this->macro] as $key => $val ){
353           $s_parameter .= $val['choosen']."|";
354         }
355         $s_parameter = preg_replace("/\|$/","",$s_parameter);
356       }
358       if($this->is_number_used()){
359         $this->generate_error = $this->is_number_used(); 
360         return false;
361       }
363       // Create new SIP entry ...
364       $sip_entry = $sip_data_array;
365       reset($this->phoneNumbers);
366       $i_new_key = key($this->phoneNumbers);
367       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
368       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
370       if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
371         $s_mail = $this->parent->by_object['mailAccount']->mail;
372       }else{
373         $s_mail = "";
374       }
376       // $SQL contains all queries
377       $SQL   = array();
378       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
379       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
380       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
382       // Generate Strings with keys and values 
383       foreach($sip_entry as $s_sip_key=>$s_sip_val){
384         if($s_sip_val == NULL) continue;
385         $s_sip_values.="'".$s_sip_val."',";
386         $s_sip_keys  .="`".$s_sip_key."`,";
387       }
388       // Remove last ,
389       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
390       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
392       // Append SIP Entry 
393       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
395       // Delete old entries
396       $b_first_deleted  =false;
397       foreach($this->a_old_telenums as $s_telenums){
398         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
399         if(!$b_first_deleted){
400           $b_first_deleted=true;
401           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
402         }
403       }
405       if(empty($this->goFonPINVoice)){
406         $this->goFonPINVoice = $this->goFonPIN;
407       } 
409       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']."
410         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
411         VALUES
412         ('".$this->phoneNumbers[$i_new_key]."','default','".$this->phoneNumbers[$i_new_key]."','".$this->goFonPINVoice."','".$this->sn."','".$s_mail."','');";
414       $i_is_accounted=false;
416       // Entension entries  Hint / Dial / Goto
417       foreach($this->phoneNumbers as $s_telenums){
418         // Entry  to call by name
419         $s_entry_name['context']  = 'GOsa';
420         $s_entry_name['exten']    = $this->uid;
421         $s_entry_name['priority'] = 1;
422         $s_entry_name['app']      = 'Goto';
423         $s_entry_name['appdata']  = $s_telenums."|1";
425         // hint
426         $s_entry_hint['context']  = 'GOsa';
427         $s_entry_hint['exten']    = $s_telenums;
428         $s_entry_hint['priority']      = 'hint';
429         $s_entry_hint['app']  = 'SIP/'.$this->uid;
431         // If no macro is selected use Dial
432         if($this->macro!="none"){ 
433           $macroname = preg_replace("/,.*$/","",$this->macro);        
434           $macroname = preg_replace("/^.*=/","",$macroname);        
435           $s_app = "Macro";$macroname;
436           $s_par = $macroname."|".$s_parameter; 
437         }else{
438           $s_app = "Dial";
439           $s_par = 'SIP/'.$this->uid;
440         }
442         // Entry  to call by number
443         $s_entry_phone['context']  = 'GOsa';
444         $s_entry_phone['exten']    = $s_telenums;
445         $s_entry_phone['priority'] = 1;
446         $s_entry_phone['app']      = $s_app;
447         $s_entry_phone['appdata']  = $s_par;
449         // append name entry only once
450         if(!$i_is_accounted){ 
451           $i_is_accounted = true;
452           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
453         }else{
454           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
455         }
456       }
458       // Append all these Entries 
459       foreach($entries as $num => $val){
460         foreach($val as $entr){
461           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
462           foreach($entr as $key2 => $val2){
463             $SQL_syn.= "`".$key2."`,";
464           }
465           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
466           $SQL_syn .= ") VALUES ("; 
467           foreach($entr as $key2 => $val2){
468             $SQL_syn .= "'".$val2."',";
469           }
470           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
471           $SQL_syn .=");\n";
472           $SQL[] =$SQL_syn;
473           $SQL_syn ="";
474         }
475       }
477       // Perform queries ...
478       foreach($SQL as $query){
479         if(!mysql_query($query,$r_con)){
480           print_red(_("Error while performing query ".mysql_error()));
481           return false;
482         }
483       }
484     }
485     return true;
486   }
489   function execute()
490   {
491     /* Do we represent a valid account? */
492     if (!$this->is_account && $this->parent == NULL){
493       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
494         _("This account has no phone extensions.")."</b>";
495       $display.= back_to_main();
496       return ($display);
497     }
499     /* Do we need to flip is_account state? */
500     if (isset($_POST['modify_state'])){
501       $this->is_account= !$this->is_account;
502     }
504     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
505     if(empty($this->macro)){
506       $this->macro ="none";
507     }
509     /* Set new Voicemail password */
510     if(isset($_POST['goFonPINVoiceSet'])){
511       $this->goFonPINVoice = $_POST['goFonPIN'];
512     }
514     /* tell user that the pluging selected is no longer available*/
515     if((!$this->macrostillavailable)&&($this->macro!="none")){
516       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
517     }
519     /* Prepare templating */
520     $smarty= get_smarty();
522     /* Assing macroselectbox values  */
523     $smarty->assign("macros",$this->macros);   
524     $smarty->assign("macro", $this->macro);   
526     /* Create parameter table, skip if no parameters given */
527     if(!isset($this->macroarray[$this->macro])){
528       $macrotab="";
529     }else{
531       $macrotab ="<table summary=\""._("Parameter")."\">";
532       /* for every single parameter-> display textfile,combo, or true false switch*/
535       /* Automatic fill out */
536       if(isset($_POST['fillout'])){
538         foreach($this->phoneNumbers as $phonenum){
539           $tmp[] = $phonenum;
540         }
542         /* Go through all params */
543         foreach($this->macroarray[$this->macro] as $key => $paras){
545           $string = $paras['default'];
547           $string=preg_replace("/%uid/i",$this->uid,$string);
548           $string=preg_replace("/%cn/i",$this->cn,$string);
550           for($i = 0 ; $i < 10; $i++){
551             if(isset($tmp[$i])){
552               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
553             }
554           }
556           $this->macroarray[$this->macro][$key]['choosen']=$string;
557         }
558       }
560       foreach($this->macroarray[$this->macro] as $paras){
562         /* get al vars */
563         $var        = $paras['var'];           
564         $name       = $paras['name'];           
565         $default    = $paras['default'];
566         $type       = $paras['type'];
567         $choosen    = $paras['choosen'] ; 
568         $str        = $default;
570         /* in case of a combo box display a combobox with selected attr */
571         $macrotab.= "<tr>";
572         switch ($type){
574           case "combo":
575             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
576           foreach(split(":",$default) as $choice){
577             if($choosen==$choice){
578               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
579             }else{
580               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
581             }
582           }
583           $str.="</select>";
584           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
585           break;
587           case "bool":
588             if(!$choosen){
589               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
590             }else{
591               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
592             }
593           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
594           break;
596           case "string":
597             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
598           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
599           break;
601         }
602         $macrotab.= "</td></tr>";
604       }
605       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
606     }//is_array()
608     /* Give smarty the table */
609     $smarty->assign("macrotab",$macrotab);
611     /* Do we represent a valid account? */
612     if (!$this->is_account && $this->parent == NULL){
613       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
614         _("This account has no phone extensions.")."</b>";
615       $display.= back_to_main();
616       return($display);
617     }
619     $display= "";
621     /* Show tab dialog headers */
622     if ($this->parent != NULL){
623       if ($this->is_account){
624         $display= $this->show_header(_("Remove phone account"),
625             _("This account has phone features enabled. You can disable them by clicking below."));
626       } else {
627         if(empty($this->uid)){
628           $display= $this->show_header(_("Create phone account"),
629               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
630         }else{
631           $display= $this->show_header(_("Create phone account"),
632               _("This account has phone features disabled. You can enable them by clicking below."));
633         }
634         return ($display);
635       }
636     }
638     /* Add phone number */
639     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
640       if (is_phone_nr($_POST['phonenumber'])){
641         $number= $_POST["phonenumber"];
642         $this->phoneNumbers[$number]= $number;
643         $this->is_modified= TRUE;
644       } else {
645         print_red(_("Please enter a valid phone number!"));
646       }
647     }
649     /* Remove phone number */
650     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
651       foreach ($_POST['phonenumber_list'] as $number){
652         unset($this->phoneNumbers[$number]);
653         $this->is_modified= TRUE;
654       }
655     }
657     /* Transfer ACL's */
658     foreach($this->attributes as $val){
659       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
660       $smarty->assign($val,$this->$val);
661     }
663     /* Fill arrays */
664     $smarty->assign ("goFonHardware", $this->goFonHardware);
665     if (!count($this->phoneNumbers)){
666       $smarty->assign ("phoneNumbers", array(""));
667     } else {
668       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
669     }
670     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
671       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
672     foreach ($this->hardware_list as $cn => $description){
673       if ($cn == $this->goFonHardware){
674         $selected= "selected";
675       } else {
676         $selected= "";
677       }
678       if (isset($this->used_hardware[$cn])){
679         $color= "style=\"color:#A0A0A0\"";
680       } else {
681         $color= "";
682       }
683       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
684     }
685     $hl.= "</select>\n";
686     $smarty->assign ("hardware_list", $hl);
688     /* Show main page */
689     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
690     return($display);
691   }
694   function save_object()
695   {
696     if (isset($_POST["phoneTab"])){
697       plugin::save_object();
699       /* Save checkbox */
700       if (isset($_POST['fon_to_mail'])){
701         $tmp= "[M]";
702       } else {
703         $tmp= "[]";
704       }
705       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
706         if ($this->goFonDeliveryMode != $tmp){
707           $this->is_modified= TRUE;
708         }
709         $this->goFonDeliveryMode= $tmp;
710       }
712       /* Every macro in the select box are available */
713       if((isset($_POST['macro']))){
714         $this->macrostillavailable=true;
715       }
717       if(is_array($this->phoneNumbers)){
718         foreach($this->phoneNumbers as $telenumms) {
719           $nummsinorder[]=$telenumms; 
720         }
721       }else{
722         $nummsinorder=array("");
723       }
725       /* get all Postvars */
726       if(isset($this->macroarray[$this->macro])){ 
727         foreach($this->macroarray[$this->macro] as $key => $paras){
728           if(isset($_POST[$paras['var']])){
729             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
730           }
732           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
733              We need this code below to read and save checkboxes correct
734            */
736           if(isset($_POST['post_success'])){
737             if($this->macroarray[$this->macro][$key]['type']=="bool"){
738               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
739                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
740               }else{
741                 $this->macroarray[$this->macro][$key]['choosen']=false;
742               }
743             }
744           }
745         }
746       }
747     }
748   }
750   function check()
751   {
752     /* Reset message array */
753     $message= array();
755     if(!$this->generate_mysql_entension_entries()){
756       $message[] = $this->generate_error;
757     }
759     /* We need at least one phone number */
760     if (count($this->phoneNumbers) == 0){
761       $message[]= sprintf(_("You need to specify at least one phone number!"));
762     }
764     if(($this->goFonPIN)==""){
765       $message[]= sprintf(_("You need to specify a Phone PIN."));
766     }else{
767       if(!is_id($this->goFonPIN)){
768         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
769       }elseif(strlen($this->goFonPIN) < 4){
770         $message[] = sprintf(_("The given PIN is too short"));
771       }
773     }
775     /* check for ! in any parameter setting*/
776     if(isset($this->macroarray[$this->macro])){
777       foreach($this->macroarray[$this->macro] as $val){
778         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
779           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
780         }
781       }
782     }
783     return ($message);
784   }
788   function save()
789   {
790     plugin::save();
792     /* Save arrays */
793     $this->attrs['telephoneNumber']= array();
794     foreach ($this->phoneNumbers as $number){
795       $this->attrs['telephoneNumber'][]= $number;
796     }
798     /* Save settings, or remove goFonMacro attribute*/
799     if($this->macro!="none"){    
800       $this->attrs['goFonMacro']=$this->macro;
801       if(isset($this->macroarray[$this->macro])){
802         foreach($this->macroarray[$this->macro] as $paras)  {
803           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
804         }
805       }
806     }else{
807       $this->attrs['goFonMacro']=array();
808     }
809     unset($this->attrs['macro'])  ;
811     $this->attrs['goFonForwarding']=array();
813     $this->generate_mysql_entension_entries(true);
815     if($this->attrs['goFonMacro']==""){
816       $this->attrs['goFonMacro']=array();
817     }
819     /* Write back to ldap */
820     $ldap= $this->config->get_ldap_link();
821     $ldap->cd($this->dn);
822     $ldap->modify($this->attrs);
823     show_ldap_error($ldap->get_error());
825     /* Optionally execute a command after we're done */
827     if ($this->initially_was_account == $this->is_account){
828       if ($this->is_modified){
829         $this->handle_post_events("modify");
830       }
831     } else {
832       $this->handle_post_events("add");
833     }
835   }
838   function insert_after($entry, $nr, $list)
839   {
840     /* Is the entry free? No? Make it free... */
841     if (isset($list[$nr])) {
842       $dest= array();
843       $newidx= 0;
845       foreach ($list as $idx => $contents){
846         $dest[$newidx++]= $contents;
847         if ($idx == $nr){
848           $dest[$newidx++]= $entry;
849         }
850       }
851     } else {
852       $dest= $list;
853       $dest[$nr]= $entry;
854     }
856     return ($dest);
857   }
860   function adapt_from_template($dn)
861   {
862     plugin::adapt_from_template($dn);
864     /* Assemble phone numbers */
865     if (isset($this->attrs['telephoneNumber'])){
866       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
867         $number= $this->attrs['telephoneNumber'][$i];
868         $this->phoneNumbers[$number]= $number;
869       }
870     }
871   }
874   function remove_from_parent()
875   {
876   
877     foreach($this->attributes as $key=>$val){
879       if(in_array($val,array("uid","cn","mail"))){
880         unset($this->attributes[$key]);
881         unset($this->$val);
882       }
883     
884     }
886     // Get Configuration for Mysql database Server
887     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
888     $s_parameter  ="";
890     // Connect to DB server
891     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
893     // Check if we are  connected correctly
894     if(!$r_con){
895       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
896           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
897       gosa_log(mysql_error());
898       return false;
899     }
901     // Select database for Extensions
902     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
904     // Test if we have the database selected correctly
905     if(!$db){
906       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
907       gosa_log(mysql_error());
908       return false;
909     }
911     $SQL="";
913     /* If deletion starts from userslist, cn uid are not set */
914     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
915       $this->uid = $this->parent->by_object['user']->uid;
916     }
918     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
919       $this->cn  = $this->parent->by_object['user']->cn;
920     }
922     $first_num = false;
923     // Delete old entries
924     foreach($this->a_old_telenums as $s_telenums){
925       if(!$first_num){
926         $first_num = $s_telenums;
927       }
928       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
929     }
931     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
932     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
933     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
936     foreach($SQL as $query){
937       if(!mysql_query($query,$r_con)){
938         print_red(_("Stop".mysql_error()));
939         return false;
940       }
941     }
945     /* unset macro attr, it will cause an error */
946     $tmp = array_flip($this->attributes);
947     unset($tmp['macro']);
948     $this->attributes=array_flip($tmp);
950     /* Cancel if there's nothing to do here */
951     if (!$this->initially_was_account){
952       return;
953     }
955     plugin::remove_from_parent();
957     /* Just keep one phone number */
958     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
959       $this->attrs['telephoneNumber']= $this->telephoneNumber;
960     } else {
961       $this->attrs['telephoneNumber']= array();
962     }
964     $ldap= $this->config->get_ldap_link();
965     $ldap->cd($this->config->current['BASE']);
966     $ldap->search("(objectClass=goFonQueue)", array("member"));
967     while($attr = $ldap->fetch()){
968       if(in_array($this->dn,$attr['member'])){
969         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
970         unset($new->by_object['ogroup']->memberList[$this->dn]);
971         unset($new->by_object['ogroup']->member[$this->dn]);
972         $new->save();
973         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
974       }
975     }
976     $ldap->cd($this->dn);
977     $ldap->modify($this->attrs);
978     show_ldap_error($ldap->get_error());
980     /* Optionally execute a command after we're done */
981     $this->handle_post_events('remove');
982   }
986   /* This function checks if the given phonenumbers are available or already in use*/
987   function is_number_used()
988   {
989     $ldap= $this->config->get_ldap_link();
990     $ldap->cd($this->config->current['BASE']);
991     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
992     while($attrs = $ldap->fetch()) {
993       unset($attrs['telephoneNumber']['count']);
994       foreach($attrs['telephoneNumber'] as $tele){
995         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
996         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
997         $numbers[$tele]=$attrs;
998       }
999     }
1001     foreach($this->phoneNumbers as $num){
1002       if(!isset($this->cn)) $this->cn = "";
1004       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1005         if(isset($numbers[$num]['uid'][0])){
1006           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1007         }else{
1008           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1009         }
1010       }
1011     }
1012   }
1015 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1016 ?>