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= array();
70 if(array_key_exists('config',$_SESSION) &&
71 array_key_exists('SERVERS',$_SESSION['config']->data) &&
72 array_key_exists('FON',$_SESSION['config']->data['SERVERS'])) {
73 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
74 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
75 if(!$r_con){
76 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
77 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
78 gosa_log(mysql_error());
79 return false;
80 }
81 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
82 if(!$db){
83 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
84 gosa_log(mysql_error());
85 return false;
86 }
88 $first = false;
89 foreach($this->phoneNumbers as $key => $val){
90 if(!$first){
91 $first = $key;
92 }
93 }
94 }
96 /* Load hardware list */
97 $ldap= $this->config->get_ldap_link();
98 $ldap->cd($this->config->current['BASE']);
99 $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
100 while ($attrs= $ldap->fetch()){
101 $cn= $attrs['cn'][0];
102 if (isset($attrs['description'])){
103 $description= " - ".$attrs['description'][0];
104 } else {
105 $description= "";
106 }
107 $this->hardware_list[$cn]= "$cn$description";
109 }
111 /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
112 $ldap->search("(objectClass=goFonMacro)", array("*"));
114 /* Add none for no macro*/
115 $this->macros['none']=_("no macro");
116 $this->macro ="none";
119 /* Fetch all Macros*/
120 while ($attrs= $ldap->fetch()){
122 /* Only visisble */
123 if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
125 /* unset Count, we don't need that here */
126 unset($attrs['displayName']['count']);
128 /* fill Selectfield variable with Macros */
129 if(isset($attrs['displayName'][0])){
130 $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
131 }else{
132 $this->macros[$attrs['dn']] = _("undefined");
133 }
135 /* Parse macro data, unset count for parameterarrays */
136 unset($attrs['goFonMacroParameter']['count']);
138 /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
139 if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
141 foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
142 /* Split Data in readable values, by delimiter ! */
143 $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
145 /* Set all attrs */
146 $id = $data[0];
147 $this->macroarray[$attrs['dn']][$id]['var'] ="var".$id;
148 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
149 $this->macroarray[$attrs['dn']][$id]['id'] =$id;
150 $this->macroarray[$attrs['dn']][$id]['name'] =$data[1];
151 $this->macroarray[$attrs['dn']][$id]['type'] =$data[2];
152 $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
153 if($data[2] == "bool"){
154 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
155 }
156 }//foreach
157 }//is_array
158 }//visible = 1
159 }//while
161 /* Go through already saved values, for a parameter */
162 $tmp = split("!",$this->goFonMacro);
164 /* it is possible that nothing has been saved yet */
165 if(is_array($tmp)){
167 /* First value is the macroname */
168 $this->macro = $tmp[0];
170 /* Macroname saved, delete that index */
171 unset($tmp[0]);
173 /* Check if makro has been removed */
174 if(!isset($this->macroarray[$this->macro])){
175 $this->macrostillavailable = false;
176 }else{
177 $this->macrostillavailable = true;
178 }
180 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
181 foreach($tmp as $var){
183 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
184 $varar = split("#",$var);
186 /* Only insert if the parameter still exists */
187 if(isset($this->macroarray[$this->macro][$varar[0]])){
188 /* Assign value */
189 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
190 }
191 }
192 }
195 /* Eventually colorize phones */
196 $ldap->cd($this->config->current['BASE']);
197 foreach ($this->hardware_list as $cn => $desc){
198 $ldap->search("(goFonHardware=$cn)", array('cn'));
199 if ($ldap->count() > 0){
200 $ldap->fetch();
201 if ($ldap->getDN() != $this->dn){
202 $this->used_hardware[$cn]= $ldap->getDN();
203 }
204 }
205 }
206 $this->hardware_list["automatic"]= _("automatic");
207 ksort($this->hardware_list);
208 $this->a_old_telenums = $this->phoneNumbers;
210 if($this->is_account){
211 $this->is_modified = true;
212 }
215 /* Get voicemail PIN from MySQL DB
216 * Because every user can change his PIN directly from the phone
217 * without any update to the ldap
218 * This means, the PIN in the DB is up to date
219 */
220 // Connect to DB server
221 if((isset($a_SETUP))&&(isset($a_SETUP['SERVER']))&&(isset($a_SETUP['LOGIN']))&&(isset($a_SETUP['PASSWORD']))){
222 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
223 if($r_con){
224 $r_db = @mysql_select_db($a_SETUP['DB'],$r_con);
225 $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."'"));
227 if((isset($vp[0]))&&(!empty($vp[0]))){
228 $this->goFonPINVoice = $vp[0];
229 }
230 }
231 }
232 @mysql_close($r_con) ;
233 }
236 // Generate MySQL Syntax
237 function generate_mysql_entension_entries($save = false){
239 if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
240 print_red(_("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer).\nYour Settings can't be saved to asterisk Database."));
241 return(true);
242 }
244 // Get Configuration for Mysql database Server
245 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON']; // DB Configuration
246 $s_parameter = ""; // Contains paramter for selected Macro
247 $r_con = false; // DB connection
248 $r_db = false; // Selected DB
249 $r_res = false; // Result resource
250 $a_ldap_attrs = array(); //
252 $s_ip = NULL; // Contains ip for Sip entry
253 $s_host = NULL; // Contains host for Sip entry
254 $s_qualify = NULL; // Qualify entry
255 $s_pin = NULL; // Entry for secret
256 $s_type = NULL; // Entry for phone type (friend , peer ..)
258 $sip_data_array = array(); // Contains complete sip entry, to generate SQL syntax
259 $i_old_key = false; // Contains index for first old phonenumber, to delete old entries corectly
260 $i_new_key = false; // Contains index for first new phonenumber, to generate new entries corectly
262 $s_sip_values = ""; // Contains string with all values for given attributes in SQL syntax
263 $s_sip_keys = ""; // Contains all needed attributes to generate sip entry in DB
265 $s_sip_key = ""; // Key for SIP entry index
266 $s_sip_val = ""; // Value for SIP entry index
268 $b_first_deleted= false; // Only delete first entry,
269 $s_telenums = ""; // for each value variable
271 $i_is_accounted =false; // Ensure that extension entry, for name to number is only once in table
274 // Connect to DB server
275 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
277 // Check if we are connected correctly
278 if(!$r_con){
279 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
280 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
281 gosa_log(mysql_error());
282 return false;
283 }
285 // Select database for Extensions
286 $r_db = @mysql_select_db($a_SETUP['DB'],$r_con);
288 // Test if we have the database selected correctly
289 if(!$r_db){
290 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
291 gosa_log(mysql_error());
292 return false;
293 }
295 // Get phonehardware to setup sip entry
296 $ldap = $this->config->get_ldap_link();
297 $r_res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
298 $a_ldap_attrs = $ldap->fetch();
300 if($this->is_number_used()){
301 $this->generate_error = $this->is_number_used();
302 return false;
303 }
305 /* If Save == true, we should save something.
306 * Generate SQL, for drop of old entries
307 * Generate SQL, for insert new entries
308 */
309 if($save == true){
311 // Attribute GoFonDefaultIP set ?
312 if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
313 $s_ip = $a_ldap_attrs['goFonDefaultIP'][0];
314 $s_host = $s_ip;
315 }else{
316 $s_ip = NULL;
317 $s_host = "dynamic";
318 }
320 // Attribute GoFonQualify set ?
321 if(isset($a_ldap_attrs['goFonQualify'])){
322 $s_qualify = $a_ldap_attrs['goFonQualify'][0];
323 }
325 // Attribute GoFonPIN set ?
326 if(isset($this->goFonPIN)){
327 $s_pin = $this->goFonPIN;
328 }
330 // Attribute GoFonType set ?
331 if(isset($a_ldap_attrs['goFonType'])){
332 $s_type = $a_ldap_attrs['goFonType'][0];
333 }
335 if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
336 $sip_data_array['dtmfmode'] = $a_ldap_attrs['goFonDmtfMode'][0];
337 }else{
338 $sip_data_array['dtmfmode'] ="rfc2833";
339 }
341 // generate SIP entry
342 $sip_data_array['id'] = "";
343 $sip_data_array['name'] = $this->uid;
344 $sip_data_array['accountcode'] = NULL;
345 $sip_data_array['amaflags'] = NULL;
346 $sip_data_array['callgroup'] = NULL;
347 $sip_data_array['callerid'] = "";
348 $sip_data_array['canreinvite'] = "no";
349 $sip_data_array['context'] = "default";
350 $sip_data_array['defaultip'] = NULL;
351 $sip_data_array['fromuser'] = NULL;
352 $sip_data_array['fromdomain'] = NULL;
353 $sip_data_array['host'] = $s_host;
354 $sip_data_array['insecure'] = NULL;
355 $sip_data_array['language'] = NULL;
356 $sip_data_array['mailbox'] = "asterisk";
357 $sip_data_array['md5secret'] = NULL;
358 $sip_data_array['nat'] = "no";
359 $sip_data_array['permit'] = NULL;
360 $sip_data_array['deny'] = NULL;
361 $sip_data_array['mask'] = NULL;
362 $sip_data_array['pickupgroup'] = NULL;
363 $sip_data_array['port'] = NULL;
364 $sip_data_array['qualify'] = $s_qualify;
365 $sip_data_array['restrictcid'] = "n";
366 $sip_data_array['rtptimeout'] = NULL;
367 $sip_data_array['rtpholdtimeout']=NULL;
368 $sip_data_array['secret'] = $this->goFonPIN;
369 $sip_data_array['type'] = $s_type ;
370 $sip_data_array['username'] = $this->uid;
371 $sip_data_array['disallow'] = NULL;
372 $sip_data_array['allow'] = NULL;
373 $sip_data_array['musiconhold'] = NULL;
374 $sip_data_array['regseconds'] = NULL;
375 $sip_data_array['ipaddr'] = $s_ip;
376 $sip_data_array['regexten'] = NULL;
377 $sip_data_array['cancallforward']=NULL;
379 // Get selected Macro Parameter and create parameter entry
380 if(isset($this->macroarray[$this->macro])){
381 foreach($this->macroarray[$this->macro] as $key => $val ){
382 $s_parameter .= $val['choosen']."|";
383 }
384 $s_parameter = preg_replace("/\|$/","",$s_parameter);
385 }
387 if($this->is_number_used()){
388 $this->generate_error = $this->is_number_used();
389 return false;
390 }
392 // Create new SIP entry ...
393 $sip_entry = $sip_data_array;
394 reset($this->phoneNumbers);
395 $i_new_key = key($this->phoneNumbers);
396 $sip_entry['callerid'] =$this->phoneNumbers[$i_new_key];
397 $sip_entry['mailbox'] =$this->phoneNumbers[$i_new_key];
399 if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
400 $s_mail = $this->parent->by_object['mailAccount']->mail;
401 }else{
402 $s_mail = "";
403 }
406 // $SQL contains all queries
407 $SQL = array();
408 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
409 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
410 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$this->phoneNumbers[$i_new_key].";";
411 // Delete old entries
412 $b_first_deleted =false;
413 foreach($this->a_old_telenums as $s_telenums){
414 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
415 if(!$b_first_deleted){
416 $b_first_deleted=true;
417 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
418 }
419 }
422 if($this->goFonHardware=="automatic"){
423 foreach($SQL as $query ){
424 mysql_query($query) ;
425 }
426 return;
427 }
429 // Generate Strings with keys and values
430 foreach($sip_entry as $s_sip_key=>$s_sip_val){
431 if($s_sip_val == NULL) continue;
432 $s_sip_values.="'".$s_sip_val."',";
433 $s_sip_keys .="`".$s_sip_key."`,";
434 }
435 // Remove last ,
436 $s_sip_values = preg_replace("/,$/","",$s_sip_values);
437 $s_sip_keys = preg_replace("/,$/","",$s_sip_keys);
439 // Append SIP Entry
440 $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
442 /* If deletion starts from userslist, cn uid are not set */
443 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
444 $this->uid = $this->parent->by_object['user']->uid;
445 }
447 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
448 $this->cn = $this->parent->by_object['user']->cn;
449 }
451 if((!isset($this->cn))||(empty($this->cn))){
452 $CNname= $this->uid;
453 }else{
454 $CNname= $this->cn;
455 }
457 $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
458 VALUES ('".$this->phoneNumbers[$i_new_key]."',
459 'default',
460 '".$this->phoneNumbers[$i_new_key]."',
461 '".$this->goFonVoicemailPIN."',
462 '".$CNname."',
463 '".$s_mail."',
464 '');";
465 $i_is_accounted=false;
467 $i = 0;
469 $is_inserted_once = false;
471 // Entension entries Hint / Dial / Goto
472 foreach($this->phoneNumbers as $s_telenums){
474 if(!$is_inserted_once){
475 $is_inserted_once = true;
476 $EXT[$i]['context'] = 'GOsa';
477 $EXT[$i]['exten'] = $this->uid;
478 $EXT[$i]['priority']= 1;
479 $EXT[$i]['app'] = "Goto";
480 $EXT[$i]['appdata'] = $s_telenums."|1";
481 $i ++;
482 }
483 /* Hint Entry */
484 $EXT[$i]['context'] = 'GOsa';
485 $EXT[$i]['exten'] = $s_telenums;
486 $EXT[$i]['priority']= "Hint";
487 $EXT[$i]['app'] = 'SIP/'.$this->uid;
488 $i ++;
489 /* SetCID */
490 //$EXT[$i]['context'] = 'GOsa';
491 //$EXT[$i]['exten'] = $s_telenums;
492 //$EXT[$i]['priority']= 1;
493 //$EXT[$i]['app'] = "SetCIDName";
494 //$EXT[$i]['appdata'] = $CNname;
495 //$i ++;
497 // If no macro is selected use Dial
498 if($this->macro!="none"){
499 $macroname = preg_replace("/,.*$/","",$this->macro);
500 $macroname = preg_replace("/^.*=/","",$macroname);
501 $s_app = "Macro";$macroname;
502 $s_par = $macroname."|".$s_parameter;
503 }else{
504 $s_app = "Dial";
505 $s_par = 'SIP/'.$this->uid."|20|r";
506 }
508 $EXT[$i]['context'] = 'GOsa';
509 $EXT[$i]['exten'] = $s_telenums;
510 $EXT[$i]['priority']= 1;
511 $EXT[$i]['app'] = $s_app;
512 $EXT[$i]['appdata'] = $s_par;
513 $i ++;
515 }
517 // Append all these Entries
518 foreach($EXT as $entr){
519 $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
520 foreach($entr as $key2 => $val2){
521 $SQL_syn.= "`".$key2."`,";
522 }
523 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
524 $SQL_syn .= ") VALUES (";
525 foreach($entr as $key2 => $val2){
526 $SQL_syn .= "'".$val2."',";
527 }
528 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
529 $SQL_syn .=");\n";
530 $SQL[] =$SQL_syn;
531 $SQL_syn ="";
532 }
534 // Perform queries ...
535 foreach($SQL as $query){
536 if(!@mysql_query($query,$r_con)){
537 print_red(_("Error while performing query:")." ".mysql_error()));
538 return false;
539 }
540 }
541 }
542 @mysql_close($r_con);
543 return true;
544 }
547 function execute()
548 {
549 $display = "";
551 if(empty($this->macro)&&(!empty($this->goFonMacro))){
553 /* Go through already saved values, for a parameter */
554 $tmp = split("!",$this->goFonMacro);
556 /* it is possible that nothing has been saved yet */
557 if(is_array($tmp)){
559 /* First value is the macroname */
560 $this->macro = $tmp[0];
562 /* Macroname saved, delete that index */
563 unset($tmp[0]);
565 /* Check if makro has been removed */
566 if(!isset($this->macroarray[$this->macro])){
567 $this->macrostillavailable = false;
568 }else{
569 $this->macrostillavailable = true;
570 }
572 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
573 foreach($tmp as $var){
575 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
576 $varar = split("#",$var);
578 /* Only insert if the parameter still exists */
579 if(isset($this->macroarray[$this->macro][$varar[0]])){
580 /* Assign value */
581 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
582 }
583 }
584 }
585 }
587 /* Do we represent a valid account? */
588 if (!$this->is_account && $this->parent == NULL){
589 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
590 _("This account has no phone extensions.")."</b>";
591 $display.= back_to_main();
592 return ($display);
593 }
595 /* Do we need to flip is_account state? */
596 if (isset($_POST['modify_state'])){
597 $this->is_account= !$this->is_account;
598 }
600 /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
601 if(empty($this->macro)){
602 $this->macro ="none";
603 }
605 /* Prepare templating */
606 $smarty= get_smarty();
608 /* tell user that the pluging selected is no longer available*/
609 if((!$this->macrostillavailable)&&($this->macro!="none")){
610 print_red(_("The macro you selected, is no longer available for you, please choose another one."));
611 }
613 /* Assing macroselectbox values */
614 $smarty->assign("macros",$this->macros);
615 $smarty->assign("macro", $this->macro);
617 /* check if there is a FON server created */
618 if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
619 print_red(_("There is currently no asterisk server defined. Possibly you are missing a server that handles the asterisk management (goFonServer).\nYour Settings can't be saved to asterisk Database."));
620 }
622 /* Create parameter table, skip if no parameters given */
623 if(!isset($this->macroarray[$this->macro])){
624 $macrotab="";
625 }else{
627 $macrotab ="<table summary=\""._("Parameter")."\">";
628 /* for every single parameter-> display textfile,combo, or true false switch*/
631 /* Automatic fill out */
632 if(isset($_POST['fillout'])){
634 foreach($this->phoneNumbers as $phonenum){
635 $tmp[] = $phonenum;
636 }
638 /* Go through all params */
639 foreach($this->macroarray[$this->macro] as $key => $paras){
641 $string = $paras['default'];
643 $string=preg_replace("/%uid/i",$this->uid,$string);
645 if(isset($this->cn)){
646 $string=preg_replace("/%cn/i",$this->cn,$string);
647 }
649 for($i = 0 ; $i < 10; $i++){
650 if(isset($tmp[$i])){
651 $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
652 }
653 }
655 $this->macroarray[$this->macro][$key]['choosen']=$string;
656 }
657 }
659 foreach($this->macroarray[$this->macro] as $paras){
661 /* get al vars */
662 $var = $paras['var'];
663 $name = $paras['name'];
664 $default = $paras['default'];
665 $type = $paras['type'];
666 $choosen = $paras['choosen'] ;
667 $str = $default;
669 /* in case of a combo box display a combobox with selected attr */
670 $macrotab.= "<tr>";
671 switch ($type){
673 case "combo":
674 $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." ".chkacl($this->acl, "goFonMacro").">";
675 foreach(split(":",$default) as $choice){
676 if($choosen==$choice){
677 $str.= "\n<option value='".$choice."' selected>".$choice." </option>";
678 }else{
679 $str.= "\n<option value='".$choice."'>".$choice." </option>";
680 }
681 }
682 $str.="</select>";
683 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
684 break;
686 case "bool":
687 if(!$choosen){
688 $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
689 }else{
690 $str="\n<input type='checkbox' name='".$var."' value='1' checked ".chkacl($this->acl, "goFonMacro").">";
691 }
692 $macrotab.= "<td colspan='2'>$str ".base64_decode($name)."";
693 break;
695 case "string":
696 $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
697 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
698 break;
700 }
701 $macrotab.= "</td></tr>";
703 }
704 $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
705 }//is_array()
707 /* Give smarty the table */
708 $smarty->assign("macrotab",$macrotab);
710 /* Do we represent a valid account? */
711 if (!$this->is_account && $this->parent == NULL){
712 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
713 _("This account has no phone extensions.")."</b>";
714 $display.= back_to_main();
715 return($display);
716 }
718 $display= "";
720 /* Show tab dialog headers */
721 if ($this->parent != NULL){
722 if ($this->is_account){
723 $display= $this->show_header(_("Remove phone account"),
724 _("This account has phone features enabled. You can disable them by clicking below."));
725 } else {
726 if(empty($this->uid)){
727 $display= $this->show_header(_("Create phone account"),
728 _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
729 }else{
730 $display= $this->show_header(_("Create phone account"),
731 _("This account has phone features disabled. You can enable them by clicking below."));
732 }
733 return ($display);
734 }
735 }
737 /* Add phone number */
738 if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
739 if (is_phone_nr($_POST['phonenumber'])){
740 $number= $_POST["phonenumber"];
741 $this->phoneNumbers[$number]= $number;
742 $this->is_modified= TRUE;
743 } else {
744 print_red(_("Please enter a valid phone number!"));
745 }
746 }
748 /* Remove phone number */
749 if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
750 foreach ($_POST['phonenumber_list'] as $number){
751 unset($this->phoneNumbers[$number]);
752 $this->is_modified= TRUE;
753 }
754 }
756 /* Transfer ACL's */
757 foreach($this->attributes as $val){
758 $smarty->assign($val."ACL", chkacl($this->acl, "$val"));
759 if(isset($this->$val)){
760 $smarty->assign($val,$this->$val);
761 }else{
762 $smarty->assign($val,"");
763 }
764 }
766 /* Fill arrays */
767 $smarty->assign ("goFonHardware", $this->goFonHardware);
768 if (!count($this->phoneNumbers)){
769 $smarty->assign ("phoneNumbers", array(""));
770 } else {
771 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
772 }
773 $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
774 _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
775 foreach ($this->hardware_list as $cn => $description){
776 if ($cn == $this->goFonHardware){
777 $selected= "selected";
778 } else {
779 $selected= "";
780 }
781 if (isset($this->used_hardware[$cn])){
782 $color= "style=\"color:#A0A0A0\"";
783 } else {
784 $color= "";
785 }
786 $hl.= " <option $color label=\"$cn\" value=\"$cn\" $selected>$description </option>\n";
787 }
788 $hl.= "</select>\n";
789 $smarty->assign ("hardware_list", $hl);
791 /* Show main page */
793 $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
794 return($display);
795 }
798 function save_object()
799 {
800 if (isset($_POST["phoneTab"])){
801 plugin::save_object();
803 /* Save checkbox */
804 if (isset($_POST['fon_to_mail'])){
805 $tmp= "[M]";
806 } else {
807 $tmp= "[]";
808 }
809 if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
810 if ($this->goFonDeliveryMode != $tmp){
811 $this->is_modified= TRUE;
812 }
813 $this->goFonDeliveryMode= $tmp;
814 }
816 /* Every macro in the select box are available */
817 if((isset($_POST['macro']))){
818 $this->macrostillavailable=true;
819 }
821 if(is_array($this->phoneNumbers)){
822 foreach($this->phoneNumbers as $telenumms) {
823 $nummsinorder[]=$telenumms;
824 }
825 }else{
826 $nummsinorder=array("");
827 }
829 /* get all Postvars */
830 if(isset($this->macroarray[$this->macro])){
831 foreach($this->macroarray[$this->macro] as $key => $paras){
832 if(isset($_POST[$paras['var']])){
833 $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
834 }
836 /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
837 We need this code below to read and save checkboxes correct
838 */
840 if(isset($_POST['post_success'])){
841 if($this->macroarray[$this->macro][$key]['type']=="bool"){
842 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
843 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
844 }else{
845 $this->macroarray[$this->macro][$key]['choosen']=false;
846 }
847 }
848 }
849 }
850 }
851 }
852 }
854 function check()
855 {
856 /* Reset message array */
857 $message= array();
859 if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
860 $message[]=(_("Voicemail PIN must be between 1-4 characters."));
861 }else{
862 if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
863 $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
864 }
865 }
868 if((strlen($this->goFonPIN)!=4)){
869 $message[]=(_("Phone PIN must be 4 characters long."));
870 }else{
871 if(preg_match("/[^0-9]/",$this->goFonPIN)){
872 $message[]=(_("The specified phone PIN contains invalid characters, only numeric values are allowed here."));
873 }
874 }
876 if(!$this->generate_mysql_entension_entries()){
877 $message[] = $this->generate_error;
878 }
880 /* We need at least one phone number */
881 if (count($this->phoneNumbers) == 0){
882 $message[]= sprintf(_("You need to specify at least one phone number!"));
883 }
885 /* check for ! in any parameter setting*/
886 if(isset($this->macroarray[$this->macro])){
887 foreach($this->macroarray[$this->macro] as $val){
888 if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
889 $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
890 }
891 }
892 }
893 return ($message);
894 }
898 function save()
899 {
900 plugin::save();
902 /* Save arrays */
903 $this->attrs['telephoneNumber']= array();
904 foreach ($this->phoneNumbers as $number){
905 $this->attrs['telephoneNumber'][]= $number;
906 }
908 /* Save settings, or remove goFonMacro attribute*/
909 if($this->macro!="none"){
910 $this->attrs['goFonMacro']=$this->macro;
911 if(isset($this->macroarray[$this->macro])){
912 foreach($this->macroarray[$this->macro] as $paras) {
913 $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
914 }
915 }
916 }else{
917 $this->attrs['goFonMacro']=array();
918 }
919 unset($this->attrs['macro']) ;
921 $this->attrs['goFonForwarding']=array();
923 $this->generate_mysql_entension_entries(true);
925 if($this->attrs['goFonMacro']==""){
926 $this->attrs['goFonMacro']=array();
927 }
929 unset($this->attrs['cn']);
931 /* Write back to ldap */
932 $ldap= $this->config->get_ldap_link();
933 $ldap->cd($this->dn);
934 $ldap->modify($this->attrs);
935 show_ldap_error($ldap->get_error());
937 /* Optionally execute a command after we're done */
939 if ($this->initially_was_account == $this->is_account){
940 if ($this->is_modified){
941 $this->handle_post_events("modify");
942 }
943 } else {
944 $this->handle_post_events("add");
945 }
947 }
950 function insert_after($entry, $nr, $list)
951 {
952 /* Is the entry free? No? Make it free... */
953 if (isset($list[$nr])) {
954 $dest= array();
955 $newidx= 0;
957 foreach ($list as $idx => $contents){
958 $dest[$newidx++]= $contents;
959 if ($idx == $nr){
960 $dest[$newidx++]= $entry;
961 }
962 }
963 } else {
964 $dest= $list;
965 $dest[$nr]= $entry;
966 }
968 return ($dest);
969 }
972 function adapt_from_template($dn)
973 {
974 plugin::adapt_from_template($dn);
976 /* Assemble phone numbers */
977 if (isset($this->attrs['telephoneNumber'])){
978 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
979 $number= $this->attrs['telephoneNumber'][$i];
980 $this->phoneNumbers[$number]= $number;
981 }
982 }
983 }
986 function remove_from_parent()
987 {
989 foreach($this->attributes as $key=>$val){
990 if(in_array($val,array("uid","cn","mail"))){
991 unset($this->attributes[$key]);
992 unset($this->$val);
993 }
994 }
996 if(array_key_exists('config', $_SESSION) &&
997 array_key_exists('SERVERS', $_SESSION['config']->data) &&
998 array_key_exists('FON', $_SESSION['config']->data['SERVERS'])) {
999 // Get Configuration for Mysql database Server
1000 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
1001 $s_parameter ="";
1003 // Connect to DB server
1004 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1006 // Check if we are connected correctly
1007 if(!$r_con){
1008 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1009 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
1010 gosa_log(@mysql_error());
1011 return false;
1012 }
1014 // Select database for Extensions
1015 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
1017 // Test if we have the database selected correctly
1018 if(!$db){
1019 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
1020 gosa_log(@mysql_error());
1021 return false;
1022 }
1024 $SQL="";
1026 /* If deletion starts from userslist, cn uid are not set */
1027 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1028 $this->uid = $this->parent->by_object['user']->uid;
1029 }
1031 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1032 $this->cn = $this->parent->by_object['user']->cn;
1033 }
1035 $first_num = false;
1036 // Delete old entries
1037 foreach($this->a_old_telenums as $s_telenums){
1038 if(!$first_num){
1039 $first_num = $s_telenums;
1040 }
1041 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1042 }
1044 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1045 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1046 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1049 foreach($SQL as $query){
1050 if(!@mysql_query($query,$r_con)){
1051 print_red(_("Stop".mysql_error()));
1052 return false;
1053 }
1054 }
1055 }
1058 /* unset macro attr, it will cause an error */
1059 $tmp = array_flip($this->attributes);
1060 unset($tmp['macro']);
1061 $this->attributes=array_flip($tmp);
1063 /* Cancel if there's nothing to do here */
1064 if (!$this->initially_was_account){
1065 return;
1066 }
1068 plugin::remove_from_parent();
1070 /* Just keep one phone number */
1071 if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1072 $this->attrs['telephoneNumber']= $this->telephoneNumber;
1073 } else {
1074 $this->attrs['telephoneNumber']= array();
1075 }
1077 $ldap= $this->config->get_ldap_link();
1078 $ldap->cd($this->config->current['BASE']);
1079 $ldap->search("(objectClass=goFonQueue)", array("member"));
1080 while($attr = $ldap->fetch()){
1081 if(in_array($this->dn,$attr['member'])){
1082 $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1083 unset($new->by_object['ogroup']->memberList[$this->dn]);
1084 unset($new->by_object['ogroup']->member[$this->dn]);
1085 $new->save();
1086 print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1087 }
1088 }
1089 $ldap->cd($this->dn);
1090 $ldap->modify($this->attrs);
1091 show_ldap_error($ldap->get_error());
1093 /* Optionally execute a command after we're done */
1094 @mysql_close($r_con);
1095 $this->handle_post_events('remove');
1096 }
1100 /* This function checks if the given phonenumbers are available or already in use*/
1101 function is_number_used()
1102 {
1103 $ldap= $this->config->get_ldap_link();
1104 $ldap->cd($this->config->current['BASE']);
1105 $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1106 while($attrs = $ldap->fetch()) {
1107 unset($attrs['telephoneNumber']['count']);
1108 foreach($attrs['telephoneNumber'] as $tele){
1109 if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1110 if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1111 $numbers[$tele]=$attrs;
1112 }
1113 }
1115 foreach($this->phoneNumbers as $num){
1116 if(!isset($this->cn)) $this->cn = "";
1118 if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1119 if(isset($numbers[$num]['uid'][0])){
1120 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1121 }else{
1122 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1123 }
1124 }
1125 }
1126 }
1127 }
1129 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1130 ?>