Code

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