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 Macroi
23 var $lastmacro = "";
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();
29 var $goFonPINVoice = "";
31 /* CLI vars */
32 var $cli_summary = "Manage users phone account";
33 var $cli_description = "Some longer text\nfor help";
34 var $cli_parameters = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
36 /* attribute list for save action */
37 var $attributes = array("goFonDeliveryMode", "goFonFormat","uid","cn","mail",
38 "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
39 var $objectclasses= array("goFonAccount");
41 function phoneAccount ($config, $dn= NULL)
42 {
43 plugin::plugin ($config, $dn);
45 /* Set phone hardware */
46 if (!isset($this->attrs['goFonHardware'])){
47 $this->goFonHardware= "automatic";
48 }
50 /* Preset voice format */
51 if (!isset($this->attrs['goFonFormat'])){
52 $this->goFonFormat= "wav";
53 }
55 /* Assemble phone numbers */
56 if (isset($this->attrs['telephoneNumber'])){
57 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
58 $number= $this->attrs['telephoneNumber'][$i];
59 $this->phoneNumbers[$number]= $number;
60 }
61 }
63 /* Set up has_mailAccount */
64 if (isset($this->attrs['objectClass'])){
65 if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
66 $this->has_mailAccount= TRUE;
67 }
68 }
70 $a_SETUP= array();
71 if(array_key_exists('config',$_SESSION) &&
72 array_key_exists('SERVERS',$_SESSION['config']->data) &&
73 array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
74 is_callable("mysql_connect")
75 ) {
76 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
77 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
78 if(!$r_con){
79 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
80 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
81 gosa_log(mysql_error());
82 return false;
83 }
84 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
85 if(!$db){
86 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
87 gosa_log(mysql_error());
88 return false;
89 }
91 $first = false;
92 foreach($this->phoneNumbers as $key => $val){
93 if(!$first){
94 $first = $key;
95 }
96 }
97 }
99 /* Load hardware list */
100 $ldap= $this->config->get_ldap_link();
101 $ldap->cd($this->config->current['BASE']);
102 $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
103 while ($attrs= $ldap->fetch()){
104 $cn= $attrs['cn'][0];
105 if (isset($attrs['description'])){
106 $description= " - ".$attrs['description'][0];
107 } else {
108 $description= "";
109 }
110 $this->hardware_list[$cn]= "$cn$description";
112 }
114 /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
115 $ldap->search("(objectClass=goFonMacro)", array("*"));
117 /* Add none for no macro*/
118 $this->macros['none']=_("no macro");
119 $this->macro ="none";
122 /* Fetch all Macros*/
123 while ($attrs= $ldap->fetch()){
125 /* Only visisble */
126 if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
128 /* unset Count, we don't need that here */
129 unset($attrs['displayName']['count']);
131 /* fill Selectfield variable with Macros */
132 if(isset($attrs['displayName'][0])){
133 $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
134 }else{
135 $this->macros[$attrs['dn']] = _("undefined");
136 }
138 /* Parse macro data, unset count for parameterarrays */
139 if (isset($attrs['goFonMacroParameter']['count'])){
140 unset($attrs['goFonMacroParameter']['count']);
141 }
143 /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
144 if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
146 foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
147 /* Split Data in readable values, by delimiter ! */
148 $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
150 /* Set all attrs */
151 $id = $data[0];
152 $this->macroarray[$attrs['dn']][$id]['var'] ="var".$id;
153 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
154 $this->macroarray[$attrs['dn']][$id]['id'] =$id;
155 $this->macroarray[$attrs['dn']][$id]['name'] =$data[1];
156 $this->macroarray[$attrs['dn']][$id]['type'] =$data[2];
157 $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
158 if($data[2] == "bool"){
159 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
160 }
161 }//foreach
162 }//is_array
163 }//visible = 1
164 }//while
166 /* Go through already saved values, for a parameter */
167 $tmp = split("!",$this->goFonMacro);
169 /* it is possible that nothing has been saved yet */
170 if(is_array($tmp)){
172 /* First value is the macroname */
173 $this->macro = $tmp[0];
175 /* Macroname saved, delete that index */
176 unset($tmp[0]);
178 /* Check if makro has been removed */
179 if(!isset($this->macroarray[$this->macro])){
180 $this->macrostillavailable = false;
181 }else{
182 $this->macrostillavailable = true;
183 }
185 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
186 foreach($tmp as $var){
188 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
189 $varar = split("#",$var);
191 /* Only insert if the parameter still exists */
192 if(isset($this->macroarray[$this->macro][$varar[0]])){
193 /* Assign value */
194 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
195 }
196 }
197 }
200 /* Eventually colorize phones */
201 $ldap->cd($this->config->current['BASE']);
202 foreach ($this->hardware_list as $cn => $desc){
203 $ldap->search("(goFonHardware=$cn)", array('cn'));
204 if ($ldap->count() > 0){
205 $ldap->fetch();
206 if ($ldap->getDN() != $this->dn){
207 $this->used_hardware[$cn]= $ldap->getDN();
208 }
209 }
210 }
211 $this->hardware_list["automatic"]= _("automatic");
212 ksort($this->hardware_list);
213 $this->a_old_telenums = $this->phoneNumbers;
215 if($this->is_account){
216 $this->is_modified = true;
217 }
220 /* Get voicemail PIN from MySQL DB
221 * Because every user can change his PIN directly from the phone
222 * without any update to the ldap
223 * This means, the PIN in the DB is up to date
224 */
225 // Connect to DB server
226 if((is_callable("mysql_pconnect"))&&(isset($a_SETUP))&&(isset($a_SETUP['SERVER']))&&(isset($a_SETUP['LOGIN']))&&(isset($a_SETUP['PASSWORD']))){
227 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
228 if($r_con){
229 $r_db = @mysql_select_db($a_SETUP['DB'],$r_con);
230 $vp = mysql_fetch_row(mysql_query("SELECT ".$a_SETUP['VOICE_TABLE'].".password FROM ".$a_SETUP['VOICE_TABLE'].", ".$a_SETUP['SIP_TABLE']." WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'"));
232 if((isset($vp[0]))&&(!empty($vp[0]))){
233 $this->goFonPINVoice = $vp[0];
234 }
235 }
236 }
237 $this->lastmacro=$this->macro;
239 if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
240 @mysql_close($r_con) ;
241 }
242 }
245 // Generate MySQL Syntax
246 function generate_mysql_entension_entries($save = false){
248 if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
249 if($save)
250 print_red(_("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer). Your settings can't be saved to asterisk database."));
251 return(true);
252 }
254 if(!is_callable("mysql_pconnect")){
255 if($save)
256 print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
257 return(true);
258 }
260 // Get Configuration for Mysql database Server
261 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON']; // DB Configuration
262 $s_parameter = ""; // Contains paramter for selected Macro
263 $r_con = false; // DB connection
264 $r_db = false; // Selected DB
265 $r_res = false; // Result resource
266 $a_ldap_attrs = array(); //
268 $s_ip = NULL; // Contains ip for Sip entry
269 $s_host = NULL; // Contains host for Sip entry
270 $s_qualify = NULL; // Qualify entry
271 $s_pin = NULL; // Entry for secret
272 $s_type = NULL; // Entry for phone type (friend , peer ..)
274 $sip_data_array = array(); // Contains complete sip entry, to generate SQL syntax
275 $i_old_key = false; // Contains index for first old phonenumber, to delete old entries corectly
276 $i_new_key = false; // Contains index for first new phonenumber, to generate new entries corectly
278 $s_sip_values = ""; // Contains string with all values for given attributes in SQL syntax
279 $s_sip_keys = ""; // Contains all needed attributes to generate sip entry in DB
281 $s_sip_key = ""; // Key for SIP entry index
282 $s_sip_val = ""; // Value for SIP entry index
284 $b_first_deleted= false; // Only delete first entry,
285 $s_telenums = ""; // for each value variable
287 $i_is_accounted =false; // Ensure that extension entry, for name to number is only once in table
290 // Connect to DB server
291 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
293 // Check if we are connected correctly
294 if(!$r_con){
295 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
296 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
297 gosa_log(mysql_error());
298 return false;
299 }
301 // Select database for Extensions
302 $r_db = @mysql_select_db($a_SETUP['DB'],$r_con);
304 // Test if we have the database selected correctly
305 if(!$r_db){
306 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
307 gosa_log(mysql_error());
308 return false;
309 }
311 // Get phonehardware to setup sip entry
312 $ldap = $this->config->get_ldap_link();
313 $r_res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
314 $a_ldap_attrs = $ldap->fetch();
316 if($this->is_number_used()){
317 $this->generate_error = $this->is_number_used();
318 return false;
319 }
321 /* If Save == true, we should save something.
322 * Generate SQL, for drop of old entries
323 * Generate SQL, for insert new entries
324 */
325 if($save == true){
327 foreach($this->a_old_telenums as $tele){
328 $oldnums[]= preg_replace("/[^0-9]/","",$tele);
329 }
331 foreach($this->phoneNumbers as $tele){
332 $newnums[]= preg_replace("/[^0-9]/","",$tele);
333 }
335 // Attribute GoFonDefaultIP set ?
336 if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
337 $s_ip = $a_ldap_attrs['goFonDefaultIP'][0];
338 $s_host = $s_ip;
339 }else{
340 $s_ip = NULL;
341 $s_host = "dynamic";
342 }
344 // Attribute GoFonQualify set ?
345 if(isset($a_ldap_attrs['goFonQualify'])){
346 $s_qualify = $a_ldap_attrs['goFonQualify'][0];
347 }
349 // Attribute GoFonPIN set ?
350 if(isset($this->goFonPIN)){
351 $s_pin = $this->goFonPIN;
352 }
354 // Attribute GoFonType set ?
355 if(isset($a_ldap_attrs['goFonType'])){
356 $s_type = $a_ldap_attrs['goFonType'][0];
357 }
359 if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
360 $sip_data_array['dtmfmode'] = $a_ldap_attrs['goFonDmtfMode'][0];
361 }else{
362 $sip_data_array['dtmfmode'] ="rfc2833";
363 }
365 // generate SIP entry
366 $sip_data_array['id'] = "";
367 $sip_data_array['name'] = $this->uid;
368 $sip_data_array['accountcode'] = NULL;
369 $sip_data_array['amaflags'] = NULL;
370 $sip_data_array['callgroup'] = NULL;
371 $sip_data_array['callerid'] = "";
372 $sip_data_array['canreinvite'] = "no";
373 $sip_data_array['context'] = "default";
374 $sip_data_array['defaultip'] = NULL;
375 $sip_data_array['fromuser'] = NULL;
376 $sip_data_array['fromdomain'] = NULL;
377 $sip_data_array['host'] = $s_host;
378 $sip_data_array['insecure'] = NULL;
379 $sip_data_array['language'] = NULL;
380 $sip_data_array['mailbox'] = "asterisk";
381 $sip_data_array['md5secret'] = NULL;
382 $sip_data_array['nat'] = "no";
383 $sip_data_array['permit'] = NULL;
384 $sip_data_array['deny'] = NULL;
385 $sip_data_array['mask'] = NULL;
386 $sip_data_array['pickupgroup'] = NULL;
387 $sip_data_array['port'] = NULL;
388 $sip_data_array['qualify'] = $s_qualify;
389 $sip_data_array['restrictcid'] = "n";
390 $sip_data_array['rtptimeout'] = NULL;
391 $sip_data_array['rtpholdtimeout']=NULL;
392 $sip_data_array['secret'] = $this->goFonPIN;
393 $sip_data_array['type'] = $s_type ;
394 $sip_data_array['username'] = $this->uid;
395 $sip_data_array['disallow'] = NULL;
396 $sip_data_array['allow'] = NULL;
397 $sip_data_array['musiconhold'] = NULL;
398 $sip_data_array['regseconds'] = NULL;
399 $sip_data_array['ipaddr'] = $s_ip;
400 $sip_data_array['regexten'] = NULL;
401 $sip_data_array['cancallforward']=NULL;
403 // Get selected Macro Parameter and create parameter entry
404 if(isset($this->macroarray[$this->macro])){
405 foreach($this->macroarray[$this->macro] as $key => $val ){
406 $s_parameter .= $val['choosen']."|";
407 }
408 $s_parameter = preg_replace("/\|$/","",$s_parameter);
409 }
411 if($this->is_number_used()){
412 $this->generate_error = $this->is_number_used();
413 return false;
414 }
416 // Create new SIP entry ...
417 $sip_entry = $sip_data_array;
418 reset($newnums);
419 $i_new_key = key($newnums);
420 $sip_entry['callerid'] =$newnums[$i_new_key];
421 $sip_entry['mailbox'] =$newnums[$i_new_key];
423 if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
424 $s_mail = $this->parent->by_object['mailAccount']->mail;
425 }else{
426 $s_mail = "";
427 }
429 // $SQL contains all queries
430 $SQL = array();
431 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
432 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
433 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$newnums[$i_new_key].";";
434 // Delete old entries
435 $b_first_deleted =false;
436 foreach($oldnums as $s_telenums){
437 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
438 if(!$b_first_deleted){
439 $b_first_deleted=true;
440 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
441 }
442 }
444 if($this->goFonHardware=="automatic"){
445 foreach($SQL as $query ){
446 mysql_query($query) ;
447 }
448 return;
449 }
451 // Generate Strings with keys and values
452 foreach($sip_entry as $s_sip_key=>$s_sip_val){
453 if($s_sip_val == NULL) continue;
454 $s_sip_values.="'".$s_sip_val."',";
455 $s_sip_keys .="`".$s_sip_key."`,";
456 }
457 // Remove last ,
458 $s_sip_values = preg_replace("/,$/","",$s_sip_values);
459 $s_sip_keys = preg_replace("/,$/","",$s_sip_keys);
461 // Append SIP Entry
462 $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
464 /* If deletion starts from userslist, cn uid are not set */
465 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
466 $this->uid = $this->parent->by_object['user']->uid;
467 }
469 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
470 $this->cn = $this->parent->by_object['user']->cn;
471 }
473 if((!isset($this->cn))||(empty($this->cn))){
474 $CNname= $this->uid;
475 }else{
476 $CNname= $this->cn;
477 }
479 $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
480 VALUES ('".$newnums[$i_new_key]."',
481 'default',
482 '".$newnums[$i_new_key]."',
483 '".$this->goFonVoicemailPIN."',
484 '".$CNname."',
485 '".$s_mail."',
486 '');";
487 $i_is_accounted=false;
489 $i = 0;
491 $is_inserted_once = false;
493 // Entension entries Hint / Dial / Goto
494 foreach($newnums as $s_telenums){
496 if(!$is_inserted_once){
497 $is_inserted_once = true;
498 $EXT[$i]['context'] = 'GOsa';
499 $EXT[$i]['exten'] = $this->uid;
500 $EXT[$i]['priority']= 1;
501 $EXT[$i]['app'] = "Goto";
502 $EXT[$i]['appdata'] = $s_telenums."|1";
503 $i ++;
504 }
505 /* Hint Entry */
506 $EXT[$i]['context'] = 'GOsa';
507 $EXT[$i]['exten'] = $s_telenums;
508 $EXT[$i]['priority']= "Hint";
509 $EXT[$i]['app'] = 'SIP/'.$this->uid;
510 $i ++;
511 /* SetCID */
512 //$EXT[$i]['context'] = 'GOsa';
513 //$EXT[$i]['exten'] = $s_telenums;
514 //$EXT[$i]['priority']= 1;
515 //$EXT[$i]['app'] = "SetCIDName";
516 //$EXT[$i]['appdata'] = $CNname;
517 //$i ++;
519 // If no macro is selected use Dial
520 if($this->macro!="none"){
521 $macroname = preg_replace("/,.*$/","",$this->macro);
522 $macroname = preg_replace("/^.*=/","",$macroname);
523 $s_app = "Macro";$macroname;
524 $s_par = $macroname."|".$s_parameter;
525 }else{
526 $s_app = "Dial";
527 $s_par = 'SIP/'.$this->uid."|20|r";
528 }
530 $EXT[$i]['context'] = 'GOsa';
531 $EXT[$i]['exten'] = $s_telenums;
532 $EXT[$i]['priority']= 1;
533 $EXT[$i]['app'] = $s_app;
534 $EXT[$i]['appdata'] = $s_par;
535 $i ++;
537 }
539 // Append all these Entries
540 foreach($EXT as $entr){
541 $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
542 foreach($entr as $key2 => $val2){
543 $SQL_syn.= "`".$key2."`,";
544 }
545 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
546 $SQL_syn .= ") VALUES (";
547 foreach($entr as $key2 => $val2){
548 $SQL_syn .= "'".$val2."',";
549 }
550 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
551 $SQL_syn .=");\n";
552 $SQL[] =$SQL_syn;
553 $SQL_syn ="";
554 }
556 // Perform queries ...
557 foreach($SQL as $query){
558 if(!@mysql_query($query,$r_con)){
559 print_red(_("Error while performing query:")." ".mysql_error());
560 return false;
561 }
562 }
563 }
564 @mysql_close($r_con);
565 return true;
566 }
569 function execute()
570 {
571 /* Call parent execute */
572 plugin::execute();
574 $display = "";
576 if(empty($this->macro)&&(!empty($this->goFonMacro))){
578 /* Go through already saved values, for a parameter */
579 $tmp = split("!",$this->goFonMacro);
581 /* it is possible that nothing has been saved yet */
582 if(is_array($tmp)){
584 /* First value is the macroname */
585 $this->macro = $tmp[0];
587 /* Macroname saved, delete that index */
588 unset($tmp[0]);
590 /* Check if makro has been removed */
591 if(!isset($this->macroarray[$this->macro])){
592 $this->macrostillavailable = false;
593 }else{
594 $this->macrostillavailable = true;
595 }
597 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
598 foreach($tmp as $var){
600 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
601 $varar = split("#",$var);
603 /* Only insert if the parameter still exists */
604 if(isset($this->macroarray[$this->macro][$varar[0]])){
605 /* Assign value */
606 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
607 }
608 }
609 }
610 }
612 /* Do we represent a valid account? */
613 if (!$this->is_account && $this->parent == NULL){
614 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
615 _("This account has no phone extensions.")."</b>";
616 $display.= back_to_main();
617 return ($display);
618 }
620 /* Do we need to flip is_account state? */
621 if (isset($_POST['modify_state'])){
622 $this->is_account= !$this->is_account;
623 }
625 /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
626 if(empty($this->macro)){
627 $this->macro ="none";
628 }
630 /* Prepare templating */
631 $smarty= get_smarty();
633 /* tell user that the pluging selected is no longer available*/
634 if((!$this->macrostillavailable)&&($this->macro!="none")){
635 print_red(_("The macro you selected, is no longer available for you, please choose another one."));
636 }
638 /* Assing macroselectbox values */
639 $smarty->assign("macros",$this->macros);
640 $smarty->assign("macro", $this->macro);
642 /* check if there is a FON server created */
643 if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
644 print_red(_("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer). Your settings can't be saved to asterisk database."));
645 }
647 /* Create parameter table, skip if no parameters given */
648 if(!isset($this->macroarray[$this->macro])){
649 $macrotab="";
650 }else{
652 $macrotab ="<table summary=\""._("Parameter")."\">";
653 /* for every single parameter-> display textfile,combo, or true false switch*/
655 foreach($this->phoneNumbers as $phonenum){
656 $tmp[] = $phonenum;
657 }
661 if($this->macro != $this->lastmacro){
662 /* Go through all params */
663 foreach($this->macroarray[$this->macro] as $key => $paras){
665 $string = $paras['default'];
667 $string=preg_replace("/%uid/i",$this->uid,$string);
669 if(isset($this->cn)){
670 $string=preg_replace("/%cn/i",$this->cn,$string);
671 }
673 for($i = 0 ; $i < 10; $i++){
674 if(isset($tmp[$i])){
675 $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
676 }
677 }
678 if(isset($tmp[0])){
679 $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
680 }
681 $this->macroarray[$this->macro][$key]['choosen']=$string;
682 }
683 }
685 foreach($this->macroarray[$this->macro] as $paras){
687 /* get al vars */
688 $var = $paras['var'];
689 $name = $paras['name'];
690 $default = $paras['default'];
691 $type = $paras['type'];
692 $choosen = $paras['choosen'] ;
693 $str = $default;
695 /* in case of a combo box display a combobox with selected attr */
696 $macrotab.= "<tr>";
697 switch ($type){
699 case "combo":
700 $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
701 foreach(split(":",$default) as $choice){
702 if($choosen==$choice){
703 $str.= "\n<option value='".$choice."' selected>".$choice." </option>";
704 }else{
705 $str.= "\n<option value='".$choice."'>".$choice." </option>";
706 }
707 }
708 $str.="</select>";
709 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
710 break;
712 case "bool":
713 if(!$choosen){
714 $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
715 }else{
716 $str="\n<input type='checkbox' name='".$var."' value='1' checked ".chkacl($this->acl, "goFonMacro").">";
717 }
718 $macrotab.= "<td colspan='2'>$str ".base64_decode($name)."";
719 break;
721 case "string":
722 $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
723 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
724 break;
726 }
727 $macrotab.= "</td></tr>";
729 }
730 $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
731 }//is_array()
733 /* Give smarty the table */
734 $smarty->assign("macrotab",$macrotab);
736 /* Do we represent a valid account? */
737 if (!$this->is_account && $this->parent == NULL){
738 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
739 _("This account has no phone extensions.")."</b>";
740 $display.= back_to_main();
741 return($display);
742 }
744 $display= "";
746 /* Show tab dialog headers */
747 if ($this->parent != NULL){
748 if ($this->is_account){
749 $display= $this->show_header(_("Remove phone account"),
750 _("This account has phone features enabled. You can disable them by clicking below."));
751 } else {
752 if(empty($this->uid)){
753 $display= $this->show_header(_("Create phone account"),
754 _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
755 }else{
756 $display= $this->show_header(_("Create phone account"),
757 _("This account has phone features disabled. You can enable them by clicking below."));
758 }
759 return ($display);
760 }
761 }
763 /* Add phone number */
764 if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
765 if (is_phone_nr($_POST['phonenumber'])){
766 $number= $_POST["phonenumber"];
767 $this->phoneNumbers[$number]= $number;
768 $this->is_modified= TRUE;
769 } else {
770 print_red(_("Please enter a valid phone number!"));
771 }
772 }
774 /* Remove phone number */
775 if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
776 foreach ($_POST['phonenumber_list'] as $number){
777 unset($this->phoneNumbers[$number]);
778 $this->is_modified= TRUE;
779 }
780 }
782 /* Transfer ACL's */
783 foreach($this->attributes as $val){
784 $smarty->assign($val."ACL", chkacl($this->acl,$val));
785 if(isset($this->$val)){
786 $smarty->assign($val,$this->$val);
787 }else{
788 $smarty->assign($val,"");
789 }
790 }
792 /* Fill arrays */
793 $smarty->assign ("goFonHardware", $this->goFonHardware);
794 if (!count($this->phoneNumbers)){
795 $smarty->assign ("phoneNumbers", array(""));
796 } else {
797 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
798 }
799 $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
800 _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
801 foreach ($this->hardware_list as $cn => $description){
802 if ($cn == $this->goFonHardware){
803 $selected= "selected";
804 } else {
805 $selected= "";
806 }
807 if (isset($this->used_hardware[$cn])){
808 $color= "style=\"color:#A0A0A0\"";
809 } else {
810 $color= "";
811 }
812 $hl.= " <option $color label=\"$cn\" value=\"$cn\" $selected>$description </option>\n";
813 }
814 $hl.= "</select>\n";
815 $smarty->assign ("hardware_list", $hl);
817 /* Show main page */
818 $this->lastmacro = $this->macro;
819 $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
820 return($display);
821 }
824 function save_object()
825 {
826 if (isset($_POST["phoneTab"])){
827 plugin::save_object();
829 /* Save checkbox */
830 if (isset($_POST['fon_to_mail'])){
831 $tmp= "[M]";
832 } else {
833 $tmp= "[]";
834 }
835 if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
836 if ($this->goFonDeliveryMode != $tmp){
837 $this->is_modified= TRUE;
838 }
839 $this->goFonDeliveryMode= $tmp;
840 }
842 /* Every macro in the select box are available */
843 if((isset($_POST['macro']))){
844 $this->macrostillavailable=true;
845 }
847 if(is_array($this->phoneNumbers)){
848 foreach($this->phoneNumbers as $telenumms) {
849 $nummsinorder[]=$telenumms;
850 }
851 }else{
852 $nummsinorder=array("");
853 }
855 /* get all Postvars */
856 if(isset($this->macroarray[$this->macro])){
857 foreach($this->macroarray[$this->macro] as $key => $paras){
858 if(isset($_POST[$paras['var']])){
859 $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
860 }
862 /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
863 We need this code below to read and save checkboxes correct
864 */
866 if(isset($_POST['post_success'])){
867 if($this->macroarray[$this->macro][$key]['type']=="bool"){
868 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
869 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
870 }else{
871 $this->macroarray[$this->macro][$key]['choosen']=false;
872 }
873 }
874 }
875 }
876 }
877 }
878 }
880 function check()
881 {
882 /* Reset message array */
883 $message= array();
885 if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
886 $message[]=(_("Voicemail PIN must be between 1-4 characters."));
887 }else{
888 if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
889 $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
890 }
891 }
893 if((strlen($this->goFonPIN)<=0)){
894 $message[]=(_("Phone PIN must be at least one character long."));
895 }else{
896 if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
897 $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
898 }
899 }
901 if(!$this->generate_mysql_entension_entries()){
902 $message[] = $this->generate_error;
903 }
905 /* We need at least one phone number */
906 if (count($this->phoneNumbers) == 0){
907 $message[]= sprintf(_("You need to specify at least one phone number!"));
908 }
910 /* check for ! in any parameter setting*/
911 if(isset($this->macroarray[$this->macro])){
912 foreach($this->macroarray[$this->macro] as $val){
913 if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
914 $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
915 }
916 }
917 }
918 return ($message);
919 }
923 function save()
924 {
925 plugin::save();
927 /* Save arrays */
928 $this->attrs['telephoneNumber']= array();
929 foreach ($this->phoneNumbers as $number){
930 $this->attrs['telephoneNumber'][]= $number;
931 }
933 /* Save settings, or remove goFonMacro attribute*/
934 if($this->macro!="none"){
935 $this->attrs['goFonMacro']=$this->macro;
936 if(isset($this->macroarray[$this->macro])){
937 foreach($this->macroarray[$this->macro] as $paras) {
938 $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
939 }
940 }
941 }else{
942 $this->attrs['goFonMacro']=array();
943 }
944 unset($this->attrs['macro']) ;
946 $this->attrs['goFonForwarding']=array();
948 $this->generate_mysql_entension_entries(true);
950 if($this->attrs['goFonMacro']==""){
951 $this->attrs['goFonMacro']=array();
952 }
954 unset($this->attrs['cn']);
956 /* Write back to ldap */
957 $ldap= $this->config->get_ldap_link();
958 $ldap->cd($this->dn);
959 $ldap->modify($this->attrs);
960 show_ldap_error($ldap->get_error());
962 /* Optionally execute a command after we're done */
964 if ($this->initially_was_account == $this->is_account){
965 if ($this->is_modified){
966 $this->handle_post_events("modify");
967 }
968 } else {
969 $this->handle_post_events("add");
970 }
972 }
975 function insert_after($entry, $nr, $list)
976 {
977 /* Is the entry free? No? Make it free... */
978 if (isset($list[$nr])) {
979 $dest= array();
980 $newidx= 0;
982 foreach ($list as $idx => $contents){
983 $dest[$newidx++]= $contents;
984 if ($idx == $nr){
985 $dest[$newidx++]= $entry;
986 }
987 }
988 } else {
989 $dest= $list;
990 $dest[$nr]= $entry;
991 }
993 return ($dest);
994 }
997 function adapt_from_template($dn)
998 {
999 plugin::adapt_from_template($dn);
1001 /* Assemble phone numbers */
1002 if (isset($this->attrs['telephoneNumber'])){
1003 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1004 $number= $this->attrs['telephoneNumber'][$i];
1005 $this->phoneNumbers[$number]= $number;
1006 }
1007 }
1008 }
1011 function remove_from_parent()
1012 {
1014 foreach($this->attributes as $key=>$val){
1015 if(in_array($val,array("uid","cn","mail"))){
1016 unset($this->attributes[$key]);
1017 unset($this->$val);
1018 }
1019 }
1021 if(array_key_exists('config', $_SESSION) &&
1022 array_key_exists('SERVERS', $_SESSION['config']->data) &&
1023 array_key_exists('FON', $_SESSION['config']->data['SERVERS'])) {
1024 // Get Configuration for Mysql database Server
1025 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
1026 $s_parameter ="";
1028 // Connect to DB server
1029 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1031 // Check if we are connected correctly
1032 if(!$r_con){
1033 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1034 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
1035 gosa_log(@mysql_error());
1036 return false;
1037 }
1039 // Select database for Extensions
1040 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
1042 // Test if we have the database selected correctly
1043 if(!$db){
1044 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
1045 gosa_log(@mysql_error());
1046 return false;
1047 }
1049 $SQL="";
1051 /* If deletion starts from userslist, cn uid are not set */
1052 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1053 $this->uid = $this->parent->by_object['user']->uid;
1054 }
1056 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1057 $this->cn = $this->parent->by_object['user']->cn;
1058 }
1060 $first_num = false;
1061 // Delete old entries
1062 foreach($this->a_old_telenums as $s_telenums){
1063 if(!$first_num){
1064 $first_num = $s_telenums;
1065 }
1066 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1067 }
1069 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1070 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1071 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1074 foreach($SQL as $query){
1075 if(!@mysql_query($query,$r_con)){
1076 print_red(_("Stop".mysql_error()));
1077 return false;
1078 }
1079 }
1080 }
1083 /* unset macro attr, it will cause an error */
1084 $tmp = array_flip($this->attributes);
1085 unset($tmp['macro']);
1086 $this->attributes=array_flip($tmp);
1088 /* Cancel if there's nothing to do here */
1089 if (!$this->initially_was_account){
1090 return;
1091 }
1093 plugin::remove_from_parent();
1095 /* Just keep one phone number */
1096 if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1097 $this->attrs['telephoneNumber']= $this->telephoneNumber;
1098 } else {
1099 $this->attrs['telephoneNumber']= array();
1100 }
1102 $ldap= $this->config->get_ldap_link();
1103 $ldap->cd($this->config->current['BASE']);
1104 $ldap->search("(objectClass=goFonQueue)", array("member"));
1105 while($attr = $ldap->fetch()){
1106 if(in_array($this->dn,$attr['member'])){
1107 $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1108 unset($new->by_object['ogroup']->memberList[$this->dn]);
1109 unset($new->by_object['ogroup']->member[$this->dn]);
1110 $new->save();
1111 print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1112 }
1113 }
1114 $ldap->cd($this->dn);
1115 $ldap->modify($this->attrs);
1116 show_ldap_error($ldap->get_error());
1118 /* Optionally execute a command after we're done */
1119 @mysql_close($r_con);
1120 $this->handle_post_events('remove');
1121 }
1125 /* This function checks if the given phonenumbers are available or already in use*/
1126 function is_number_used()
1127 {
1128 $ldap= $this->config->get_ldap_link();
1129 $ldap->cd($this->config->current['BASE']);
1130 $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1131 while($attrs = $ldap->fetch()) {
1132 unset($attrs['telephoneNumber']['count']);
1133 foreach($attrs['telephoneNumber'] as $tele){
1134 if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1135 if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1136 $numbers[$tele]=$attrs;
1137 }
1138 }
1140 foreach($this->phoneNumbers as $num){
1141 if(!isset($this->cn)) $this->cn = "";
1143 if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1144 if(isset($numbers[$num]['uid'][0])){
1145 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1146 }else{
1147 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1148 }
1149 }
1150 }
1151 }
1152 }
1154 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1155 ?>