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","telephoneNumber", "goFonMacro","macro");
40 var $objectclasses= array("goFonAccount");
42 function phoneAccount ($config, $dn= NULL)
43 {
44 plugin::plugin ($config, $dn);
46 /* Set phone hardware */
47 if (!isset($this->attrs['goFonHardware'])){
48 $this->goFonHardware= "automatic";
49 }
51 /* Preset voice format */
52 if (!isset($this->attrs['goFonFormat'])){
53 $this->goFonFormat= "wav";
54 }
56 /* Assemble phone numbers */
57 if (isset($this->attrs['telephoneNumber'])){
58 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
59 $number= $this->attrs['telephoneNumber'][$i];
60 $this->phoneNumbers[$number]= $number;
61 }
62 }
64 /* Set up has_mailAccount */
65 if (isset($this->attrs['objectClass'])){
66 if (in_array("gosaMailAccount", $this->attrs['objectClass'])){
67 $this->has_mailAccount= TRUE;
68 }
69 }
71 $a_SETUP= array();
72 if(array_key_exists('config',$_SESSION) &&
73 array_key_exists('SERVERS',$_SESSION['config']->data) &&
74 array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
75 is_callable("mysql_connect")
76 ) {
77 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
78 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
79 if(!$r_con){
80 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
81 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
82 gosa_log(mysql_error());
83 return false;
84 }
85 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
86 if(!$db){
87 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
88 gosa_log(mysql_error());
89 return false;
90 }
92 $first = false;
93 foreach($this->phoneNumbers as $key => $val){
94 if(!$first){
95 $first = $key;
96 }
97 }
98 }
100 /* Load hardware list */
101 $ldap= $this->config->get_ldap_link();
102 $ldap->cd($this->config->current['BASE']);
103 $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
104 while ($attrs= $ldap->fetch()){
105 $cn= $attrs['cn'][0];
106 if (isset($attrs['description'])){
107 $description= " - ".$attrs['description'][0];
108 } else {
109 $description= "";
110 }
111 $this->hardware_list[$cn]= "$cn$description";
113 }
115 /* Perform search, to get Macro Parameters,Name,Dn,Displayname etc*/
116 $ldap->search("(objectClass=goFonMacro)", array("*"));
118 /* Add none for no macro*/
119 $this->macros['none']=_("no macro");
120 $this->macro ="none";
123 /* Fetch all Macros*/
124 while ($attrs= $ldap->fetch()){
126 /* Only visisble */
127 if((isset($attrs['goFonMacroVisible'][0]))&&($attrs['goFonMacroVisible'][0] ==1)){
129 /* unset Count, we don't need that here */
130 unset($attrs['displayName']['count']);
132 /* fill Selectfield variable with Macros */
133 if(isset($attrs['displayName'][0])){
134 $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
135 }else{
136 $this->macros[$attrs['dn']] = _("undefined");
137 }
139 /* Parse macro data, unset count for parameterarrays */
140 if (isset($attrs['goFonMacroParameter']['count'])){
141 unset($attrs['goFonMacroParameter']['count']);
142 }
144 /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
145 if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
147 foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
148 /* Split Data in readable values, by delimiter ! */
149 $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
151 /* Set all attrs */
152 $id = $data[0];
153 $this->macroarray[$attrs['dn']][$id]['var'] ="var".$id;
154 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
155 $this->macroarray[$attrs['dn']][$id]['id'] =$id;
156 $this->macroarray[$attrs['dn']][$id]['name'] =$data[1];
157 $this->macroarray[$attrs['dn']][$id]['type'] =$data[2];
158 $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
159 if($data[2] == "bool"){
160 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
161 }
162 }//foreach
163 }//is_array
164 }//visible = 1
165 }//while
167 /* Go through already saved values, for a parameter */
168 $tmp = split("!",$this->goFonMacro);
170 /* it is possible that nothing has been saved yet */
171 if(is_array($tmp)){
173 /* First value is the macroname */
174 $this->macro = $tmp[0];
176 /* Macroname saved, delete that index */
177 unset($tmp[0]);
179 /* Check if makro has been removed */
180 if(!isset($this->macroarray[$this->macro])){
181 $this->macrostillavailable = false;
182 }else{
183 $this->macrostillavailable = true;
184 }
186 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
187 foreach($tmp as $var){
189 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
190 $varar = split("#",$var);
192 /* Only insert if the parameter still exists */
193 if(isset($this->macroarray[$this->macro][$varar[0]])){
194 /* Assign value */
195 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
196 }
197 }
198 }
201 /* Eventually colorize phones */
202 $ldap->cd($this->config->current['BASE']);
203 foreach ($this->hardware_list as $cn => $desc){
204 $ldap->search("(goFonHardware=$cn)", array('cn'));
205 if ($ldap->count() > 0){
206 $ldap->fetch();
207 if ($ldap->getDN() != $this->dn){
208 $this->used_hardware[$cn]= $ldap->getDN();
209 }
210 }
211 }
212 $this->hardware_list["automatic"]= _("automatic");
213 ksort($this->hardware_list);
214 $this->a_old_telenums = $this->phoneNumbers;
216 if($this->is_account){
217 $this->is_modified = true;
218 }
221 /* Get voicemail PIN from MySQL DB
222 * Because every user can change his PIN directly from the phone
223 * without any update to the ldap
224 * This means, the PIN in the DB is up to date
225 */
226 // Connect to DB server
227 if((is_callable("mysql_pconnect"))&&(isset($a_SETUP))&&(isset($a_SETUP['SERVER']))&&(isset($a_SETUP['LOGIN']))&&(isset($a_SETUP['PASSWORD']))){
228 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
229 if($r_con){
230 $r_db = @mysql_select_db($a_SETUP['DB'],$r_con);
231 $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."'"));
233 if((isset($vp[0]))&&(!empty($vp[0]))){
234 $this->goFonPINVoice = $vp[0];
235 }
236 }
237 }
238 $this->lastmacro=$this->macro;
240 if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
241 @mysql_close($r_con) ;
242 }
243 }
246 // Generate MySQL Syntax
247 function generate_mysql_entension_entries($save = false){
249 if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
250 if($save)
251 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."));
252 return(true);
253 }
255 if(!is_callable("mysql_pconnect")){
256 if($save)
257 print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
258 return(true);
259 }
261 // Get Configuration for Mysql database Server
262 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON']; // DB Configuration
263 $s_parameter = ""; // Contains paramter for selected Macro
264 $r_con = false; // DB connection
265 $r_db = false; // Selected DB
266 $r_res = false; // Result resource
267 $a_ldap_attrs = array(); //
269 $s_ip = NULL; // Contains ip for Sip entry
270 $s_host = NULL; // Contains host for Sip entry
271 $s_qualify = "yes"; // Qualify entry
272 $s_pin = NULL; // Entry for secret
273 $s_type = NULL; // Entry for phone type (friend , peer ..)
275 $sip_data_array = array(); // Contains complete sip entry, to generate SQL syntax
276 $i_old_key = false; // Contains index for first old phonenumber, to delete old entries corectly
277 $i_new_key = false; // Contains index for first new phonenumber, to generate new entries corectly
279 $s_sip_values = ""; // Contains string with all values for given attributes in SQL syntax
280 $s_sip_keys = ""; // Contains all needed attributes to generate sip entry in DB
282 $s_sip_key = ""; // Key for SIP entry index
283 $s_sip_val = ""; // Value for SIP entry index
285 $b_first_deleted= false; // Only delete first entry,
286 $s_telenums = ""; // for each value variable
288 $i_is_accounted = false; // Ensure that extension entry, for name to number is only once in table
291 // Connect to DB server
292 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
294 // Check if we are connected correctly
295 if(!$r_con){
296 $this->generate_error = sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
297 $a_SETUP['SERVER'],$a_SETUP['LOGIN']);
298 gosa_log(mysql_error());
299 return false;
300 }
302 // Select database for Extensions
303 $r_db = @mysql_select_db($a_SETUP['DB'],$r_con);
305 // Test if we have the database selected correctly
306 if(!$r_db){
307 $this->generate_error = sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']);
308 gosa_log(mysql_error());
309 return false;
310 }
312 // Get phonehardware to setup sip entry
313 $ldap = $this->config->get_ldap_link();
314 $r_res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
315 $a_ldap_attrs = $ldap->fetch();
317 if($this->is_number_used()){
318 $this->generate_error = $this->is_number_used();
319 return false;
320 }
322 /* If Save == true, we should save something.
323 * Generate SQL, for drop of old entries
324 * Generate SQL, for insert new entries
325 */
326 if($save == true){
328 foreach($this->a_old_telenums as $tele){
329 $oldnums[]= preg_replace("/[^0-9]/","",$tele);
330 }
332 foreach($this->phoneNumbers as $tele){
333 $newnums[]= preg_replace("/[^0-9]/","",$tele);
334 }
336 // Attribute GoFonDefaultIP set ?
337 if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
338 $s_ip = $a_ldap_attrs['goFonDefaultIP'][0];
339 $s_host = $s_ip;
340 }else{
341 $s_ip = NULL;
342 $s_host = "dynamic";
343 }
345 // Attribute GoFonQualify set ?
346 if(isset($a_ldap_attrs['goFonQualify'])){
347 $s_qualify = $a_ldap_attrs['goFonQualify'][0];
348 }
350 // Attribute GoFonPIN set ?
351 if(isset($this->goFonPIN)){
352 $s_pin = $this->goFonPIN;
353 }
355 // Attribute GoFonType set ?
356 if(isset($a_ldap_attrs['goFonType'])){
357 $s_type = $a_ldap_attrs['goFonType'][0];
358 }
360 if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
361 $sip_data_array['dtmfmode'] = $a_ldap_attrs['goFonDmtfMode'][0];
362 }else{
363 $sip_data_array['dtmfmode'] ="rfc2833";
364 }
366 // generate SIP entry
367 $sip_data_array['id'] = "";
368 $sip_data_array['name'] = $this->uid;
369 $sip_data_array['accountcode'] = NULL;
370 $sip_data_array['amaflags'] = NULL;
371 $sip_data_array['callgroup'] = NULL;
372 $sip_data_array['callerid'] = "";
373 $sip_data_array['canreinvite'] = "no";
374 $sip_data_array['context'] = "default";
375 $sip_data_array['defaultip'] = NULL;
376 $sip_data_array['fromuser'] = NULL;
377 $sip_data_array['fromdomain'] = NULL;
378 $sip_data_array['host'] = $s_host;
379 $sip_data_array['insecure'] = NULL;
380 $sip_data_array['language'] = NULL;
381 $sip_data_array['mailbox'] = "asterisk";
382 $sip_data_array['md5secret'] = NULL;
383 $sip_data_array['nat'] = "no";
384 $sip_data_array['permit'] = NULL;
385 $sip_data_array['deny'] = NULL;
386 $sip_data_array['mask'] = NULL;
387 $sip_data_array['pickupgroup'] = NULL;
388 $sip_data_array['port'] = NULL;
389 $sip_data_array['qualify'] = $s_qualify;
390 $sip_data_array['restrictcid'] = "n";
391 $sip_data_array['rtptimeout'] = NULL;
392 $sip_data_array['rtpholdtimeout']=NULL;
393 $sip_data_array['secret'] = $this->goFonPIN;
394 $sip_data_array['type'] = $s_type ;
395 $sip_data_array['username'] = $this->uid;
396 $sip_data_array['disallow'] = NULL;
397 $sip_data_array['allow'] = NULL;
398 $sip_data_array['musiconhold'] = NULL;
399 $sip_data_array['regseconds'] = NULL;
400 $sip_data_array['ipaddr'] = $s_ip;
401 $sip_data_array['regexten'] = NULL;
402 $sip_data_array['cancallforward']=NULL;
404 // Get selected Macro Parameter and create parameter entry
405 if(isset($this->macroarray[$this->macro])){
406 foreach($this->macroarray[$this->macro] as $key => $val ){
407 $s_parameter .= $val['choosen']."|";
408 }
409 $s_parameter = preg_replace("/\|$/","",$s_parameter);
410 }
412 if($this->is_number_used()){
413 $this->generate_error = $this->is_number_used();
414 return false;
415 }
417 // Create new SIP entry ...
418 $sip_entry = $sip_data_array;
419 reset($newnums);
420 $i_new_key = key($newnums);
421 $sip_entry['callerid'] =$newnums[$i_new_key];
422 $sip_entry['mailbox'] =$newnums[$i_new_key];
424 if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
425 $s_mail = $this->parent->by_object['mailAccount']->mail;
426 }else{
427 $s_mail = "";
428 }
430 // $SQL contains all queries
431 $SQL = array();
432 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
433 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
434 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$newnums[$i_new_key].";";
435 // Delete old entries
436 $b_first_deleted =false;
437 if(isset($oldnums) && is_array($oldnums)){
438 foreach($oldnums as $s_telenums){
439 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
440 if(!$b_first_deleted){
441 $b_first_deleted=true;
442 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id=".$s_telenums.";";
443 }
444 }
445 }
446 if($this->goFonHardware=="automatic"){
447 foreach($SQL as $query ){
448 mysql_query($query) ;
449 }
450 return;
451 }
453 // Generate Strings with keys and values
454 foreach($sip_entry as $s_sip_key=>$s_sip_val){
455 if($s_sip_val == NULL) continue;
456 $s_sip_values.="'".$s_sip_val."',";
457 $s_sip_keys .="`".$s_sip_key."`,";
458 }
459 // Remove last ,
460 $s_sip_values = preg_replace("/,$/","",$s_sip_values);
461 $s_sip_keys = preg_replace("/,$/","",$s_sip_keys);
463 // Append SIP Entry
464 $SQL[] ="INSERT INTO ".$a_SETUP['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
466 /* If deletion starts from userslist, cn uid are not set */
467 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
468 $this->uid = $this->parent->by_object['user']->uid;
469 }
471 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
472 $this->cn = $this->parent->by_object['user']->cn;
473 }
475 if((!isset($this->cn))||(empty($this->cn))){
476 $CNname= $this->uid;
477 }else{
478 $CNname= $this->cn;
479 }
481 $SQL[]= "INSERT INTO ".$a_SETUP['VOICE_TABLE']." (`customer_id`,`context`,`mailbox`,`password`,`fullname`,`email`,`pager`)
482 VALUES ('".$newnums[$i_new_key]."',
483 'default',
484 '".$newnums[$i_new_key]."',
485 '".$this->goFonVoicemailPIN."',
486 '".$CNname."',
487 '".$s_mail."',
488 '');";
489 $i_is_accounted=false;
491 $i = 0;
493 $is_inserted_once = false;
495 // Entension entries Hint / Dial / Goto
496 foreach($newnums as $s_telenums){
498 if(!$is_inserted_once){
499 $is_inserted_once = true;
500 $EXT[$i]['context'] = 'GOsa';
501 $EXT[$i]['exten'] = $this->uid;
502 $EXT[$i]['priority']= 1;
503 $EXT[$i]['app'] = "Goto";
504 $EXT[$i]['appdata'] = $s_telenums."|1";
505 $i ++;
506 }
507 /* Hint Entry */
508 $EXT[$i]['context'] = 'GOsa';
509 $EXT[$i]['exten'] = $s_telenums;
510 $EXT[$i]['priority']= "Hint";
511 $EXT[$i]['app'] = 'SIP/'.$this->uid;
512 $i ++;
513 /* SetCID */
514 //$EXT[$i]['context'] = 'GOsa';
515 //$EXT[$i]['exten'] = $s_telenums;
516 //$EXT[$i]['priority']= 1;
517 //$EXT[$i]['app'] = "SetCIDName";
518 //$EXT[$i]['appdata'] = $CNname;
519 //$i ++;
521 // If no macro is selected use Dial
522 if($this->macro!="none"){
523 $macroname = preg_replace("/,.*$/","",$this->macro);
524 $macroname = preg_replace("/^.*=/","",$macroname);
525 $s_app = "Macro";$macroname;
526 $s_par = $macroname."|".$s_parameter;
527 }else{
528 $s_app = "Dial";
529 $s_par = 'SIP/'.$this->uid."|20|r";
530 }
532 $EXT[$i]['context'] = 'GOsa';
533 $EXT[$i]['exten'] = $s_telenums;
534 $EXT[$i]['priority']= 1;
535 $EXT[$i]['app'] = $s_app;
536 $EXT[$i]['appdata'] = $s_par;
537 $i ++;
539 }
541 // Append all these Entries
542 foreach($EXT as $entr){
543 $SQL_syn = "INSERT INTO ".$a_SETUP['EXT_TABLE']." (";
544 foreach($entr as $key2 => $val2){
545 $SQL_syn.= "`".$key2."`,";
546 }
547 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
548 $SQL_syn .= ") VALUES (";
549 foreach($entr as $key2 => $val2){
550 $SQL_syn .= "'".$val2."',";
551 }
552 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
553 $SQL_syn .=");\n";
554 $SQL[] =$SQL_syn;
555 $SQL_syn ="";
556 }
558 // Perform queries ...
559 foreach($SQL as $query){
560 if(!@mysql_query($query,$r_con)){
561 print_red(_("Error while performing query:")." ".mysql_error());
562 return false;
563 }
564 }
565 }
566 @mysql_close($r_con);
567 return true;
568 }
571 function execute()
572 {
573 /* Call parent execute */
574 plugin::execute();
576 $display = "";
578 if(empty($this->macro)&&(!empty($this->goFonMacro))){
580 /* Go through already saved values, for a parameter */
581 $tmp = split("!",$this->goFonMacro);
583 /* it is possible that nothing has been saved yet */
584 if(is_array($tmp)){
586 /* First value is the macroname */
587 $this->macro = $tmp[0];
589 /* Macroname saved, delete that index */
590 unset($tmp[0]);
592 /* Check if makro has been removed */
593 if(!isset($this->macroarray[$this->macro])){
594 $this->macrostillavailable = false;
595 }else{
596 $this->macrostillavailable = true;
597 }
599 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
600 foreach($tmp as $var){
602 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
603 $varar = split("#",$var);
605 /* Only insert if the parameter still exists */
606 if(isset($this->macroarray[$this->macro][$varar[0]])){
607 /* Assign value */
608 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
609 }
610 }
611 }
612 }
614 /* Do we represent a valid account? */
615 if (!$this->is_account && $this->parent == NULL){
616 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
617 _("This account has no phone extensions.")."</b>";
618 $display.= back_to_main();
619 return ($display);
620 }
622 /* Do we need to flip is_account state? */
623 if (isset($_POST['modify_state'])){
624 $this->is_account= !$this->is_account;
625 }
627 /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
628 if(empty($this->macro)){
629 $this->macro ="none";
630 }
632 /* Prepare templating */
633 $smarty= get_smarty();
635 /* tell user that the pluging selected is no longer available*/
636 if((!$this->macrostillavailable)&&($this->macro!="none")){
637 print_red(_("The macro you selected, is no longer available for you, please choose another one."));
638 }
640 /* Assing macroselectbox values */
641 $smarty->assign("macros",$this->macros);
642 $smarty->assign("macro", $this->macro);
644 /* check if there is a FON server created */
645 if(!isset($_SESSION['config']->data['SERVERS']['FON'])){
646 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."));
647 }
649 /* Create parameter table, skip if no parameters given */
650 if(!isset($this->macroarray[$this->macro])){
651 $macrotab="";
652 }else{
654 $macrotab ="<table summary=\""._("Parameter")."\">";
655 /* for every single parameter-> display textfile,combo, or true false switch*/
657 foreach($this->phoneNumbers as $phonenum){
658 $tmp[] = $phonenum;
659 }
663 if($this->macro != $this->lastmacro){
664 /* Go through all params */
665 foreach($this->macroarray[$this->macro] as $key => $paras){
667 $string = $paras['default'];
669 $string=preg_replace("/%uid/i",$this->uid,$string);
671 if(isset($this->cn)){
672 $string=preg_replace("/%cn/i",$this->cn,$string);
673 }
675 for($i = 0 ; $i < 10; $i++){
676 if(isset($tmp[$i])){
677 $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
678 }
679 }
680 if(isset($tmp[0])){
681 $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
682 }
683 $this->macroarray[$this->macro][$key]['choosen']=$string;
684 }
685 }
687 foreach($this->macroarray[$this->macro] as $paras){
689 /* get al vars */
690 $var = $paras['var'];
691 $name = $paras['name'];
692 $default = $paras['default'];
693 $type = $paras['type'];
694 $choosen = $paras['choosen'] ;
695 $str = $default;
697 /* in case of a combo box display a combobox with selected attr */
698 $macrotab.= "<tr>";
699 switch ($type){
701 case "combo":
702 $str= "<select name='".$var."' ".chkacl($this->acl, "goFonMacro")." >";
703 foreach(split(":",$default) as $choice){
704 if($choosen==$choice){
705 $str.= "\n<option value='".$choice."' selected>".$choice." </option>";
706 }else{
707 $str.= "\n<option value='".$choice."'>".$choice." </option>";
708 }
709 }
710 $str.="</select>";
711 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
712 break;
714 case "bool":
715 if(!$choosen){
716 $str="\n<input type='checkbox' name='".$var."' value='1' ".chkacl($this->acl, "goFonMacro")." >";
717 }else{
718 $str="\n<input type='checkbox' name='".$var."' value='1' checked ".chkacl($this->acl, "goFonMacro").">";
719 }
720 $macrotab.= "<td colspan='2'>$str ".base64_decode($name)."";
721 break;
723 case "string":
724 $str="<input name='".$var."' value='".$choosen."' ".chkacl($this->acl, "goFonMacro")." style='width:340px;'>";
725 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
726 break;
728 }
729 $macrotab.= "</td></tr>";
731 }
732 $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
733 }//is_array()
735 /* Give smarty the table */
736 $smarty->assign("macrotab",$macrotab);
738 /* Do we represent a valid account? */
739 if (!$this->is_account && $this->parent == NULL){
740 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
741 _("This account has no phone extensions.")."</b>";
742 $display.= back_to_main();
743 return($display);
744 }
746 $display= "";
748 /* Show tab dialog headers */
749 if ($this->parent != NULL){
750 if ($this->is_account){
751 $display= $this->show_header(_("Remove phone account"),
752 _("This account has phone features enabled. You can disable them by clicking below."));
753 } else {
754 if(empty($this->uid)){
755 $display= $this->show_header(_("Create phone account"),
756 _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
757 }else{
758 $display= $this->show_header(_("Create phone account"),
759 _("This account has phone features disabled. You can enable them by clicking below."));
760 }
761 return ($display);
762 }
763 }
765 /* Add phone number */
766 if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
767 if (is_phone_nr($_POST['phonenumber'])){
768 $number= $_POST["phonenumber"];
769 $this->phoneNumbers[$number]= $number;
770 $this->is_modified= TRUE;
771 } else {
772 print_red(_("Please enter a valid phone number!"));
773 }
774 }
776 /* Remove phone number */
777 if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
778 foreach ($_POST['phonenumber_list'] as $number){
779 unset($this->phoneNumbers[$number]);
780 $this->is_modified= TRUE;
781 }
782 }
784 /* Transfer ACL's */
785 foreach($this->attributes as $val){
786 $smarty->assign($val."ACL", chkacl($this->acl,$val));
787 if(isset($this->$val)){
788 $smarty->assign($val,$this->$val);
789 }else{
790 $smarty->assign($val,"");
791 }
792 }
794 /* Fill arrays */
795 $smarty->assign ("goFonHardware", $this->goFonHardware);
796 if (!count($this->phoneNumbers)){
797 $smarty->assign ("phoneNumbers", array(""));
798 } else {
799 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
800 }
801 $hl= "<select size=\"1\" name=\"goFonHardware\" title=\"".
802 _("Choose your private phone")."\" ".chkacl($this->acl, "goFonHardware").">\n";
803 foreach ($this->hardware_list as $cn => $description){
804 if ($cn == $this->goFonHardware){
805 $selected= "selected";
806 } else {
807 $selected= "";
808 }
809 if (isset($this->used_hardware[$cn])){
810 $color= "style=\"color:#A0A0A0\"";
811 } else {
812 $color= "";
813 }
814 $hl.= " <option $color label=\"$cn\" value=\"$cn\" $selected>$description </option>\n";
815 }
816 $hl.= "</select>\n";
817 $smarty->assign ("hardware_list", $hl);
819 /* Show main page */
820 $this->lastmacro = $this->macro;
821 $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
822 return($display);
823 }
826 function save_object()
827 {
828 if (isset($_POST["phoneTab"])){
829 plugin::save_object();
831 /* Save checkbox */
832 if (isset($_POST['fon_to_mail'])){
833 $tmp= "[M]";
834 } else {
835 $tmp= "[]";
836 }
837 if (chkacl ($this->acl, "goFonDeliveryMode") == ""){
838 if ($this->goFonDeliveryMode != $tmp){
839 $this->is_modified= TRUE;
840 }
841 $this->goFonDeliveryMode= $tmp;
842 }
844 /* Every macro in the select box are available */
845 if((isset($_POST['macro']))){
846 $this->macrostillavailable=true;
847 }
849 if(is_array($this->phoneNumbers)){
850 foreach($this->phoneNumbers as $telenumms) {
851 $nummsinorder[]=$telenumms;
852 }
853 }else{
854 $nummsinorder=array("");
855 }
857 /* get all Postvars */
858 if(isset($this->macroarray[$this->macro])){
859 foreach($this->macroarray[$this->macro] as $key => $paras){
860 if(isset($_POST[$paras['var']])){
861 $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
862 }
864 /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
865 We need this code below to read and save checkboxes correct
866 */
868 if(isset($_POST['post_success'])){
869 if($this->macroarray[$this->macro][$key]['type']=="bool"){
870 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
871 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
872 }else{
873 $this->macroarray[$this->macro][$key]['choosen']=false;
874 }
875 }
876 }
877 }
878 }
879 }
880 }
882 function check()
883 {
884 /* Call common method to give check the hook */
885 $message= plugin::check();
887 if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
888 $message[]=(_("Voicemail PIN must be between 1-4 characters."));
889 }else{
890 if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
891 $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
892 }
893 }
895 if((strlen($this->goFonPIN)<=0)){
896 $message[]=(_("Phone PIN must be at least one character long."));
897 }else{
898 if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
899 $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
900 }
901 }
903 if(!$this->generate_mysql_entension_entries()){
904 $message[] = $this->generate_error;
905 }
907 /* We need at least one phone number */
908 if (count($this->phoneNumbers) == 0){
909 $message[]= sprintf(_("You need to specify at least one phone number!"));
910 }
912 /* check for ! in any parameter setting*/
913 if(isset($this->macroarray[$this->macro])){
914 foreach($this->macroarray[$this->macro] as $val){
915 if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
916 $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
917 }
918 }
919 }
920 return ($message);
921 }
925 function save()
926 {
927 plugin::save();
929 /* Save arrays */
930 $this->attrs['telephoneNumber']= array();
931 foreach ($this->phoneNumbers as $number){
932 $this->attrs['telephoneNumber'][]= $number;
933 }
935 /* Save settings, or remove goFonMacro attribute*/
936 if($this->macro!="none"){
937 $this->attrs['goFonMacro']=$this->macro;
938 if(isset($this->macroarray[$this->macro])){
939 foreach($this->macroarray[$this->macro] as $paras) {
940 $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
941 }
942 }
943 }else{
944 $this->attrs['goFonMacro']=array();
945 }
946 unset($this->attrs['macro']) ;
948 $this->attrs['goFonForwarding']=array();
950 $this->generate_mysql_entension_entries(true);
952 if($this->attrs['goFonMacro']==""){
953 $this->attrs['goFonMacro']=array();
954 }
956 unset($this->attrs['cn']);
958 /* Write back to ldap */
959 $ldap= $this->config->get_ldap_link();
960 $ldap->cd($this->dn);
961 $this->cleanup();
962 $ldap->modify ($this->attrs);
964 show_ldap_error($ldap->get_error(), _("Saving phone account failed"));
966 /* Optionally execute a command after we're done */
968 if ($this->initially_was_account == $this->is_account){
969 if ($this->is_modified){
970 $this->handle_post_events("modify");
971 }
972 } else {
973 $this->handle_post_events("add");
974 }
976 }
979 function insert_after($entry, $nr, $list)
980 {
981 /* Is the entry free? No? Make it free... */
982 if (isset($list[$nr])) {
983 $dest= array();
984 $newidx= 0;
986 foreach ($list as $idx => $contents){
987 $dest[$newidx++]= $contents;
988 if ($idx == $nr){
989 $dest[$newidx++]= $entry;
990 }
991 }
992 } else {
993 $dest= $list;
994 $dest[$nr]= $entry;
995 }
997 return ($dest);
998 }
1001 function adapt_from_template($dn)
1002 {
1003 plugin::adapt_from_template($dn);
1005 /* Assemble phone numbers */
1006 if (isset($this->attrs['telephoneNumber'])){
1007 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1008 $number= $this->attrs['telephoneNumber'][$i];
1009 $this->phoneNumbers[$number]= $number;
1010 }
1011 }
1012 }
1015 function remove_from_parent()
1016 {
1017 if(!$this->initially_was_account) return;
1019 foreach($this->attributes as $key=>$val){
1020 if(in_array($val,array("uid","cn"))){
1021 unset($this->attributes[$key]);
1022 unset($this->$val);
1023 }
1024 }
1025 if(array_key_exists('config', $_SESSION) &&
1026 array_key_exists('SERVERS', $_SESSION['config']->data) &&
1027 array_key_exists('FON', $_SESSION['config']->data['SERVERS']) &&
1028 is_callable("mysql_pconnect")) {
1029 // Get Configuration for Mysql database Server
1030 $a_SETUP = $_SESSION['config']->data['SERVERS']['FON'];
1031 $s_parameter ="";
1033 // Connect to DB server
1034 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1036 // Check if we are connected correctly
1037 if(!$r_con){
1038 print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1039 $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1040 gosa_log(@mysql_error());
1041 return false;
1042 }
1044 // Select database for Extensions
1045 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
1047 // Test if we have the database selected correctly
1048 if(!$db){
1049 print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1050 gosa_log(@mysql_error());
1051 return false;
1052 }
1054 $SQL="";
1056 /* If deletion starts from userslist, cn uid are not set */
1057 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1058 $this->uid = $this->parent->by_object['user']->uid;
1059 }
1061 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1062 $this->cn = $this->parent->by_object['user']->cn;
1063 }
1065 $first_num = false;
1066 // Delete old entries
1067 foreach($this->a_old_telenums as $s_telenums){
1068 if(!$first_num){
1069 $first_num = $s_telenums;
1070 }
1071 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1072 }
1074 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1075 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1076 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1078 foreach($SQL as $query){
1079 if(!@mysql_query($query,$r_con)){
1080 print_red(_("Stop".mysql_error()));
1081 return false;
1082 }
1083 }
1084 }else{
1085 print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1086 return false;
1087 }
1089 /* unset macro attr, it will cause an error */
1090 $tmp = array_flip($this->attributes);
1091 unset($tmp['macro']);
1092 $this->attributes=array_flip($tmp);
1094 /* Cancel if there's nothing to do here */
1095 if (!$this->initially_was_account){
1096 return;
1097 }
1099 plugin::remove_from_parent();
1101 /* Just keep one phone number */
1102 if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1103 $this->attrs['telephoneNumber']= $this->telephoneNumber;
1104 } else {
1105 $this->attrs['telephoneNumber']= array();
1106 }
1109 $ldap= $this->config->get_ldap_link();
1110 $ldap->cd($this->config->current['BASE']);
1111 $ldap->search("(objectClass=goFonQueue)", array("member"));
1112 while($attr = $ldap->fetch()){
1113 if(in_array($this->dn,$attr['member'])){
1114 $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1115 unset($new->by_object['ogroup']->memberList[$this->dn]);
1116 unset($new->by_object['ogroup']->member[$this->dn]);
1117 $new->save();
1118 print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
1119 }
1120 }
1121 $ldap->cd($this->dn);
1122 $this->cleanup();
1123 $ldap->modify ($this->attrs);
1125 show_ldap_error($ldap->get_error(), _("Removing phone account failed"));
1127 /* Optionally execute a command after we're done */
1128 @mysql_close($r_con);
1129 $this->handle_post_events('remove');
1130 }
1134 /* This function checks if the given phonenumbers are available or already in use*/
1135 function is_number_used()
1136 {
1137 $ldap= $this->config->get_ldap_link();
1138 $ldap->cd($this->config->current['BASE']);
1139 $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1140 while($attrs = $ldap->fetch()) {
1141 unset($attrs['telephoneNumber']['count']);
1142 foreach($attrs['telephoneNumber'] as $tele){
1143 if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1144 if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1145 $numbers[$tele]=$attrs;
1146 }
1147 }
1149 foreach($this->phoneNumbers as $num){
1150 if(!isset($this->cn)) $this->cn = "";
1152 if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1153 if(isset($numbers[$num]['uid'][0])){
1154 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1155 }else{
1156 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1157 }
1158 }
1159 }
1160 }
1163 /* Create phoneAccount part of copy & paste dialog */
1164 function getCopyDialog()
1165 {
1166 if(!$this->is_account) return("");
1167 $smarty = get_smarty();
1168 if (!count($this->phoneNumbers)){
1169 $smarty->assign ("phoneNumbers", array(""));
1170 } else {
1171 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1172 }
1174 $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1175 $smarty->assign("goFonPIN",$this->goFonPIN);
1177 $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1178 $ret =array();
1179 $ret['string'] = $display;
1180 $ret['status'] = "";
1181 return($ret);
1182 }
1184 /* Save posts from copy & paste dialog dialog */
1185 function saveCopyDialog()
1186 {
1187 if(!$this->is_account) return;
1188 $this->execute();
1189 if(isset($_POST['goFonVoicemailPIN'])) {
1190 $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1191 }
1192 if(isset($_POST['goFonPIN'])){
1193 $this->goFonPIN = $_POST['goFonPIN'];
1194 }
1195 }
1196 }
1198 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1199 ?>