Code

Removed call forwarding - this should do the macro
[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 Macor
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 $uid;
28   var $cn;
30   /* CLI vars */
31   var $cli_summary            = "Manage users phone account";
32   var $cli_description        = "Some longer text\nfor help";
33   var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
35   /* attribute list for save action */
36   var $attributes             = array("goFonDeliveryMode", "goFonFormat",
37       "goFonHardware", "goFonPIN", "telephoneNumber", "goFonMacro","macro");
38   var $objectclasses= array("goFonAccount");
40   function phoneAccount ($config, $dn= NULL)
41   {
42     plugin::plugin ($config, $dn);
44     /* Set phone hardware */
45     if (!isset($this->attrs['goFonHardware'])){
46       $this->goFonHardware= "automatic";
47     }
49     /* Preset voice format */
50     if (!isset($this->attrs['goFonFormat'])){
51       $this->goFonFormat= "wav";
52     }
54     /* Assemble phone numbers */
55     if (isset($this->attrs['telephoneNumber'])){
56       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
57         $number= $this->attrs['telephoneNumber'][$i];
58         $this->phoneNumbers[$number]= $number;
59       }
60     }
62     /* Set up has_mailAccount */
63     if (isset($this->attrs['objectClass'])){
64       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
65         $this->has_mailAccount= TRUE;
66       }
67     }
70     /* Load hardware list */
71     $ldap= $this->config->get_ldap_link();
72     $ldap->cd($this->config->current['BASE']);
73     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
74     while ($attrs= $ldap->fetch()){
75       $cn= $attrs['cn'][0];
76       if (isset($attrs['description'])){
77         $description= " - ".$attrs['description'][0];
78       } else {
79         $description= "";
80       }
81       $this->hardware_list[$cn]= "$cn$description";
83     }
85     /* Prepare templating */
86     $smarty= get_smarty();
89     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
90     $ldap->search("(objectClass=goFonMacro)", array("*"));
92     /* Add none for no macro*/
93     $this->macros['none']=_("no macro");    
94     $this->macro ="none";
97     /* Fetch all Macros*/
98     while ($attrs= $ldap->fetch()){
100       /* Only visisble */
101       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
103         /* unset Count, we don't need that here */
104         unset($attrs['displayName']['count']);
106         /* fill Selectfield variable with Macros */
107         if(isset($attrs['displayName'][0])){
108           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
109         }else{
110           $this->macros[$attrs['dn']] = _("undefined");
111         }
113         /* Parse macro data, unset count for parameterarrays  */
114         unset($attrs['goFonMacroParameter']['count']);
116         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
117         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
119           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
120             /* Split Data in readable values, by delimiter !  */
121             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
123             /* Set all attrs */
124             $id = $data[0];
125             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
126             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
127             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
128             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
129             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
130             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
131             if($data[2] == "bool"){
132               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
133             }
134           }//foreach
135         }//is_array
136       }//visible = 1
137     }//while
139     /* Go through already saved values, for a parameter */
140     $tmp = split("!",$this->goFonMacro);
142     /* it is possible that nothing has been saved yet */
143     if(is_array($tmp)){
145       /* First value is the macroname */
146       $this->macro = $tmp[0];
148       /* Macroname saved, delete that index */
149       unset($tmp[0]);
151       /* Check if makro has been removed */
152       if(!isset($this->macroarray[$this->macro])){
153         $this->macrostillavailable = false;
154       }else{
155         $this->macrostillavailable = true;
156       }
158       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
159       foreach($tmp as $var){
161         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
162         $varar = split("#",$var);
164         /* Only insert if the parameter still exists */
165         if(isset($this->macroarray[$this->macro][$varar[0]])){
166           /* Assign value */
167           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
168         }
169       }
170     }
173     /* Eventually colorize phones */
174     $ldap->cd($this->config->current['BASE']);
175     foreach ($this->hardware_list as $cn => $desc){
176       $ldap->search("(goFonHardware=$cn)", array('cn'));
177       if ($ldap->count() > 0){
178         $ldap->fetch();
179         if ($ldap->getDN() != $this->dn){
180           $this->used_hardware[$cn]= $ldap->getDN();
181         }
182       }
183     }
184     $this->hardware_list["automatic"]= _("automatic");
185     ksort($this->hardware_list);
186     $this->a_old_telenums = $this->phoneNumbers;
187   }
192   // Generate MySQL Syntax
193   function generate_mysql_entension_entries($save = false){
195     // Get Configuration for Mysql database Server
196     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
197     $s_parameter    = "";                                           // Contains paramter for selected Macro 
198     $r_con          = false;                                        // DB connection
199     $r_db           = false;                                        // Selected DB
200     $r_res          = false;                                        // Result resource
201     $a_ldap_attrs   = array();                                      //  
203     $s_ip           = NULL;                   // Contains ip for Sip entry
204     $s_host         = NULL;                   // Contains host for Sip entry
205     $s_qualify      = NULL;                   // Qualify entry
206     $s_pin          = NULL;                   // Entry for secret
207     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
209     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
210     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
211     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
213     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
214     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
216     $s_sip_key      = "";     // Key for SIP entry index      
217     $s_sip_val      = "";     // Value for SIP entry index      
219     $b_first_deleted= false;  // Only delete first entry, 
220     $s_telenums     = "";     // for each value variable
222     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
225     // Connect to DB server
226     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
228     // Check if we are  connected correctly
229     if(!$r_con){
230       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
231           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
232       gosa_log(mysql_error());
233       return false;
234     }
236     // Select database for Extensions
237     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
239     // Test if we have the database selected correctly
240     if(!$r_db){
241       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
242       gosa_log(mysql_error());
243       return false;
244     }
246     // Get phonehardware to setup sip entry
247     $ldap         = $this->config->get_ldap_link();
248     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
249     $a_ldap_attrs = $ldap->fetch();
251     if($this->is_number_used()){
252       $this->generate_error = $this->is_number_used(); 
253       return false;
254     }
258     /* If Save == true, we should save something.
259      * Generate SQL, for drop of old entries
260      * Generate SQL, for insert of new entries
261      */ 
262     if($save == true){
263       // Attribute GoFonDefaultIP set ?
264       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
265         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
266         $s_host     = $s_ip;
267       }else{
268         $s_ip       = NULL;
269         $s_host     = "dynamic";
270       }
272       // Attribute GoFonQualify set ?
273       if(isset($a_ldap_attrs['goFonQualify'])){
274         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
275       }
277       // Attribute GoFonPIN set ?
278       if(isset($this->goFonPIN)){
279         $s_pin      = $this->goFonPIN;
280       }
282       // Attribute GoFonType set ?
283       if(isset($a_ldap_attrs['goFonType'])){
284         $s_type = $a_ldap_attrs['goFonType'][0];
285       }
287       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
288         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
289       }else{
290         $sip_data_array['dtmfmode']     ="rfc2833";
291       }
293       // generate SIP entry
294       $sip_data_array['id']           = "";
295       $sip_data_array['name']         = $this->uid;
296       $sip_data_array['accountcode']  = NULL;          
297       $sip_data_array['amaflags']     = NULL;
298       $sip_data_array['callgroup']    = NULL;
299       $sip_data_array['callerid']     = "";
300       $sip_data_array['canreinvite']  = "yes";
301       $sip_data_array['context']      = "default";
302       $sip_data_array['defaultip']    = NULL;
303       $sip_data_array['fromuser']     = NULL;
304       $sip_data_array['fromdomain']   = NULL;
305       $sip_data_array['host']         = $s_host;
306       $sip_data_array['insecure']     = NULL;
307       $sip_data_array['language']     = NULL;
308       $sip_data_array['mailbox']      = "asterisk";
309       $sip_data_array['md5secret']    = NULL;
310       $sip_data_array['nat']          = "no";
311       $sip_data_array['permit']       = NULL;
312       $sip_data_array['deny']         = NULL;
313       $sip_data_array['mask']         = NULL;
314       $sip_data_array['pickupgroup']  = NULL;
315       $sip_data_array['port']         = NULL;
316       $sip_data_array['qualify']      = $s_qualify;
317       $sip_data_array['restrictcid']  = "n";
318       $sip_data_array['rtptimeout']   = NULL;
319       $sip_data_array['rtpholdtimeout']=NULL;
320       $sip_data_array['secret']       = $s_pin;
321       $sip_data_array['type']         = $s_type ;
322       $sip_data_array['username']     = $this->uid;
323       $sip_data_array['disallow']     = NULL;
324       $sip_data_array['allow']        = NULL;
325       $sip_data_array['musiconhold']  = NULL;
326       $sip_data_array['regseconds']   = NULL;
327       $sip_data_array['ipaddr']       = $s_ip;
328       $sip_data_array['regexten']     = NULL;
329       $sip_data_array['cancallforward']=NULL;
331       // Get selected Macro Parameter and create parameter entry 
332       if(isset($this->macroarray[$this->macro])){
333         foreach($this->macroarray[$this->macro] as $key => $val ){
334           $s_parameter .= $val['choosen']."|";
335         }
336         $s_parameter = preg_replace("/\|$/","",$s_parameter);
337       }
339       if($this->is_number_used()){
340         $this->generate_error = $this->is_number_used(); 
341         return false;
342       }
344       // Create new SIP entry ...
345       $sip_entry = $sip_data_array;
346       reset($this->phoneNumbers);
347       $i_new_key = key($this->phoneNumbers);
348       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
349       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
351       if((isset($this->parent->by_object['mailAccount']->mail))&&($this->parent->by_object['mailAccount']->is_account==true)){
352         $s_mail = $this->parent->by_object['mailAccount']->mail;
353       }else{
354         $s_mail = "";
355       }
357       // $SQL contains all queries
358       $SQL   = array();
359       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
360       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
361       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
363       // Generate Strings with keys and values 
364       foreach($sip_entry as $s_sip_key=>$s_sip_val){
365         if($s_sip_val == NULL) continue;
366         $s_sip_values.="'".$s_sip_val."',";
367         $s_sip_keys  .="`".$s_sip_key."`,";
368       }
369       // Remove last ,
370       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
371       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
373       // Append SIP Entry 
374       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
376       // Delete old entries
377       $b_first_deleted  =false;
378       foreach($this->a_old_telenums as $s_telenums){
379         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
380         if(!$b_first_deleted){
381           $b_first_deleted=true;
382           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
383         }
384       }
386       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']."
387         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
388         VALUES
389         ('".$this->phoneNumbers[$i_new_key]."','default','".$this->phoneNumbers[$i_new_key]."','".$this->goFonPIN."','".$this->sn."','".$s_mail."','');";
391       $i_is_accounted=false;
393       // Entension entries  Hint / Dial / Goto
394       foreach($this->phoneNumbers as $s_telenums){
395         // Entry  to call by name
396         $s_entry_name['context']  = 'GOsa';
397         $s_entry_name['exten']    = $this->uid;
398         $s_entry_name['priority'] = 1;
399         $s_entry_name['app']      = 'Goto';
400         $s_entry_name['appdata']  = $s_telenums."|1";
402         // hint
403         $s_entry_hint['context']  = 'GOsa';
404         $s_entry_hint['exten']    = $s_telenums;
405         $s_entry_hint['priority']      = 'hint';
406         $s_entry_hint['app']  = 'SIP/'.$this->uid;
408         // If no macro is selected use Dial
409         if($this->macro!="none"){ 
410           $macroname = preg_replace("/,.*$/","",$this->macro);        
411           $macroname = preg_replace("/^.*=/","",$macroname);        
412           $s_app = "Macro";$macroname;
413           $s_par = $macroname."|".$s_parameter; 
414         }else{
415           $s_app = "Dial";
416           $s_par = 'SIP/'.$this->uid;
417         }
419         // Entry  to call by number
420         $s_entry_phone['context']  = 'GOsa';
421         $s_entry_phone['exten']    = $s_telenums;
422         $s_entry_phone['priority'] = 1;
423         $s_entry_phone['app']      = $s_app;
424         $s_entry_phone['appdata']  = $s_par;
426         // append name entry only once
427         if(!$i_is_accounted){ 
428           $i_is_accounted = true;
429           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
430         }else{
431           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
432         }
433       }
435       // Append all these Entries 
436       foreach($entries as $num => $val){
437         foreach($val as $entr){
438           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
439           foreach($entr as $key2 => $val2){
440             $SQL_syn.= "`".$key2."`,";
441           }
442           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
443           $SQL_syn .= ") VALUES ("; 
444           foreach($entr as $key2 => $val2){
445             $SQL_syn .= "'".$val2."',";
446           }
447           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
448           $SQL_syn .=");\n";
449           $SQL[] =$SQL_syn;
450           $SQL_syn ="";
451         }
452       }
454       // Perform queries ...
455       foreach($SQL as $query){
456         if(!mysql_query($query,$r_con)){
457           print_red(_("Error while performing query ".mysql_error()));
458           return false;
459         }
460       }
461     }
462     return true;
463   }
478   function execute()
479   {
480     /* force postmodify event, to restart phones */
482     $this->parent->by_object['user']->is_modified=TRUE;
483     $this->is_modified=TRUE; 
485     $this->uid = $this->parent->by_object['user']->uid;
486     $this->cn  = $this->parent->by_object['user']->cn;
489     /* Do we need to flip is_account state? */
490     if (isset($_POST['modify_state'])){
491       $this->is_account= !$this->is_account;
492     }
494     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
495     if(empty($this->macro)){
496       $this->macro ="none";
497     }
499     /* tell user that the pluging selected is no longer available*/
500     if((!$this->macrostillavailable)&&($this->macro!="none")){
501       print_red(_("The macro you selected in the past, is no longer available for you, please choose another one."));
502     }
504     /* Prepare templating */
505     $smarty= get_smarty();
507     /* Assing macroselectbox values  */
508     $smarty->assign("macros",$this->macros);   
509     $smarty->assign("macro", $this->macro);   
511     /* Create parameter table, skip if no parameters given */
512     if(!isset($this->macroarray[$this->macro])){
513       $macrotab="";
514     }else{
516       $macrotab ="<table summary=\""._("Parameter")."\">";
517       /* for every single parameter-> display textfile,combo, or true false switch*/
520       /* Automatic fill out */
521       if(isset($_POST['fillout'])){
523         foreach($this->phoneNumbers as $phonenum){
524           $tmp[] = $phonenum;
525         }
527         /* Go through all params */
528         foreach($this->macroarray[$this->macro] as $key => $paras){
530           $string = $paras['default'];
532           $string=preg_replace("/%uid/i",$this->uid,$string);
533           $string=preg_replace("/%cn/i",$this->cn,$string);
535           for($i = 0 ; $i < 10; $i++){
536             if(isset($tmp[$i])){
537               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
538             }
539           }
541           $this->macroarray[$this->macro][$key]['choosen']=$string;
542         }
543       }
545       foreach($this->macroarray[$this->macro] as $paras){
547         /* get al vars */
548         $var        = $paras['var'];           
549         $name       = $paras['name'];           
550         $default    = $paras['default'];
551         $type       = $paras['type'];
552         $choosen    = $paras['choosen'] ; 
553         $str        = $default;
555         /* in case of a combo box display a combobox with selected attr */
556         $macrotab.= "<tr>";
557         switch ($type){
559           case "combo":
560             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
561           foreach(split(":",$default) as $choice){
562             if($choosen==$choice){
563               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
564             }else{
565               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
566             }
567           }
568           $str.="</select>";
569           $macrotab.= "<td>$name</td><td>$str";
570           break;
572           case "bool":
573             if(!$choosen){
574               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
575             }else{
576               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
577             }
578           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
579           break;
581           case "string":
582             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
583           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
584           break;
586         }
587         $macrotab.= "</td></tr>";
589       }
590       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
591     }//is_array()
593     /* Give smarty the table */
594     $smarty->assign("macrotab",$macrotab);
596     /* Do we represent a valid account? */
597     if (!$this->is_account && $this->parent == NULL){
598       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
599         _("This account has no phone extensions.")."</b>";
600       $display.= back_to_main();
601       return($display);
602     }
604     $display= "";
606     /* Show tab dialog headers */
607     if ($this->parent != NULL){
608       if ($this->is_account){
609         $display= $this->show_header(_("Remove phone account"),
610             _("This account has phone features enabled. You can disable them by clicking below."));
611       } else {
612         if(empty($this->uid)){
613           $display= $this->show_header(_("Create phone account"),
614               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
615         }else{
616           $display= $this->show_header(_("Create phone account"),
617               _("This account has phone features disabled. You can enable them by clicking below."));
618         }
619         return ($display);
620       }
621     }
623     /* Add phone number */
624     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
625       if (is_phone_nr($_POST['phonenumber'])){
626         $number= $_POST["phonenumber"];
627         $this->phoneNumbers[$number]= $number;
628         $this->is_modified= TRUE;
629       } else {
630         print_red(_("Please enter a valid phone number!"));
631       }
632     }
634     /* Remove phone number */
635     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
636       foreach ($_POST['phonenumber_list'] as $number){
637         unset($this->phoneNumbers[$number]);
638         $this->is_modified= TRUE;
639       }
640     }
642     /* Transfer ACL's */
643     foreach($this->attributes as $val){
644       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
645       $smarty->assign($val,$this->$val);
646     }
648     /* Fill arrays */
649     $smarty->assign ("goFonHardware", $this->goFonHardware);
650     if (!count($this->phoneNumbers)){
651       $smarty->assign ("phoneNumbers", array(""));
652     } else {
653       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
654     }
655     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
656       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
657     foreach ($this->hardware_list as $cn => $description){
658       if ($cn == $this->goFonHardware){
659         $selected= "selected";
660       } else {
661         $selected= "";
662       }
663       if (isset($this->used_hardware[$cn])){
664         $color= "style=\"color:#A0A0A0\"";
665       } else {
666         $color= "";
667       }
668       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
669     }
670     $hl.= "</select>\n";
671     $smarty->assign ("hardware_list", $hl);
673     /* Show main page */
674     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
675     return($display);
676   }
679   function save_object()
680   {
681     if (isset($_POST["phoneTab"])){
682       plugin::save_object();
684       /* Save checkbox */
685       if (isset($_POST['fon_to_mail'])){
686         $tmp= "[M]";
687       } else {
688         $tmp= "[]";
689       }
690       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
691         if ($this->goFonDeliveryMode != $tmp){
692           $this->is_modified= TRUE;
693         }
694         $this->goFonDeliveryMode= $tmp;
695       }
697       /* Every macro in the select box are available */
698       if((isset($_POST['macro']))){
699         $this->macrostillavailable=true;
700       }
702       if(is_array($this->phoneNumbers)){
703         foreach($this->phoneNumbers as $telenumms) {
704           $nummsinorder[]=$telenumms; 
705         }
706       }else{
707         $nummsinorder=array("");
708       }
710       /* get all Postvars */
711       if(isset($this->macroarray[$this->macro])){ 
712         foreach($this->macroarray[$this->macro] as $key => $paras){
713           if(isset($_POST[$paras['var']])){
714             //            $par = $this->macroarray[$this->macro][$key];
715             //            $string = "";
716             //            if(preg_match("/.*%telephoneNumber_.*/",$par['default'])){
717             //              $string = $par['default'];
718             //              foreach($nummsinorder as $nummsinorderkey=> $nummsinorderval){
719             //                $string = (str_replace("%telephoneNumber_".($nummsinorderkey+1),$nummsinorderval,$string));
720             //              }
721             //            }
723             //            if(preg_match("/.*%uid.*/",$par['default'])){
724             //              if(empty($string)) $string = $par['default'];
725             //              $string = str_replace("%uid",$this->uid,$string);
726             //            }    
728             //            if(!empty($string)){  
729             //              $this->macroarray[$this->macro][$key]['choosen'] = $string; 
730             //            }else{
731             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
732             //            }
733           }
735           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
736              We need this code below to read and save checkboxes correct
737            */
739           if(isset($_POST['post_success'])){
740             if($this->macroarray[$this->macro][$key]['type']=="bool"){
741               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
742                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
743               }else{
744                 $this->macroarray[$this->macro][$key]['choosen']=false;
745               }
746             }
747           }
748         }
749       }
750     }
751   }
753   function check()
754   {
755     /* Reset message array */
756     $message= array();
758     if(!$this->generate_mysql_entension_entries()){
759       $message[] = $this->generate_error;
760     }
762     /* We need at least one phone number */
763     if (count($this->phoneNumbers) == 0){
764       $message[]= sprintf(_("You need to specify at least one phone number!"));
765     }
767     if(($this->goFonPIN)==""){
768       $message[]= sprintf(_("You need to specify a Phone PIN."));
769     }else{
770       if(strcmp ((int)($this->goFonPIN),($this->goFonPIN))){
771         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
772       }elseif(strlen($this->goFonPIN) < 4){
773         $message[] = sprintf(_("The given PIN is too short"));
774       }
776     }
778     /* check for ! in any parameter setting*/
779     if(isset($this->macroarray[$this->macro])){
780       foreach($this->macroarray[$this->macro] as $val){
781         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
782           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
783         }
784       }
785     }
786     return ($message);
787   }
791   function save()
792   {
793     plugin::save();
795     /* Save arrays */
796     $this->attrs['telephoneNumber']= array();
797     foreach ($this->phoneNumbers as $number){
798       $this->attrs['telephoneNumber'][]= $number;
799     }
801     /* Save settings, or remove goFonMacro attribute*/
802     if($this->macro!="none"){    
803       $this->attrs['goFonMacro']=$this->macro;
804       if(isset($this->macroarray[$this->macro])){
805         foreach($this->macroarray[$this->macro] as $paras)  {
806           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
807         }
808       }
809     }else{
810       $this->attrs['goFonMacro']=array();
811     }
812     unset($this->attrs['macro'])  ;
814     $this->generate_mysql_entension_entries(true);
816     if($this->attrs['goFonMacro']==""){
817       $this->attrs['goFonMacro']=array();
818     }
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     // Get Configuration for Mysql database Server
877     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
878     $s_parameter  ="";
880     // Connect to DB server
881     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
883     // Check if we are  connected correctly
884     if(!$r_con){
885       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
886           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
887       gosa_log(mysql_error());
888       return false;
889     }
891     // Select database for Extensions
892     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
894     // Test if we have the database selected correctly
895     if(!$db){
896       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
897       gosa_log(mysql_error());
898       return false;
899     }
901     $SQL="";
903     /* If deletion starts from userslist, cn uid are not set */
904     $this->uid = $this->parent->by_object['user']->uid;
905     $this->cn  = $this->parent->by_object['user']->cn;
907     $first_num = false;
908     // Delete old entries
909     foreach($this->a_old_telenums as $s_telenums){
910       if(!$first_num){
911         $first_num = $s_telenums;
912       }
913       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
914     }
916     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
917     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
918     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
921     foreach($SQL as $query){
922       if(!mysql_query($query,$r_con)){
923         print_red(_("Stop".mysql_error()));
924         return false;
925       }
926     }
930     /* unset macro attr, it will cause an error */
931     $tmp = array_flip($this->attributes);
932     unset($tmp['macro']);
933     $this->attributes=array_flip($tmp);
935     /* Cancel if there's nothing to do here */
936     if (!$this->initially_was_account){
937       return;
938     }
940     plugin::remove_from_parent();
942     /* Just keep one phone number */
943     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
944       $this->attrs['telephoneNumber']= $this->telephoneNumber;
945     } else {
946       $this->attrs['telephoneNumber']= array();
947     }
949     $ldap= $this->config->get_ldap_link();
950     $ldap->cd($this->config->current['BASE']);
951     $ldap->search("(objectClass=goFonQueue)", array("member"));
952     while($attr = $ldap->fetch()){
953       if(in_array($this->dn,$attr['member'])){
954         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
955         unset($new->by_object['ogroup']->memberList[$this->dn]);
956         unset($new->by_object['ogroup']->member[$this->dn]);
957         $new->save();
958         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
959       }
960     }
961     $ldap->cd($this->dn);
962     $ldap->modify($this->attrs);
963     show_ldap_error($ldap->get_error());
965     /* Optionally execute a command after we're done */
966     $this->handle_post_events('remove');
967   }
971   /* This function checks if the given phonenumbers are available or already in use*/
972   function is_number_used()
973   {
974     $ldap= $this->config->get_ldap_link();
975     $ldap->cd($this->config->current['BASE']);
976     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue))", array("telephoneNumber","cn","uid"));
977     while($attrs = $ldap->fetch()) {
978       unset($attrs['telephoneNumber']['count']);
979       foreach($attrs['telephoneNumber'] as $tele){
980         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
981         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
982         $numbers[$tele]=$attrs;
983       }
984     }
986     foreach($this->phoneNumbers as $num){
987       if(!isset($this->cn)) $this->cn = "";
989       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
990         if(isset($numbers[$num]['uid'][0])){
991           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
992         }else{
993           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
994         }
995       }
996     }
997   }
1002 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1003 ?>