Code

534de790f8e9c42588426b5209bd56a30987affc
[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;
211     if($this->is_account){
212       $this->is_modified = true;
213     }
214   }
217   // Generate MySQL Syntax
218   function generate_mysql_entension_entries($save = false){
220     // Get Configuration for Mysql database Server
221     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
222     $s_parameter    = "";                                           // Contains paramter for selected Macro 
223     $r_con          = false;                                        // DB connection
224     $r_db           = false;                                        // Selected DB
225     $r_res          = false;                                        // Result resource
226     $a_ldap_attrs   = array();                                      //  
228     $s_ip           = NULL;                   // Contains ip for Sip entry
229     $s_host         = NULL;                   // Contains host for Sip entry
230     $s_qualify      = NULL;                   // Qualify entry
231     $s_pin          = NULL;                   // Entry for secret
232     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
234     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
235     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
236     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
238     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
239     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
241     $s_sip_key      = "";     // Key for SIP entry index      
242     $s_sip_val      = "";     // Value for SIP entry index      
244     $b_first_deleted= false;  // Only delete first entry, 
245     $s_telenums     = "";     // for each value variable
247     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
250     // Connect to DB server
251     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
253     // Check if we are  connected correctly
254     if(!$r_con){
255       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
256           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
257       gosa_log(mysql_error());
258       return false;
259     }
261     // Select database for Extensions
262     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
264     // Test if we have the database selected correctly
265     if(!$r_db){
266       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
267       gosa_log(mysql_error());
268       return false;
269     }
271     // Get phonehardware to setup sip entry
272     $ldap         = $this->config->get_ldap_link();
273     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
274     $a_ldap_attrs = $ldap->fetch();
276     if($this->is_number_used()){
277       $this->generate_error = $this->is_number_used(); 
278       return false;
279     }
281     /* If Save == true, we should save something.
282      * Generate SQL, for drop of old entries
283      * Generate SQL, for insert new entries
284      */ 
285     if($save == true){
286       // Attribute GoFonDefaultIP set ?
287       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
288         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
289         $s_host     = $s_ip;
290       }else{
291         $s_ip       = NULL;
292         $s_host     = "dynamic";
293       }
295       // Attribute GoFonQualify set ?
296       if(isset($a_ldap_attrs['goFonQualify'])){
297         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
298       }
300       // Attribute GoFonPIN set ?
301       if(isset($this->goFonPIN)){
302         $s_pin      = $this->goFonPIN;
303       }
305       // Attribute GoFonType set ?
306       if(isset($a_ldap_attrs['goFonType'])){
307         $s_type = $a_ldap_attrs['goFonType'][0];
308       }
310       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
311         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
312       }else{
313         $sip_data_array['dtmfmode']     ="rfc2833";
314       }
316       // generate SIP entry
317       $sip_data_array['id']           = "";
318       $sip_data_array['name']         = $this->uid;
319       $sip_data_array['accountcode']  = NULL;          
320       $sip_data_array['amaflags']     = NULL;
321       $sip_data_array['callgroup']    = NULL;
322       $sip_data_array['callerid']     = "";
323       $sip_data_array['canreinvite']  = "yes";
324       $sip_data_array['context']      = "default";
325       $sip_data_array['defaultip']    = NULL;
326       $sip_data_array['fromuser']     = NULL;
327       $sip_data_array['fromdomain']   = NULL;
328       $sip_data_array['host']         = $s_host;
329       $sip_data_array['insecure']     = NULL;
330       $sip_data_array['language']     = NULL;
331       $sip_data_array['mailbox']      = "asterisk";
332       $sip_data_array['md5secret']    = NULL;
333       $sip_data_array['nat']          = "no";
334       $sip_data_array['permit']       = NULL;
335       $sip_data_array['deny']         = NULL;
336       $sip_data_array['mask']         = NULL;
337       $sip_data_array['pickupgroup']  = NULL;
338       $sip_data_array['port']         = NULL;
339       $sip_data_array['qualify']      = $s_qualify;
340       $sip_data_array['restrictcid']  = "n";
341       $sip_data_array['rtptimeout']   = NULL;
342       $sip_data_array['rtpholdtimeout']=NULL;
343       $sip_data_array['secret']       = $s_pin;
344       $sip_data_array['type']         = $s_type ;
345       $sip_data_array['username']     = $this->uid;
346       $sip_data_array['disallow']     = NULL;
347       $sip_data_array['allow']        = NULL;
348       $sip_data_array['musiconhold']  = NULL;
349       $sip_data_array['regseconds']   = NULL;
350       $sip_data_array['ipaddr']       = $s_ip;
351       $sip_data_array['regexten']     = NULL;
352       $sip_data_array['cancallforward']=NULL;
354       // Get selected Macro Parameter and create parameter entry 
355       if(isset($this->macroarray[$this->macro])){
356         foreach($this->macroarray[$this->macro] as $key => $val ){
357           $s_parameter .= $val['choosen']."|";
358         }
359         $s_parameter = preg_replace("/\|$/","",$s_parameter);
360       }
362       if($this->is_number_used()){
363         $this->generate_error = $this->is_number_used(); 
364         return false;
365       }
367       // Create new SIP entry ...
368       $sip_entry = $sip_data_array;
369       reset($this->phoneNumbers);
370       $i_new_key = key($this->phoneNumbers);
371       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
372       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
374       if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
375         $s_mail = $this->parent->by_object['mailAccount']->mail;
376       }else{
377         $s_mail = "";
378       }
380       // $SQL contains all queries
381       $SQL   = array();
382       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
383       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
384       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
386       // Generate Strings with keys and values 
387       foreach($sip_entry as $s_sip_key=>$s_sip_val){
388         if($s_sip_val == NULL) continue;
389         $s_sip_values.="'".$s_sip_val."',";
390         $s_sip_keys  .="`".$s_sip_key."`,";
391       }
392       // Remove last ,
393       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
394       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
396       // Append SIP Entry 
397       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
399       // Delete old entries
400       $b_first_deleted  =false;
401       foreach($this->a_old_telenums as $s_telenums){
402         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
403         if(!$b_first_deleted){
404           $b_first_deleted=true;
405           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
406         }
407       }
409       if(empty($this->goFonPINVoice)){
410         $this->goFonPINVoice = $this->goFonPIN;
411       } 
413       /* If deletion starts from userslist, cn uid are not set */
414       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
415         $this->uid = $this->parent->by_object['user']->uid;
416       }
418       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
419         $this->cn  = $this->parent->by_object['user']->cn;
420       }
422       if((!isset($this->cn))||(empty($this->cn))){
423         $CNname= $this->uid;
424       }else{
425         $CNname= $this->cn;
426       }
428       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']."
429         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
430         VALUES
431         ('".$this->phoneNumbers[$i_new_key]."','default','".$this->phoneNumbers[$i_new_key]."','".$this->goFonPINVoice."','".$CNname."','".$s_mail."','');";
433       $i_is_accounted=false;
434     
435       $i = 0; 
436   
437       // Entension entries  Hint / Dial / Goto
438       foreach($this->phoneNumbers as $s_telenums){
440         /* Mapping : Name TO Number*/
441         $EXT[$i]['context'] = 'GOsa';
442         $EXT[$i]['exten']   = $this->uid;
443         $EXT[$i]['priority']= 1;
444         $EXT[$i]['app']     = "Goto";
445         $EXT[$i]['appdata'] = $s_telenums."|1";
446         $i ++;  
447         /* Hint Entry */
448         $EXT[$i]['context'] = 'GOsa';
449         $EXT[$i]['exten']   = $s_telenums;
450         $EXT[$i]['priority']= "Hint";
451         $EXT[$i]['app']     = 'SIP/'.$this->uid;
452         $i ++;  
453         /* SetCID */
454         $EXT[$i]['context'] = 'GOsa';
455         $EXT[$i]['exten']   = $s_telenums;
456         $EXT[$i]['priority']= 1;
457         $EXT[$i]['app']     = "SetCIDName";
458         $EXT[$i]['appdata'] = $CNname;
459         $i ++;  
461         // If no macro is selected use Dial
462         if($this->macro!="none"){ 
463           $macroname = preg_replace("/,.*$/","",$this->macro);        
464           $macroname = preg_replace("/^.*=/","",$macroname);        
465           $s_app = "Macro";$macroname;
466           $s_par = $macroname."|".$s_parameter; 
467         }else{
468           $s_app = "Dial";
469           $s_par = 'SIP/'.$this->uid;
470         }
472         $EXT[$i]['context'] = 'GOsa';
473         $EXT[$i]['exten']   = $s_telenums;
474         $EXT[$i]['priority']= 2;
475         $EXT[$i]['app']     = $s_app;
476         $EXT[$i]['appdata'] = $s_par;
477         $i ++;
479       }
481       // Append all these Entries 
482       foreach($EXT as $entr){
483         $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
484         foreach($entr as $key2 => $val2){
485           $SQL_syn.= "`".$key2."`,";
486         }
487         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
488         $SQL_syn .= ") VALUES ("; 
489         foreach($entr as $key2 => $val2){
490           $SQL_syn .= "'".$val2."',";
491         }
492         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
493         $SQL_syn .=");\n";
494         $SQL[] =$SQL_syn;
495         $SQL_syn ="";
496       }
498       // Perform queries ...
499       foreach($SQL as $query){
500         if(!mysql_query($query,$r_con)){
501           print_red(_("Error while performing query ".mysql_error()));
502           return false;
503         }
504       }
505     }
506     return true;
507   }
510   function execute()
511   {
512     /* Do we represent a valid account? */
513     if (!$this->is_account && $this->parent == NULL){
514       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
515         _("This account has no phone extensions.")."</b>";
516       $display.= back_to_main();
517       return ($display);
518     }
520     /* Do we need to flip is_account state? */
521     if (isset($_POST['modify_state'])){
522       $this->is_account= !$this->is_account;
523     }
525     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
526     if(empty($this->macro)){
527       $this->macro ="none";
528     }
530     /* Set new Voicemail password */
531     if(isset($_POST['goFonPINVoiceSet'])){
532       $this->goFonPINVoice = $_POST['goFonPIN'];
533     }
535     /* tell user that the pluging selected is no longer available*/
536     if((!$this->macrostillavailable)&&($this->macro!="none")){
537       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
538     }
540     /* Prepare templating */
541     $smarty= get_smarty();
543     /* Assing macroselectbox values  */
544     $smarty->assign("macros",$this->macros);   
545     $smarty->assign("macro", $this->macro);   
547     /* Create parameter table, skip if no parameters given */
548     if(!isset($this->macroarray[$this->macro])){
549       $macrotab="";
550     }else{
552       $macrotab ="<table summary=\""._("Parameter")."\">";
553       /* for every single parameter-> display textfile,combo, or true false switch*/
556       /* Automatic fill out */
557       if(isset($_POST['fillout'])){
559         foreach($this->phoneNumbers as $phonenum){
560           $tmp[] = $phonenum;
561         }
563         /* Go through all params */
564         foreach($this->macroarray[$this->macro] as $key => $paras){
566           $string = $paras['default'];
568           $string=preg_replace("/%uid/i",$this->uid,$string);
569           
570           if(isset($this->cn)){
571             $string=preg_replace("/%cn/i",$this->cn,$string);
572           }
574           for($i = 0 ; $i < 10; $i++){
575             if(isset($tmp[$i])){
576               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
577             }
578           }
580           $this->macroarray[$this->macro][$key]['choosen']=$string;
581         }
582       }
584       foreach($this->macroarray[$this->macro] as $paras){
586         /* get al vars */
587         $var        = $paras['var'];           
588         $name       = $paras['name'];           
589         $default    = $paras['default'];
590         $type       = $paras['type'];
591         $choosen    = $paras['choosen'] ; 
592         $str        = $default;
594         /* in case of a combo box display a combobox with selected attr */
595         $macrotab.= "<tr>";
596         switch ($type){
598           case "combo":
599             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
600           foreach(split(":",$default) as $choice){
601             if($choosen==$choice){
602               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
603             }else{
604               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
605             }
606           }
607           $str.="</select>";
608           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
609           break;
611           case "bool":
612             if(!$choosen){
613               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
614             }else{
615               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
616             }
617           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
618           break;
620           case "string":
621             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
622           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
623           break;
625         }
626         $macrotab.= "</td></tr>";
628       }
629       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
630     }//is_array()
632     /* Give smarty the table */
633     $smarty->assign("macrotab",$macrotab);
635     /* Do we represent a valid account? */
636     if (!$this->is_account && $this->parent == NULL){
637       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
638         _("This account has no phone extensions.")."</b>";
639       $display.= back_to_main();
640       return($display);
641     }
643     $display= "";
645     /* Show tab dialog headers */
646     if ($this->parent != NULL){
647       if ($this->is_account){
648         $display= $this->show_header(_("Remove phone account"),
649             _("This account has phone features enabled. You can disable them by clicking below."));
650       } else {
651         if(empty($this->uid)){
652           $display= $this->show_header(_("Create phone account"),
653               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
654         }else{
655           $display= $this->show_header(_("Create phone account"),
656               _("This account has phone features disabled. You can enable them by clicking below."));
657         }
658         return ($display);
659       }
660     }
662     /* Add phone number */
663     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
664       if (is_phone_nr($_POST['phonenumber'])){
665         $number= $_POST["phonenumber"];
666         $this->phoneNumbers[$number]= $number;
667         $this->is_modified= TRUE;
668       } else {
669         print_red(_("Please enter a valid phone number!"));
670       }
671     }
673     /* Remove phone number */
674     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
675       foreach ($_POST['phonenumber_list'] as $number){
676         unset($this->phoneNumbers[$number]);
677         $this->is_modified= TRUE;
678       }
679     }
681     /* Transfer ACL's */
682     foreach($this->attributes as $val){
683       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
684       if(isset($this->$val)){
685         $smarty->assign($val,$this->$val);
686       }else{
687         $smarty->assign($val,"");
688       }
689     }
691     /* Fill arrays */
692     $smarty->assign ("goFonHardware", $this->goFonHardware);
693     if (!count($this->phoneNumbers)){
694       $smarty->assign ("phoneNumbers", array(""));
695     } else {
696       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
697     }
698     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
699       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
700     foreach ($this->hardware_list as $cn => $description){
701       if ($cn == $this->goFonHardware){
702         $selected= "selected";
703       } else {
704         $selected= "";
705       }
706       if (isset($this->used_hardware[$cn])){
707         $color= "style=\"color:#A0A0A0\"";
708       } else {
709         $color= "";
710       }
711       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
712     }
713     $hl.= "</select>\n";
714     $smarty->assign ("hardware_list", $hl);
716     /* Show main page */
717     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
718     return($display);
719   }
722   function save_object()
723   {
724     if (isset($_POST["phoneTab"])){
725       plugin::save_object();
727       /* Save checkbox */
728       if (isset($_POST['fon_to_mail'])){
729         $tmp= "[M]";
730       } else {
731         $tmp= "[]";
732       }
733       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
734         if ($this->goFonDeliveryMode != $tmp){
735           $this->is_modified= TRUE;
736         }
737         $this->goFonDeliveryMode= $tmp;
738       }
740       /* Every macro in the select box are available */
741       if((isset($_POST['macro']))){
742         $this->macrostillavailable=true;
743       }
745       if(is_array($this->phoneNumbers)){
746         foreach($this->phoneNumbers as $telenumms) {
747           $nummsinorder[]=$telenumms; 
748         }
749       }else{
750         $nummsinorder=array("");
751       }
753       /* get all Postvars */
754       if(isset($this->macroarray[$this->macro])){ 
755         foreach($this->macroarray[$this->macro] as $key => $paras){
756           if(isset($_POST[$paras['var']])){
757             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
758           }
760           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
761              We need this code below to read and save checkboxes correct
762            */
764           if(isset($_POST['post_success'])){
765             if($this->macroarray[$this->macro][$key]['type']=="bool"){
766               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
767                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
768               }else{
769                 $this->macroarray[$this->macro][$key]['choosen']=false;
770               }
771             }
772           }
773         }
774       }
775     }
776   }
778   function check()
779   {
780     /* Reset message array */
781     $message= array();
783     if(!$this->generate_mysql_entension_entries()){
784       $message[] = $this->generate_error;
785     }
787     /* We need at least one phone number */
788     if (count($this->phoneNumbers) == 0){
789       $message[]= sprintf(_("You need to specify at least one phone number!"));
790     }
792     if(($this->goFonPIN)==""){
793       $message[]= sprintf(_("You need to specify a Phone PIN."));
794     }else{
795       if(!is_id($this->goFonPIN)){
796         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
797       }elseif(strlen($this->goFonPIN) < 4){
798         $message[] = sprintf(_("The given PIN is too short"));
799       }
801     }
803     /* check for ! in any parameter setting*/
804     if(isset($this->macroarray[$this->macro])){
805       foreach($this->macroarray[$this->macro] as $val){
806         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
807           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
808         }
809       }
810     }
811     return ($message);
812   }
816   function save()
817   {
818     plugin::save();
820     /* Save arrays */
821     $this->attrs['telephoneNumber']= array();
822     foreach ($this->phoneNumbers as $number){
823       $this->attrs['telephoneNumber'][]= $number;
824     }
826     /* Save settings, or remove goFonMacro attribute*/
827     if($this->macro!="none"){    
828       $this->attrs['goFonMacro']=$this->macro;
829       if(isset($this->macroarray[$this->macro])){
830         foreach($this->macroarray[$this->macro] as $paras)  {
831           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
832         }
833       }
834     }else{
835       $this->attrs['goFonMacro']=array();
836     }
837     unset($this->attrs['macro'])  ;
839     $this->attrs['goFonForwarding']=array();
841     $this->generate_mysql_entension_entries(true);
843     if($this->attrs['goFonMacro']==""){
844       $this->attrs['goFonMacro']=array();
845     }
847     unset($this->attrs['cn']);
849     /* Write back to ldap */
850     $ldap= $this->config->get_ldap_link();
851     $ldap->cd($this->dn);
852     $ldap->modify($this->attrs);
853     show_ldap_error($ldap->get_error());
855     /* Optionally execute a command after we're done */
857     if ($this->initially_was_account == $this->is_account){
858       if ($this->is_modified){
859         $this->handle_post_events("modify");
860       }
861     } else {
862       $this->handle_post_events("add");
863     }
865   }
868   function insert_after($entry, $nr, $list)
869   {
870     /* Is the entry free? No? Make it free... */
871     if (isset($list[$nr])) {
872       $dest= array();
873       $newidx= 0;
875       foreach ($list as $idx => $contents){
876         $dest[$newidx++]= $contents;
877         if ($idx == $nr){
878           $dest[$newidx++]= $entry;
879         }
880       }
881     } else {
882       $dest= $list;
883       $dest[$nr]= $entry;
884     }
886     return ($dest);
887   }
890   function adapt_from_template($dn)
891   {
892     plugin::adapt_from_template($dn);
894     /* Assemble phone numbers */
895     if (isset($this->attrs['telephoneNumber'])){
896       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
897         $number= $this->attrs['telephoneNumber'][$i];
898         $this->phoneNumbers[$number]= $number;
899       }
900     }
901   }
904   function remove_from_parent()
905   {
906   
907     foreach($this->attributes as $key=>$val){
909       if(in_array($val,array("uid","cn","mail"))){
910         unset($this->attributes[$key]);
911         unset($this->$val);
912       }
913     
914     }
916     // Get Configuration for Mysql database Server
917     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
918     $s_parameter  ="";
920     // Connect to DB server
921     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
923     // Check if we are  connected correctly
924     if(!$r_con){
925       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
926           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
927       gosa_log(mysql_error());
928       return false;
929     }
931     // Select database for Extensions
932     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
934     // Test if we have the database selected correctly
935     if(!$db){
936       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
937       gosa_log(mysql_error());
938       return false;
939     }
941     $SQL="";
943     /* If deletion starts from userslist, cn uid are not set */
944     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
945       $this->uid = $this->parent->by_object['user']->uid;
946     }
948     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
949       $this->cn  = $this->parent->by_object['user']->cn;
950     }
952     $first_num = false;
953     // Delete old entries
954     foreach($this->a_old_telenums as $s_telenums){
955       if(!$first_num){
956         $first_num = $s_telenums;
957       }
958       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
959     }
961     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
962     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
963     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
966     foreach($SQL as $query){
967       if(!mysql_query($query,$r_con)){
968         print_red(_("Stop".mysql_error()));
969         return false;
970       }
971     }
975     /* unset macro attr, it will cause an error */
976     $tmp = array_flip($this->attributes);
977     unset($tmp['macro']);
978     $this->attributes=array_flip($tmp);
980     /* Cancel if there's nothing to do here */
981     if (!$this->initially_was_account){
982       return;
983     }
985     plugin::remove_from_parent();
987     /* Just keep one phone number */
988     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
989       $this->attrs['telephoneNumber']= $this->telephoneNumber;
990     } else {
991       $this->attrs['telephoneNumber']= array();
992     }
994     $ldap= $this->config->get_ldap_link();
995     $ldap->cd($this->config->current['BASE']);
996     $ldap->search("(objectClass=goFonQueue)", array("member"));
997     while($attr = $ldap->fetch()){
998       if(in_array($this->dn,$attr['member'])){
999         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1000         unset($new->by_object['ogroup']->memberList[$this->dn]);
1001         unset($new->by_object['ogroup']->member[$this->dn]);
1002         $new->save();
1003         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1004       }
1005     }
1006     $ldap->cd($this->dn);
1007     $ldap->modify($this->attrs);
1008     show_ldap_error($ldap->get_error());
1010     /* Optionally execute a command after we're done */
1011     $this->handle_post_events('remove');
1012   }
1016   /* This function checks if the given phonenumbers are available or already in use*/
1017   function is_number_used()
1018   {
1019     $ldap= $this->config->get_ldap_link();
1020     $ldap->cd($this->config->current['BASE']);
1021     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1022     while($attrs = $ldap->fetch()) {
1023       unset($attrs['telephoneNumber']['count']);
1024       foreach($attrs['telephoneNumber'] as $tele){
1025         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1026         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1027         $numbers[$tele]=$attrs;
1028       }
1029     }
1031     foreach($this->phoneNumbers as $num){
1032       if(!isset($this->cn)) $this->cn = "";
1034       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1035         if(isset($numbers[$num]['uid'][0])){
1036           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1037         }else{
1038           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1039         }
1040       }
1041     }
1042   }
1045 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1046 ?>