Code

4dacfe3ca8f44c74a2567d6d8fe071c8317a6e89
[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 //            $string = preg_replace("/%telephoneNumber/",$this->attrs['telephoneNumber'][0],$string);
138 //            $string = preg_replace("/%cn/",$this->attrs['cn'][0],$string);
139             $this->macroarray[$attrs['dn']][$id]['choosen']= $string; 
141             $this->macroarray[$attrs['dn']][$id]['id']     = $id;
142             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
143             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
144             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
145             if($data[2] == "bool"){
146               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
147             }
148           }//foreach
149         }//is_array
150       }//visible = 1
151     }//while
153     /* Go through already saved values, for a parameter */
154     $tmp = split("!",$this->goFonMacro);
156     /* it is possible that nothing has been saved yet */
157     if(is_array($tmp)){
159       /* First value is the macroname */
160       $this->macro = $tmp[0];
162       /* Macroname saved, delete that index */
163       unset($tmp[0]);
165       /* Check if makro has been removed */
166       if(!isset($this->macroarray[$this->macro])){
167         $this->macrostillavailable = false;
168       }else{
169         $this->macrostillavailable = true;
170       }
172       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
173       foreach($tmp as $var){
175         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
176         $varar = split("#",$var);
178         /* Only insert if the parameter still exists */
179         if(isset($this->macroarray[$this->macro][$varar[0]])){
180           /* Assign value */
181           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
182         }
183       }
184     }
187     /* Eventually colorize phones */
188     $ldap->cd($this->config->current['BASE']);
189     foreach ($this->hardware_list as $cn => $desc){
190       $ldap->search("(goFonHardware=$cn)", array('cn'));
191       if ($ldap->count() > 0){
192         $ldap->fetch();
193         if ($ldap->getDN() != $this->dn){
194           $this->used_hardware[$cn]= $ldap->getDN();
195         }
196       }
197     }
198     $this->hardware_list["automatic"]= _("automatic");
199     ksort($this->hardware_list);
200     $this->a_old_telenums = $this->phoneNumbers;
201   }
206   // Generate MySQL Syntax
207   function generate_mysql_entension_entries($save = false){
209     // Get Configuration for Mysql database Server
210     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
211     $s_parameter  ="";
213     // Connect to DB server
214     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
216     // Check if we are  connected correctly
217     if(!$r_con){
218       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
219           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
220       gosa_log(mysql_error());
221       return false;
222     }
224     // Select database for Extensions
225     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
227     // Test if we have the database selected correctly
228     if(!$db){
229       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
230       gosa_log(mysql_error());
231       return false;
232     }
234     // Get phonehardware to setup sip entry
235     $ldap= $this->config->get_ldap_link();
236     $res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
237     $attrs = $ldap->fetch();
239     // Attribute GoFonDefaultIP set ?
240     if(((isset($attrs['goFonDefaultIP'][0]))&&($attrs['goFonDefaultIP'][0] != "dynamic"))){
241       $ip = $attrs['goFonDefaultIP'][0];
242       $host = $ip;
243     }else{
244       $ip = NULL;
245       $host = "dynamic";
246     }
248     // Attribute GoFonQualify set ?
249     if(!isset($attrs['goFonQualify'])){
250       $qualify = NULL;
251     }else{
252       $qualify = $attrs['goFonQualify'][0];
253     }
255     // Attribute GoFonPIN set ?
256     if(!isset($this->goFonPIN)){
257       $pin = NULL;
258     }else{
259       $pin = $this->goFonPIN;
260     }
262     // Attribute GoFonType set ?
263     if(!isset($attrs['goFonType'])){
264       $type = NULL;
265     }else{
266       $type = $attrs['goFonType'][0];
267     }
269     // generate SIP entry
270     $sip_data_array['id']           = "";
271     $sip_data_array['name']         = $this->uid;
272     $sip_data_array['accountcode']  = NULL;          
273     $sip_data_array['amaflags']     = NULL;
274     $sip_data_array['callgroup']    = NULL;
275     $sip_data_array['callerid']     = "";
276     $sip_data_array['canreinvite']  = "yes";
278     // Must be default and the name of an entry that already exists
279     $sip_data_array['context']      = "default";
280     $sip_data_array['defaultip']    = NULL;
282     if(isset($attrs['goFonDmtfMode'][0])){
283       $sip_data_array['dtmfmode']     = $attrs['goFonDmtfMode'][0];
284     }else{
285       $sip_data_array['dtmfmode']     ="rfc2833";
286     }
287     $sip_data_array['fromuser']     = NULL;
288     $sip_data_array['fromdomain']   = NULL;
289     $sip_data_array['host']         = $host;
290     $sip_data_array['insecure']     = NULL;
291     $sip_data_array['language']     = NULL;
292     $sip_data_array['mailbox']      = "asterisk";
293     $sip_data_array['md5secret']    = NULL;
294     $sip_data_array['nat']          = "no";
295     $sip_data_array['permit']       = NULL;
296     $sip_data_array['deny']         = NULL;
297     $sip_data_array['mask']         = NULL;
298     $sip_data_array['pickupgroup']  = NULL;
299     $sip_data_array['port']         = NULL;
300     $sip_data_array['qualify']      = $qualify;
301     $sip_data_array['restrictcid']  = "n";
302     $sip_data_array['rtptimeout']   = NULL;
303     $sip_data_array['rtpholdtimeout']=NULL;
304     $sip_data_array['secret']       = $pin;
305     $sip_data_array['type']         = $type ;
306     $sip_data_array['username']     = $this->uid;
307     $sip_data_array['disallow']     = NULL;
308     $sip_data_array['allow']        = NULL;
309     $sip_data_array['musiconhold']  = NULL;
310     $sip_data_array['regseconds']   = NULL;
311     $sip_data_array['ipaddr']       = $ip;
312     $sip_data_array['regexten']     = NULL;
313     $sip_data_array['cancallforward']=NULL;
315     // Get selected Macro Parameter and create parameter entry 
316     if(isset($this->macroarray[$this->macro])){
317       foreach($this->macroarray[$this->macro] as $key => $val ){
318         $s_parameter .= $val['choosen']."|";
319       }
320       $s_parameter = preg_replace("/\|$/","",$s_parameter);
321     }
329     // $SQL contains all queries
330     $SQL = array();
331     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
332     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
334     // Create new SIP entry ...
335     $sip_entry = $sip_data_array;
337     reset($this->phoneNumbers);
339     $key = key($this->phoneNumbers);
340     $sip_entry['callerid']  =$this->phoneNumbers[$key];
341     $sip_entry['mailbox']   =$this->phoneNumbers[$key];
343     if($this->is_number_used()){
344       $this->generate_error = $this->is_number_used(); 
345       return false;
346     }
348     if($save == true){
349       if(isset($this->parent->by_object['mailAccount']->mail)){
350         $mail = $this->parent->by_object['mailAccount']->mail;
351       }else{
352         $mail = "";
353       }
356       $SQL[]= "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$this->phoneNumbers[$key]."';"; 
357       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." 
358         (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`) 
359         VALUES 
360         ('".$this->phoneNumbers[$key]."','default','".$this->phoneNumbers[$key]."','".$this->goFonPIN."','".$this->sn."','".$mail."','');";
362       // Generate Strings with keys and values 
363       $values = "";
364       $keys   = "";
365       foreach($sip_entry as $key=>$val){
366         if($val == NULL) continue;
367         $values.="'".$val."',";
368         $keys  .="`".$key."`,";
369       }
370       // Remove last ,
371       $values =  preg_replace("/,$/","",$values);
372       $keys   =  preg_replace("/,$/","",$keys);
374       // Append SIP Entry 
375       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$keys.") VALUES (".$values.");";
377       // Delete old entries
378       foreach($this->a_old_telenums as $s_telenums){
379         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
380       }
382       $i_is_accounted=false;
384       // Entension entries  Hint / Dial / Goto
385       foreach($this->phoneNumbers as $s_telenums){
386         // Entry  to call by name
387         $s_entry_name['context']  = 'GOsa';
388         $s_entry_name['exten']    = $this->uid;
389         $s_entry_name['priority'] = 1;
390         $s_entry_name['app']      = 'Goto';
391         $s_entry_name['appdata']  = $s_telenums."|1";
393         // hint
394         $s_entry_hint['context']  = 'GOsa';
395         $s_entry_hint['exten']    = $s_telenums;
396         $s_entry_hint['app']      = 'hint';
397         $s_entry_hint['appdata']  = 'SIP/'.$this->uid;
399         // If no macro is selected use Dial
400         if($this->macro!="none"){ 
401           $macroname = preg_replace("/,.*$/","",$this->macro);        
402           $macroname = preg_replace("/^.*=/","",$macroname);        
403           $s_app = "Macro";$macroname;
404           $s_par = $macroname."|".$s_parameter; 
405         }else{
406           $s_app = "Dial";
407           $s_par = 'SIP/'.$this->uid;
408         }
410         // Entry  to call by number
411         $s_entry_phone['context']  = 'GOsa';
412         $s_entry_phone['exten']    = $s_telenums;
413         $s_entry_phone['priority'] = 1;
414         $s_entry_phone['app']      = $s_app;
415         $s_entry_phone['appdata']  = $s_par;
417         // append name entry only once
418         if(!$i_is_accounted){ 
419           $i_is_accounted = true;
420           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone,"name"=>$s_entry_name); 
421         }else{
422           $entries[]=array("hint"=>$s_entry_hint,"phone"=>$s_entry_phone);
423         }
424       }
426       // Append all these Entries 
427       foreach($entries as $num => $val){
428         foreach($val as $entr){
429           $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
430           foreach($entr as $key2 => $val2){
431             $SQL_syn.= "`".$key2."`,";
432           }
433           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
434           $SQL_syn .= ") VALUES ("; 
435           foreach($entr as $key2 => $val2){
436             $SQL_syn .= "'".$val2."',";
437           }
438           $SQL_syn = preg_replace("/,$/","",$SQL_syn);
439           $SQL_syn .=");\n";
440           $SQL[] =$SQL_syn;
441           $SQL_syn ="";
442         }
443       }
445       // Perform queries ...
446       foreach($SQL as $query){
447         if(!mysql_query($query,$r_con)){
448           print_red(_("Error while performing query ".mysql_error()));
449           return false;
450         }
451       }
452     }
453     return true;
454   }
469   function execute()
470   {
471     /* force postmodify event, to restart phones */
472     
473     $this->parent->by_object['user']->is_modified=TRUE;
474     $this->is_modified=TRUE; 
476     /* Do we need to flip is_account state? */
477     if (isset($_POST['modify_state'])){
478       $this->is_account= !$this->is_account;
479     }
481     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
482     if(empty($this->macro)){
483       $this->macro ="none";
484     }
486     /* tell user that the pluging selected is no longer available*/
487     if((!$this->macrostillavailable)&&($this->macro!="none")){
488       print_red(_("The macro you selected in the past, is no longer available for you, please choose another one."));
489     }
491     /* Prepare templating */
492     $smarty= get_smarty();
494     /* Assing macroselectbox values  */
495     $smarty->assign("macros",$this->macros);   
496     $smarty->assign("macro", $this->macro);   
498     /* Create parameter table, skip if no parameters given */
499     if(!isset($this->macroarray[$this->macro])){
500       $macrotab="";
501     }else{
503       $macrotab ="<table summary=\""._("Parameter")."\">";
504       /* for every single parameter-> display textfile,combo, or true false switch*/
507       foreach($this->macroarray[$this->macro] as $paras){
509         /* get al vars */
510         $var        = $paras['var'];           
511         $name       = $paras['name'];           
512         $default    = $paras['default'];
513         $type       = $paras['type'];
514         $choosen    = $paras['choosen'] ; 
515         $str        = $default;
517         /* in case of a combo box display a combobox with selected attr */
518         $macrotab.= "<tr>";
519         switch ($type){
521           case "combo":
522             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
523           foreach(split(":",$default) as $choice){
524             if($choosen==$choice){
525               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
526             }else{
527               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
528             }
529           }
530           $str.="</select>";
531           $macrotab.= "<td>$name</td><td>$str";
532           break;
534           case "bool":
535             if(!$choosen){
536               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
537             }else{
538               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
539             }
540           $macrotab.= "<td colspan='2'>$str&nbsp;$name";
541           break;
543           case "string":
544             $choosen = preg_replace("/%uid/",$this->attrs['uid'][0],$choosen);
545             foreach($this->phoneNumbers as  $phone){
546               $tmp_phone[] = $phone;
547             }            
548   
549             $choosen = preg_replace("/%telephoneNumber/",$tmp_phone[0],$choosen);
550             $choosen = preg_replace("/%cn/",$this->attrs['cn'][0],$choosen);
552             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro").">";
553           $macrotab.= "<td>$name</td><td>$str";
554           break;
556         }
557         $macrotab.= "</td></tr>";
559       }
560       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
561     }//is_array()
563     /* Give smarty the table */
564     $smarty->assign("macrotab",$macrotab);
566     /* Do we represent a valid account? */
567     if (!$this->is_account && $this->parent == NULL){
568       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
569         _("This account has no phone extensions.")."</b>";
570       $display.= back_to_main();
571       return($display);
572     }
574     $display= "";
576     /* Show tab dialog headers */
577     if ($this->parent != NULL){
578       if ($this->is_account){
579         $display= $this->show_header(_("Remove phone account"),
580             _("This account has phone features enabled. You can disable them by clicking below."));
581       } else {
582         $display= $this->show_header(_("Create phone account"),
583             _("This account has phone features disabled. You can enable them by clicking below."));
584         return ($display);
585       }
586     }
588     /* Add phone number */
589     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
590       if (is_phone_nr($_POST['phonenumber'])){
591         $number= $_POST["phonenumber"];
592         $this->phoneNumbers[$number]= $number;
593         $this->is_modified= TRUE;
594       } else {
595         print_red(_("Please enter a valid phone number!"));
596       }
597     }
599     /* Remove phone number */
600     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
601       foreach ($_POST['phonenumber_list'] as $number){
602         unset($this->phoneNumbers[$number]);
603         $this->is_modified= TRUE;
604       }
605     }
607     /* Check for forwarding action */
608     foreach ($this->forwarders as $nr => $fw){
610       /* Buttons pressed? */
611       if (isset($_POST["add_fw$nr"])){
612         $this->forwarders= $this->insert_after("", $nr, $this->forwarders);
613       }
614       if (isset($_POST["remove_fw$nr"])){
615         unset($this->forwarders[$nr]);
616       }
617     }
619     /* Transfer ACL's */
620     foreach($this->attributes as $val){
621       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
622       $smarty->assign($val,$this->$val);
623     }
625     /* Fill arrays */
626     $smarty->assign ("goFonHardware", $this->goFonHardware);
627     if (!count($this->phoneNumbers)){
628       $smarty->assign ("phoneNumbers", array(""));
629     } else {
630       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
631     }
632     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
633       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
634     foreach ($this->hardware_list as $cn => $description){
635       if ($cn == $this->goFonHardware){
636         $selected= "selected";
637       } else {
638         $selected= "";
639       }
640       if (isset($this->used_hardware[$cn])){
641         $color= "style=\"color:#A0A0A0\"";
642       } else {
643         $color= "";
644       }
645       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
646     }
647     $hl.= "</select>\n";
648     $smarty->assign ("hardware_list", $hl);
650     /* Generate forwarder view */
651     $forwarder_list="";
652     $acl= chkacl($this->acl, "goFonForwaring");
653     foreach ($this->forwarders as $nr => $fw){
654       if ($fw == ""){
655         $number= ""; $timeout= "";
656       } else {
657         list($number, $timeout)= split(";", $fw);
658       }
659       $forwarder_list.= "<tr><td>";
660       $forwarder_list.= "<input name=\"fwn$nr\" size=25 align=\"middle\" maxlength=60 value=\"$number\" $acl>";
661       $forwarder_list.= "</td><td>";
662       $forwarder_list.= "<input name=\"fwt$nr\" size=5 align=\"middle\" maxlength=5 value=\"$timeout\" $acl>";
663       $forwarder_list.= "</td><td>";
664       $forwarder_list.= "<input type=\"submit\" value=\""._("Add")."\" name=\"add_fw$nr\" $acl>";
665       if (count($this->forwarders) > 1){
666         $forwarder_list.= "<input type=\"submit\" value=\""._("Remove")."\" name=\"remove_fw$nr\" $acl>";
667       }
668       $forwarder_list.= "</td></tr>";
669     }
670     $smarty->assign("forwarder_list", $forwarder_list);
672     /* Show main page */
673     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
674     return($display);
675   }
678   function save_object()
679   {
680     if (isset($_POST["phoneTab"])){
681       plugin::save_object();
683       /* Save checkbox */
684       if (isset($_POST['fon_to_mail'])){
685         $tmp= "[M]";
686       } else {
687         $tmp= "[]";
688       }
689       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
690         if ($this->goFonDeliveryMode != $tmp){
691           $this->is_modified= TRUE;
692         }
693         $this->goFonDeliveryMode= $tmp;
694       }
696       /* Save forwarding numbers and timeouts */
697       if (chkacl ($this->acl, "goFonForwarder") == ""){
698         foreach ($this->forwarders as $nr => $fw){
699           $tmp= $_POST["fwn$nr"].";".$_POST["fwt$nr"];
700           if ($this->forwarders[$nr] != $tmp){
701             $this->is_modified= TRUE;
702           }
703           $this->forwarders[$nr]= $tmp;
704         }
705       }
707       /* Every macro in the select box are available */
708       if((isset($_POST['macro']))){
709         $this->macrostillavailable=true;
710       }
712       if(is_array($this->phoneNumbers)){
713         foreach($this->phoneNumbers as $telenumms) {
714           $nummsinorder[]=$telenumms; 
715         }
716       }else{
717         $nummsinorder=array("");
718       }
720       /* get all Postvars */
721       if(isset($this->macroarray[$this->macro])){ 
722         foreach($this->macroarray[$this->macro] as $key => $paras){
723           if(isset($_POST[$paras['var']])){
724             $par = $this->macroarray[$this->macro][$key];
725             $string = "";
726             if(preg_match("/.*%telephoneNumber_.*/",$par['default'])){
727               $string = $par['default'];
728               foreach($nummsinorder as $nummsinorderkey=> $nummsinorderval){
729                 $string = (str_replace("%telephoneNumber_".($nummsinorderkey+1),$nummsinorderval,$string));
730               }
731             }
732             
733             if(preg_match("/.*%uid.*/",$par['default'])){
734               if(empty($string)) $string = $par['default'];
735               $string = str_replace("%uid",$this->uid,$string);
736             }    
737   
738             if(!empty($string)){  
739               $this->macroarray[$this->macro][$key]['choosen'] = $string; 
740             }else{
741               $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
742             }
743           }
745           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
746              We need this code below to read and save checkboxes correct
747            */
748   
749           if(isset($_POST['post_success'])){
750             if($this->macroarray[$this->macro][$key]['type']=="bool"){
751               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
752                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
753               }else{
754                 $this->macroarray[$this->macro][$key]['choosen']=false;
755               }
756             }
757           }
758         }
759       }
760     }
761   }
763   function check()
764   {
765     /* Reset message array */
766     $message= array();
768     if(!$this->generate_mysql_entension_entries()){
769       $message[] = $this->generate_error;
770     }
772     /* We need at least one phone number */
773     if (count($this->phoneNumbers) == 0){
774       $message[]= sprintf(_("You need to specify at least one phone number!"));
775     }
777     if(($this->goFonPIN)==""){
778       $message[]= sprintf(_("You need to specify a Phone PIN."));
779     }else{
780       if(strcmp ((int)($this->goFonPIN),($this->goFonPIN))){
781         $message[] = sprintf(_("The given PIN is not valid, only numbers are allowed for this type."));
782       }elseif(strlen($this->goFonPIN) < 4){
783         $message[] = sprintf(_("The given PIN is too short"));
784       }
786     }
787     /* Check timestamps and phonenumbers */
788     foreach ($this->forwarders as $fw){
790       /* Skip empty values */
791       if ($fw == ";"){
792         continue;
793       }         
795       /* Check */
796       list($number, $timeout)= split(";", $fw);
797       if (!is_phone_nr($number)){
798         $message[]= sprintf(_("The number '%s' is no valid phone number!"), $number);
799       }
800       if (!is_id($timeout)){
801         $message[]= sprintf(_("The timeout '%s' contains invalid characters!"), $timeout);
802       }
803     }
805     /* check for ! in any parameter setting*/
806     if(isset($this->macroarray[$this->macro])){
807       foreach($this->macroarray[$this->macro] as $val){
808         if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
809           $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
810         }
811       }
812     }
813     return ($message);
814   }
818   function save()
819   {
820     plugin::save();
822     /* Save arrays */
823     $this->attrs['telephoneNumber']= array();
824     foreach ($this->phoneNumbers as $number){
825       $this->attrs['telephoneNumber'][]= $number;
826     }
827     $this->attrs['goFonForwarding']= array();
828     foreach ($this->forwarders as $index => $number){
829       $this->attrs['goFonForwarding'][]= "$index;$number";
830     }
832     /* Save settings, or remove goFonMacro attribute*/
833     if($this->macro!="none"){    
834       $this->attrs['goFonMacro']=$this->macro;
835       if(isset($this->macroarray[$this->macro])){
836         foreach($this->macroarray[$this->macro] as $paras)  {
837           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
838         }
839       }
840     }else{
841       $this->attrs['goFonMacro']=array();
842     }
843     unset($this->attrs['macro'])  ;
845     $this->generate_mysql_entension_entries(true);
847     if($this->attrs['goFonMacro']==""){
848       $this->attrs['goFonMacro']=array();
849     }
850     /* Write back to ldap */
851     $ldap= $this->config->get_ldap_link();
852     $ldap->cd($this->dn);
853     $ldap->modify($this->attrs);
854     show_ldap_error($ldap->get_error());
856     /* Optionally execute a command after we're done */
857     
858     if ($this->initially_was_account == $this->is_account){
859       if ($this->is_modified){
860         $this->handle_post_events("modify");
861       }
862     } else {
863       $this->handle_post_events("add");
864     }
866   }
869   function insert_after($entry, $nr, $list)
870   {
871     /* Is the entry free? No? Make it free... */
872     if (isset($list[$nr])) {
873       $dest= array();
874       $newidx= 0;
876       foreach ($list as $idx => $contents){
877         $dest[$newidx++]= $contents;
878         if ($idx == $nr){
879           $dest[$newidx++]= $entry;
880         }
881       }
882     } else {
883       $dest= $list;
884       $dest[$nr]= $entry;
885     }
887     return ($dest);
888   }
891   function adapt_from_template($dn)
892   {
893     plugin::adapt_from_template($dn);
895     /* Assemble phone numbers */
896     if (isset($this->attrs['telephoneNumber'])){
897       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
898         $number= $this->attrs['telephoneNumber'][$i];
899         $this->phoneNumbers[$number]= $number;
900       }
901     }
903     /* Assemble forwarders */
904     if (isset($this->attrs['goFonForwarding'])){
905       for ($i= 0; $i<$this->attrs['goFonForwarding']['count']; $i++){
906         list($num, $v1, $v2) =split(';', $this->attrs['goFonForwarding'][$i]);
907         $this->forwarders[$num]= "$v1;$v2";
908       }
909     } else {
910       $this->forwarders= array("");
911     }
912   }
915   function remove_from_parent()
916   {
917     // Get Configuration for Mysql database Server
918     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
919     $s_parameter  ="";
921     // Connect to DB server
922     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
924     // Check if we are  connected correctly
925     if(!$r_con){
926       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
927           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
928       gosa_log(mysql_error());
929       return false;
930     }
932     // Select database for Extensions
933     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
935     // Test if we have the database selected correctly
936     if(!$db){
937       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
938       gosa_log(mysql_error());
939       return false;
940     }
942     $SQL="";
944     
946     $first_num = false;
947     // Delete old entries
948     foreach($this->a_old_telenums as $s_telenums){
949       if(!$first_num){
950         $first_num = $s_telenums;
951       }
952       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
953     }
955     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
956     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
957     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
960     foreach($SQL as $query){
961       if(!mysql_query($query,$r_con)){
962         print_red(_("Stop".mysql_error()));
963         return false;
964       }
965     }
969     /* unset macro attr, it will cause an error */
970     $tmp = array_flip($this->attributes);
971     unset($tmp['macro']);
972     $this->attributes=array_flip($tmp);
974     /* Cancel if there's nothing to do here */
975     if (!$this->initially_was_account){
976       return;
977     }
979     plugin::remove_from_parent();
981     /* Just keep one phone number */
982     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
983       $this->attrs['telephoneNumber']= $this->telephoneNumber[0];
984     } else {
985       $this->attrs['telephoneNumber']= array();
986     }
988     $ldap= $this->config->get_ldap_link();
989     $ldap->cd($this->config->current['BASE']);
990     $ldap->search("(objectClass=goFonQueue)", array("member"));
991     while($attr = $ldap->fetch()){
992       if(in_array($this->dn,$attr['member'])){
993         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
994         unset($new->by_object['ogroup']->memberList[$this->dn]);
995         unset($new->by_object['ogroup']->member[$this->dn]);
996         $new->save();
997         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
998       }
999     }
1000     $ldap->cd($this->dn);
1001     $ldap->modify($this->attrs);
1002     show_ldap_error($ldap->get_error());
1004     /* Optionally execute a command after we're done */
1005     $this->handle_post_events('remove');
1006   }
1010   /* This function checks if the given phonenumbers are available or already in use*/
1011   function is_number_used()
1012   {
1013     $ldap= $this->config->get_ldap_link();
1014     $ldap->cd($this->config->current['BASE']);
1015     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue))", array("telephoneNumber","cn","uid"));
1016     while($attrs = $ldap->fetch()) {
1017       unset($attrs['telephoneNumber']['count']);
1018       foreach($attrs['telephoneNumber'] as $tele){
1019         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1020         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1021         $numbers[$tele]=$attrs;
1022       }
1023     }
1025     foreach($this->phoneNumbers as $num){
1026       if(!isset($this->cn)) $this->cn = "";
1028       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1029         if(isset($numbers[$num]['uid'][0])){
1030           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1031         }else{
1032           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1033         }
1034       }
1035     }
1036   }
1041 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1042 ?>