Code

2232b09839f0166a4329ba7e72de10d0b0d47c50
[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 $goFonForwarding        = "";
14   var $goFonFormat            = "";
15   var $goFonPIN               = "";
16   var $goFonDeliveryMode      = "";
17   var $phoneNumbers           = array();
18   var $forwarders             = array();
19   var $mail                   = "";
20   var $hardware_list          = array();
21   var $used_hardware          = array();
22   var $goFonMacro             = "";
23   var $macro                  = 0;              // Selected Macor
24   var $macros                 = array();        // List of macros for smarty select box
25   var $macroarray             = array();        // All needed macro informations
26   var $macrostillavailable    = false;
27   var $generate_error         = "";
28   var $a_old_telenums           = array();
29   var $uid;
30   var $cn;
32   /* CLI vars */
33   var $cli_summary            = "Manage users phone account";
34   var $cli_description        = "Some longer text\nfor help";
35   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
37   /* attribute list for save action */
38   var $attributes             = array("goFonDeliveryMode", "goFonForwarding", "goFonFormat",
39       "goFonHardware", "goFonPIN", "telephoneNumber", "goFonMacro","macro");
40   var $objectclasses= array("goFonAccount");
42   function phoneAccount ($config, $dn= NULL)
43   {
44     plugin::plugin ($config, $dn);
46     /* Set phone hardware */
47     if (!isset($this->attrs['goFonHardware'])){
48       $this->goFonHardware= "automatic";
49     }
51     /* Preset voice format */
52     if (!isset($this->attrs['goFonFormat'])){
53       $this->goFonFormat= "wav";
54     }
56     /* Assemble phone numbers */
57     if (isset($this->attrs['telephoneNumber'])){
58       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
59         $number= $this->attrs['telephoneNumber'][$i];
60         $this->phoneNumbers[$number]= $number;
61       }
62     }
63     /* Assemble forwarders */
64     if (isset($this->attrs['goFonForwarding'])){
65       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
66         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
67         $this->forwarders[$num]= "$v1;$v2";
68       }
69     } else {
70       $this->forwarders= array("");
71     }
73     /* Set up has_mailAccount */
74     if (isset($this->attrs['objectClass'])){
75       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
76         $this->has_mailAccount= TRUE;
77       }
78     }
81     /* Load hardware list */
82     $ldap= $this->config->get_ldap_link();
83     $ldap->cd($this->config->current['BASE']);
84     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
85     while ($attrs= $ldap->fetch()){
86       $cn= $attrs['cn'][0];
87       if (isset($attrs['description'])){
88         $description= " - ".$attrs['description'][0];
89       } else {
90         $description= "";
91       }
92       $this->hardware_list[$cn]= "$cn$description";
94     }
96     /* Prepare templating */
97     $smarty= get_smarty();
100     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
101     $ldap->search("(objectClass=goFonMacro)", array("*"));
103     /* Add none for no macro*/
104     $this->macros['none']=_("no macro");    
105     $this->macro ="none";
108     /* Fetch all Macros*/
109     while ($attrs= $ldap->fetch()){
111       /* Only visisble */
112       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
114         /* unset Count, we don't need that here */
115         unset($attrs['displayName']['count']);
117         /* fill Selectfield variable with Macros */
118         if(isset($attrs['displayName'][0])){
119           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
120         }else{
121           $this->macros[$attrs['dn']] = _("undefined");
122         }
124         /* Parse macro data, unset count for parameterarrays  */
125         unset($attrs['goFonMacroParameter']['count']);
127         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
128         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
130           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
131             /* Split Data in readable values, by delimiter !  */
132             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
134             /* Set all attrs */
135             $id = $data[0];
136             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
137             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
138             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
139             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
140             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
141             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
142             if($data[2] == "bool"){
143               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
144             }
145           }//foreach
146         }//is_array
147       }//visible = 1
148     }//while
150     /* Go through already saved values, for a parameter */
151     $tmp = split("!",$this->goFonMacro);
153     /* it is possible that nothing has been saved yet */
154     if(is_array($tmp)){
156       /* First value is the macroname */
157       $this->macro = $tmp[0];
159       /* Macroname saved, delete that index */
160       unset($tmp[0]);
162       /* Check if makro has been removed */
163       if(!isset($this->macroarray[$this->macro])){
164         $this->macrostillavailable = false;
165       }else{
166         $this->macrostillavailable = true;
167       }
169       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
170       foreach($tmp as $var){
172         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
173         $varar = split("#",$var);
175         /* Only insert if the parameter still exists */
176         if(isset($this->macroarray[$this->macro][$varar[0]])){
177           /* Assign value */
178           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
179         }
180       }
181     }
184     /* Eventually colorize phones */
185     $ldap->cd($this->config->current['BASE']);
186     foreach ($this->hardware_list as $cn => $desc){
187       $ldap->search("(goFonHardware=$cn)", array('cn'));
188       if ($ldap->count() > 0){
189         $ldap->fetch();
190         if ($ldap->getDN() != $this->dn){
191           $this->used_hardware[$cn]= $ldap->getDN();
192         }
193       }
194     }
195     $this->hardware_list["automatic"]= _("automatic");
196     ksort($this->hardware_list);
197     $this->a_old_telenums = $this->phoneNumbers;
198   }
203   // Generate MySQL Syntax
204   function generate_mysql_entension_entries($save = false){
206     // Get Configuration for Mysql database Server
207     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
208     $s_parameter    = "";                                           // Contains paramter for selected Macro 
209     $r_con          = false;                                        // DB connection
210     $r_db           = false;                                        // Selected DB
211     $r_res          = false;                                        // Result resource
212     $a_ldap_attrs   = array();                                      //  
214     $s_ip           = NULL;                   // Contains ip for Sip entry
215     $s_host         = NULL;                   // Contains host for Sip entry
216     $s_qualify      = NULL;                   // Qualify entry
217     $s_pin          = NULL;                   // Entry for secret
218     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
220     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
221     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
222     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
224     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
225     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
227     $s_sip_key      = "";     // Key for SIP entry index      
228     $s_sip_val      = "";     // Value for SIP entry index      
230     $b_first_deleted= false;  // Only delete first entry, 
231     $s_telenums     = "";     // for each value variable
233     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
236     // Connect to DB server
237     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
239     // Check if we are  connected correctly
240     if(!$r_con){
241       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
242           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
243       gosa_log(mysql_error());
244       return false;
245     }
247     // Select database for Extensions
248     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
250     // Test if we have the database selected correctly
251     if(!$r_db){
252       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
253       gosa_log(mysql_error());
254       return false;
255     }
257     // Get phonehardware to setup sip entry
258     $ldap         = $this->config->get_ldap_link();
259     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
260     $a_ldap_attrs = $ldap->fetch();
262     if($this->is_number_used()){
263       $this->generate_error = $this->is_number_used(); 
264       return false;
265     }
269     /* If Save == true, we should save something.
270      * Generate SQL, for drop of old entries
271      * Generate SQL, for insert of new entries
272      */ 
273     if($save == true){
274       // Attribute GoFonDefaultIP set ?
275       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
276         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
277         $s_host     = $s_ip;
278       }else{
279         $s_ip       = NULL;
280         $s_host     = "dynamic";
281       }
283       // Attribute GoFonQualify set ?
284       if(isset($a_ldap_attrs['goFonQualify'])){
285         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
286       }
288       // Attribute GoFonPIN set ?
289       if(isset($this->goFonPIN)){
290         $s_pin      = $this->goFonPIN;
291       }
293       // Attribute GoFonType set ?
294       if(isset($a_ldap_attrs['goFonType'])){
295         $s_type = $a_ldap_attrs['goFonType'][0];
296       }
298       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
299         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
300       }else{
301         $sip_data_array['dtmfmode']     ="rfc2833";
302       }
304       // generate SIP entry
305       $sip_data_array['id']           = "";
306       $sip_data_array['name']         = $this->uid;
307       $sip_data_array['accountcode']  = NULL;          
308       $sip_data_array['amaflags']     = NULL;
309       $sip_data_array['callgroup']    = NULL;
310       $sip_data_array['callerid']     = "";
311       $sip_data_array['canreinvite']  = "yes";
312       $sip_data_array['context']      = "default";
313       $sip_data_array['defaultip']    = NULL;
314       $sip_data_array['fromuser']     = NULL;
315       $sip_data_array['fromdomain']   = NULL;
316       $sip_data_array['host']         = $s_host;
317       $sip_data_array['insecure']     = NULL;
318       $sip_data_array['language']     = NULL;
319       $sip_data_array['mailbox']      = "asterisk";
320       $sip_data_array['md5secret']    = NULL;
321       $sip_data_array['nat']          = "no";
322       $sip_data_array['permit']       = NULL;
323       $sip_data_array['deny']         = NULL;
324       $sip_data_array['mask']         = NULL;
325       $sip_data_array['pickupgroup']  = NULL;
326       $sip_data_array['port']         = NULL;
327       $sip_data_array['qualify']      = $s_qualify;
328       $sip_data_array['restrictcid']  = "n";
329       $sip_data_array['rtptimeout']   = NULL;
330       $sip_data_array['rtpholdtimeout']=NULL;
331       $sip_data_array['secret']       = $s_pin;
332       $sip_data_array['type']         = $s_type ;
333       $sip_data_array['username']     = $this->uid;
334       $sip_data_array['disallow']     = NULL;
335       $sip_data_array['allow']        = NULL;
336       $sip_data_array['musiconhold']  = NULL;
337       $sip_data_array['regseconds']   = NULL;
338       $sip_data_array['ipaddr']       = $s_ip;
339       $sip_data_array['regexten']     = NULL;
340       $sip_data_array['cancallforward']=NULL;
342       // Get selected Macro Parameter and create parameter entry 
343       if(isset($this->macroarray[$this->macro])){
344         foreach($this->macroarray[$this->macro] as $key => $val ){
345           $s_parameter .= $val['choosen']."|";
346         }
347         $s_parameter = preg_replace("/\|$/","",$s_parameter);
348       }
350       if($this->is_number_used()){
351         $this->generate_error = $this->is_number_used(); 
352         return false;
353       }
355       // Create new SIP entry ...
356       $sip_entry = $sip_data_array;
357       reset($this->phoneNumbers);
358       $i_new_key = key($this->phoneNumbers);
359       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
360       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
362       if((isset($this->parent->by_object['mailAccount']->mail))&&($this->parent->by_object['mailAccount']->is_account==true)){
363         $s_mail = $this->parent->by_object['mailAccount']->mail;
364       }else{
365         $s_mail = "";
366       }
368       // $SQL contains all queries
369       $SQL   = array();
370       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
371       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
372       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
374       // Generate Strings with keys and values 
375       foreach($sip_entry as $s_sip_key=>$s_sip_val){
376         if($s_sip_val == NULL) continue;
377         $s_sip_values.="'".$s_sip_val."',";
378         $s_sip_keys  .="`".$s_sip_key."`,";
379       }
380       // Remove last ,
381       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
382       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
384       // Append SIP Entry 
385       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
387       // Delete old entries
388       $b_first_deleted  =false;
389       foreach($this->a_old_telenums as $s_telenums){
390         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
391         if(!$b_first_deleted){
392           $b_first_deleted=true;
393           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
394         }
395       }
397       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']."
398         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
399         VALUES
400         ('".$this->phoneNumbers[$i_new_key]."','default','".$this->phoneNumbers[$i_new_key]."','".$this->goFonPIN."','".$this->sn."','".$s_mail."','');";
402       $i_is_accounted=false;
404       // Entension entries  Hint / Dial / Goto
405       foreach($this->phoneNumbers as $s_telenums){
406         // Entry  to call by name
407         $s_entry_name['context']  = 'GOsa';
408         $s_entry_name['exten']    = $this->uid;
409         $s_entry_name['priority'] = 1;
410         $s_entry_name['app']      = 'Goto';
411         $s_entry_name['appdata']  = $s_telenums."|1";
413         // hint
414         $s_entry_hint['context']  = 'GOsa';
415         $s_entry_hint['exten']    = $s_telenums;
416         $s_entry_hint['priority']      = 'hint';
417         $s_entry_hint['app']  = 'SIP/'.$this->uid;
419         // If no macro is selected use Dial
420         if($this->macro!="none"){ 
421           $macroname = preg_replace("/,.*$/","",$this->macro);        
422           $macroname = preg_replace("/^.*=/","",$macroname);        
423           $s_app = "Macro";$macroname;
424           $s_par = $macroname."|".$s_parameter; 
425         }else{
426           $s_app = "Dial";
427           $s_par = 'SIP/'.$this->uid;
428         }
430         // Entry  to call by number
431         $s_entry_phone['context']  = 'GOsa';
432         $s_entry_phone['exten']    = $s_telenums;
433         $s_entry_phone['priority'] = 1;
434         $s_entry_phone['app']      = $s_app;
435         $s_entry_phone['appdata']  = $s_par;
437         // append name entry only once
438         if(!$i_is_accounted){ 
439           $i_is_accounted = true;
440           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
441         }else{
442           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
443         }
444       }
446       // Append all these Entries 
447       foreach($entries as $num => $val){
448         foreach($val as $entr){
449           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
450           foreach($entr as $key2 => $val2){
451             $SQL_syn.= "`".$key2."`,";
452           }
453           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
454           $SQL_syn .= ") VALUES ("; 
455           foreach($entr as $key2 => $val2){
456             $SQL_syn .= "'".$val2."',";
457           }
458           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
459           $SQL_syn .=");\n";
460           $SQL[] =$SQL_syn;
461           $SQL_syn ="";
462         }
463       }
465       // Perform queries ...
466       foreach($SQL as $query){
467         if(!mysql_query($query,$r_con)){
468           print_red(_("Error while performing query ".mysql_error()));
469           return false;
470         }
471       }
472     }
473     return true;
474   }
489   function execute()
490   {
491     /* force postmodify event, to restart phones */
493     $this->parent->by_object['user']->is_modified=TRUE;
494     $this->is_modified=TRUE; 
496     $this->uid = $this->parent->by_object['user']->uid;
497     $this->cn  = $this->parent->by_object['user']->cn;
500     /* Do we need to flip is_account state? */
501     if (isset($_POST['modify_state'])){
502       $this->is_account= !$this->is_account;
503     }
505     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
506     if(empty($this->macro)){
507       $this->macro ="none";
508     }
510     /* tell user that the pluging selected is no longer available*/
511     if((!$this->macrostillavailable)&&($this->macro!="none")){
512       print_red(_("The macro you selected in the past, is no longer available for you, please choose another one."));
513     }
515     /* Prepare templating */
516     $smarty= get_smarty();
518     /* Assing macroselectbox values  */
519     $smarty->assign("macros",$this->macros);   
520     $smarty->assign("macro", $this->macro);   
522     /* Create parameter table, skip if no parameters given */
523     if(!isset($this->macroarray[$this->macro])){
524       $macrotab="";
525     }else{
527       $macrotab ="<table summary=\""._("Parameter")."\" width='100%'>";
528       /* for every single parameter-> display textfile,combo, or true false switch*/
531       /* Automatic fill out */
532       if(isset($_POST['fillout'])){
534         foreach($this->phoneNumbers as $phonenum){
535           $tmp[] = $phonenum;
536         }
538         /* Go through all params */
539         foreach($this->macroarray[$this->macro] as $key => $paras){
541           $string = $paras['default'];
543           $string=preg_replace("/%uid/i",$this->uid,$string);
544           $string=preg_replace("/%cn/i",$this->cn,$string);
546           for($i = 0 ; $i < 10; $i++){
547             if(isset($tmp[$i])){
548               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
549             }
550           }
552           $this->macroarray[$this->macro][$key]['choosen']=$string;
553         }
554       }
556       foreach($this->macroarray[$this->macro] as $paras){
558         /* get al vars */
559         $var        = $paras['var'];           
560         $name       = $paras['name'];           
561         $default    = $paras['default'];
562         $type       = $paras['type'];
563         $choosen    = $paras['choosen'] ; 
564         $str        = $default;
566         /* in case of a combo box display a combobox with selected attr */
567         $macrotab.= "<tr>";
568         switch ($type){
570           case "combo":
571             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
572           foreach(split(":",$default) as $choice){
573             if($choosen==$choice){
574               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
575             }else{
576               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
577             }
578           }
579           $str.="</select>";
580           $macrotab.= "<td>$name</td><td>$str";
581           break;
583           case "bool":
584             if(!$choosen){
585               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
586             }else{
587               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
588             }
589           $macrotab.= "<td colspan='2'>$str&nbsp;$name";
590           break;
592           case "string":
593             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
594           $macrotab.= "<td colspan='2'>$name</td></tr><tr><td colspan='2' style='width:350px'>$str";
595           break;
597         }
598         $macrotab.= "</td></tr><tr><td colspan='2'>&nbsp;</td></tr>";
600       }
601       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
602     }//is_array()
604     /* Give smarty the table */
605     $smarty->assign("macrotab",$macrotab);
607     /* Do we represent a valid account? */
608     if (!$this->is_account && $this->parent == NULL){
609       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
610         _("This account has no phone extensions.")."</b>";
611       $display.= back_to_main();
612       return($display);
613     }
615     $display= "";
617     /* Show tab dialog headers */
618     if ($this->parent != NULL){
619       if ($this->is_account){
620         $display= $this->show_header(_("Remove phone account"),
621             _("This account has phone features enabled. You can disable them by clicking below."));
622       } else {
623         if(empty($this->uid)){
624           $display= $this->show_header(_("Create phone account"),
625               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
626         }else{
627           $display= $this->show_header(_("Create phone account"),
628               _("This account has phone features disabled. You can enable them by clicking below."));
629         }
630         return ($display);
631       }
632     }
634     /* Add phone number */
635     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
636       if (is_phone_nr($_POST['phonenumber'])){
637         $number= $_POST["phonenumber"];
638         $this->phoneNumbers[$number]= $number;
639         $this->is_modified= TRUE;
640       } else {
641         print_red(_("Please enter a valid phone number!"));
642       }
643     }
645     /* Remove phone number */
646     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
647       foreach ($_POST['phonenumber_list'] as $number){
648         unset($this->phoneNumbers[$number]);
649         $this->is_modified= TRUE;
650       }
651     }
653     /* Check for forwarding action */
654     foreach ($this->forwarders as $nr => $fw){
656       /* Buttons pressed? */
657       if (isset($_POST["add_fw$nr"])){
658         $this->forwarders= $this->insert_after("", $nr, $this->forwarders);
659       }
660       if (isset($_POST["remove_fw$nr"])){
661         unset($this->forwarders[$nr]);
662       }
663     }
665     /* Transfer ACL's */
666     foreach($this->attributes as $val){
667       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
668       $smarty->assign($val,$this->$val);
669     }
671     /* Fill arrays */
672     $smarty->assign ("goFonHardware", $this->goFonHardware);
673     if (!count($this->phoneNumbers)){
674       $smarty->assign ("phoneNumbers", array(""));
675     } else {
676       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
677     }
678     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
679       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
680     foreach ($this->hardware_list as $cn => $description){
681       if ($cn == $this->goFonHardware){
682         $selected= "selected";
683       } else {
684         $selected= "";
685       }
686       if (isset($this->used_hardware[$cn])){
687         $color= "style=\"color:#A0A0A0\"";
688       } else {
689         $color= "";
690       }
691       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
692     }
693     $hl.= "</select>\n";
694     $smarty->assign ("hardware_list", $hl);
696     /* Generate forwarder view */
697     $forwarder_list="";
698     $acl= chkacl($this->acl, "goFonForwaring");
699     foreach ($this->forwarders as $nr => $fw){
700       if ($fw == ""){
701         $number= ""; $timeout= "";
702       } else {
703         list($number, $timeout)= split(";", $fw);
704       }
705       $forwarder_list.= "<tr><td>";
706       $forwarder_list.= "<input name=\"fwn$nr\" size=25 align=\"middle\" maxlength=60 value=\"$number\" $acl>";
707       $forwarder_list.= "</td><td>";
708       $forwarder_list.= "<input name=\"fwt$nr\" size=5 align=\"middle\" maxlength=5 value=\"$timeout\" $acl>";
709       $forwarder_list.= "</td><td>";
710       $forwarder_list.= "<input type=\"submit\" value=\""._("Add")."\" name=\"add_fw$nr\" $acl>";
711       if (count($this->forwarders) > 1){
712         $forwarder_list.= "<input type=\"submit\" value=\""._("Remove")."\" name=\"remove_fw$nr\" $acl>";
713       }
714       $forwarder_list.= "</td></tr>";
715     }
716     $smarty->assign("forwarder_list", $forwarder_list);
718     /* Show main page */
719     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
720     return($display);
721   }
724   function save_object()
725   {
726     if (isset($_POST["phoneTab"])){
727       plugin::save_object();
729       /* Save checkbox */
730       if (isset($_POST['fon_to_mail'])){
731         $tmp= "[M]";
732       } else {
733         $tmp= "[]";
734       }
735       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
736         if ($this->goFonDeliveryMode != $tmp){
737           $this->is_modified= TRUE;
738         }
739         $this->goFonDeliveryMode= $tmp;
740       }
742       /* Save forwarding numbers and timeouts */
743       if (chkacl ($this->acl, "goFonForwarder") == ""){
744         foreach ($this->forwarders as $nr => $fw){
745           $tmp= $_POST["fwn$nr"].";".$_POST["fwt$nr"];
746           if ($this->forwarders[$nr] != $tmp){
747             $this->is_modified= TRUE;
748           }
749           $this->forwarders[$nr]= $tmp;
750         }
751       }
753       /* Every macro in the select box are available */
754       if((isset($_POST['macro']))){
755         $this->macrostillavailable=true;
756       }
758       if(is_array($this->phoneNumbers)){
759         foreach($this->phoneNumbers as $telenumms) {
760           $nummsinorder[]=$telenumms; 
761         }
762       }else{
763         $nummsinorder=array("");
764       }
766       /* get all Postvars */
767       if(isset($this->macroarray[$this->macro])){ 
768         foreach($this->macroarray[$this->macro] as $key => $paras){
769           if(isset($_POST[$paras['var']])){
770             //            $par = $this->macroarray[$this->macro][$key];
771             //            $string = "";
772             //            if(preg_match("/.*%telephoneNumber_.*/",$par['default'])){
773             //              $string = $par['default'];
774             //              foreach($nummsinorder as $nummsinorderkey=> $nummsinorderval){
775             //                $string = (str_replace("%telephoneNumber_".($nummsinorderkey+1),$nummsinorderval,$string));
776             //              }
777             //            }
779             //            if(preg_match("/.*%uid.*/",$par['default'])){
780             //              if(empty($string)) $string = $par['default'];
781             //              $string = str_replace("%uid",$this->uid,$string);
782             //            }    
784             //            if(!empty($string)){  
785             //              $this->macroarray[$this->macro][$key]['choosen'] = $string; 
786             //            }else{
787             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
788             //            }
789           }
791           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
792              We need this code below to read and save checkboxes correct
793            */
795           if(isset($_POST['post_success'])){
796             if($this->macroarray[$this->macro][$key]['type']=="bool"){
797               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
798                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
799               }else{
800                 $this->macroarray[$this->macro][$key]['choosen']=false;
801               }
802             }
803           }
804         }
805       }
806     }
807   }
809   function check()
810   {
811     /* Reset message array */
812     $message= array();
814     if(!$this->generate_mysql_entension_entries()){
815       $message[] = $this->generate_error;
816     }
818     /* We need at least one phone number */
819     if (count($this->phoneNumbers) == 0){
820       $message[]= sprintf(_("You need to specify at least one phone number!"));
821     }
823     if(($this->goFonPIN)==""){
824       $message[]= sprintf(_("You need to specify a Phone PIN."));
825     }else{
826       if(strcmp ((int)($this->goFonPIN),($this->goFonPIN))){
827         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
828       }elseif(strlen($this->goFonPIN) < 4){
829         $message[] = sprintf(_("The given PIN is too short"));
830       }
832     }
833     /* Check timestamps and phonenumbers */
834     foreach ($this->forwarders as $fw){
836       /* Skip empty values */
837       if ($fw == ";"){
838         continue;
839       }         
841       /* Check */
842       list($number, $timeout)= split(";", $fw);
843       if (!is_phone_nr($number)){
844         $message[]= sprintf(_("The number '%s' is no valid phone number!"), $number);
845       }
846       if (!is_id($timeout)){
847         $message[]= sprintf(_("The timeout '%s' contains invalid characters!"), $timeout);
848       }
849     }
851     /* check for ! in any parameter setting*/
852     if(isset($this->macroarray[$this->macro])){
853       foreach($this->macroarray[$this->macro] as $val){
854         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
855           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
856         }
857       }
858     }
859     return ($message);
860   }
864   function save()
865   {
866     plugin::save();
868     /* Save arrays */
869     $this->attrs['telephoneNumber']= array();
870     foreach ($this->phoneNumbers as $number){
871       $this->attrs['telephoneNumber'][]= $number;
872     }
873     $this->attrs['goFonForwarding']= array();
874     foreach ($this->forwarders as $index => $number){
875       $this->attrs['goFonForwarding'][]= "$index;$number";
876     }
878     /* Save settings, or remove goFonMacro attribute*/
879     if($this->macro!="none"){    
880       $this->attrs['goFonMacro']=$this->macro;
881       if(isset($this->macroarray[$this->macro])){
882         foreach($this->macroarray[$this->macro] as $paras)  {
883           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
884         }
885       }
886     }else{
887       $this->attrs['goFonMacro']=array();
888     }
889     unset($this->attrs['macro'])  ;
891     $this->generate_mysql_entension_entries(true);
893     if($this->attrs['goFonMacro']==""){
894       $this->attrs['goFonMacro']=array();
895     }
896     /* Write back to ldap */
897     $ldap= $this->config->get_ldap_link();
898     $ldap->cd($this->dn);
899     $ldap->modify($this->attrs);
900     show_ldap_error($ldap->get_error());
902     /* Optionally execute a command after we're done */
904     if ($this->initially_was_account == $this->is_account){
905       if ($this->is_modified){
906         $this->handle_post_events("modify");
907       }
908     } else {
909       $this->handle_post_events("add");
910     }
912   }
915   function insert_after($entry, $nr, $list)
916   {
917     /* Is the entry free? No? Make it free... */
918     if (isset($list[$nr])) {
919       $dest= array();
920       $newidx= 0;
922       foreach ($list as $idx => $contents){
923         $dest[$newidx++]= $contents;
924         if ($idx == $nr){
925           $dest[$newidx++]= $entry;
926         }
927       }
928     } else {
929       $dest= $list;
930       $dest[$nr]= $entry;
931     }
933     return ($dest);
934   }
937   function adapt_from_template($dn)
938   {
939     plugin::adapt_from_template($dn);
941     /* Assemble phone numbers */
942     if (isset($this->attrs['telephoneNumber'])){
943       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
944         $number= $this->attrs['telephoneNumber'][$i];
945         $this->phoneNumbers[$number]= $number;
946       }
947     }
949     /* Assemble forwarders */
950     if (isset($this->attrs['goFonForwarding'])){
951       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
952         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
953         $this->forwarders[$num]= "$v1;$v2";
954       }
955     } else {
956       $this->forwarders= array("");
957     }
958   }
961   function remove_from_parent()
962   {
963     // Get Configuration for Mysql database Server
964     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
965     $s_parameter  ="";
967     // Connect to DB server
968     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
970     // Check if we are  connected correctly
971     if(!$r_con){
972       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
973           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
974       gosa_log(mysql_error());
975       return false;
976     }
978     // Select database for Extensions
979     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
981     // Test if we have the database selected correctly
982     if(!$db){
983       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
984       gosa_log(mysql_error());
985       return false;
986     }
988     $SQL="";
990     /* If deletion starts from userslist, cn uid are not set */
991     $this->uid = $this->parent->by_object['user']->uid;
992     $this->cn  = $this->parent->by_object['user']->cn;
994     $first_num = false;
995     // Delete old entries
996     foreach($this->a_old_telenums as $s_telenums){
997       if(!$first_num){
998         $first_num = $s_telenums;
999       }
1000       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1001     }
1003     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1004     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1005     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1008     foreach($SQL as $query){
1009       if(!mysql_query($query,$r_con)){
1010         print_red(_("Stop".mysql_error()));
1011         return false;
1012       }
1013     }
1017     /* unset macro attr, it will cause an error */
1018     $tmp = array_flip($this->attributes);
1019     unset($tmp['macro']);
1020     $this->attributes=array_flip($tmp);
1022     /* Cancel if there's nothing to do here */
1023     if (!$this->initially_was_account){
1024       return;
1025     }
1027     plugin::remove_from_parent();
1029     /* Just keep one phone number */
1030     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1031       $this->attrs['telephoneNumber']= $this->telephoneNumber;
1032     } else {
1033       $this->attrs['telephoneNumber']= array();
1034     }
1036     $ldap= $this->config->get_ldap_link();
1037     $ldap->cd($this->config->current['BASE']);
1038     $ldap->search("(objectClass=goFonQueue)", array("member"));
1039     while($attr = $ldap->fetch()){
1040       if(in_array($this->dn,$attr['member'])){
1041         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1042         unset($new->by_object['ogroup']->memberList[$this->dn]);
1043         unset($new->by_object['ogroup']->member[$this->dn]);
1044         $new->save();
1045         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1046       }
1047     }
1048     $ldap->cd($this->dn);
1049     $ldap->modify($this->attrs);
1050     show_ldap_error($ldap->get_error());
1052     /* Optionally execute a command after we're done */
1053     $this->handle_post_events('remove');
1054   }
1058   /* This function checks if the given phonenumbers are available or already in use*/
1059   function is_number_used()
1060   {
1061     $ldap= $this->config->get_ldap_link();
1062     $ldap->cd($this->config->current['BASE']);
1063     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue))", array("telephoneNumber","cn","uid"));
1064     while($attrs = $ldap->fetch()) {
1065       unset($attrs['telephoneNumber']['count']);
1066       foreach($attrs['telephoneNumber'] as $tele){
1067         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1068         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1069         $numbers[$tele]=$attrs;
1070       }
1071     }
1073     foreach($this->phoneNumbers as $num){
1074       if(!isset($this->cn)) $this->cn = "";
1076       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1077         if(isset($numbers[$num]['uid'][0])){
1078           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1079         }else{
1080           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1081         }
1082       }
1083     }
1084   }
1089 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1090 ?>