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 $CopyPasteVars = array("phoneNumbers");
38 var $attributes = array("goFonDeliveryMode", "goFonFormat","uid","cn",
39 "goFonHardware","goFonPIN","goFonVoicemailPIN",
40 "telephoneNumber", "goFonMacro","macro");
41 var $objectclasses= array("goFonAccount");
43 var $uid ="";
45 function phoneAccount ($config, $dn= NULL, $parent= NULL)
46 {
47 plugin::plugin ($config, $dn, $parent);
49 /* Set uid, it is used in handle_post_events */
50 if(isset($this->attrs['uid'])){
51 $this->uid = $this->attrs['uid'][0];
52 }
54 /* Set phone hardware */
55 if (!isset($this->attrs['goFonHardware'])){
56 $this->goFonHardware= "automatic";
57 }
59 /* Preset voice format */
60 if (!isset($this->attrs['goFonFormat'])){
61 $this->goFonFormat= "wav";
62 }
64 /* Assemble phone numbers */
65 if (isset($this->attrs['telephoneNumber'])){
66 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
67 $number= $this->attrs['telephoneNumber'][$i];
68 $this->phoneNumbers[$number]= $number;
69 }
70 }
72 /* Set up has_mailAccount */
73 if (isset($this->attrs['objectClass'])){
74 if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
75 $this->has_mailAccount= TRUE;
76 }
77 }
79 $a_SETUP= array();
80 if(array_key_exists('config',$_SESSION) &&
81 array_key_exists('SERVERS',$_SESSION['config']->data) &&
82 array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
83 is_callable("mysql_connect")
84 ) {
85 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
86 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
87 if(!$r_con){
88 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
89 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
90 gosa_log(mysql_error());
91 return false;
92 }
93 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
94 if(!$db){
95 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
96 gosa_log(mysql_error());
97 return false;
98 }
100 $first = false;
101 foreach($this->phoneNumbers as $key => $val){
102 if(!$first){
103 $first = $key;
104 }
105 }
106 }
108 /* Load hardware list */
109 $ldap= $this->config->get_ldap_link();
110 $ldap->cd($this->config->current['BASE']);
111 $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
112 while ($attrs= $ldap->fetch()){
113 $cn= $attrs['cn'][0];
114 if (isset($attrs['description'])){
115 $description= " - ".$attrs['description'][0];
116 } else {
117 $description= "";
118 }
119 $this->hardware_list[$cn]= "$cn$description";
121 }
123 /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
124 $ldap->search("(objectClass=goFonMacro)", array("*"));
126 /* Add none for no macro*/
127 $this->macros['none']=_("no macro");
128 $this->macro ="none";
131 /* Fetch all Macros*/
132 while ($attrs= $ldap->fetch()){
134 /* Only visisble */
135 if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
137 /* unset Count, we don't need that here */
138 unset($attrs['displayName']['count']);
140 /* fill Selectfield variable with Macros */
141 if(isset($attrs['displayName'][0])){
142 $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
143 }else{
144 $this->macros[$attrs['dn']] = _("undefined");
145 }
147 /* Parse macro data, unset count for parameterarrays */
148 if (isset($attrs['goFonMacroParameter']['count'])){
149 unset($attrs['goFonMacroParameter']['count']);
150 }
152 /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
153 if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
155 foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
156 /* Split Data in readable values, by delimiter ! */
157 $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
159 /* Set all attrs */
160 $id = $data[0];
161 $this->macroarray[$attrs['dn']][$id]['var'] ="var".$id;
162 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
163 $this->macroarray[$attrs['dn']][$id]['id'] =$id;
164 $this->macroarray[$attrs['dn']][$id]['name'] =$data[1];
165 $this->macroarray[$attrs['dn']][$id]['type'] =$data[2];
166 $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
167 if($data[2] == "bool"){
168 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
169 }
170 }//foreach
171 }//is_array
172 }//visible = 1
173 }//while
175 /* Go through already saved values, for a parameter */
176 $tmp = split("!",$this->goFonMacro);
178 /* it is possible that nothing has been saved yet */
179 if(is_array($tmp)){
181 /* First value is the macroname */
182 $this->macro = $tmp[0];
184 /* Macroname saved, delete that index */
185 unset($tmp[0]);
187 /* Check if makro has been removed */
188 if(!isset($this->macroarray[$this->macro])){
189 $this->macrostillavailable = false;
190 }else{
191 $this->macrostillavailable = true;
192 }
194 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
195 foreach($tmp as $var){
197 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
198 $varar = split("#",$var);
200 /* Only insert if the parameter still exists */
201 if(isset($this->macroarray[$this->macro][$varar[0]])){
202 /* Assign value */
203 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
204 }
205 }
206 }
209 /* Eventually colorize phones */
210 $ldap->cd($this->config->current['BASE']);
211 foreach ($this->hardware_list as $cn => $desc){
212 $ldap->search("(goFonHardware=$cn)", array('cn'));
213 if ($ldap->count() > 0){
214 $ldap->fetch();
215 if ($ldap->getDN() != $this->dn){
216 $this->used_hardware[$cn]= $ldap->getDN();
217 }
218 }
219 }
220 $this->hardware_list["automatic"]= _("automatic");
221 ksort($this->hardware_list);
222 $this->a_old_telenums = $this->phoneNumbers;
224 if($this->is_account){
225 $this->is_modified = true;
226 }
229 /* Get voicemail PIN from MySQL DB
230 * Because every user can change his PIN directly from the phone
231 * without any update to the ldap
232 * This means, the PIN in the DB is up to date
233 */
234 // Connect to DB server
235 if((is_callable("mysql_pconnect"))&&(isset($a_SETUP))&&(isset($a_SETUP['SERVER']))&&(isset($a_SETUP['LOGIN']))&&(isset($a_SETUP['PASSWORD']))){
236 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
237 if($r_con){
238 $r_db = @mysql_select_db($a_SETUP['DB'],$r_con);
239 $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."'"));
241 if((isset($vp[0]))&&(!empty($vp[0]))){
242 $this->goFonPINVoice = $vp[0];
243 }
244 }
245 }
246 $this->lastmacro=$this->macro;
248 if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
249 @mysql_close($r_con) ;
250 }
251 }
254 // Generate MySQL Syntax
255 function generate_mysql_entension_entries($save = false){
257 if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
258 if($save)
259 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."));
260 return(true);
261 }
263 if(!is_callable("mysql_pconnect")){
264 if($save)
265 print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
266 return(true);
267 }
269 // Get Configuration for Mysql database Server
270 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON']; // DB Configuration
271 $s_parameter = ""; // Contains paramter for selected Macro
272 $r_con = false; // DB connection
273 $r_db = false; // Selected DB
274 $r_res = false; // Result resource
275 $a_ldap_attrs = array(); //
277 $s_ip = NULL; // Contains ip for Sip entry
278 $s_host = NULL; // Contains host for Sip entry
279 $s_qualify = "yes"; // Qualify entry
280 $s_pin = NULL; // Entry for secret
281 $s_type = NULL; // Entry for phone type (friend , peer ..)
283 $sip_data_array = array(); // Contains complete sip entry, to generate SQL syntax
284 $i_old_key = false; // Contains index for first old phonenumber, to delete old entries corectly
285 $i_new_key = false; // Contains index for first new phonenumber, to generate new entries corectly
287 $s_sip_values = ""; // Contains string with all values for given attributes in SQL syntax
288 $s_sip_keys = ""; // Contains all needed attributes to generate sip entry in DB
290 $s_sip_key = ""; // Key for SIP entry index
291 $s_sip_val = ""; // Value for SIP entry index
293 $b_first_deleted= false; // Only delete first entry,
294 $s_telenums = ""; // for each value variable
296 $i_is_accounted = false; // Ensure that extension entry, for name to number is only once in table
299 // Connect to DB server
300 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
302 // Check if we are connected correctly
303 if(!$r_con){
304 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
305 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
306 gosa_log(mysql_error());
307 return false;
308 }
310 // Select database for Extensions
311 $r_db = @mysql_select_db($a_SETUP['DB'],$r_con);
313 // Test if we have the database selected correctly
314 if(!$r_db){
315 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
316 gosa_log(mysql_error());
317 return false;
318 }
320 // Get phonehardware to setup sip entry
321 $ldap = $this->config->get_ldap_link();
322 $r_res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
323 $a_ldap_attrs = $ldap->fetch();
325 if($this->is_number_used()){
326 $this->generate_error = $this->is_number_used();
327 return false;
328 }
330 /* If Save == true, we should save something.
331 * Generate SQL, for drop of old entries
332 * Generate SQL, for insert new entries
333 */
334 if($save == true){
336 foreach($this->a_old_telenums as $tele){
337 $oldnums[]= preg_replace("/[^0-9]/","",$tele);
338 }
340 foreach($this->phoneNumbers as $tele){
341 $newnums[]= preg_replace("/[^0-9]/","",$tele);
342 }
344 // Attribute GoFonDefaultIP set ?
345 if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
346 $s_ip = $a_ldap_attrs['goFonDefaultIP'][0];
347 $s_host = $s_ip;
348 }else{
349 $s_ip = NULL;
350 $s_host = "dynamic";
351 }
353 // Attribute GoFonQualify set ?
354 if(isset($a_ldap_attrs['goFonQualify'])){
355 $s_qualify = $a_ldap_attrs['goFonQualify'][0];
356 }
358 // Attribute GoFonPIN set ?
359 if(isset($this->goFonPIN)){
360 $s_pin = $this->goFonPIN;
361 }
363 // Attribute GoFonType set ?
364 if(isset($a_ldap_attrs['goFonType'])){
365 $s_type = $a_ldap_attrs['goFonType'][0];
366 }
368 if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
369 $sip_data_array['dtmfmode'] = $a_ldap_attrs['goFonDmtfMode'][0];
370 }else{
371 $sip_data_array['dtmfmode'] ="rfc2833";
372 }
374 // generate SIP entry
375 $sip_data_array['id'] = "";
376 $sip_data_array['name'] = $this->uid;
377 $sip_data_array['accountcode'] = NULL;
378 $sip_data_array['amaflags'] = NULL;
379 $sip_data_array['callgroup'] = NULL;
380 $sip_data_array['callerid'] = "";
381 $sip_data_array['canreinvite'] = "no";
382 $sip_data_array['context'] = "default";
383 $sip_data_array['defaultip'] = NULL;
384 $sip_data_array['fromuser'] = NULL;
385 $sip_data_array['fromdomain'] = NULL;
386 $sip_data_array['host'] = $s_host;
387 $sip_data_array['insecure'] = NULL;
388 $sip_data_array['language'] = NULL;
389 $sip_data_array['mailbox'] = "asterisk";
390 $sip_data_array['md5secret'] = NULL;
391 $sip_data_array['nat'] = "no";
392 $sip_data_array['permit'] = NULL;
393 $sip_data_array['deny'] = NULL;
394 $sip_data_array['mask'] = NULL;
395 $sip_data_array['pickupgroup'] = NULL;
396 $sip_data_array['port'] = NULL;
397 $sip_data_array['qualify'] = $s_qualify;
398 $sip_data_array['restrictcid'] = "n";
399 $sip_data_array['rtptimeout'] = NULL;
400 $sip_data_array['rtpholdtimeout']=NULL;
401 $sip_data_array['secret'] = $this->goFonPIN;
402 $sip_data_array['type'] = $s_type ;
403 $sip_data_array['username'] = $this->uid;
404 $sip_data_array['disallow'] = NULL;
405 $sip_data_array['allow'] = NULL;
406 $sip_data_array['musiconhold'] = NULL;
407 $sip_data_array['regseconds'] = NULL;
408 $sip_data_array['ipaddr'] = $s_ip;
409 $sip_data_array['regexten'] = NULL;
410 $sip_data_array['cancallforward']=NULL;
412 // Get selected Macro Parameter and create parameter entry
413 if(isset($this->macroarray[$this->macro])){
414 foreach($this->macroarray[$this->macro] as $key => $val ){
415 $s_parameter .= $val['choosen']."|";
416 }
417 $s_parameter = preg_replace("/\|$/","",$s_parameter);
418 }
420 if($this->is_number_used()){
421 $this->generate_error = $this->is_number_used();
422 return false;
423 }
425 // Create new SIP entry ...
426 $sip_entry = $sip_data_array;
427 reset($newnums);
428 $i_new_key = key($newnums);
429 $sip_entry['callerid'] =$newnums[$i_new_key];
430 $sip_entry['mailbox'] =$newnums[$i_new_key];
432 if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
433 $s_mail = $this->parent->by_object['mailAccount']->mail;
434 }else{
435 $s_mail = "";
436 }
438 // $SQL contains all queries
439 $SQL = array();
440 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
441 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
442 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$newnums[$i_new_key].";";
443 // Delete old entries
444 $b_first_deleted =false;
445 if(isset($oldnums) && is_array($oldnums)){
446 foreach($oldnums as $s_telenums){
447 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
448 if(!$b_first_deleted){
449 $b_first_deleted=true;
450 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
451 }
452 }
453 }
454 if($this->goFonHardware=="automatic"){
455 foreach($SQL as $query ){
456 mysql_query($query) ;
457 }
458 return;
459 }
461 // Generate Strings with keys and values
462 foreach($sip_entry as $s_sip_key=>$s_sip_val){
463 if($s_sip_val == NULL) continue;
464 $s_sip_values.="'".$s_sip_val."',";
465 $s_sip_keys .="`".$s_sip_key."`,";
466 }
467 // Remove last ,
468 $s_sip_values = preg_replace("/,$/","",$s_sip_values);
469 $s_sip_keys = preg_replace("/,$/","",$s_sip_keys);
471 // Append SIP Entry
472 $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
474 /* If deletion starts from userslist, cn uid are not set */
475 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
476 $this->uid = $this->parent->by_object['user']->uid;
477 }
479 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
480 $this->cn = $this->parent->by_object['user']->cn;
481 }
483 if((!isset($this->cn))||(empty($this->cn))){
484 $CNname= $this->uid;
485 }else{
486 $CNname= $this->cn;
487 }
489 $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
490 VALUES ('".$newnums[$i_new_key]."',
491 'default',
492 '".$newnums[$i_new_key]."',
493 '".$this->goFonVoicemailPIN."',
494 '".$CNname."',
495 '".$s_mail."',
496 '');";
497 $i_is_accounted=false;
499 $i = 0;
501 $is_inserted_once = false;
503 // Entension entries Hint / Dial / Goto
504 foreach($newnums as $s_telenums){
506 if(!$is_inserted_once){
507 $is_inserted_once = true;
508 $EXT[$i]['context'] = 'GOsa';
509 $EXT[$i]['exten'] = $this->uid;
510 $EXT[$i]['priority']= 1;
511 $EXT[$i]['app'] = "Goto";
512 $EXT[$i]['appdata'] = $s_telenums."|1";
513 $i ++;
514 }
515 /* Hint Entry */
516 $EXT[$i]['context'] = 'GOsa';
517 $EXT[$i]['exten'] = $s_telenums;
518 $EXT[$i]['priority']= "Hint";
519 $EXT[$i]['app'] = 'SIP/'.$this->uid;
520 $i ++;
521 /* SetCID */
522 //$EXT[$i]['context'] = 'GOsa';
523 //$EXT[$i]['exten'] = $s_telenums;
524 //$EXT[$i]['priority']= 1;
525 //$EXT[$i]['app'] = "SetCIDName";
526 //$EXT[$i]['appdata'] = $CNname;
527 //$i ++;
529 // If no macro is selected use Dial
530 if($this->macro!="none"){
531 $macroname = preg_replace("/,.*$/","",$this->macro);
532 $macroname = preg_replace("/^.*=/","",$macroname);
533 $s_app = "Macro";$macroname;
534 $s_par = $macroname."|".$s_parameter;
535 }else{
536 $s_app = "Dial";
537 $s_par = 'SIP/'.$this->uid."|20|r";
538 }
540 $EXT[$i]['context'] = 'GOsa';
541 $EXT[$i]['exten'] = $s_telenums;
542 $EXT[$i]['priority']= 1;
543 $EXT[$i]['app'] = $s_app;
544 $EXT[$i]['appdata'] = $s_par;
545 $i ++;
547 }
549 // Append all these Entries
550 foreach($EXT as $entr){
551 $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
552 foreach($entr as $key2 => $val2){
553 $SQL_syn.= "`".$key2."`,";
554 }
555 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
556 $SQL_syn .= ") VALUES (";
557 foreach($entr as $key2 => $val2){
558 $SQL_syn .= "'".$val2."',";
559 }
560 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
561 $SQL_syn .=");\n";
562 $SQL[] =$SQL_syn;
563 $SQL_syn ="";
564 }
566 // Perform queries ...
567 foreach($SQL as $query){
568 if(!@mysql_query($query,$r_con)){
569 print_red(_("Error while performing query:")." ".mysql_error());
570 return false;
571 }
572 }
573 }
574 @mysql_close($r_con);
575 return true;
576 }
579 function execute()
580 {
581 /* Call parent execute */
582 plugin::execute();
584 $display = "";
586 $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
588 if(empty($this->macro)&&(!empty($this->goFonMacro))){
590 /* Go through already saved values, for a parameter */
591 $tmp = split("!",$this->goFonMacro);
593 /* it is possible that nothing has been saved yet */
594 if(is_array($tmp)){
596 /* First value is the macroname */
597 $this->macro = $tmp[0];
599 /* Macroname saved, delete that index */
600 unset($tmp[0]);
602 /* Check if makro has been removed */
603 if(!isset($this->macroarray[$this->macro])){
604 $this->macrostillavailable = false;
605 }else{
606 $this->macrostillavailable = true;
607 }
609 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
610 foreach($tmp as $var){
612 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
613 $varar = split("#",$var);
615 /* Only insert if the parameter still exists */
616 if(isset($this->macroarray[$this->macro][$varar[0]])){
617 /* Assign value */
618 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
619 }
620 }
621 }
622 }
624 /* Do we represent a valid account? */
625 if (!$this->is_account && $this->parent == NULL){
626 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
627 _("This account has no phone extensions.")."</b>";
628 $display.= back_to_main();
629 return ($display);
630 }
632 /* Do we need to flip is_account state? */
633 if (isset($_POST['modify_state'])){
634 $this->is_account= !$this->is_account;
635 }
637 /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
638 if(empty($this->macro)){
639 $this->macro ="none";
640 }
642 /* Prepare templating */
643 $smarty= get_smarty();
645 /* tell user that the pluging selected is no longer available*/
646 if((!$this->macrostillavailable)&&($this->macro!="none")){
647 print_red(_("The macro you selected, is no longer available for you, please choose another one."));
648 }
650 /* Assing macroselectbox values */
651 $smarty->assign("macros",$this->macros);
652 $smarty->assign("macro", $this->macro);
654 /* check if there is a FON server created */
655 if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
656 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."));
657 }
659 /* Create parameter table, skip if no parameters given */
660 if(!isset($this->macroarray[$this->macro])){
661 $macrotab="";
662 }else{
664 $macrotab ="<table summary=\""._("Parameter")."\">";
665 /* for every single parameter-> display textfile,combo, or true false switch*/
667 foreach($this->phoneNumbers as $phonenum){
668 $tmp[] = $phonenum;
669 }
673 if($this->macro != $this->lastmacro){
674 /* Go through all params */
675 foreach($this->macroarray[$this->macro] as $key => $paras){
677 $string = $paras['default'];
679 $string=preg_replace("/%uid/i",$this->uid,$string);
681 if(isset($this->cn)){
682 $string=preg_replace("/%cn/i",$this->cn,$string);
683 }
685 for($i = 0 ; $i < 10; $i++){
686 if(isset($tmp[$i])){
687 $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
688 }
689 }
690 if(isset($tmp[0])){
691 $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
692 }
693 $this->macroarray[$this->macro][$key]['choosen']=$string;
694 }
695 }
697 foreach($this->macroarray[$this->macro] as $paras){
699 /* get al vars */
700 $var = $paras['var'];
701 $name = $paras['name'];
702 $default = $paras['default'];
703 $type = $paras['type'];
704 $choosen = $paras['choosen'] ;
705 $str = $default;
707 $dis = "";
708 if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
709 $dis = " disabled ";
710 }
712 /* in case of a combo box display a combobox with selected attr */
713 $macrotab.= "<tr>";
714 switch ($type){
716 case "combo":
717 $str= "<select name='".$var."' ".$dis.">";
718 foreach(split(":",$default) as $choice){
719 if($choosen==$choice){
720 $str.= "\n<option value='".$choice."' selected>".$choice." </option>";
721 }else{
722 $str.= "\n<option value='".$choice."'>".$choice." </option>";
723 }
724 }
725 $str.="</select>";
726 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
727 break;
729 case "bool":
730 if(!$choosen){
731 $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis.">";
732 }else{
733 $str="\n<input type='checkbox' name='".$var."' value='1' checked ".$dis.">";
734 }
735 $macrotab.= "<td colspan='2'>$str ".base64_decode($name)."";
736 break;
738 case "string":
739 $str="<input name='".$var."' value='".$choosen."' style='width:340px;' ".$dis.">";
740 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
741 break;
743 }
744 $macrotab.= "</td></tr>";
746 }
747 $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
748 }//is_array()
750 /* Give smarty the table */
751 $smarty->assign("macrotab",$macrotab);
753 /* Do we represent a valid account? */
754 if (!$this->is_account && $this->parent == NULL){
755 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
756 _("This account has no phone extensions.")."</b>";
757 $display.= back_to_main();
758 return($display);
759 }
761 $display= "";
763 /* Show tab dialog headers */
764 if ($this->parent != NULL){
765 if ($this->is_account){
766 $display= $this->show_disable_header(_("Remove phone account"),
767 _("This account has phone features enabled. You can disable them by clicking below."));
768 } else {
769 if(empty($this->uid)){
770 $display= $this->show_enable_header(_("Create phone account"),
771 _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
772 }else{
773 $display= $this->show_enable_header(_("Create phone account"),
774 _("This account has phone features disabled. You can enable them by clicking below."));
775 }
776 return ($display);
777 }
778 }
780 /* Add phone number */
781 if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
782 if (is_phone_nr($_POST['phonenumber'])){
783 $number= $_POST["phonenumber"];
784 $this->phoneNumbers[$number]= $number;
785 $this->is_modified= TRUE;
786 } else {
787 print_red(_("Please enter a valid phone number!"));
788 }
789 }
791 /* Remove phone number */
792 if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
793 foreach ($_POST['phonenumber_list'] as $number){
794 unset($this->phoneNumbers[$number]);
795 $this->is_modified= TRUE;
796 }
797 }
799 /* Transfer ACL's */
800 foreach($this->attributes as $val){
801 $smarty->assign($val."ACL",$this->getacl($val,$SkipWrite));
802 if(isset($this->$val)){
803 $smarty->assign($val,$this->$val);
804 }else{
805 $smarty->assign($val,"");
806 }
807 }
809 /* Fill arrays */
810 $smarty->assign ("goFonHardware", $this->goFonHardware);
811 if (!count($this->phoneNumbers)){
812 $smarty->assign ("phoneNumbers", array(""));
813 } else {
814 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
815 }
818 $dis = "";
819 if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
820 $dis= " disabled ";
821 }
822 $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
823 _("Choose your private phone")."\">\n";
824 foreach ($this->hardware_list as $cn => $description){
826 if ($cn == $this->goFonHardware){
827 $selected= "selected";
828 } else {
829 $selected= "";
830 }
832 if (isset($this->used_hardware[$cn])){
833 $color= "style=\"color:#A0A0A0\"";
834 } else {
835 $color= "";
836 }
837 $hl.= " <option $color label=\"$cn\" value=\"$cn\" $selected>$description </option>\n";
838 }
839 $hl.= "</select>\n";
840 $smarty->assign ("hardware_list", $hl);
842 /* Show main page */
843 $this->lastmacro = $this->macro;
844 $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
845 return($display);
846 }
849 function save_object()
850 {
851 $SkipWrite = (!isset($this->parent) || !$this->parent) && !isset($_SESSION['edit']);
852 if (isset($_POST["phoneTab"])){
853 plugin::save_object();
855 /* Every macro in the select box are available */
856 if((isset($_POST['macro']))){
857 $this->macrostillavailable=true;
858 }
860 if(is_array($this->phoneNumbers)){
861 foreach($this->phoneNumbers as $telenumms) {
862 $nummsinorder[]=$telenumms;
863 }
864 }else{
865 $nummsinorder=array("");
866 }
869 /* Save checkbox */
870 $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
871 if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
872 if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
873 $tmp .= "M";
874 }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
875 $tmp = preg_replace ("/M/","",$tmp);
876 }
877 }
878 $this->goFonDeliveryMode= "[".$tmp."]";
882 /* get all Postvars */
883 if(isset($this->macroarray[$this->macro])){
884 if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
885 foreach($this->macroarray[$this->macro] as $key => $paras){
886 if(isset($_POST[$paras['var']])){
887 $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
888 }
890 /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
891 We need this code below to read and save checkboxes correct
892 */
894 if(isset($_POST['post_success'])){
895 if($this->macroarray[$this->macro][$key]['type']=="bool"){
896 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
897 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
898 }else{
899 $this->macroarray[$this->macro][$key]['choosen']=false;
900 }
901 }
902 }
903 }
904 }
905 }
906 }
907 }
909 function check()
910 {
911 /* Call common method to give check the hook */
912 $message= plugin::check();
914 if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
915 $message[]=(_("Voicemail PIN must be between 1-4 characters."));
916 }else{
917 if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
918 $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
919 }
920 }
922 if((strlen($this->goFonPIN)<=0)){
923 $message[]=(_("Phone PIN must be at least one character long."));
924 }else{
925 if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
926 $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
927 }
928 }
930 if(!$this->generate_mysql_entension_entries()){
931 $message[] = $this->generate_error;
932 }
934 /* We need at least one phone number */
935 if (count($this->phoneNumbers) == 0){
936 $message[]= sprintf(_("You need to specify at least one phone number!"));
937 }
939 /* check for ! in any parameter setting*/
940 if(isset($this->macroarray[$this->macro])){
941 foreach($this->macroarray[$this->macro] as $val){
942 if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
943 $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
944 }
945 }
946 }
947 return ($message);
948 }
952 function save()
953 {
954 plugin::save();
956 /* Save arrays */
957 $this->attrs['telephoneNumber']= array();
958 foreach ($this->phoneNumbers as $number){
959 $this->attrs['telephoneNumber'][]= $number;
960 }
962 /* Save settings, or remove goFonMacro attribute*/
963 if($this->macro!="none"){
964 $this->attrs['goFonMacro']=$this->macro;
965 if(isset($this->macroarray[$this->macro])){
966 foreach($this->macroarray[$this->macro] as $paras) {
967 $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
968 }
969 }
970 }else{
971 $this->attrs['goFonMacro']=array();
972 }
973 unset($this->attrs['macro']) ;
975 $this->attrs['goFonForwarding']=array();
977 $this->generate_mysql_entension_entries(true);
979 if($this->attrs['goFonMacro']==""){
980 $this->attrs['goFonMacro']=array();
981 }
983 unset($this->attrs['cn']);
985 /* Write back to ldap */
986 $ldap= $this->config->get_ldap_link();
987 $ldap->cd($this->dn);
988 $this->cleanup();
989 $ldap->modify ($this->attrs);
991 show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/phone account with dn '%s' failed."),$this->dn));
993 /* Optionally execute a command after we're done */
995 if ($this->initially_was_account == $this->is_account){
996 if ($this->is_modified){
997 $this->handle_post_events("modify",array("uid"=> $this->uid));
998 }
999 } else {
1000 $this->handle_post_events("add",array("uid" => $this->uid));
1001 }
1003 }
1006 function insert_after($entry, $nr, $list)
1007 {
1008 /* Is the entry free? No? Make it free... */
1009 if (isset($list[$nr])) {
1010 $dest= array();
1011 $newidx= 0;
1013 foreach ($list as $idx => $contents){
1014 $dest[$newidx++]= $contents;
1015 if ($idx == $nr){
1016 $dest[$newidx++]= $entry;
1017 }
1018 }
1019 } else {
1020 $dest= $list;
1021 $dest[$nr]= $entry;
1022 }
1024 return ($dest);
1025 }
1028 function adapt_from_template($dn)
1029 {
1030 plugin::adapt_from_template($dn);
1032 /* Assemble phone numbers */
1033 if (isset($this->attrs['telephoneNumber'])){
1034 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1035 $number= $this->attrs['telephoneNumber'][$i];
1036 $this->phoneNumbers[$number]= $number;
1037 }
1038 }
1039 }
1042 function remove_from_parent()
1043 {
1044 if(!$this->initially_was_account) return;
1046 foreach($this->attributes as $key=>$val){
1047 if(in_array($val,array("uid","cn"))){
1048 unset($this->attributes[$key]);
1049 unset($this->$val);
1050 }
1051 }
1052 if(array_key_exists('config', $_SESSION) &&
1053 array_key_exists('SERVERS', $_SESSION['config']->data) &&
1054 array_key_exists('FON', $_SESSION['config']->data['SERVERS']) &&
1055 is_callable("mysql_pconnect")) {
1056 // Get Configuration for Mysql database Server
1057 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
1058 $s_parameter ="";
1060 // Connect to DB server
1061 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1063 // Check if we are connected correctly
1064 if(!$r_con){
1065 print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1066 $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1067 gosa_log(@mysql_error());
1068 return false;
1069 }
1071 // Select database for Extensions
1072 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
1074 // Test if we have the database selected correctly
1075 if(!$db){
1076 print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1077 gosa_log(@mysql_error());
1078 return false;
1079 }
1081 $SQL="";
1083 /* If deletion starts from userslist, cn uid are not set */
1084 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1085 $this->uid = $this->parent->by_object['user']->uid;
1086 }
1088 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1089 $this->cn = $this->parent->by_object['user']->cn;
1090 }
1092 $first_num = false;
1093 // Delete old entries
1094 foreach($this->a_old_telenums as $s_telenums){
1095 if(!$first_num){
1096 $first_num = $s_telenums;
1097 }
1098 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1099 }
1101 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1102 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1103 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1105 foreach($SQL as $query){
1106 if(!@mysql_query($query,$r_con)){
1107 print_red(_("Stop".mysql_error()));
1108 return false;
1109 }
1110 }
1111 }else{
1112 print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1113 return false;
1114 }
1116 /* unset macro attr, it will cause an error */
1117 $tmp = array_flip($this->attributes);
1118 unset($tmp['macro']);
1119 $this->attributes=array_flip($tmp);
1121 /* Cancel if there's nothing to do here */
1122 if (!$this->initially_was_account){
1123 return;
1124 }
1126 plugin::remove_from_parent();
1128 /* Just keep one phone number */
1129 if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1130 $this->attrs['telephoneNumber']= $this->telephoneNumber;
1131 } else {
1132 $this->attrs['telephoneNumber']= array();
1133 }
1136 $ldap= $this->config->get_ldap_link();
1137 $ldap->cd($this->config->current['BASE']);
1138 $ldap->search("(objectClass=goFonQueue)", array("member"));
1139 while($attr = $ldap->fetch()){
1140 if(in_array($this->dn,$attr['member'])){
1141 $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1142 unset($new->by_object['ogroup']->memberList[$this->dn]);
1143 unset($new->by_object['ogroup']->member[$this->dn]);
1144 $new->save();
1145 print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1146 }
1147 }
1148 $ldap->cd($this->dn);
1149 $this->cleanup();
1150 $ldap->modify ($this->attrs);
1152 show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/phone account with dn '%s' failed."),$this->dn));
1154 /* Optionally execute a command after we're done */
1155 @mysql_close($r_con);
1156 $this->handle_post_events('remove',array("uid" => $this->uid));
1157 }
1161 /* This function checks if the given phonenumbers are available or already in use*/
1162 function is_number_used()
1163 {
1164 $ldap= $this->config->get_ldap_link();
1165 $ldap->cd($this->config->current['BASE']);
1166 $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1167 while($attrs = $ldap->fetch()) {
1168 unset($attrs['telephoneNumber']['count']);
1169 foreach($attrs['telephoneNumber'] as $tele){
1170 if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1171 if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1172 $numbers[$tele]=$attrs;
1173 }
1174 }
1176 foreach($this->phoneNumbers as $num){
1177 if(!isset($this->cn)) $this->cn = "";
1179 if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1180 if(isset($numbers[$num]['uid'][0])){
1181 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1182 }else{
1183 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1184 }
1185 }
1186 }
1187 }
1190 /* Create phoneAccount part of copy & paste dialog */
1191 function getCopyDialog()
1192 {
1193 if(!$this->is_account) return("");
1194 $smarty = get_smarty();
1195 if (!count($this->phoneNumbers)){
1196 $smarty->assign ("phoneNumbers", array(""));
1197 } else {
1198 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1199 }
1201 $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1202 $smarty->assign("goFonPIN",$this->goFonPIN);
1204 $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1205 $ret =array();
1206 $ret['string'] = $display;
1207 $ret['status'] = "";
1208 return($ret);
1209 }
1211 /* Save posts from copy & paste dialog dialog */
1212 function saveCopyDialog()
1213 {
1214 if(!$this->is_account) return;
1215 $this->execute();
1216 if(isset($_POST['goFonVoicemailPIN'])) {
1217 $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1218 }
1219 if(isset($_POST['goFonPIN'])){
1220 $this->goFonPIN = $_POST['goFonPIN'];
1221 }
1222 }
1225 /* Return plugin informations for acl handling */
1226 function plInfo()
1227 {
1228 return (array(
1229 "plShortName" => _("Phone"),
1230 "plDescription" => _("Phone account settings"),
1231 "plSelfModify" => TRUE,
1232 "plDepends" => array("user"),
1233 "plPriority" => 7, // Position in tabs
1234 "plSection" => "personal", // This belongs to personal
1235 "plCategory" => array("users"),
1236 "plOptions" => array(),
1238 "plProvidedAcls" => array(
1239 "telephoneNumber" => _("Telephone number"),
1240 "goFonMacro" => _("Macro settings"),
1241 "goFonHardware" => _("Phone hardware"),
1242 "goFonPIN" => _("Telephone pin"),
1243 "goFonVoicemailPIN" => _("Voicemail pin"))
1244 ));
1245 }
1246 }
1248 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1249 ?>