Code

451ed7ae61e1b521b235f56015632334f94788fe
[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();
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", "goFonForwarding", "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     }
61     /* Assemble forwarders */
62     if (isset($this->attrs['goFonForwarding'])){
63       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
64         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
65         $this->forwarders[$num]= "$v1;$v2";
66       }
67     } else {
68       $this->forwarders= array("");
69     }
71     /* Set up has_mailAccount */
72     if (isset($this->attrs['objectClass'])){
73       if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
74         $this->has_mailAccount= TRUE;
75       }
76     }
79     /* Load hardware list */
80     $ldap= $this->config->get_ldap_link();
81     $ldap->cd($this->config->current['BASE']);
82     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
83     while ($attrs= $ldap->fetch()){
84       $cn= $attrs['cn'][0];
85       if (isset($attrs['description'])){
86         $description= " - ".$attrs['description'][0];
87       } else {
88         $description= "";
89       }
90       $this->hardware_list[$cn]= "$cn$description";
92     }
94     /* Prepare templating */
95     $smarty= get_smarty();
98     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
99     $ldap->search("(objectClass=goFonMacro)", array("*"));
101     /* Add none for no macro*/
102     $this->macros['none']=_("no macro");    
103     $this->macro ="none";
106     /* Fetch all Macros*/
107     while ($attrs= $ldap->fetch()){
109       /* Only visisble */
110       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
112         /* unset Count, we don't need that here */
113         unset($attrs['displayName']['count']);
115         /* fill Selectfield variable with Macros */
116         if(isset($attrs['displayName'][0])){
117           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
118         }else{
119           $this->macros[$attrs['dn']] = _("undefined");
120         }
122         /* Parse macro data, unset count for parameterarrays  */
123         unset($attrs['goFonMacroParameter']['count']);
125         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
126         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
128           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
129             /* Split Data in readable values, by delimiter !  */
130             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
132             /* Set all attrs */
133             $id = $data[0];
134             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
135             $string= $data[3];
136             $string = preg_replace("/%uid/",$this->attrs['uid'][0],$data[3]);
137             for($i = 0 ; $i < 10; $i++){
138               if(isset($this->attrs['telephoneNumber'][$i])){
139                 $string = preg_replace("/%telephoneNumber_".($i+1)."/",$this->attrs['telephoneNumber'][$i],$string);
140               }
141             }
142             $string = preg_replace("/%cn/",$this->attrs['cn'][0],$string);
143             $this->macroarray[$attrs['dn']][$id]['choosen']= $string; 
145             $this->macroarray[$attrs['dn']][$id]['id']     = $id;
146             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
147             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
148             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
149             if($data[2] == "bool"){
150               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
151             }
152           }//foreach
153         }//is_array
154       }//visible = 1
155     }//while
157     /* Go through already saved values, for a parameter */
158     $tmp = split("!",$this->goFonMacro);
160     /* it is possible that nothing has been saved yet */
161     if(is_array($tmp)){
163       /* First value is the macroname */
164       $this->macro = $tmp[0];
166       /* Macroname saved, delete that index */
167       unset($tmp[0]);
169       /* Check if makro has been removed */
170       if(!isset($this->macroarray[$this->macro])){
171         $this->macrostillavailable = false;
172       }else{
173         $this->macrostillavailable = true;
174       }
176       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
177       foreach($tmp as $var){
179         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
180         $varar = split("#",$var);
182         /* Only insert if the parameter still exists */
183         if(isset($this->macroarray[$this->macro][$varar[0]])){
184           /* Assign value */
185           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
186         }
187       }
188     }
191     /* Eventually colorize phones */
192     $ldap->cd($this->config->current['BASE']);
193     foreach ($this->hardware_list as $cn => $desc){
194       $ldap->search("(goFonHardware=$cn)", array('cn'));
195       if ($ldap->count() > 0){
196         $ldap->fetch();
197         if ($ldap->getDN() != $this->dn){
198           $this->used_hardware[$cn]= $ldap->getDN();
199         }
200       }
201     }
202     $this->hardware_list["automatic"]= _("automatic");
203     ksort($this->hardware_list);
204     $this->a_old_telenums = $this->phoneNumbers;
205   }
210   // Generate MySQL Syntax
211   function generate_mysql_entension_entries($save = false){
213     // Get Configuration for Mysql database Server
214     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
215     $s_parameter  ="";
217     // Connect to DB server
218     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
220     // Check if we are  connected correctly
221     if(!$r_con){
222       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
223           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
224       gosa_log(mysql_error());
225       return false;
226     }
228     // Select database for Extensions
229     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
231     // Test if we have the database selected correctly
232     if(!$db){
233       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
234       gosa_log(mysql_error());
235       return false;
236     }
238     // Get phonehardware to setup sip entry
239     $ldap= $this->config->get_ldap_link();
240     $res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
241     $attrs = $ldap->fetch();
243     // Attribute GoFonDefaultIP set ?
244     if(((isset($attrs['goFonDefaultIP'][0]))&&($attrs['goFonDefaultIP'][0] != "dynamic"))){
245       $ip = $attrs['goFonDefaultIP'][0];
246       $host = $ip;
247     }else{
248       $ip = NULL;
249       $host = "dynamic";
250     }
252     // Attribute GoFonQualify set ?
253     if(!isset($attrs['goFonQualify'])){
254       $qualify = NULL;
255     }else{
256       $qualify = $attrs['goFonQualify'][0];
257     }
259     // Attribute GoFonPIN set ?
260     if(!isset($this->goFonPIN)){
261       $pin = NULL;
262     }else{
263       $pin = $this->goFonPIN;
264     }
266     // Attribute GoFonType set ?
267     if(!isset($attrs['goFonType'])){
268       $type = NULL;
269     }else{
270       $type = $attrs['goFonType'][0];
271     }
273     // generate SIP entry
274     $sip_data_array['id']           = "";
275     $sip_data_array['name']         = $this->uid;
276     $sip_data_array['accountcode']  = NULL;          
277     $sip_data_array['amaflags']     = NULL;
278     $sip_data_array['callgroup']    = NULL;
279     $sip_data_array['callerid']     = "";
280     $sip_data_array['canreinvite']  = "yes";
282     // Must be default and the name of an entry that already exists
283     $sip_data_array['context']      = "default";
284     $sip_data_array['defaultip']    = NULL;
286     if(isset($attrs['goFonDmtfMode'][0])){
287       $sip_data_array['dtmfmode']     = $attrs['goFonDmtfMode'][0];
288     }else{
289       $sip_data_array['dtmfmode']     ="rfc2833";
290     }
291     $sip_data_array['fromuser']     = NULL;
292     $sip_data_array['fromdomain']   = NULL;
293     $sip_data_array['host']         = $host;
294     $sip_data_array['insecure']     = NULL;
295     $sip_data_array['language']     = NULL;
296     $sip_data_array['mailbox']      = "asterisk";
297     $sip_data_array['md5secret']    = NULL;
298     $sip_data_array['nat']          = "no";
299     $sip_data_array['permit']       = NULL;
300     $sip_data_array['deny']         = NULL;
301     $sip_data_array['mask']         = NULL;
302     $sip_data_array['pickupgroup']  = NULL;
303     $sip_data_array['port']         = NULL;
304     $sip_data_array['qualify']      = $qualify;
305     $sip_data_array['restrictcid']  = "n";
306     $sip_data_array['rtptimeout']   = NULL;
307     $sip_data_array['rtpholdtimeout']=NULL;
308     $sip_data_array['secret']       = $pin;
309     $sip_data_array['type']         = $type ;
310     $sip_data_array['username']     = $this->uid;
311     $sip_data_array['disallow']     = NULL;
312     $sip_data_array['allow']        = NULL;
313     $sip_data_array['musiconhold']  = NULL;
314     $sip_data_array['regseconds']   = NULL;
315     $sip_data_array['ipaddr']       = $ip;
316     $sip_data_array['regexten']     = NULL;
317     $sip_data_array['cancallforward']=NULL;
319     // Get selected Macro Parameter and create parameter entry 
320     if(isset($this->macroarray[$this->macro])){
321       foreach($this->macroarray[$this->macro] as $key => $val ){
322         $s_parameter .= $val['choosen']."|";
323       }
324       $s_parameter = preg_replace("/\|$/","",$s_parameter);
325     }
333     // $SQL contains all queries
334     $SQL = array();
335     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
336     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
338     // Create new SIP entry ...
339     $sip_entry = $sip_data_array;
341     reset($this->phoneNumbers);
343     $key = key($this->phoneNumbers);
344     $sip_entry['callerid']  =$this->phoneNumbers[$key];
345     $sip_entry['mailbox']   =$this->phoneNumbers[$key];
347     if($this->is_number_used()){
348       $this->generate_error = $this->is_number_used(); 
349       return false;
350     }
352     if($save == true){
353       if(isset($this->parent->by_object['mailAccount']->mail)){
354         $mail = $this->parent->by_object['mailAccount']->mail;
355       }else{
356         $mail = "";
357       }
360       $SQL[]= "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$this->phoneNumbers[$key]."';"; 
361       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." 
362         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`) 
363         VALUES 
364         ('".$this->phoneNumbers[$key]."','default','".$this->phoneNumbers[$key]."','".$this->goFonPIN."','".$this->sn."','".$mail."','');";
366       // Generate Strings with keys and values 
367       $values = "";
368       $keys   = "";
369       foreach($sip_entry as $key=>$val){
370         if($val == NULL) continue;
371         $values.="'".$val."',";
372         $keys  .="`".$key."`,";
373       }
374       // Remove last ,
375       $values =  preg_replace("/,$/","",$values);
376       $keys   =  preg_replace("/,$/","",$keys);
378       // Append SIP Entry 
379       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$keys.") VALUES (".$values.");";
381       // Delete old entries
382       foreach($this->a_old_telenums as $s_telenums){
383         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
384       }
386       $i_is_accounted=false;
388       // Entension entries  Hint / Dial / Goto
389       foreach($this->phoneNumbers as $s_telenums){
390         // Entry  to call by name
391         $s_entry_name['context']  = 'GOsa';
392         $s_entry_name['exten']    = $this->uid;
393         $s_entry_name['priority'] = 1;
394         $s_entry_name['app']      = 'Goto';
395         $s_entry_name['appdata']  = $s_telenums."|1";
397         // hint
398         $s_entry_hint['context']  = 'GOsa';
399         $s_entry_hint['exten']    = $s_telenums;
400         $s_entry_hint['app']      = 'hint';
401         $s_entry_hint['appdata']  = 'SIP/'.$this->uid;
403         // If no macro is selected use Dial
404         if($this->macro!="none"){ 
405           $macroname = preg_replace("/,.*$/","",$this->macro);        
406           $macroname = preg_replace("/^.*=/","",$macroname);        
407           $s_app = "Macro";$macroname;
408           $s_par = $macroname."|".$s_parameter; 
409         }else{
410           $s_app = "Dial";
411           $s_par = 'SIP/'.$this->uid;
412         }
414         // Entry  to call by number
415         $s_entry_phone['context']  = 'GOsa';
416         $s_entry_phone['exten']    = $s_telenums;
417         $s_entry_phone['priority'] = 1;
418         $s_entry_phone['app']      = $s_app;
419         $s_entry_phone['appdata']  = $s_par;
421         // append name entry only once
422         if(!$i_is_accounted){ 
423           $i_is_accounted = true;
424           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
425         }else{
426           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
427         }
428       }
430       // Append all these Entries 
431       foreach($entries as $num => $val){
432         foreach($val as $entr){
433           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
434           foreach($entr as $key2 => $val2){
435             $SQL_syn.= "`".$key2."`,";
436           }
437           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
438           $SQL_syn .= ") VALUES ("; 
439           foreach($entr as $key2 => $val2){
440             $SQL_syn .= "'".$val2."',";
441           }
442           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
443           $SQL_syn .=");\n";
444           $SQL[] =$SQL_syn;
445           $SQL_syn ="";
446         }
447       }
449       // Perform queries ...
450       foreach($SQL as $query){
451         if(!mysql_query($query,$r_con)){
452           print_red(_("Error while performing query ".mysql_error()));
453           return false;
454         }
455       }
456     }
457     return true;
458   }
473   function execute()
474   {
475     /* force postmodify event, to restart phones */
476     
477     $this->parent->by_object['user']->is_modified=TRUE;
478     $this->is_modified=TRUE; 
480     /* Do we need to flip is_account state? */
481     if (isset($_POST['modify_state'])){
482       $this->is_account= !$this->is_account;
483     }
485     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
486     if(empty($this->macro)){
487       $this->macro ="none";
488     }
490     /* tell user that the pluging selected is no longer available*/
491     if((!$this->macrostillavailable)&&($this->macro!="none")){
492       print_red(_("The macro you selected in the past, is no longer available for you, please choose another one."));
493     }
495     /* Prepare templating */
496     $smarty= get_smarty();
498     /* Assing macroselectbox values  */
499     $smarty->assign("macros",$this->macros);   
500     $smarty->assign("macro", $this->macro);   
502     /* Create parameter table, skip if no parameters given */
503     if(!isset($this->macroarray[$this->macro])){
504       $macrotab="";
505     }else{
507       $macrotab ="<table summary=\""._("Parameter")."\">";
508       /* for every single parameter-> display textfile,combo, or true false switch*/
511       foreach($this->macroarray[$this->macro] as $paras){
513         /* get al vars */
514         $var        = $paras['var'];           
515         $name       = $paras['name'];           
516         $default    = $paras['default'];
517         $type       = $paras['type'];
518         $choosen    = $paras['choosen'] ; 
519         $str        = $default;
521         /* in case of a combo box display a combobox with selected attr */
522         $macrotab.= "<tr>";
523         switch ($type){
525           case "combo":
526             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
527           foreach(split(":",$default) as $choice){
528             if($choosen==$choice){
529               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
530             }else{
531               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
532             }
533           }
534           $str.="</select>";
535           $macrotab.= "<td>$name</td><td>$str";
536           break;
538           case "bool":
539             if(!$choosen){
540               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
541             }else{
542               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
543             }
544           $macrotab.= "<td colspan='2'>$str&nbsp;$name";
545           break;
547           case "string":
548           $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro").">";
549           $macrotab.= "<td>$name</td><td>$str";
550           break;
552         }
553         $macrotab.= "</td></tr>";
555       }
556       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
557     }//is_array()
559     /* Give smarty the table */
560     $smarty->assign("macrotab",$macrotab);
562     /* Do we represent a valid account? */
563     if (!$this->is_account && $this->parent == NULL){
564       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
565         _("This account has no phone extensions.")."</b>";
566       $display.= back_to_main();
567       return($display);
568     }
570     $display= "";
572     /* Show tab dialog headers */
573     if ($this->parent != NULL){
574       if ($this->is_account){
575         $display= $this->show_header(_("Remove phone account"),
576             _("This account has phone features enabled. You can disable them by clicking below."));
577       } else {
578         $display= $this->show_header(_("Create phone account"),
579             _("This account has phone features disabled. You can enable them by clicking below."));
580         return ($display);
581       }
582     }
584     /* Add phone number */
585     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
586       if (is_phone_nr($_POST['phonenumber'])){
587         $number= $_POST["phonenumber"];
588         $this->phoneNumbers[$number]= $number;
589         $this->is_modified= TRUE;
590       } else {
591         print_red(_("Please enter a valid phone number!"));
592       }
593     }
595     /* Remove phone number */
596     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
597       foreach ($_POST['phonenumber_list'] as $number){
598         unset($this->phoneNumbers[$number]);
599         $this->is_modified= TRUE;
600       }
601     }
603     /* Check for forwarding action */
604     foreach ($this->forwarders as $nr => $fw){
606       /* Buttons pressed? */
607       if (isset($_POST["add_fw$nr"])){
608         $this->forwarders= $this->insert_after("", $nr, $this->forwarders);
609       }
610       if (isset($_POST["remove_fw$nr"])){
611         unset($this->forwarders[$nr]);
612       }
613     }
615     /* Transfer ACL's */
616     foreach($this->attributes as $val){
617       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
618       $smarty->assign($val,$this->$val);
619     }
621     /* Fill arrays */
622     $smarty->assign ("goFonHardware", $this->goFonHardware);
623     if (!count($this->phoneNumbers)){
624       $smarty->assign ("phoneNumbers", array(""));
625     } else {
626       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
627     }
628     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
629       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
630     foreach ($this->hardware_list as $cn => $description){
631       if ($cn == $this->goFonHardware){
632         $selected= "selected";
633       } else {
634         $selected= "";
635       }
636       if (isset($this->used_hardware[$cn])){
637         $color= "style=\"color:#A0A0A0\"";
638       } else {
639         $color= "";
640       }
641       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
642     }
643     $hl.= "</select>\n";
644     $smarty->assign ("hardware_list", $hl);
646     /* Generate forwarder view */
647     $forwarder_list="";
648     $acl= chkacl($this->acl, "goFonForwaring");
649     foreach ($this->forwarders as $nr => $fw){
650       if ($fw == ""){
651         $number= ""; $timeout= "";
652       } else {
653         list($number, $timeout)= split(";", $fw);
654       }
655       $forwarder_list.= "<tr><td>";
656       $forwarder_list.= "<input name=\"fwn$nr\" size=25 align=\"middle\" maxlength=60 value=\"$number\" $acl>";
657       $forwarder_list.= "</td><td>";
658       $forwarder_list.= "<input name=\"fwt$nr\" size=5 align=\"middle\" maxlength=5 value=\"$timeout\" $acl>";
659       $forwarder_list.= "</td><td>";
660       $forwarder_list.= "<input type=\"submit\" value=\""._("Add")."\" name=\"add_fw$nr\" $acl>";
661       if (count($this->forwarders) > 1){
662         $forwarder_list.= "<input type=\"submit\" value=\""._("Remove")."\" name=\"remove_fw$nr\" $acl>";
663       }
664       $forwarder_list.= "</td></tr>";
665     }
666     $smarty->assign("forwarder_list", $forwarder_list);
668     /* Show main page */
669     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
670     return($display);
671   }
674   function save_object()
675   {
676     if (isset($_POST["phoneTab"])){
677       plugin::save_object();
679       /* Save checkbox */
680       if (isset($_POST['fon_to_mail'])){
681         $tmp= "[M]";
682       } else {
683         $tmp= "[]";
684       }
685       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
686         if ($this->goFonDeliveryMode != $tmp){
687           $this->is_modified= TRUE;
688         }
689         $this->goFonDeliveryMode= $tmp;
690       }
692       /* Save forwarding numbers and timeouts */
693       if (chkacl ($this->acl, "goFonForwarder") == ""){
694         foreach ($this->forwarders as $nr => $fw){
695           $tmp= $_POST["fwn$nr"].";".$_POST["fwt$nr"];
696           if ($this->forwarders[$nr] != $tmp){
697             $this->is_modified= TRUE;
698           }
699           $this->forwarders[$nr]= $tmp;
700         }
701       }
703       /* Every macro in the select box are available */
704       if((isset($_POST['macro']))){
705         $this->macrostillavailable=true;
706       }
708       if(is_array($this->phoneNumbers)){
709         foreach($this->phoneNumbers as $telenumms) {
710           $nummsinorder[]=$telenumms; 
711         }
712       }else{
713         $nummsinorder=array("");
714       }
716       /* get all Postvars */
717       if(isset($this->macroarray[$this->macro])){ 
718         foreach($this->macroarray[$this->macro] as $key => $paras){
719           if(isset($_POST[$paras['var']])){
720 //            $par = $this->macroarray[$this->macro][$key];
721 //            $string = "";
722 //            if(preg_match("/.*%telephoneNumber_.*/",$par['default'])){
723 //              $string = $par['default'];
724 //              foreach($nummsinorder as $nummsinorderkey=> $nummsinorderval){
725 //                $string = (str_replace("%telephoneNumber_".($nummsinorderkey+1),$nummsinorderval,$string));
726 //              }
727 //            }
728             
729 //            if(preg_match("/.*%uid.*/",$par['default'])){
730 //              if(empty($string)) $string = $par['default'];
731 //              $string = str_replace("%uid",$this->uid,$string);
732 //            }    
733   
734 //            if(!empty($string)){  
735 //              $this->macroarray[$this->macro][$key]['choosen'] = $string; 
736 //            }else{
737               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
738 //            }
739           }
741           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
742              We need this code below to read and save checkboxes correct
743            */
744   
745           if(isset($_POST['post_success'])){
746             if($this->macroarray[$this->macro][$key]['type']=="bool"){
747               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
748                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
749               }else{
750                 $this->macroarray[$this->macro][$key]['choosen']=false;
751               }
752             }
753           }
754         }
755       }
756     }
757   }
759   function check()
760   {
761     /* Reset message array */
762     $message= array();
764     if(!$this->generate_mysql_entension_entries()){
765       $message[] = $this->generate_error;
766     }
768     /* We need at least one phone number */
769     if (count($this->phoneNumbers) == 0){
770       $message[]= sprintf(_("You need to specify at least one phone number!"));
771     }
773     if(($this->goFonPIN)==""){
774       $message[]= sprintf(_("You need to specify a Phone PIN."));
775     }else{
776       if(strcmp ((int)($this->goFonPIN),($this->goFonPIN))){
777         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
778       }elseif(strlen($this->goFonPIN) < 4){
779         $message[] = sprintf(_("The given PIN is too short"));
780       }
782     }
783     /* Check timestamps and phonenumbers */
784     foreach ($this->forwarders as $fw){
786       /* Skip empty values */
787       if ($fw == ";"){
788         continue;
789       }         
791       /* Check */
792       list($number, $timeout)= split(";", $fw);
793       if (!is_phone_nr($number)){
794         $message[]= sprintf(_("The number '%s' is no valid phone number!"), $number);
795       }
796       if (!is_id($timeout)){
797         $message[]= sprintf(_("The timeout '%s' contains invalid characters!"), $timeout);
798       }
799     }
801     /* check for ! in any parameter setting*/
802     if(isset($this->macroarray[$this->macro])){
803       foreach($this->macroarray[$this->macro] as $val){
804         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
805           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
806         }
807       }
808     }
809     return ($message);
810   }
814   function save()
815   {
816     plugin::save();
818     /* Save arrays */
819     $this->attrs['telephoneNumber']= array();
820     foreach ($this->phoneNumbers as $number){
821       $this->attrs['telephoneNumber'][]= $number;
822     }
823     $this->attrs['goFonForwarding']= array();
824     foreach ($this->forwarders as $index => $number){
825       $this->attrs['goFonForwarding'][]= "$index;$number";
826     }
828     /* Save settings, or remove goFonMacro attribute*/
829     if($this->macro!="none"){    
830       $this->attrs['goFonMacro']=$this->macro;
831       if(isset($this->macroarray[$this->macro])){
832         foreach($this->macroarray[$this->macro] as $paras)  {
833           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
834         }
835       }
836     }else{
837       $this->attrs['goFonMacro']=array();
838     }
839     unset($this->attrs['macro'])  ;
841     $this->generate_mysql_entension_entries(true);
843     if($this->attrs['goFonMacro']==""){
844       $this->attrs['goFonMacro']=array();
845     }
846     /* Write back to ldap */
847     $ldap= $this->config->get_ldap_link();
848     $ldap->cd($this->dn);
849     $ldap->modify($this->attrs);
850     show_ldap_error($ldap->get_error());
852     /* Optionally execute a command after we're done */
853     
854     if ($this->initially_was_account == $this->is_account){
855       if ($this->is_modified){
856         $this->handle_post_events("modify");
857       }
858     } else {
859       $this->handle_post_events("add");
860     }
862   }
865   function insert_after($entry, $nr, $list)
866   {
867     /* Is the entry free? No? Make it free... */
868     if (isset($list[$nr])) {
869       $dest= array();
870       $newidx= 0;
872       foreach ($list as $idx => $contents){
873         $dest[$newidx++]= $contents;
874         if ($idx == $nr){
875           $dest[$newidx++]= $entry;
876         }
877       }
878     } else {
879       $dest= $list;
880       $dest[$nr]= $entry;
881     }
883     return ($dest);
884   }
887   function adapt_from_template($dn)
888   {
889     plugin::adapt_from_template($dn);
891     /* Assemble phone numbers */
892     if (isset($this->attrs['telephoneNumber'])){
893       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
894         $number= $this->attrs['telephoneNumber'][$i];
895         $this->phoneNumbers[$number]= $number;
896       }
897     }
899     /* Assemble forwarders */
900     if (isset($this->attrs['goFonForwarding'])){
901       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
902         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
903         $this->forwarders[$num]= "$v1;$v2";
904       }
905     } else {
906       $this->forwarders= array("");
907     }
908   }
911   function remove_from_parent()
912   {
913     // Get Configuration for Mysql database Server
914     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
915     $s_parameter  ="";
917     // Connect to DB server
918     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
920     // Check if we are  connected correctly
921     if(!$r_con){
922       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
923           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
924       gosa_log(mysql_error());
925       return false;
926     }
928     // Select database for Extensions
929     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
931     // Test if we have the database selected correctly
932     if(!$db){
933       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
934       gosa_log(mysql_error());
935       return false;
936     }
938     $SQL="";
940     /* If deletion starts from userslist, cn uid are not set */
941     $this->uid = $this->parent->by_object['user']->uid;
942     $this->cn  = $this->parent->by_object['user']->cn;
944     $first_num = false;
945     // Delete old entries
946     foreach($this->a_old_telenums as $s_telenums){
947       if(!$first_num){
948         $first_num = $s_telenums;
949       }
950       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
951     }
953     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
954     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
955     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
958     foreach($SQL as $query){
959       if(!mysql_query($query,$r_con)){
960         print_red(_("Stop".mysql_error()));
961         return false;
962       }
963     }
967     /* unset macro attr, it will cause an error */
968     $tmp = array_flip($this->attributes);
969     unset($tmp['macro']);
970     $this->attributes=array_flip($tmp);
972     /* Cancel if there's nothing to do here */
973     if (!$this->initially_was_account){
974       return;
975     }
977     plugin::remove_from_parent();
979     /* Just keep one phone number */
980     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
981       $this->attrs['telephoneNumber']= $this->telephoneNumber[0];
982     } else {
983       $this->attrs['telephoneNumber']= array();
984     }
986     $ldap= $this->config->get_ldap_link();
987     $ldap->cd($this->config->current['BASE']);
988     $ldap->search("(objectClass=goFonQueue)", array("member"));
989     while($attr = $ldap->fetch()){
990       if(in_array($this->dn,$attr['member'])){
991         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
992         unset($new->by_object['ogroup']->memberList[$this->dn]);
993         unset($new->by_object['ogroup']->member[$this->dn]);
994         $new->save();
995         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
996       }
997     }
998     $ldap->cd($this->dn);
999     $ldap->modify($this->attrs);
1000     show_ldap_error($ldap->get_error());
1002     /* Optionally execute a command after we're done */
1003     $this->handle_post_events('remove');
1004   }
1008   /* This function checks if the given phonenumbers are available or already in use*/
1009   function is_number_used()
1010   {
1011     $ldap= $this->config->get_ldap_link();
1012     $ldap->cd($this->config->current['BASE']);
1013     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue))", array("telephoneNumber","cn","uid"));
1014     while($attrs = $ldap->fetch()) {
1015       unset($attrs['telephoneNumber']['count']);
1016       foreach($attrs['telephoneNumber'] as $tele){
1017         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1018         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1019         $numbers[$tele]=$attrs;
1020       }
1021     }
1023     foreach($this->phoneNumbers as $num){
1024       if(!isset($this->cn)) $this->cn = "";
1026       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1027         if(isset($numbers[$num]['uid'][0])){
1028           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1029         }else{
1030           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1031         }
1032       }
1033     }
1034   }
1039 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1040 ?>