Code

814d890268a70951b60b7566e3ba5d17e02c54a9
[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 $goFonVoicemailPIN      = "";
16   var $goFonDeliveryMode      = "";
17   var $phoneNumbers           = array();
18   var $mail                   = "";
19   var $hardware_list          = array();
20   var $used_hardware          = array();
21   var $goFonMacro             = "";
22   var $macro                  = 0;              // Selected Macro
23   var $macros                 = array();        // List of macros for smarty select box
24   var $macroarray             = array();        // All needed macro informations
25   var $macrostillavailable    = false;
26   var $generate_error         = "";
27   var $a_old_telenums         = array();
28   var $goFonPINVoice          = "";
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","uid","cn","mail",
37       "goFonHardware","goFonPIN","goFonVoicemailPIN","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     }
69     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
70     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
71     if(!$r_con){
72       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
73           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
74       gosa_log(mysql_error());
75       return false;
76     }
77     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
78     if(!$db){
79       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
80       gosa_log(mysql_error());
81       return false;
82     }
83  
84     $first = false; 
85     foreach($this->phoneNumbers as $key => $val){
86       if(!$first){
87         $first = $key;
88       }
89     }
91     /* Load hardware list */
92     $ldap= $this->config->get_ldap_link();
93     $ldap->cd($this->config->current['BASE']);
94     $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
95     while ($attrs= $ldap->fetch()){
96       $cn= $attrs['cn'][0];
97       if (isset($attrs['description'])){
98         $description= " - ".$attrs['description'][0];
99       } else {
100         $description= "";
101       }
102       $this->hardware_list[$cn]= "$cn$description";
104     }
106     /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
107     $ldap->search("(objectClass=goFonMacro)", array("*"));
109     /* Add none for no macro*/
110     $this->macros['none']=_("no macro");    
111     $this->macro ="none";
114     /* Fetch all Macros*/
115     while ($attrs= $ldap->fetch()){
117       /* Only visisble */
118       if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
120         /* unset Count, we don't need that here */
121         unset($attrs['displayName']['count']);
123         /* fill Selectfield variable with Macros */
124         if(isset($attrs['displayName'][0])){
125           $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
126         }else{
127           $this->macros[$attrs['dn']] = _("undefined");
128         }
130         /* Parse macro data, unset count for parameterarrays  */
131         unset($attrs['goFonMacroParameter']['count']);
133         /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
134         if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
136           foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
137             /* Split Data in readable values, by delimiter !  */
138             $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
140             /* Set all attrs */
141             $id = $data[0];
142             $this->macroarray[$attrs['dn']][$id]['var']    ="var".$id;
143             $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3]; 
144             $this->macroarray[$attrs['dn']][$id]['id']     =$id;
145             $this->macroarray[$attrs['dn']][$id]['name']   =$data[1];
146             $this->macroarray[$attrs['dn']][$id]['type']   =$data[2];
147             $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
148             if($data[2] == "bool"){
149               $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
150             }
151           }//foreach
152         }//is_array
153       }//visible = 1
154     }//while
156     /* Go through already saved values, for a parameter */
157     $tmp = split("!",$this->goFonMacro);
159     /* it is possible that nothing has been saved yet */
160     if(is_array($tmp)){
162       /* First value is the macroname */
163       $this->macro = $tmp[0];
165       /* Macroname saved, delete that index */
166       unset($tmp[0]);
168       /* Check if makro has been removed */
169       if(!isset($this->macroarray[$this->macro])){
170         $this->macrostillavailable = false;
171       }else{
172         $this->macrostillavailable = true;
173       }
175       /* for each parametervalues ( parameterID#value like 25#twentyfive) */
176       foreach($tmp as $var){
178         /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
179         $varar = split("#",$var);
181         /* Only insert if the parameter still exists */
182         if(isset($this->macroarray[$this->macro][$varar[0]])){
183           /* Assign value */
184           $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
185         }
186       }
187     }
190     /* Eventually colorize phones */
191     $ldap->cd($this->config->current['BASE']);
192     foreach ($this->hardware_list as $cn => $desc){
193       $ldap->search("(goFonHardware=$cn)", array('cn'));
194       if ($ldap->count() > 0){
195         $ldap->fetch();
196         if ($ldap->getDN() != $this->dn){
197           $this->used_hardware[$cn]= $ldap->getDN();
198         }
199       }
200     }
201     $this->hardware_list["automatic"]= _("automatic");
202     ksort($this->hardware_list);
203     $this->a_old_telenums = $this->phoneNumbers;
205     if($this->is_account){
206       $this->is_modified = true;
207     }
209   }
212   // Generate MySQL Syntax
213   function generate_mysql_entension_entries($save = false){
215     // Get Configuration for Mysql database Server
216     $a_SETUP        = $_SESSION['config']->data['SERVERS']['FON'];  // DB Configuration
217     $s_parameter    = "";                                           // Contains paramter for selected Macro 
218     $r_con          = false;                                        // DB connection
219     $r_db           = false;                                        // Selected DB
220     $r_res          = false;                                        // Result resource
221     $a_ldap_attrs   = array();                                      //  
223     $s_ip           = NULL;                   // Contains ip for Sip entry
224     $s_host         = NULL;                   // Contains host for Sip entry
225     $s_qualify      = NULL;                   // Qualify entry
226     $s_pin          = NULL;                   // Entry for secret
227     $s_type         = NULL;                   // Entry for phone type (friend , peer ..)
229     $sip_data_array = array();                // Contains complete sip entry, to generate SQL syntax
230     $i_old_key      = false;                  // Contains index for first old phonenumber, to delete old entries corectly
231     $i_new_key      = false;                  // Contains index for first new phonenumber, to generate new  entries corectly
233     $s_sip_values   = "";     // Contains string with all values for given attributes in SQL syntax
234     $s_sip_keys     = "";     // Contains all needed attributes to generate sip entry in DB
236     $s_sip_key      = "";     // Key for SIP entry index      
237     $s_sip_val      = "";     // Value for SIP entry index      
239     $b_first_deleted= false;  // Only delete first entry, 
240     $s_telenums     = "";     // for each value variable
242     $i_is_accounted =false;   // Ensure that extension entry, for name to number is only once in table
245     // Connect to DB server
246     $r_con =  @mysql_connect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
248     // Check if we are  connected correctly
249     if(!$r_con){
250       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
251           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
252       gosa_log(mysql_error());
253       return false;
254     }
256     // Select database for Extensions
257     $r_db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
259     // Test if we have the database selected correctly
260     if(!$r_db){
261       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
262       gosa_log(mysql_error());
263       return false;
264     }
266     // Get phonehardware to setup sip entry
267     $ldap         = $this->config->get_ldap_link();
268     $r_res        = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
269     $a_ldap_attrs = $ldap->fetch();
271     if($this->is_number_used()){
272       $this->generate_error = $this->is_number_used(); 
273       return false;
274     }
276     /* If Save == true, we should save something.
277      * Generate SQL, for drop of old entries
278      * Generate SQL, for insert new entries
279      */ 
280     if($save == true){
282       // Attribute GoFonDefaultIP set ?
283       if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
284         $s_ip       = $a_ldap_attrs['goFonDefaultIP'][0];
285         $s_host     = $s_ip;
286       }else{
287         $s_ip       = NULL;
288         $s_host     = "dynamic";
289       }
291       // Attribute GoFonQualify set ?
292       if(isset($a_ldap_attrs['goFonQualify'])){
293         $s_qualify = $a_ldap_attrs['goFonQualify'][0];
294       }
296       // Attribute GoFonPIN set ?
297       if(isset($this->goFonPIN)){
298         $s_pin      = $this->goFonPIN;
299       }
301       // Attribute GoFonType set ?
302       if(isset($a_ldap_attrs['goFonType'])){
303         $s_type = $a_ldap_attrs['goFonType'][0];
304       }
306       if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
307         $sip_data_array['dtmfmode']     = $a_ldap_attrs['goFonDmtfMode'][0];
308       }else{
309         $sip_data_array['dtmfmode']     ="rfc2833";
310       }
312       // generate SIP entry
313       $sip_data_array['id']           = "";
314       $sip_data_array['name']         = $this->uid;
315       $sip_data_array['accountcode']  = NULL;          
316       $sip_data_array['amaflags']     = NULL;
317       $sip_data_array['callgroup']    = NULL;
318       $sip_data_array['callerid']     = "";
319       $sip_data_array['canreinvite']  = "no";
320       $sip_data_array['context']      = "default";
321       $sip_data_array['defaultip']    = NULL;
322       $sip_data_array['fromuser']     = NULL;
323       $sip_data_array['fromdomain']   = NULL;
324       $sip_data_array['host']         = $s_host;
325       $sip_data_array['insecure']     = NULL;
326       $sip_data_array['language']     = NULL;
327       $sip_data_array['mailbox']      = "asterisk";
328       $sip_data_array['md5secret']    = NULL;
329       $sip_data_array['nat']          = "no";
330       $sip_data_array['permit']       = NULL;
331       $sip_data_array['deny']         = NULL;
332       $sip_data_array['mask']         = NULL;
333       $sip_data_array['pickupgroup']  = NULL;
334       $sip_data_array['port']         = NULL;
335       $sip_data_array['qualify']      = $s_qualify;
336       $sip_data_array['restrictcid']  = "n";
337       $sip_data_array['rtptimeout']   = NULL;
338       $sip_data_array['rtpholdtimeout']=NULL;
339       $sip_data_array['secret']       = $this->goFonPIN;
340       $sip_data_array['type']         = $s_type ;
341       $sip_data_array['username']     = $this->uid;
342       $sip_data_array['disallow']     = NULL;
343       $sip_data_array['allow']        = NULL;
344       $sip_data_array['musiconhold']  = NULL;
345       $sip_data_array['regseconds']   = NULL;
346       $sip_data_array['ipaddr']       = $s_ip;
347       $sip_data_array['regexten']     = NULL;
348       $sip_data_array['cancallforward']=NULL;
350       // Get selected Macro Parameter and create parameter entry 
351       if(isset($this->macroarray[$this->macro])){
352         foreach($this->macroarray[$this->macro] as $key => $val ){
353           $s_parameter .= $val['choosen']."|";
354         }
355         $s_parameter = preg_replace("/\|$/","",$s_parameter);
356       }
358       if($this->is_number_used()){
359         $this->generate_error = $this->is_number_used(); 
360         return false;
361       }
363       // Create new SIP entry ...
364       $sip_entry = $sip_data_array;
365       reset($this->phoneNumbers);
366       $i_new_key = key($this->phoneNumbers);
367       $sip_entry['callerid']  =$this->phoneNumbers[$i_new_key];
368       $sip_entry['mailbox']   =$this->phoneNumbers[$i_new_key];
370       if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
371         $s_mail = $this->parent->by_object['mailAccount']->mail;
372       }else{
373         $s_mail = "";
374       }
377       // $SQL contains all queries
378       $SQL   = array();
379       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
380       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
381       $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";"; 
383       // Generate Strings with keys and values 
384       foreach($sip_entry as $s_sip_key=>$s_sip_val){
385         if($s_sip_val == NULL) continue;
386         $s_sip_values.="'".$s_sip_val."',";
387         $s_sip_keys  .="`".$s_sip_key."`,";
388       }
389       // Remove last ,
390       $s_sip_values =  preg_replace("/,$/","",$s_sip_values);
391       $s_sip_keys   =  preg_replace("/,$/","",$s_sip_keys);
393       // Append SIP Entry 
394       $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
396       // Delete old entries
397       $b_first_deleted  =false;
398       foreach($this->a_old_telenums as $s_telenums){
399         $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
400         if(!$b_first_deleted){
401           $b_first_deleted=true;
402           $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
403         }
404       }
406       /* If deletion starts from userslist, cn uid are not set */
407       if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
408         $this->uid = $this->parent->by_object['user']->uid;
409       }
411       if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
412         $this->cn  = $this->parent->by_object['user']->cn;
413       }
415       if((!isset($this->cn))||(empty($this->cn))){
416         $CNname= $this->uid;
417       }else{
418         $CNname= $this->cn;
419       }
421       $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
422           VALUES   ('".$this->phoneNumbers[$i_new_key]."',
423                     'default',
424                     '".$this->phoneNumbers[$i_new_key]."',
425                     '".$this->goFonVoicemailPIN."',
426                     '".$CNname."',
427                     '".$s_mail."',
428                     '');";
429       $i_is_accounted=false;
430     
431       $i = 0; 
432   
433       // Entension entries  Hint / Dial / Goto
434       foreach($this->phoneNumbers as $s_telenums){
436         /* Mapping : Name TO Number*/
437         $EXT[$i]['context'] = 'GOsa';
438         $EXT[$i]['exten']   = $this->uid;
439         $EXT[$i]['priority']= 1;
440         $EXT[$i]['app']     = "Goto";
441         $EXT[$i]['appdata'] = $s_telenums."|1";
442         $i ++;  
443         /* Hint Entry */
444         $EXT[$i]['context'] = 'GOsa';
445         $EXT[$i]['exten']   = $s_telenums;
446         $EXT[$i]['priority']= "Hint";
447         $EXT[$i]['app']     = 'SIP/'.$this->uid;
448         $i ++;  
449         /* SetCID */
450         $EXT[$i]['context'] = 'GOsa';
451         $EXT[$i]['exten']   = $s_telenums;
452         $EXT[$i]['priority']= 1;
453         $EXT[$i]['app']     = "SetCIDName";
454         $EXT[$i]['appdata'] = $CNname;
455         $i ++;  
457         // If no macro is selected use Dial
458         if($this->macro!="none"){ 
459           $macroname = preg_replace("/,.*$/","",$this->macro);        
460           $macroname = preg_replace("/^.*=/","",$macroname);        
461           $s_app = "Macro";$macroname;
462           $s_par = $macroname."|".$s_parameter; 
463         }else{
464           $s_app = "Dial";
465           $s_par = 'SIP/'.$this->uid;
466         }
468         $EXT[$i]['context'] = 'GOsa';
469         $EXT[$i]['exten']   = $s_telenums;
470         $EXT[$i]['priority']= 2;
471         $EXT[$i]['app']     = $s_app;
472         $EXT[$i]['appdata'] = $s_par;
473         $i ++;
475       }
477       // Append all these Entries 
478       foreach($EXT as $entr){
479         $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
480         foreach($entr as $key2 => $val2){
481           $SQL_syn.= "`".$key2."`,";
482         }
483         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
484         $SQL_syn .= ") VALUES ("; 
485         foreach($entr as $key2 => $val2){
486           $SQL_syn .= "'".$val2."',";
487         }
488         $SQL_syn = preg_replace("/,$/","",$SQL_syn);
489         $SQL_syn .=");\n";
490         $SQL[] =$SQL_syn;
491         $SQL_syn ="";
492       }
494       // Perform queries ...
495       foreach($SQL as $query){
496         if(!@mysql_query($query,$r_con)){
497           print_red(_("Error while performing query ".mysql_error()));
498           return false;
499         }
500       }
501     }
502     return true;
503   }
506   function execute()
507   {
508     /* Do we represent a valid account? */
509     if (!$this->is_account && $this->parent == NULL){
510       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
511         _("This account has no phone extensions.")."</b>";
512       $display.= back_to_main();
513       return ($display);
514     }
516     /* Do we need to flip is_account state? */
517     if (isset($_POST['modify_state'])){
518       $this->is_account= !$this->is_account;
519     }
521     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
522     if(empty($this->macro)){
523       $this->macro ="none";
524     }
526     /* tell user that the pluging selected is no longer available*/
527     if((!$this->macrostillavailable)&&($this->macro!="none")){
528       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
529     }
531     /* Prepare templating */
532     $smarty= get_smarty();
534     /* Assing macroselectbox values  */
535     $smarty->assign("macros",$this->macros);   
536     $smarty->assign("macro", $this->macro);   
538     /* Create parameter table, skip if no parameters given */
539     if(!isset($this->macroarray[$this->macro])){
540       $macrotab="";
541     }else{
543       $macrotab ="<table summary=\""._("Parameter")."\">";
544       /* for every single parameter-> display textfile,combo, or true false switch*/
547       /* Automatic fill out */
548       if(isset($_POST['fillout'])){
550         foreach($this->phoneNumbers as $phonenum){
551           $tmp[] = $phonenum;
552         }
554         /* Go through all params */
555         foreach($this->macroarray[$this->macro] as $key => $paras){
557           $string = $paras['default'];
559           $string=preg_replace("/%uid/i",$this->uid,$string);
560           
561           if(isset($this->cn)){
562             $string=preg_replace("/%cn/i",$this->cn,$string);
563           }
565           for($i = 0 ; $i < 10; $i++){
566             if(isset($tmp[$i])){
567               $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
568             }
569           }
571           $this->macroarray[$this->macro][$key]['choosen']=$string;
572         }
573       }
575       foreach($this->macroarray[$this->macro] as $paras){
577         /* get al vars */
578         $var        = $paras['var'];           
579         $name       = $paras['name'];           
580         $default    = $paras['default'];
581         $type       = $paras['type'];
582         $choosen    = $paras['choosen'] ; 
583         $str        = $default;
585         /* in case of a combo box display a combobox with selected attr */
586         $macrotab.= "<tr>";
587         switch ($type){
589           case "combo":
590             $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")."  ".chkacl($this->acl, "goFonMacro").">";
591           foreach(split(":",$default) as $choice){
592             if($choosen==$choice){
593               $str.= "\n<option value='".$choice."' selected>".$choice."&nbsp;</option>";
594             }else{
595               $str.= "\n<option value='".$choice."'>".$choice."&nbsp;</option>";
596             }
597           }
598           $str.="</select>";
599           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
600           break;
602           case "bool":
603             if(!$choosen){
604               $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
605             }else{
606               $str="\n<input type='checkbox' name='".$var."' value='1' checked  ".chkacl($this->acl, "goFonMacro").">";
607             }
608           $macrotab.= "<td colspan='2'>$str&nbsp;".base64_decode($name)."";
609           break;
611           case "string":
612             $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
613           $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
614           break;
616         }
617         $macrotab.= "</td></tr>";
619       }
620       $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
621     }//is_array()
623     /* Give smarty the table */
624     $smarty->assign("macrotab",$macrotab);
626     /* Do we represent a valid account? */
627     if (!$this->is_account && $this->parent == NULL){
628       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
629         _("This account has no phone extensions.")."</b>";
630       $display.= back_to_main();
631       return($display);
632     }
634     $display= "";
636     /* Show tab dialog headers */
637     if ($this->parent != NULL){
638       if ($this->is_account){
639         $display= $this->show_header(_("Remove phone account"),
640             _("This account has phone features enabled. You can disable them by clicking below."));
641       } else {
642         if(empty($this->uid)){
643           $display= $this->show_header(_("Create phone account"),
644               _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
645         }else{
646           $display= $this->show_header(_("Create phone account"),
647               _("This account has phone features disabled. You can enable them by clicking below."));
648         }
649         return ($display);
650       }
651     }
653     /* Add phone number */
654     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
655       if (is_phone_nr($_POST['phonenumber'])){
656         $number= $_POST["phonenumber"];
657         $this->phoneNumbers[$number]= $number;
658         $this->is_modified= TRUE;
659       } else {
660         print_red(_("Please enter a valid phone number!"));
661       }
662     }
664     /* Remove phone number */
665     if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
666       foreach ($_POST['phonenumber_list'] as $number){
667         unset($this->phoneNumbers[$number]);
668         $this->is_modified= TRUE;
669       }
670     }
672     /* Transfer ACL's */
673     foreach($this->attributes as $val){
674       $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
675       if(isset($this->$val)){
676         $smarty->assign($val,$this->$val);
677       }else{
678         $smarty->assign($val,"");
679       }
680     }
682     /* Fill arrays */
683     $smarty->assign ("goFonHardware", $this->goFonHardware);
684     if (!count($this->phoneNumbers)){
685       $smarty->assign ("phoneNumbers", array(""));
686     } else {
687       $smarty->assign ("phoneNumbers", $this->phoneNumbers);
688     }
689     $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
690       _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
691     foreach ($this->hardware_list as $cn => $description){
692       if ($cn == $this->goFonHardware){
693         $selected= "selected";
694       } else {
695         $selected= "";
696       }
697       if (isset($this->used_hardware[$cn])){
698         $color= "style=\"color:#A0A0A0\"";
699       } else {
700         $color= "";
701       }
702       $hl.= "  <option $color label=\"$cn\" value=\"$cn\" $selected>$description&nbsp;</option>\n";
703     }
704     $hl.= "</select>\n";
705     $smarty->assign ("hardware_list", $hl);
707     /* Show main page */
709     $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
710     return($display);
711   }
714   function save_object()
715   {
716     if (isset($_POST["phoneTab"])){
717       plugin::save_object();
719       /* Save checkbox */
720       if (isset($_POST['fon_to_mail'])){
721         $tmp= "[M]";
722       } else {
723         $tmp= "[]";
724       }
725       if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
726         if ($this->goFonDeliveryMode != $tmp){
727           $this->is_modified= TRUE;
728         }
729         $this->goFonDeliveryMode= $tmp;
730       }
732       /* Every macro in the select box are available */
733       if((isset($_POST['macro']))){
734         $this->macrostillavailable=true;
735       }
737       if(is_array($this->phoneNumbers)){
738         foreach($this->phoneNumbers as $telenumms) {
739           $nummsinorder[]=$telenumms; 
740         }
741       }else{
742         $nummsinorder=array("");
743       }
745       /* get all Postvars */
746       if(isset($this->macroarray[$this->macro])){ 
747         foreach($this->macroarray[$this->macro] as $key => $paras){
748           if(isset($_POST[$paras['var']])){
749             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
750           }
752           /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code 
753              We need this code below to read and save checkboxes correct
754            */
756           if(isset($_POST['post_success'])){
757             if($this->macroarray[$this->macro][$key]['type']=="bool"){
758               if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
759                 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
760               }else{
761                 $this->macroarray[$this->macro][$key]['choosen']=false;
762               }
763             }
764           }
765         }
766       }
767     }
768   }
770   function check()
771   {
772     /* Reset message array */
773     $message= array();
775     if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
776       $message[]=(_("Voicemail PIN must be between 1-4 characters."));
777     }else{
778       if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
779         $message[]=(_("The specified oicemail PIN contains invalid characters, only numeric values are allowed here."));
780       }
781     }
784     if((strlen($this->goFonPIN)!=4)){
785       $message[]=(_("Phone PIN must be 4 characters long."));
786     }else{
787       if(preg_match("/[^0-9]/",$this->goFonPIN)){
788         $message[]=(_("The specified phone PIN contains invalid characters, only numeric values are allowed here."));
789       }
790     }
792     if(!$this->generate_mysql_entension_entries()){
793       $message[] = $this->generate_error;
794     }
796     /* We need at least one phone number */
797     if (count($this->phoneNumbers) == 0){
798       $message[]= sprintf(_("You need to specify at least one phone number!"));
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     }
824     /* Save settings, or remove goFonMacro attribute*/
825     if($this->macro!="none"){    
826       $this->attrs['goFonMacro']=$this->macro;
827       if(isset($this->macroarray[$this->macro])){
828         foreach($this->macroarray[$this->macro] as $paras)  {
829           $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
830         }
831       }
832     }else{
833       $this->attrs['goFonMacro']=array();
834     }
835     unset($this->attrs['macro'])  ;
837     $this->attrs['goFonForwarding']=array();
839     $this->generate_mysql_entension_entries(true);
841     if($this->attrs['goFonMacro']==""){
842       $this->attrs['goFonMacro']=array();
843     }
845     unset($this->attrs['cn']);
847     /* Write back to ldap */
848     $ldap= $this->config->get_ldap_link();
849     $ldap->cd($this->dn);
850     $ldap->modify($this->attrs);
851     show_ldap_error($ldap->get_error());
853     /* Optionally execute a command after we're done */
855     if ($this->initially_was_account == $this->is_account){
856       if ($this->is_modified){
857         $this->handle_post_events("modify");
858       }
859     } else {
860       $this->handle_post_events("add");
861     }
863   }
866   function insert_after($entry, $nr, $list)
867   {
868     /* Is the entry free? No? Make it free... */
869     if (isset($list[$nr])) {
870       $dest= array();
871       $newidx= 0;
873       foreach ($list as $idx => $contents){
874         $dest[$newidx++]= $contents;
875         if ($idx == $nr){
876           $dest[$newidx++]= $entry;
877         }
878       }
879     } else {
880       $dest= $list;
881       $dest[$nr]= $entry;
882     }
884     return ($dest);
885   }
888   function adapt_from_template($dn)
889   {
890     plugin::adapt_from_template($dn);
892     /* Assemble phone numbers */
893     if (isset($this->attrs['telephoneNumber'])){
894       for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
895         $number= $this->attrs['telephoneNumber'][$i];
896         $this->phoneNumbers[$number]= $number;
897       }
898     }
899   }
902   function remove_from_parent()
903   {
904   
905     foreach($this->attributes as $key=>$val){
906       if(in_array($val,array("uid","cn","mail"))){
907         unset($this->attributes[$key]);
908         unset($this->$val);
909       }
910     }
912     // Get Configuration for Mysql database Server
913     $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
914     $s_parameter  ="";
916     // Connect to DB server
917     $r_con =  @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
919     // Check if we are  connected correctly
920     if(!$r_con){
921       $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
922           $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
923       gosa_log(@mysql_error());
924       return false;
925     }
927     // Select database for Extensions
928     $db  =  @mysql_select_db($a_SETUP['DB'],$r_con);
930     // Test if we have the database selected correctly
931     if(!$db){
932       $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
933       gosa_log(@mysql_error());
934       return false;
935     }
937     $SQL="";
939     /* If deletion starts from userslist, cn uid are not set */
940     if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
941       $this->uid = $this->parent->by_object['user']->uid;
942     }
944     if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
945       $this->cn  = $this->parent->by_object['user']->cn;
946     }
948     $first_num = false;
949     // Delete old entries
950     foreach($this->a_old_telenums as $s_telenums){
951       if(!$first_num){
952         $first_num = $s_telenums;
953       }
954       $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
955     }
957     $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
958     $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
959     $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
962     foreach($SQL as $query){
963       if(!@mysql_query($query,$r_con)){
964         print_red(_("Stop".mysql_error()));
965         return false;
966       }
967     }
971     /* unset macro attr, it will cause an error */
972     $tmp = array_flip($this->attributes);
973     unset($tmp['macro']);
974     $this->attributes=array_flip($tmp);
976     /* Cancel if there's nothing to do here */
977     if (!$this->initially_was_account){
978       return;
979     }
981     plugin::remove_from_parent();
983     /* Just keep one phone number */
984     if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
985       $this->attrs['telephoneNumber']= $this->telephoneNumber;
986     } else {
987       $this->attrs['telephoneNumber']= array();
988     }
990     $ldap= $this->config->get_ldap_link();
991     $ldap->cd($this->config->current['BASE']);
992     $ldap->search("(objectClass=goFonQueue)", array("member"));
993     while($attr = $ldap->fetch()){
994       if(in_array($this->dn,$attr['member'])){
995         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
996         unset($new->by_object['ogroup']->memberList[$this->dn]);
997         unset($new->by_object['ogroup']->member[$this->dn]);
998         $new->save();
999         print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1000       }
1001     }
1002     $ldap->cd($this->dn);
1003     $ldap->modify($this->attrs);
1004     show_ldap_error($ldap->get_error());
1006     /* Optionally execute a command after we're done */
1007     $this->handle_post_events('remove');
1008   }
1012   /* This function checks if the given phonenumbers are available or already in use*/
1013   function is_number_used()
1014   {
1015     $ldap= $this->config->get_ldap_link();
1016     $ldap->cd($this->config->current['BASE']);
1017     $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1018     while($attrs = $ldap->fetch()) {
1019       unset($attrs['telephoneNumber']['count']);
1020       foreach($attrs['telephoneNumber'] as $tele){
1021         if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1022         if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1023         $numbers[$tele]=$attrs;
1024       }
1025     }
1027     foreach($this->phoneNumbers as $num){
1028       if(!isset($this->cn)) $this->cn = "";
1030       if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1031         if(isset($numbers[$num]['uid'][0])){
1032           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1033         }else{
1034           return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1035         }
1036       }
1037     }
1038   }
1041 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1042 ?>