Code

Added unset tabbed attribute
[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     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
86     $ldap->search("(objectClass=goFonMacro)", array("*"));
88     /* Add none for no macro*/
89     $this->macros['none']=_("no macro");    
90     $this->macro ="none";
93     /* Fetch all Macros*/
94     while ($attrs= $ldap->fetch()){
96       /* Only visisble */
97       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
99         /* unset Count, we don't need that here */
100         unset($attrs['displayName']['count']);
102         /* fill Selectfield variable with Macros */
103         if(isset($attrs['displayName'][0])){
104           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
105         }else{
106           $this->macros[$attrs['dn']] = _("undefined");
107         }
109         /* Parse macro data, unset count for parameterarrays  */
110         unset($attrs['goFonMacroParameter']['count']);
112         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
113         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
115           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
116             /* Split Data in readable values, by delimiter !  */
117             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
119             /* Set all attrs */
120             $id = $data[0];
121             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
122             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
123             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
124             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
125             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
126             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
127             if($data[2] == "bool"){
128               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
129             }
130           }//foreach
131         }//is_array
132       }//visible = 1
133     }//while
135     /* Go through already saved values, for a parameter */
136     $tmp = split("!",$this->goFonMacro);
138     /* it is possible that nothing has been saved yet */
139     if(is_array($tmp)){
141       /* First value is the macroname */
142       $this->macro = $tmp[0];
144       /* Macroname saved, delete that index */
145       unset($tmp[0]);
147       /* Check if makro has been removed */
148       if(!isset($this->macroarray[$this->macro])){
149         $this->macrostillavailable = false;
150       }else{
151         $this->macrostillavailable = true;
152       }
154       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
155       foreach($tmp as $var){
157         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
158         $varar = split("#",$var);
160         /* Only insert if the parameter still exists */
161         if(isset($this->macroarray[$this->macro][$varar[0]])){
162           /* Assign value */
163           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
164         }
165       }
166     }
169     /* Eventually colorize phones */
170     $ldap->cd($this->config->current['BASE']);
171     foreach ($this->hardware_list as $cn => $desc){
172       $ldap->search("(goFonHardware=$cn)", array('cn'));
173       if ($ldap->count() > 0){
174         $ldap->fetch();
175         if ($ldap->getDN() != $this->dn){
176           $this->used_hardware[$cn]= $ldap->getDN();
177         }
178       }
179     }
180     $this->hardware_list["automatic"]= _("automatic");
181     ksort($this->hardware_list);
182     $this->a_old_telenums = $this->phoneNumbers;
183   }
186   // Generate MySQL Syntax
187   function generate_mysql_entension_entries($save = false){
189     // Get Configuration for Mysql database Server
190     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
191     $s_parameter    = "";                                           // Contains paramter for selected Macro 
192     $r_con          = false;                                        // DB connection
193     $r_db           = false;                                        // Selected DB
194     $r_res          = false;                                        // Result resource
195     $a_ldap_attrs   = array();                                      //  
197     $s_ip           = NULL;                   // Contains ip for Sip entry
198     $s_host         = NULL;                   // Contains host for Sip entry
199     $s_qualify      = NULL;                   // Qualify entry
200     $s_pin          = NULL;                   // Entry for secret
201     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
203     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
204     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
205     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
207     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
208     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
210     $s_sip_key      = "";     // Key for SIP entry index      
211     $s_sip_val      = "";     // Value for SIP entry index      
213     $b_first_deleted= false;  // Only delete first entry, 
214     $s_telenums     = "";     // for each value variable
216     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
219     // Connect to DB server
220     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
222     // Check if we are  connected correctly
223     if(!$r_con){
224       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
225           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
226       gosa_log(mysql_error());
227       return false;
228     }
230     // Select database for Extensions
231     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
233     // Test if we have the database selected correctly
234     if(!$r_db){
235       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
236       gosa_log(mysql_error());
237       return false;
238     }
240     // Get phonehardware to setup sip entry
241     $ldap         = $this->config->get_ldap_link();
242     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
243     $a_ldap_attrs = $ldap->fetch();
245     if($this->is_number_used()){
246       $this->generate_error = $this->is_number_used(); 
247       return false;
248     }
252     /* If Save == true, we should save something.
253      * Generate SQL, for drop of old entries
254      * Generate SQL, for insert of new entries
255      */ 
256     if($save == true){
257       // Attribute GoFonDefaultIP set ?
258       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
259         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
260         $s_host     = $s_ip;
261       }else{
262         $s_ip       = NULL;
263         $s_host     = "dynamic";
264       }
266       // Attribute GoFonQualify set ?
267       if(isset($a_ldap_attrs['goFonQualify'])){
268         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
269       }
271       // Attribute GoFonPIN set ?
272       if(isset($this->goFonPIN)){
273         $s_pin      = $this->goFonPIN;
274       }
276       // Attribute GoFonType set ?
277       if(isset($a_ldap_attrs['goFonType'])){
278         $s_type = $a_ldap_attrs['goFonType'][0];
279       }
281       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
282         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
283       }else{
284         $sip_data_array['dtmfmode']     ="rfc2833";
285       }
287       // generate SIP entry
288       $sip_data_array['id']           = "";
289       $sip_data_array['name']         = $this->uid;
290       $sip_data_array['accountcode']  = NULL;          
291       $sip_data_array['amaflags']     = NULL;
292       $sip_data_array['callgroup']    = NULL;
293       $sip_data_array['callerid']     = "";
294       $sip_data_array['canreinvite']  = "yes";
295       $sip_data_array['context']      = "default";
296       $sip_data_array['defaultip']    = NULL;
297       $sip_data_array['fromuser']     = NULL;
298       $sip_data_array['fromdomain']   = NULL;
299       $sip_data_array['host']         = $s_host;
300       $sip_data_array['insecure']     = NULL;
301       $sip_data_array['language']     = NULL;
302       $sip_data_array['mailbox']      = "asterisk";
303       $sip_data_array['md5secret']    = NULL;
304       $sip_data_array['nat']          = "no";
305       $sip_data_array['permit']       = NULL;
306       $sip_data_array['deny']         = NULL;
307       $sip_data_array['mask']         = NULL;
308       $sip_data_array['pickupgroup']  = NULL;
309       $sip_data_array['port']         = NULL;
310       $sip_data_array['qualify']      = $s_qualify;
311       $sip_data_array['restrictcid']  = "n";
312       $sip_data_array['rtptimeout']   = NULL;
313       $sip_data_array['rtpholdtimeout']=NULL;
314       $sip_data_array['secret']       = $s_pin;
315       $sip_data_array['type']         = $s_type ;
316       $sip_data_array['username']     = $this->uid;
317       $sip_data_array['disallow']     = NULL;
318       $sip_data_array['allow']        = NULL;
319       $sip_data_array['musiconhold']  = NULL;
320       $sip_data_array['regseconds']   = NULL;
321       $sip_data_array['ipaddr']       = $s_ip;
322       $sip_data_array['regexten']     = NULL;
323       $sip_data_array['cancallforward']=NULL;
325       // Get selected Macro Parameter and create parameter entry 
326       if(isset($this->macroarray[$this->macro])){
327         foreach($this->macroarray[$this->macro] as $key => $val ){
328           $s_parameter .= $val['choosen']."|";
329         }
330         $s_parameter = preg_replace("/\|$/","",$s_parameter);
331       }
333       if($this->is_number_used()){
334         $this->generate_error = $this->is_number_used(); 
335         return false;
336       }
338       // Create new SIP entry ...
339       $sip_entry = $sip_data_array;
340       reset($this->phoneNumbers);
341       $i_new_key = key($this->phoneNumbers);
342       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
343       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
345       if((isset($this->parent->by_object['mailAccount']->mail))&&($this->parent->by_object['mailAccount']->is_account==true)){
346         $s_mail = $this->parent->by_object['mailAccount']->mail;
347       }else{
348         $s_mail = "";
349       }
351       // $SQL contains all queries
352       $SQL   = array();
353       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
354       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
355       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
357       // Generate Strings with keys and values 
358       foreach($sip_entry as $s_sip_key=>$s_sip_val){
359         if($s_sip_val == NULL) continue;
360         $s_sip_values.="'".$s_sip_val."',";
361         $s_sip_keys  .="`".$s_sip_key."`,";
362       }
363       // Remove last ,
364       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
365       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
367       // Append SIP Entry 
368       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
370       // Delete old entries
371       $b_first_deleted  =false;
372       foreach($this->a_old_telenums as $s_telenums){
373         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
374         if(!$b_first_deleted){
375           $b_first_deleted=true;
376           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
377         }
378       }
380       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']."
381         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
382         VALUES
383         ('".$this->phoneNumbers[$i_new_key]."','default','".$this->phoneNumbers[$i_new_key]."','".$this->goFonPIN."','".$this->sn."','".$s_mail."','');";
385       $i_is_accounted=false;
387       // Entension entries  Hint / Dial / Goto
388       foreach($this->phoneNumbers as $s_telenums){
389         // Entry  to call by name
390         $s_entry_name['context']  = 'GOsa';
391         $s_entry_name['exten']    = $this->uid;
392         $s_entry_name['priority'] = 1;
393         $s_entry_name['app']      = 'Goto';
394         $s_entry_name['appdata']  = $s_telenums."|1";
396         // hint
397         $s_entry_hint['context']  = 'GOsa';
398         $s_entry_hint['exten']    = $s_telenums;
399         $s_entry_hint['priority']      = 'hint';
400         $s_entry_hint['app']  = 'SIP/'.$this->uid;
402         // If no macro is selected use Dial
403         if($this->macro!="none"){ 
404           $macroname = preg_replace("/,.*$/","",$this->macro);        
405           $macroname = preg_replace("/^.*=/","",$macroname);        
406           $s_app = "Macro";$macroname;
407           $s_par = $macroname."|".$s_parameter; 
408         }else{
409           $s_app = "Dial";
410           $s_par = 'SIP/'.$this->uid;
411         }
413         // Entry  to call by number
414         $s_entry_phone['context']  = 'GOsa';
415         $s_entry_phone['exten']    = $s_telenums;
416         $s_entry_phone['priority'] = 1;
417         $s_entry_phone['app']      = $s_app;
418         $s_entry_phone['appdata']  = $s_par;
420         // append name entry only once
421         if(!$i_is_accounted){ 
422           $i_is_accounted = true;
423           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
424         }else{
425           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
426         }
427       }
429       // Append all these Entries 
430       foreach($entries as $num => $val){
431         foreach($val as $entr){
432           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
433           foreach($entr as $key2 => $val2){
434             $SQL_syn.= "`".$key2."`,";
435           }
436           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
437           $SQL_syn .= ") VALUES ("; 
438           foreach($entr as $key2 => $val2){
439             $SQL_syn .= "'".$val2."',";
440           }
441           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
442           $SQL_syn .=");\n";
443           $SQL[] =$SQL_syn;
444           $SQL_syn ="";
445         }
446       }
448       // Perform queries ...
449       foreach($SQL as $query){
450         if(!mysql_query($query,$r_con)){
451           print_red(_("Error while performing query ".mysql_error()));
452           return false;
453         }
454       }
455     }
456     return true;
457   }
460   function execute()
461   {
462     /* Do we represent a valid account? */
463     if (!$this->is_account && $this->parent == NULL){
464       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
465         _("This account has no phone extensions.")."</b>";
466       $display.= back_to_main();
467       return ($display);
468     }
470     /* force postmodify event, to restart phones */
471     if ($this->parent != NULL){
472       $this->parent->by_object['user']->is_modified=TRUE;
473       $this->is_modified= TRUE; 
475       $this->uid = $this->parent->by_object['user']->uid;
476       $this->cn  = $this->parent->by_object['user']->cn;
477     }
479     /* Do we need to flip is_account state? */
480     if (isset($_POST['modify_state'])){
481       $this->is_account= !$this->is_account;
482     }
484     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
485     if(empty($this->macro)){
486       $this->macro ="none";
487     }
489     /* tell user that the pluging selected is no longer available*/
490     if((!$this->macrostillavailable)&&($this->macro!="none")){
491       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
492     }
494     /* Prepare templating */
495     $smarty= get_smarty();
497     /* Assing macroselectbox values  */
498     $smarty->assign("macros",$this->macros);   
499     $smarty->assign("macro", $this->macro);   
501     /* Create parameter table, skip if no parameters given */
502     if(!isset($this->macroarray[$this->macro])){
503       $macrotab="";
504     }else{
506       $macrotab ="<table summary=\""._("Parameter")."\">";
507       /* for every single parameter-> display textfile,combo, or true false switch*/
510       /* Automatic fill out */
511       if(isset($_POST['fillout'])){
513         foreach($this->phoneNumbers as $phonenum){
514           $tmp[] = $phonenum;
515         }
517         /* Go through all params */
518         foreach($this->macroarray[$this->macro] as $key => $paras){
520           $string = $paras['default'];
522           $string=preg_replace("/%uid/i",$this->uid,$string);
523           $string=preg_replace("/%cn/i",$this->cn,$string);
525           for($i = 0 ; $i < 10; $i++){
526             if(isset($tmp[$i])){
527               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
528             }
529           }
531           $this->macroarray[$this->macro][$key]['choosen']=$string;
532         }
533       }
535       foreach($this->macroarray[$this->macro] as $paras){
537         /* get al vars */
538         $var        = $paras['var'];           
539         $name       = $paras['name'];           
540         $default    = $paras['default'];
541         $type       = $paras['type'];
542         $choosen    = $paras['choosen'] ; 
543         $str        = $default;
545         /* in case of a combo box display a combobox with selected attr */
546         $macrotab.= "<tr>";
547         switch ($type){
549           case "combo":
550             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
551           foreach(split(":",$default) as $choice){
552             if($choosen==$choice){
553               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
554             }else{
555               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
556             }
557           }
558           $str.="</select>";
559           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
560           break;
562           case "bool":
563             if(!$choosen){
564               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
565             }else{
566               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
567             }
568           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
569           break;
571           case "string":
572             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
573           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
574           break;
576         }
577         $macrotab.= "</td></tr>";
579       }
580       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
581     }//is_array()
583     /* Give smarty the table */
584     $smarty->assign("macrotab",$macrotab);
586     /* Do we represent a valid account? */
587     if (!$this->is_account && $this->parent == NULL){
588       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
589         _("This account has no phone extensions.")."</b>";
590       $display.= back_to_main();
591       return($display);
592     }
594     $display= "";
596     /* Show tab dialog headers */
597     if ($this->parent != NULL){
598       if ($this->is_account){
599         $display= $this->show_header(_("Remove phone account"),
600             _("This account has phone features enabled. You can disable them by clicking below."));
601       } else {
602         if(empty($this->uid)){
603           $display= $this->show_header(_("Create phone account"),
604               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
605         }else{
606           $display= $this->show_header(_("Create phone account"),
607               _("This account has phone features disabled. You can enable them by clicking below."));
608         }
609         return ($display);
610       }
611     }
613     /* Add phone number */
614     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
615       if (is_phone_nr($_POST['phonenumber'])){
616         $number= $_POST["phonenumber"];
617         $this->phoneNumbers[$number]= $number;
618         $this->is_modified= TRUE;
619       } else {
620         print_red(_("Please enter a valid phone number!"));
621       }
622     }
624     /* Remove phone number */
625     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
626       foreach ($_POST['phonenumber_list'] as $number){
627         unset($this->phoneNumbers[$number]);
628         $this->is_modified= TRUE;
629       }
630     }
632     /* Transfer ACL's */
633     foreach($this->attributes as $val){
634       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
635       $smarty->assign($val,$this->$val);
636     }
638     /* Fill arrays */
639     $smarty->assign ("goFonHardware", $this->goFonHardware);
640     if (!count($this->phoneNumbers)){
641       $smarty->assign ("phoneNumbers", array(""));
642     } else {
643       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
644     }
645     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
646       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
647     foreach ($this->hardware_list as $cn => $description){
648       if ($cn == $this->goFonHardware){
649         $selected= "selected";
650       } else {
651         $selected= "";
652       }
653       if (isset($this->used_hardware[$cn])){
654         $color= "style=\"color:#A0A0A0\"";
655       } else {
656         $color= "";
657       }
658       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
659     }
660     $hl.= "</select>\n";
661     $smarty->assign ("hardware_list", $hl);
663     /* Show main page */
664     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
665     return($display);
666   }
669   function save_object()
670   {
671     if (isset($_POST["phoneTab"])){
672       plugin::save_object();
674       /* Save checkbox */
675       if (isset($_POST['fon_to_mail'])){
676         $tmp= "[M]";
677       } else {
678         $tmp= "[]";
679       }
680       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
681         if ($this->goFonDeliveryMode != $tmp){
682           $this->is_modified= TRUE;
683         }
684         $this->goFonDeliveryMode= $tmp;
685       }
687       /* Every macro in the select box are available */
688       if((isset($_POST['macro']))){
689         $this->macrostillavailable=true;
690       }
692       if(is_array($this->phoneNumbers)){
693         foreach($this->phoneNumbers as $telenumms) {
694           $nummsinorder[]=$telenumms; 
695         }
696       }else{
697         $nummsinorder=array("");
698       }
700       /* get all Postvars */
701       if(isset($this->macroarray[$this->macro])){ 
702         foreach($this->macroarray[$this->macro] as $key => $paras){
703           if(isset($_POST[$paras['var']])){
704             //            $par = $this->macroarray[$this->macro][$key];
705             //            $string = "";
706             //            if(preg_match("/.*%telephoneNumber_.*/",$par['default'])){
707             //              $string = $par['default'];
708             //              foreach($nummsinorder as $nummsinorderkey=> $nummsinorderval){
709             //                $string = (str_replace("%telephoneNumber_".($nummsinorderkey+1),$nummsinorderval,$string));
710             //              }
711             //            }
713             //            if(preg_match("/.*%uid.*/",$par['default'])){
714             //              if(empty($string)) $string = $par['default'];
715             //              $string = str_replace("%uid",$this->uid,$string);
716             //            }    
718             //            if(!empty($string)){  
719             //              $this->macroarray[$this->macro][$key]['choosen'] = $string; 
720             //            }else{
721             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
722             //            }
723           }
725           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
726              We need this code below to read and save checkboxes correct
727            */
729           if(isset($_POST['post_success'])){
730             if($this->macroarray[$this->macro][$key]['type']=="bool"){
731               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
732                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
733               }else{
734                 $this->macroarray[$this->macro][$key]['choosen']=false;
735               }
736             }
737           }
738         }
739       }
740     }
741   }
743   function check()
744   {
745     /* Reset message array */
746     $message= array();
748     if(!$this->generate_mysql_entension_entries()){
749       $message[] = $this->generate_error;
750     }
752     /* We need at least one phone number */
753     if (count($this->phoneNumbers) == 0){
754       $message[]= sprintf(_("You need to specify at least one phone number!"));
755     }
757     if(($this->goFonPIN)==""){
758       $message[]= sprintf(_("You need to specify a Phone PIN."));
759     }else{
760       if(!is_id($this->goFonPIN)){
761         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
762       }elseif(strlen($this->goFonPIN) < 4){
763         $message[] = sprintf(_("The given PIN is too short"));
764       }
766     }
768     /* check for ! in any parameter setting*/
769     if(isset($this->macroarray[$this->macro])){
770       foreach($this->macroarray[$this->macro] as $val){
771         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
772           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
773         }
774       }
775     }
776     return ($message);
777   }
781   function save()
782   {
783     plugin::save();
785     /* Save arrays */
786     $this->attrs['telephoneNumber']= array();
787     foreach ($this->phoneNumbers as $number){
788       $this->attrs['telephoneNumber'][]= $number;
789     }
791     /* Save settings, or remove goFonMacro attribute*/
792     if($this->macro!="none"){    
793       $this->attrs['goFonMacro']=$this->macro;
794       if(isset($this->macroarray[$this->macro])){
795         foreach($this->macroarray[$this->macro] as $paras)  {
796           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
797         }
798       }
799     }else{
800       $this->attrs['goFonMacro']=array();
801     }
802     unset($this->attrs['macro'])  ;
804     $this->attrs['goFonForwarding']=array();
806     $this->generate_mysql_entension_entries(true);
808     if($this->attrs['goFonMacro']==""){
809       $this->attrs['goFonMacro']=array();
810     }
812     /* Write back to ldap */
813     $ldap= $this->config->get_ldap_link();
814     $ldap->cd($this->dn);
815     $ldap->modify($this->attrs);
816     show_ldap_error($ldap->get_error());
818     /* Optionally execute a command after we're done */
820     if ($this->initially_was_account == $this->is_account){
821       if ($this->is_modified){
822         $this->handle_post_events("modify");
823       }
824     } else {
825       $this->handle_post_events("add");
826     }
828   }
831   function insert_after($entry, $nr, $list)
832   {
833     /* Is the entry free? No? Make it free... */
834     if (isset($list[$nr])) {
835       $dest= array();
836       $newidx= 0;
838       foreach ($list as $idx => $contents){
839         $dest[$newidx++]= $contents;
840         if ($idx == $nr){
841           $dest[$newidx++]= $entry;
842         }
843       }
844     } else {
845       $dest= $list;
846       $dest[$nr]= $entry;
847     }
849     return ($dest);
850   }
853   function adapt_from_template($dn)
854   {
855     plugin::adapt_from_template($dn);
857     /* Assemble phone numbers */
858     if (isset($this->attrs['telephoneNumber'])){
859       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
860         $number= $this->attrs['telephoneNumber'][$i];
861         $this->phoneNumbers[$number]= $number;
862       }
863     }
864   }
867   function remove_from_parent()
868   {
869     // Get Configuration for Mysql database Server
870     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
871     $s_parameter  ="";
873     // Connect to DB server
874     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
876     // Check if we are  connected correctly
877     if(!$r_con){
878       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
879           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
880       gosa_log(mysql_error());
881       return false;
882     }
884     // Select database for Extensions
885     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
887     // Test if we have the database selected correctly
888     if(!$db){
889       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
890       gosa_log(mysql_error());
891       return false;
892     }
894     $SQL="";
896     /* If deletion starts from userslist, cn uid are not set */
897     $this->uid = $this->parent->by_object['user']->uid;
898     $this->cn  = $this->parent->by_object['user']->cn;
900     $first_num = false;
901     // Delete old entries
902     foreach($this->a_old_telenums as $s_telenums){
903       if(!$first_num){
904         $first_num = $s_telenums;
905       }
906       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
907     }
909     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
910     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
911     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
914     foreach($SQL as $query){
915       if(!mysql_query($query,$r_con)){
916         print_red(_("Stop".mysql_error()));
917         return false;
918       }
919     }
923     /* unset macro attr, it will cause an error */
924     $tmp = array_flip($this->attributes);
925     unset($tmp['macro']);
926     $this->attributes=array_flip($tmp);
928     /* Cancel if there's nothing to do here */
929     if (!$this->initially_was_account){
930       return;
931     }
933     plugin::remove_from_parent();
935     /* Just keep one phone number */
936     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
937       $this->attrs['telephoneNumber']= $this->telephoneNumber;
938     } else {
939       $this->attrs['telephoneNumber']= array();
940     }
942     $ldap= $this->config->get_ldap_link();
943     $ldap->cd($this->config->current['BASE']);
944     $ldap->search("(objectClass=goFonQueue)", array("member"));
945     while($attr = $ldap->fetch()){
946       if(in_array($this->dn,$attr['member'])){
947         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
948         unset($new->by_object['ogroup']->memberList[$this->dn]);
949         unset($new->by_object['ogroup']->member[$this->dn]);
950         $new->save();
951         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
952       }
953     }
954     $ldap->cd($this->dn);
955     $ldap->modify($this->attrs);
956     show_ldap_error($ldap->get_error());
958     /* Optionally execute a command after we're done */
959     $this->handle_post_events('remove');
960   }
964   /* This function checks if the given phonenumbers are available or already in use*/
965   function is_number_used()
966   {
967     $ldap= $this->config->get_ldap_link();
968     $ldap->cd($this->config->current['BASE']);
969     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
970     while($attrs = $ldap->fetch()) {
971       unset($attrs['telephoneNumber']['count']);
972       foreach($attrs['telephoneNumber'] as $tele){
973         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
974         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
975         $numbers[$tele]=$attrs;
976       }
977     }
979     foreach($this->phoneNumbers as $num){
980       if(!isset($this->cn)) $this->cn = "";
982       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
983         if(isset($numbers[$num]['uid'][0])){
984           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
985         }else{
986           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
987         }
988       }
989     }
990   }
995 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
996 ?>