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 = array();
12 var $goFonHardware = "automatic";
13 var $goFonFormat = "wav";
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 = "";
30 var $goFonHomeServer = "0"; // Contains the dn of the server that manage this account
31 var $init_HomeServer = "0"; // Contains the dn of the server that manage this account
32 var $goFonHomeServers = array(); // Contains all available server configurations
34 /* CLI vars */
35 var $cli_summary = "Manage users phone account";
36 var $cli_description = "Some longer text\nfor help";
37 var $cli_parameters = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
39 /* attribute list for save action */
40 var $CopyPasteVars = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
41 "hardware_list","used_hardware");
43 var $attributes = array("goFonDeliveryMode", "goFonFormat","cn","goFonHomeServer",
44 "goFonHardware","goFonPIN","goFonVoicemailPIN","telephoneNumber", "goFonMacro","macro");
45 var $objectclasses= array("goFonAccount");
47 var $uid;
49 var $view_logged = FALSE;
50 var $multiple_support = TRUE;
52 function phoneAccount (&$config, $dn= NULL, $parent= NULL)
53 {
54 plugin::plugin ($config, $dn, $parent);
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 /* Set uid */
72 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
73 $this->uid = $this->parent->by_object['user']->uid;
74 }
75 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
76 $this->cn = $this->parent->by_object['user']->cn;
77 }
79 /* Check server configurations
80 * Load all server configuration in $this->goFonHomeServers if available
81 * and first server as default if necessary.
82 * Check if connection is successfull for the selected server $this->goFonHomeServer
83 */
86 /* Set available server */
87 $config = session::get('config');
88 if(isset($config->data['SERVERS']['FON'])){
89 $this->goFonHomeServers = $config->data['SERVERS']['FON'];
90 }
92 $a_SETUP= array();
93 if($this->is_account && isset($config->data['SERVERS']['FON']) &&
94 array_key_exists('FON',$config->data['SERVERS']) &&
95 is_callable("mysql_connect")
96 ) {
98 /* Servers defined? Watch here... */
99 if (count($this->goFonHomeServers)){
101 /* Set default server */
102 if(empty($this->goFonHomeServer) || $this->goFonHomeServer == "0"){
103 $this->goFonHomeServer= $this->goFonHomeServers[0]['DN'];
104 }
106 /* Remember inital home server, to be able to remove old entries */
107 $this->init_HomeServer = $this->goFonHomeServer;
109 /* Get config */
110 if(!isset($this->goFonHomeServers[$this->goFonHomeServer])){
111 print_red(sprintf(_("The specified goFonHomeServer '%s' is not available in GOsa server configuration. Saving this account will create a new entry on the server '%s'. Use cancel if you do not want to create a new entry ignoring old accounts."),$this->goFonHomeServer, $this->goFonHomeServers[0]['DN']));
113 $this->goFonHomeServer = $this->goFonHomeServers[0]['DN'];
114 $this->init_HomeServer = $this->goFonHomeServers[0]['DN'];
115 }
116 $cur_cfg = $this->goFonHomeServers[$this->goFonHomeServer];
118 $r_con = @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
119 if(!$r_con){
120 # print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
121 # $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
122 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
123 }
124 $db = @mysql_select_db($cur_cfg['DB'],$r_con);
125 if(!$db){
126 # print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
127 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
128 }
130 $first = false;
131 foreach($this->phoneNumbers as $key => $val){
132 if(!$first){
133 $first = $key;
134 }
135 }
136 }
137 }
139 /* Get available phone hardware
140 * Search for all available phone hardware
141 */
142 $tmp = get_sub_list("(objectClass=goFonHardware)","",array(get_ou("phoneou")),
143 $this->config->current['BASE'],array("cn","description"), GL_NO_ACL_CHECK);
144 foreach($tmp as $attrs){
145 $cn= $attrs['cn'][0];
146 $description= "";
147 if (isset($attrs['description'])){
148 $description= " - ".$attrs['description'][0];
149 }
150 $this->hardware_list[$cn]= "$cn$description";
151 }
152 $this->hardware_list["automatic"]= _("automatic");
153 ksort($this->hardware_list);
156 /* Collect all usd phones
157 goFonHardware set.
158 */
159 $deps_a = array(
160 get_people_ou(),
161 get_ou("ogroupou"),
162 get_ou("serverou"),
163 get_ou("terminalou"),
164 get_ou("workstationou"),
165 get_ou("printerou"),
166 get_ou("componentou"),
167 get_ou("phoneou"));
169 $tmp = get_sub_list("(goFonHardware=*)","",$deps_a,$this->config->current['BASE'],
170 array('cn','dn','goFonHardware'),GL_NO_ACL_CHECK);
171 foreach($tmp as $attrs){
172 $cn = $attrs['goFonHardware'][0];
173 if(isset($this->hardware_list[$cn])){
174 $this->used_hardware[$cn]= $cn;
175 }
176 }
179 /* Get available Macros
180 * Search for all Marcos that are visible and create
181 * an array with name and parameters
182 */
183 $tmp = get_sub_list("(&(objectClass=goFonMacro)(goFonMacroVisible=1))","",array(get_ou("macroou")),
184 $this->config->current['BASE'],array("displayName","goFonMacroParameter","dn"), GL_NONE);
187 /* Add none for no macro*/
188 $this->macros['none']=_("no macro");
189 $this->macro ="none";
191 /* Fetch all Macros*/
192 foreach($tmp as $attrs){
194 /* unset Count, we don't need that here */
195 unset($attrs['displayName']['count']);
197 /* Parse macro data, unset count for parameterarrays */
198 if (isset($attrs['goFonMacroParameter']['count'])){
199 unset($attrs['goFonMacroParameter']['count']);
200 }
202 /* fill Selectfield variable with Macros */
203 if(isset($attrs['displayName'][0])){
204 $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
205 }else{
206 $this->macros[$attrs['dn']] = _("undefined");
207 }
209 /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
210 if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
212 foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
213 /* Split Data in readable values, by delimiter ! */
214 $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
216 /* Set all attrs */
217 $id = $data[0];
218 $this->macroarray[$attrs['dn']][$id]['var'] ="var".$id;
219 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
220 $this->macroarray[$attrs['dn']][$id]['id'] =$id;
221 $this->macroarray[$attrs['dn']][$id]['name'] =$data[1];
222 $this->macroarray[$attrs['dn']][$id]['type'] =$data[2];
223 $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
224 if($data[2] == "bool"){
225 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
226 }
227 }//foreach
228 }//is_array
229 }//while
232 /* Parse used Macro
233 * If we have a macro selected, parse it and set values
234 * in $this->macroarray[$this->macro].
235 */
236 $tmp = split("!",$this->goFonMacro);
237 if(is_array($tmp)){
239 /* First value is the macroname */
240 $this->macro = $tmp[0];
242 /* Macroname saved, delete that index */
243 unset($tmp[0]);
245 /* Check if makro has been removed */
246 if(!isset($this->macros[$this->macro])){
247 $this->macrostillavailable = false;
248 }else{
249 $this->macrostillavailable = true;
250 }
252 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
253 foreach($tmp as $var){
255 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
256 $varar = split("#",$var);
258 /* Only insert if the parameter still exists */
259 if(isset($this->macroarray[$this->macro][$varar[0]])){
260 /* Assign value */
261 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
262 }
263 }
264 }
267 $this->a_old_telenums = $this->phoneNumbers;
269 /* Get voicemail PIN from MySQL DB
270 * Because every user can change his PIN directly from the phone
271 * without any update to the ldap
272 * This means, the PIN in the DB is up to date
273 */
274 // Connect to DB server
275 if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
276 $r_con = @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
277 if($r_con){
278 $r_db = @mysql_select_db($cur_cfg['DB'],$r_con);
280 $query_tmp = "SELECT ".$cur_cfg['VOICE_TABLE'].".password FROM ".$cur_cfg['VOICE_TABLE'].", ".
281 $cur_cfg['SIP_TABLE']." WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'";
283 $vp = mysql_fetch_row(mysql_query($query_tmp));
284 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
285 if((isset($vp[0]))&&(!empty($vp[0]))){
286 $this->goFonPINVoice = $vp[0];
287 }
288 }
289 }
290 $this->lastmacro=$this->macro;
292 if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
293 @mysql_close($r_con) ;
294 }
295 }
298 /* This function generates the Database entries.
299 * The Parameter 'save' could be true or false.
300 * false - means only testing no database transactions.
301 * true - write database entries.
302 *
303 * 'sip_users','voice_mail' and 'extensions' table entries will be created.
304 *
305 * If the phone hardware is 'automatic' the table entries will only be removed
306 * and not added.
307 */
308 function generate_mysql_entension_entries($save = false)
309 {
310 /* Check if there is at least one server available
311 * If not, return and tell the user that saving failed
312 */
313 if(!count($this->goFonHomeServers)){
314 if($save){
315 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."));
316 }
317 return(true);
318 }
320 /* Check if Mysql extension is available */
321 if(!is_callable("mysql_pconnect")){
322 if($save)
323 print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
324 return(true);
325 }
327 /**********************
328 * Attribute Initialisation
329 **********************/
331 $old_connection = false;
333 // Get Configuration for Mysql database Server
334 $s_parameter = ""; // Contains paramter for selected Macro
335 $r_con = false; // DB connection
336 $r_db = false; // Selected DB
337 $r_res = false; // Result resource
338 $a_ldap_attrs = array(); //
340 $s_ip = NULL; // Contains ip for Sip entry
341 $s_host = NULL; // Contains host for Sip entry
342 $s_qualify = "yes"; // Qualify entry
343 $s_pin = NULL; // Entry for secret
344 $s_type = NULL; // Entry for phone type (friend , peer ..)
346 $sip_data_array = array(); // Contains complete sip entry, to generate SQL syntax
347 $i_old_key = false; // Contains index for first old phonenumber, to delete old entries corectly
348 $i_new_key = false; // Contains index for first new phonenumber, to generate new entries corectly
350 $s_sip_values = ""; // Contains string with all values for given attributes in SQL syntax
351 $s_sip_keys = ""; // Contains all needed attributes to generate sip entry in DB
353 $s_sip_key = ""; // Key for SIP entry index
354 $s_sip_val = ""; // Value for SIP entry index
356 $b_first_deleted= false; // Only delete first entry,
357 $s_telenums = ""; // for each value variable
359 $i_is_accounted = false; // Ensure that extension entry, for name to number is only once in table
361 restore_error_handler();
363 /* Prepare some basic attributes */
364 $oldnums = array();
365 foreach($this->a_old_telenums as $tele){
366 $oldnums[]= preg_replace("/[^0-9]/","",$tele);
367 }
368 foreach($this->phoneNumbers as $tele){
369 $newnums[]= preg_replace("/[^0-9]/","",$tele);
370 }
372 /* If deletion starts from userslist, cn uid are not set */
373 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
374 $this->uid = $this->parent->by_object['user']->uid;
375 }
376 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
377 $this->cn = $this->parent->by_object['user']->cn;
378 }
379 /* Create voicemail entry
380 */
381 if((!isset($this->cn))||(empty($this->cn))){
382 $CNname= $this->uid;
383 }else{
384 $CNname= $this->cn;
385 }
387 if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
388 $s_mail = $this->parent->by_object['mailAccount']->mail;
389 }else{
390 $s_mail = "";
391 }
392 /* Get phonehardware to setup sip entry */
393 $ldap = $this->config->get_ldap_link();
394 $r_res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
395 $a_ldap_attrs = $ldap->fetch();
397 /* Check selected phone hardware, is a default IP set? */
398 if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
399 $s_ip = $a_ldap_attrs['goFonDefaultIP'][0];
400 $s_host = $s_ip;
401 }else{
402 $s_ip = NULL;
403 $s_host = "dynamic";
404 }
406 // Attribute GoFonQualify set ?
407 if(isset($a_ldap_attrs['goFonQualify'])){
408 $s_qualify = $a_ldap_attrs['goFonQualify'][0];
409 }
411 // Attribute GoFonPIN set ?
412 if(isset($this->goFonPIN)){
413 $s_pin = $this->goFonPIN;
414 }
416 // Attribute GoFonType set ?
417 if(isset($a_ldap_attrs['goFonType'])){
418 $s_type = $a_ldap_attrs['goFonType'][0];
419 }
421 if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
422 $sip_data_array['dtmfmode'] = $a_ldap_attrs['goFonDmtfMode'][0];
423 }else{
424 $sip_data_array['dtmfmode'] ="rfc2833";
425 }
427 /* Check if phone number is used */
428 if($this->is_number_used()){
429 $this->generate_error = $this->is_number_used();
430 return false;
431 }
435 /**********************
436 * Check Server Connection Information
437 **********************/
439 /* Create Mysql handle for the current goFonHomeServer, if possible
440 * Get configuration to old asterisk home server
441 */
442 $a_New = $this->goFonHomeServers[$this->goFonHomeServer]; // DB Configuration
443 $new_connection = @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
444 if(!$new_connection){
445 $this->generate_error = sprintf(
446 _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
447 $a_New['SERVER'],$a_New['LOGIN']);
448 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
449 return false;
450 }
451 $new_database = @mysql_select_db($a_New['DB'],$new_connection);
452 if(!$new_database){
453 $this->generate_error = sprintf(
454 _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
455 $a_New['DB'],$a_New['SERVER']);
456 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
457 return false;
458 }
460 /* If the home server has changed, we must remove entries from old
461 * server and add new entries in new server.
462 */
463 if($this->init_HomeServer != $this->goFonHomeServer){
465 /* Get configuration to old asterisk home server */
466 $a_Remove = $this->goFonHomeServers[$this->init_HomeServer]; // DB Configuration
468 /* Create connection to the database that contains the old entry.
469 */
470 $old_connection = @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
471 if(!$old_connection){
472 $this->generate_error = sprintf(
473 _("The old MySQL home server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
474 $a_Remove['SERVER'],$a_Remove['LOGIN']);
475 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
476 return false;
477 }
478 $old_database = @mysql_select_db($a_Remove['DB'],$old_connection);
479 if(!$old_database){
480 $this->generate_error = sprintf(
481 _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
482 $a_Remove['DB'],$a_Remove['SERVER']);
483 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
484 return false;
485 }
486 }
488 /* Save means that we must save changes, not only test */
489 if($save == true){
491 /**********************
492 * Remove entries from old home server
493 **********************/
495 /* Check if there is an old entry
496 * If there is an old entry, get callerid and remove voicemail and extensions
497 */
498 if($old_connection){
499 $query = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
500 $rid = mysql_query($query,$old_connection);
501 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
503 /* Old entry found, remove it */
504 $query_a = array();
505 if(mysql_affected_rows($old_connection)){
506 $result = mysql_fetch_assoc($rid);
507 $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
508 $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
509 $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
510 foreach($oldnums as $s_telenums) {
511 $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
512 }
514 foreach($query_a as $qry){
515 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
516 if(!mysql_query($qry,$old_connection)){
517 trigger_error(mysql_error($old_connection));
518 }
519 }
520 }
521 }
523 /**********************
524 * Update / Insert sip_users entry
525 **********************/
527 /* Set the first given phone number as callerid */
528 reset($newnums);
529 $i_new_key = key($newnums);
530 $sip_data_array['callerid'] =$newnums[$i_new_key];
531 $sip_data_array['mailbox'] =$newnums[$i_new_key];
533 /* Check if there is already an entry in sip_users for this uid */
534 $SQL_query_array = array();
535 $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n";
536 $rid = mysql_query($query,$new_connection);
537 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
538 if(mysql_affected_rows($new_connection)){
540 /**********************
541 * Update sip_users entry
542 **********************/
543 $result = mysql_fetch_assoc($rid);
544 $sip_data_array['host'] = $s_host;
545 $sip_data_array['qualify'] = $s_qualify;
546 $sip_data_array['secret'] = $this->goFonPIN;
547 $sip_data_array['type'] = $s_type ;
548 $sip_data_array['username'] = $this->uid;
549 $sip_data_array['ipaddr'] = $s_ip;
551 /* Remove not changed attributes, to avoid updating table with same values */
552 foreach($sip_data_array as $name => $value){
553 if($result[$name] == $value){
554 unset($sip_data_array[$name]);
555 }
556 }
557 /* Only update entry if there is something to uopdate */
558 if(count($sip_data_array)){
559 $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
560 foreach($sip_data_array as $key => $val){
561 $query.= "".$key."='".$val."',";
562 }
563 $query = preg_replace("/,$/","",$query);
564 $query.= " WHERE name='".$this->uid."';";
565 $SQL_query_array[] = $query;
566 }
567 } else {
569 /**********************
570 * Insert sip_users entry
571 **********************/
572 //generate SIP entry
573 $sip_data_array['id'] = "";
574 $sip_data_array['name'] = $this->uid;
575 $sip_data_array['accountcode'] = NULL;
576 $sip_data_array['amaflags'] = NULL;
577 $sip_data_array['callgroup'] = NULL;
578 $sip_data_array['canreinvite'] = "no";
579 $sip_data_array['context'] = "default";
580 $sip_data_array['defaultip'] = NULL;
581 $sip_data_array['fromuser'] = NULL;
582 $sip_data_array['fromdomain'] = NULL;
583 $sip_data_array['host'] = $s_host;
584 $sip_data_array['insecure'] = NULL;
585 $sip_data_array['language'] = NULL;
586 $sip_data_array['mailbox'] = $newnums[$i_new_key];
587 $sip_data_array['md5secret'] = NULL;
588 $sip_data_array['nat'] = "no";
589 $sip_data_array['permit'] = NULL;
590 $sip_data_array['deny'] = NULL;
591 $sip_data_array['mask'] = NULL;
592 $sip_data_array['pickupgroup'] = NULL;
593 $sip_data_array['port'] = NULL;
594 $sip_data_array['qualify'] = $s_qualify;
595 $sip_data_array['restrictcid'] = "n";
596 $sip_data_array['rtptimeout'] = NULL;
597 $sip_data_array['rtpholdtimeout']=NULL;
598 $sip_data_array['secret'] = $this->goFonPIN;
599 $sip_data_array['type'] = $s_type ;
600 $sip_data_array['username'] = $this->uid;
601 $sip_data_array['disallow'] = NULL;
602 $sip_data_array['allow'] = NULL;
603 $sip_data_array['musiconhold'] = NULL;
604 $sip_data_array['regseconds'] = NULL;
605 $sip_data_array['ipaddr'] = $s_ip;
606 $sip_data_array['regexten'] = NULL;
607 $sip_data_array['cancallforward']=NULL;
609 /* There is currently no entry for this user in the sip_users table.
610 * We should create one i
611 */
612 foreach($sip_data_array as $s_sip_key=>$s_sip_val){
613 if($s_sip_val === NULL) continue;
614 $s_sip_values.="'".$s_sip_val."',";
615 $s_sip_keys .="`".$s_sip_key."`,";
616 }
617 $s_sip_values = preg_replace("/,$/","",$s_sip_values);
618 $s_sip_keys = preg_replace("/,$/","",$s_sip_keys);
620 /* Add sip entries to mysql queries */
621 $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
622 }
625 /**********************
626 * Update / Insert Voice mail entry
627 **********************/
629 $customer_id = $newnums[$i_new_key];
631 $voice_data_array = array(
632 "customer_id" => $customer_id,
633 "mailbox" => $customer_id,
634 "password" => $this->goFonVoicemailPIN,
635 "fullname" => $CNname,
636 "email" => $s_mail);
638 /* Set pager number if available */
639 if(isset($this->parent->by_object['user']->pager)){
640 $voice_data_array['pager'] = $this->parent->by_object['user']->pager;
641 }
643 /* Check if there is already an entry in sip_users for this uid */
644 $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n";
645 $rid = mysql_query($query_tmp,$new_connection);
646 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
647 if(mysql_affected_rows($new_connection)){
649 /**********************
650 * Update Voice mail entry
651 **********************/
652 $result = mysql_fetch_assoc($rid) ;
654 foreach($voice_data_array as $name => $value){
655 if($result[$name] == $value){
656 unset($voice_data_array[$name]);
657 }
658 }
660 /* Only update entry if there is something to uopdate */
661 if(count($voice_data_array)){
662 $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
663 foreach($voice_data_array as $key => $val){
664 $query.= "".$key."='".$val."',";
665 }
666 $query = preg_replace("/,$/","",$query);
667 $query.= " WHERE customer_id='".$customer_id."';";
668 $SQL_query_array[] = $query;
669 }
670 }else{
672 /**********************
673 * Insert Voice mail entry
674 **********************/
675 $voice_data_array['context'] = "default";
677 /* There is currently no voice mail entry for this user.
678 * We should create one
679 */
680 $s_voi_values = $s_voi_keys = "";
681 foreach($voice_data_array as $s_voi_key=>$s_voi_val){
682 if($s_voi_val === NULL) continue;
683 $s_voi_values.="'".$s_voi_val."',";
684 $s_voi_keys .="`".$s_voi_key."`,";
685 }
686 $s_voi_values = preg_replace("/,$/","",$s_voi_values);
687 $s_voi_keys = preg_replace("/,$/","",$s_voi_keys);
689 /* Add sip entries to mysql queries */
690 $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
691 }
694 /**********************
695 * Remove/Insert extension entries
696 **********************/
698 /* Remove old entries */
699 $query = array();
700 $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
701 foreach($oldnums as $s_telenums){
702 $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
703 }
704 foreach($newnums as $s_telenums){
705 $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
706 }
707 foreach($query as $qry){
708 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
709 if(!mysql_query($qry,$new_connection)){
710 trigger_error(mysql_error($new_connection));
711 }
712 }
714 /**********************
715 * Insert extension entries
716 **********************/
718 // Get selected Macro Parameter and create parameter entry
719 if(isset($this->macroarray[$this->macro])){
720 foreach($this->macroarray[$this->macro] as $key => $val ){
721 $s_parameter .= $val['choosen']."|";
722 }
723 $s_parameter = preg_replace("/\|$/","",$s_parameter);
724 }
726 $i = 0;
727 $EXT = array();
728 if(!is_numeric($this->uid)){
729 $EXT[$i]['context'] = 'GOsa';
730 $EXT[$i]['exten'] = $this->uid;
731 $EXT[$i]['priority']= 1;
732 $EXT[$i]['app'] = "Goto";
733 $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
734 $i ++;
735 }
737 // Entension entries Hint / Dial / Goto
738 foreach($newnums as $s_telenums){
740 /* Hint Entry */
741 $EXT[$i]['context'] = 'GOsa';
742 $EXT[$i]['exten'] = $s_telenums;
743 $EXT[$i]['priority']= "Hint";
744 $EXT[$i]['app'] = 'SIP/'.$this->uid;
745 $i ++;
746 /* SetCID */
747 //$EXT[$i]['context'] = 'GOsa';
748 //$EXT[$i]['exten'] = $s_telenums;
749 //$EXT[$i]['priority']= 1;
750 //$EXT[$i]['app'] = "SetCIDName";
751 //$EXT[$i]['appdata'] = $CNname;
752 //$i ++;
754 // If no macro is selected use Dial
755 if($this->macro!="none"){
756 $macroname = preg_replace("/,.*$/","",$this->macro);
757 $macroname = preg_replace("/^.*=/","",$macroname);
758 $s_app = "Macro";$macroname;
759 $s_par = $macroname."|".$s_parameter;
760 }else{
761 $s_app = "Dial";
762 $s_par = 'SIP/'.$this->uid."|20|r";
763 }
765 $EXT[$i]['context'] = 'GOsa';
766 $EXT[$i]['exten'] = $s_telenums;
767 $EXT[$i]['priority']= 1;
768 $EXT[$i]['app'] = $s_app;
769 $EXT[$i]['appdata'] = $s_par;
770 $i ++;
771 }
773 // Append all these Entries
774 foreach($EXT as $entr){
775 $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
776 foreach($entr as $key2 => $val2){
777 $SQL_syn.= "`".$key2."`,";
778 }
779 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
780 $SQL_syn .= ") VALUES (";
781 foreach($entr as $key2 => $val2){
782 $SQL_syn .= "'".$val2."',";
783 }
784 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
785 $SQL_syn .=");\n";
787 $SQL_query_array[] =$SQL_syn;
788 $SQL_syn ="";
789 }
791 // Perform queries ...
792 if($this->goFonHardware != "automatic"){
793 foreach($SQL_query_array as $query){
794 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
795 if(!@mysql_query($query,$new_connection)){
796 print_red(_("Error while performing query:")." ".mysql_error());
797 return false;
798 }
799 }
800 }
801 }
802 @mysql_close($new_connection);
803 return true;
804 }
807 function execute()
808 {
809 /* Call parent execute */
810 plugin::execute();
812 /* Log view */
813 if($this->is_account && !$this->view_logged){
814 $this->view_logged = TRUE;
815 new log("view","users/".get_class($this),$this->dn);
816 }
818 $display = "";
819 $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
820 if(empty($this->macro)&&(!empty($this->goFonMacro))){
822 /* Go through already saved values, for a parameter */
823 $tmp = split("!",$this->goFonMacro);
825 /* it is possible that nothing has been saved yet */
826 if(is_array($tmp)){
828 /* First value is the macroname */
829 $this->macro = $tmp[0];
831 /* Macroname saved, delete that index */
832 unset($tmp[0]);
834 /* Check if macro has been removed */
835 if(!isset($this->macroarray[$this->macro])){
836 $this->macrostillavailable = false;
837 }else{
838 $this->macrostillavailable = true;
839 }
841 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
842 foreach($tmp as $var){
844 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
845 $varar = split("#",$var);
847 /* Only insert if the parameter still exists */
848 if(isset($this->macroarray[$this->macro][$varar[0]])){
849 /* Assign value */
850 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
851 }
852 }
853 }
854 }
856 /* Do we represent a valid account? */
857 if (!$this->is_account && $this->parent === NULL){
858 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
859 _("This account has no phone extensions.")."</b>";
860 $display.= back_to_main();
861 return ($display);
862 }
864 /* Do we need to flip is_account state? */
865 if (isset($_POST['modify_state'])){
866 $this->is_account= !$this->is_account;
867 }
869 /* Do we represent a valid account? */
870 if (!$this->is_account && $this->parent === NULL){
871 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
872 _("This account has no phone extensions.")."</b>";
873 $display.= back_to_main();
874 return($display);
875 }
877 $display= "";
879 /* Show tab dialog headers */
881 if (!$this->multiple_support_active && $this->parent !== NULL){
882 if ($this->is_account){
883 $display= $this->show_disable_header(_("Remove phone account"),
884 _("This account has phone features enabled. You can disable them by clicking below."));
885 } else {
886 if(empty($this->uid)){
887 $display= $this->show_enable_header(_("Create phone account"),
888 _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
889 }else{
890 $display= $this->show_enable_header(_("Create phone account"),
891 _("This account has phone features disabled. You can enable them by clicking below."));
892 }
893 return ($display);
894 }
895 }
896 /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
897 if(empty($this->macro)){
898 $this->macro ="none";
899 }
901 /* Prepare templating */
902 $smarty= get_smarty();
904 /* tell user that the selected plugin is no longer available */
905 if((!$this->macrostillavailable)&&($this->macro!="none")){
906 print_red(_("The macro you selected, is no longer available for you, please choose another one."));
907 }
909 /* Assing macroselectbox values */
910 $smarty->assign("macros",$this->macros);
911 $smarty->assign("macro", $this->macro);
913 /* check if there is a FON server created */
914 if(!count($this->goFonHomeServer)){
915 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."));
916 }
918 /* Create html parameter table for selected macro parameters
919 * skip if no parameters given
920 */
921 if(!isset($this->macroarray[$this->macro])){
922 $macrotab="";
923 }else{
925 $macrotab ="<table summary=\""._("Parameter")."\">";
926 /* for every single parameter-> display textfile,combo, or true false switch*/
928 foreach($this->phoneNumbers as $phonenum){
929 $tmp[] = $phonenum;
930 }
932 if($this->macro != $this->lastmacro){
933 /* Go through all params */
934 foreach($this->macroarray[$this->macro] as $key => $paras){
936 $string = $paras['default'];
938 $string=preg_replace("/%uid/i",$this->uid,$string);
940 if(isset($this->cn)){
941 $string=preg_replace("/%cn/i",$this->cn,$string);
942 }
944 for($i = 0 ; $i < 10; $i++){
945 if(isset($tmp[$i])){
946 $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
947 }
948 }
949 if(isset($tmp[0])){
950 $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
951 }
952 $this->macroarray[$this->macro][$key]['choosen']=$string;
953 }
954 }
956 foreach($this->macroarray[$this->macro] as $paras){
958 /* get al vars */
959 $var = $paras['var'];
960 $name = $paras['name'];
961 $default = $paras['default'];
962 $type = $paras['type'];
963 $choosen = $paras['choosen'] ;
964 $str = $default;
966 $dis = "";
967 if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
968 $dis = " disabled ";
969 }
971 /* in case of a combo box display a combobox with selected attr */
972 $macrotab.= "<tr>";
973 switch ($type){
975 case "combo":
976 $str= "<select name='".$var."' ".$dis." >";
977 foreach(split(":",$default) as $choice){
978 if($choosen==$choice){
979 $str.= "\n<option value='".$choice."' selected>".$choice." </option>";
980 }else{
981 $str.= "\n<option value='".$choice."'>".$choice." </option>";
982 }
983 }
984 $str.="</select>";
985 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
986 break;
988 case "bool":
989 if(!$choosen){
990 $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
991 }else{
992 $str="\n<input type='checkbox' name='".$var."' value='1' checked ".$dis.">";
993 }
994 $macrotab.= "<td colspan='2'>$str ".base64_decode($name)."";
995 break;
997 case "string":
998 $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
999 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
1000 break;
1002 }
1003 $macrotab.= "</td></tr>";
1005 }
1006 $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
1007 }//is_array()
1009 /* Give smarty the table */
1010 $smarty->assign("macrotab",$macrotab);
1013 /* Add phone number */
1014 if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1015 if (tests::is_phone_nr($_POST['phonenumber'])){
1016 $number= $_POST["phonenumber"];
1017 $this->phoneNumbers[$number]= $number;
1018 $this->is_modified= TRUE;
1019 } else {
1020 print_red(_("Please enter a valid phone number!"));
1021 }
1022 }
1024 /* Remove phone number */
1025 if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1026 foreach ($_POST['phonenumber_list'] as $number){
1027 unset($this->phoneNumbers[$number]);
1028 $this->is_modified= TRUE;
1029 }
1030 }
1032 /* Assign acls */
1033 $tmp = $this->plInfo();
1034 foreach($tmp['plProvidedAcls'] as $name => $translation){
1035 $smarty->assign($name."ACL",$this->getacl($name));
1036 }
1038 /* Transfer ACL's */
1039 foreach($this->attributes as $val){
1040 if(isset($this->$val)){
1041 $smarty->assign($val,$this->$val);
1042 }else{
1043 $smarty->assign($val,"");
1044 }
1045 }
1047 /* Create home server array */
1048 $tmp = array();
1049 foreach($this->goFonHomeServers as $dn => $attrs){
1050 if(!is_numeric($dn)){
1051 $tmp[$dn] = $attrs['SERVER'];
1052 }
1053 }
1054 $smarty->assign("goFonHomeServers",$tmp);
1056 /* Fill arrays */
1057 $smarty->assign ("goFonHardware", $this->goFonHardware);
1058 if (!count($this->phoneNumbers)){
1059 $smarty->assign ("phoneNumbers", array());
1060 } else {
1061 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1062 }
1064 $dis = "";
1065 if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1066 $dis= " disabled ";
1067 }
1068 $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1069 _("Choose your private phone")."\">\n";
1071 foreach ($this->hardware_list as $cn => $description){
1072 if ($cn == $this->goFonHardware){
1073 $selected= "selected";
1074 } else {
1075 $selected= "";
1076 }
1077 if (isset($this->used_hardware[$cn])){
1078 $color= "style=\"color:#A0A0A0\"";
1079 } else {
1080 $color= "";
1081 }
1082 $hl.= " <option $color label=\"$cn\" value=\"$cn\" $selected>$description </option>\n";
1083 }
1084 $hl.= "</select>\n";
1085 $smarty->assign ("hardware_list", $hl);
1088 foreach($this->attributes as $attr){
1089 if(in_array($attr,$this->multi_boxes)){
1090 $smarty->assign("use_".$attr,TRUE);
1091 }else{
1092 $smarty->assign("use_".$attr,FALSE);
1093 }
1094 }
1096 /* Show main page */
1097 $this->lastmacro = $this->macro;
1098 $smarty->assign("multiple_support",$this->multiple_support_active);
1099 $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1100 return($display);
1101 }
1104 function save_object()
1105 {
1106 $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1107 if (isset($_POST["phoneTab"])){
1109 plugin::save_object();
1111 /* Save checkbox */
1112 $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1113 if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1114 if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1115 $tmp .= "M";
1116 }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1117 $tmp = preg_replace ("/M/","",$tmp);
1118 }
1119 }
1120 $this->goFonDeliveryMode= "[".$tmp."]";
1123 /* Every macro in the select box are available */
1124 if((isset($_POST['macro']))){
1125 $this->macrostillavailable=true;
1126 }
1128 if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1129 $this->is_modified =true;
1130 }
1132 if(is_array($this->phoneNumbers)){
1133 foreach($this->phoneNumbers as $telenumms) {
1134 $nummsinorder[]=$telenumms;
1135 }
1136 }else{
1137 $nummsinorder=array("");
1138 }
1141 /* get all Postvars */
1142 if(isset($this->macroarray[$this->macro])){
1144 if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1145 foreach($this->macroarray[$this->macro] as $key => $paras){
1147 $backup = $this->macroarray[$this->macro][$key];
1149 if(isset($_POST[$paras['var']])){
1150 $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1151 }
1153 /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1154 We need this code below to read and save checkboxes correct
1155 */
1157 if(isset($_POST['post_success'])){
1158 if($this->macroarray[$this->macro][$key]['type']=="bool"){
1159 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1160 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1161 }else{
1162 $this->macroarray[$this->macro][$key]['choosen']=false;
1163 }
1164 }
1165 }
1166 }
1167 if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1168 $this->modified = TRUE;
1169 }
1170 }
1171 }
1172 }
1173 }
1175 function check()
1176 {
1177 /* Call common method to give check the hook */
1178 $message= plugin::check();
1180 if(!count($this->goFonHomeServers)){
1181 $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1182 }
1184 if(empty($this->goFonHomeServer)){
1185 $message[] = _("Please select a valid goFonHomeServer.");
1186 }
1188 if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1189 $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1190 }else{
1191 if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1192 $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1193 }
1194 }
1196 if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1197 $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1198 }
1200 if ($this->initially_was_account != $this->is_account || $this->is_modified){
1201 if(!$this->generate_mysql_entension_entries()){
1202 $message[] = $this->generate_error;
1203 }
1204 }
1206 /* We need at least one phone number */
1207 if (count($this->phoneNumbers) == 0){
1208 $message[]= sprintf(_("You need to specify at least one phone number!"));
1209 }
1211 /* check for ! in any parameter setting*/
1212 if(isset($this->macroarray[$this->macro])){
1213 foreach($this->macroarray[$this->macro] as $val){
1214 if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1215 $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1216 }
1217 }
1218 }
1219 return ($message);
1220 }
1224 function save()
1225 {
1226 plugin::save();
1228 /* Force saving macro again
1229 * This ensures that
1230 * - the macro is available on the destiantion server.
1231 * - the macro saved is up to date on the destination server.
1232 */
1233 if(!empty($this->macro) && $this->macro != "none") {
1234 $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1235 $macro_tab -> save();
1236 }
1238 /* Save arrays */
1239 $tmp_numbers = array();
1240 foreach ($this->phoneNumbers as $number){
1241 $tmp_numbers[] = $number;
1242 }
1244 /* Save settings, or remove goFonMacro attribute*/
1245 if($this->macro!="none"){
1246 $this->attrs['goFonMacro']=$this->macro;
1247 if(isset($this->macroarray[$this->macro])){
1248 foreach($this->macroarray[$this->macro] as $paras) {
1249 $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1250 }
1251 }
1252 }else{
1253 $this->attrs['goFonMacro']=array();
1254 }
1255 unset($this->attrs['macro']) ;
1257 $this->attrs['goFonForwarding']=array();
1259 if ($this->initially_was_account != $this->is_account || $this->is_modified){
1260 $str = $this->generate_mysql_entension_entries(true);
1261 if(empty($str)){
1262 print_red($str);
1263 }
1264 }
1266 if($this->attrs['goFonMacro']==""){
1267 $this->attrs['goFonMacro']=array();
1268 }
1270 unset($this->attrs['cn']);
1272 /* Write back to ldap */
1273 $ldap= $this->config->get_ldap_link();
1274 $ldap->cd($this->dn);
1275 $this->cleanup();
1277 /* Force saving numbers, else it will be overwriten by user account. */
1278 $this->attrs['telephoneNumber'] =$tmp_numbers;
1279 $ldap->modify ($this->attrs);
1281 /* Log last action */
1282 if($this->initially_was_account){
1283 new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1284 }else{
1285 new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1286 }
1288 show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/phone account with dn '%s' failed."),$this->dn));
1290 /* Optionally execute a command after we're done */
1292 if ($this->initially_was_account == $this->is_account){
1293 if ($this->is_modified){
1294 $this->handle_post_events("modify",array("uid" => $this->uid));
1295 }
1296 } else {
1297 $this->handle_post_events("add",array("uid" => $this->uid));
1298 }
1300 }
1303 function adapt_from_template($dn)
1304 {
1305 plugin::adapt_from_template($dn);
1307 /* Assemble phone numbers */
1308 if (isset($this->attrs['telephoneNumber'])){
1309 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1310 $number= $this->attrs['telephoneNumber'][$i];
1311 $this->phoneNumbers[$number]= $number;
1312 }
1313 }
1314 }
1317 function remove_from_parent()
1318 {
1319 if(!$this->initially_was_account) return;
1321 foreach($this->attributes as $key=>$val){
1322 if(in_array($val,array("uid","cn"))){
1323 unset($this->attributes[$key]);
1324 unset($this->$val);
1325 }
1326 }
1327 if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1329 // Get Configuration for initial Mysql database Server
1330 $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1331 $s_parameter ="";
1333 // Connect to DB server
1334 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1336 // Check if we are connected correctly
1337 if(!$r_con){
1338 print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1339 $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1340 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1341 return false;
1342 }
1344 // Select database for Extensions
1345 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
1347 // Test if we have the database selected correctly
1348 if(!$db){
1349 print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1350 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1351 return false;
1352 }
1354 $SQL="";
1356 /* If deletion starts from userslist, cn uid are not set */
1357 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1358 $this->uid = $this->parent->by_object['user']->uid;
1359 }
1361 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1362 $this->cn = $this->parent->by_object['user']->cn;
1363 }
1365 $first_num = false;
1366 // Delete old entries
1367 foreach($this->a_old_telenums as $s_telenums){
1368 if(!$first_num){
1369 $first_num = $s_telenums;
1370 }
1371 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1372 }
1374 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1375 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1376 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1378 foreach($SQL as $query){
1379 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1380 if(!@mysql_query($query,$r_con)){
1381 print_red(_("Stop".mysql_error()));
1382 return false;
1383 }
1384 }
1385 }else{
1386 print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1387 return false;
1388 }
1390 /* unset macro attr, it will cause an error */
1391 $tmp = array_flip($this->attributes);
1392 unset($tmp['macro']);
1393 $this->attributes=array_flip($tmp);
1395 /* Cancel if there's nothing to do here */
1396 if (!$this->initially_was_account){
1397 return;
1398 }
1400 plugin::remove_from_parent();
1402 /* Just keep one phone number */
1403 if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1404 $this->attrs['telephoneNumber']= $this->telephoneNumber;
1405 } else {
1406 $this->attrs['telephoneNumber']= array();
1407 }
1410 $ldap= $this->config->get_ldap_link();
1411 $ldap->cd($this->config->current['BASE']);
1412 $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1413 while($attr = $ldap->fetch()){
1414 if(in_array($this->dn,$attr['member'])){
1415 $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1416 unset($new->by_object['ogroup']->memberList[$this->dn]);
1417 unset($new->by_object['ogroup']->member[$this->dn]);
1418 $new->save();
1419 print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1420 }
1421 }
1422 $ldap->cd($this->dn);
1423 $this->cleanup();
1424 $ldap->modify ($this->attrs);
1426 new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1427 show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/phone account with dn '%s' failed."),$this->dn));
1429 /* Optionally execute a command after we're done */
1430 @mysql_close($r_con);
1431 $this->handle_post_events('remove',array("uid"=> $this->uid));
1432 }
1436 /* This function checks if the given phonenumbers are available or already in use*/
1437 function is_number_used()
1438 {
1439 $ldap= $this->config->get_ldap_link();
1440 $ldap->cd($this->config->current['BASE']);
1441 $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1442 while($attrs = $ldap->fetch()) {
1443 unset($attrs['telephoneNumber']['count']);
1444 foreach($attrs['telephoneNumber'] as $tele){
1445 if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1446 if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1447 $numbers[$tele]=$attrs;
1448 }
1449 }
1451 foreach($this->phoneNumbers as $num){
1452 if(!isset($this->cn)) $this->cn = "";
1454 if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1455 if(isset($numbers[$num]['uid'][0])){
1456 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1457 }else{
1458 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1459 }
1460 }
1461 }
1462 }
1465 /* Create phoneAccount part of copy & paste dialog */
1466 function getCopyDialog()
1467 {
1468 if(!$this->is_account) return("");
1469 $smarty = get_smarty();
1470 if (!count($this->phoneNumbers)){
1471 $smarty->assign ("phoneNumbers", array(""));
1472 } else {
1473 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1474 }
1476 $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1477 $smarty->assign("goFonPIN",$this->goFonPIN);
1479 $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1480 $ret =array();
1481 $ret['string'] = $display;
1482 $ret['status'] = "";
1483 return($ret);
1484 }
1486 /* Save posts from copy & paste dialog dialog */
1487 function saveCopyDialog()
1488 {
1489 if(!$this->is_account) return;
1490 $this->execute();
1491 if(isset($_POST['goFonVoicemailPIN'])) {
1492 $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1493 }
1494 if(isset($_POST['goFonPIN'])){
1495 $this->goFonPIN = $_POST['goFonPIN'];
1496 }
1497 }
1500 function allow_remove()
1501 {
1502 /* Check if previously selected server is still available */
1503 if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1504 return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1505 }
1506 }
1508 /* Return plugin informations for acl handling */
1509 static function plInfo()
1510 {
1511 return (array(
1512 "plShortName" => _("Phone"),
1513 "plDescription" => _("Phone account settings"),
1514 "plSelfModify" => TRUE,
1515 "plDepends" => array("user"),
1516 "plPriority" => 7, // Position in tabs
1517 "plSection" => "personal", // This belongs to personal
1518 "plCategory" => array("gofonreport" => array("description" => _("GOfon reports"),
1519 "objectClass" => "")),
1521 "plOptions" => array(),
1523 "plProvidedAcls" => array(
1524 "telephoneNumber" => _("Telephone number"),
1525 "goFonHomeServer" => _("Home server"),
1526 "goFonMacro" => _("Macro settings"),
1527 "goFonHardware" => _("Phone hardware"),
1528 "goFonPIN" => _("Telephone pin"),
1529 "goFonVoicemailPIN" => _("Voicemail pin"))
1530 ));
1531 }
1535 function multiple_execute()
1536 {
1537 plugin::multiple_execute();
1538 return($this->execute());
1539 }
1541 function get_multi_init_values()
1542 {
1543 $ret = plugin::get_multi_init_values();
1544 $ret['phoneNumbers'] = array();
1545 foreach($this->phoneNumbers as $number){
1546 $ret['phoneNumbers'][] = $number." [".$this->attrs['cn'][0]."]";
1547 }
1548 $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1549 return($ret);
1550 }
1552 function init_multiple_support($attrs,$all)
1553 {
1554 plugin::init_multiple_support($attrs,$all);
1556 $this->phoneNumbers = array();
1557 if(isset($all['phoneNumbers'])){
1558 for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1559 $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1560 }
1561 }
1562 }
1564 function multiple_save_object()
1565 {
1566 /* Simply call parents save_object */
1567 if (isset($_POST["phoneTab"])){
1569 plugin::save_object();
1570 plugin::multiple_save_object();
1572 /* Every macro in the select box are available */
1573 if((isset($_POST['macro']))){
1574 $this->macrostillavailable=true;
1575 }
1577 if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1578 $this->is_modified =true;
1579 }
1581 /* get all Postvars */
1582 if(isset($this->macroarray[$this->macro])){
1583 foreach($this->macroarray[$this->macro] as $key => $paras){
1584 $backup = $this->macroarray[$this->macro][$key];
1585 if(isset($_POST[$paras['var']])){
1586 $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1587 }
1588 if(isset($_POST['post_success'])){
1589 if($this->macroarray[$this->macro][$key]['type']=="bool"){
1590 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1591 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1592 }else{
1593 $this->macroarray[$this->macro][$key]['choosen']=false;
1594 }
1595 }
1596 }
1597 }
1598 if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1599 $this->modified = TRUE;
1600 }
1601 }
1602 }
1603 }
1605 function multiple_check()
1606 {
1607 $message = plugin::multiple_check();
1609 if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1610 $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1611 }
1613 if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1614 $message[] = _("Please select a valid goFonHomeServer.");
1615 }
1617 if(in_array("goFonVoicemailPIN",$this->multi_boxes) &&
1618 ( (strlen($this->goFonVoicemailPIN)==0)||
1619 (strlen($this->goFonVoicemailPIN)>4))){
1620 $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1621 }else{
1622 if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1623 $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1624 }
1625 }
1627 if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1628 $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1629 }
1631 /* check for ! in any parameter setting*/
1632 if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1633 foreach($this->macroarray[$this->macro] as $val){
1634 if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1635 $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1636 }
1637 }
1638 }
1640 return($message);
1641 }
1643 function get_multi_edit_values()
1644 {
1645 $ret = plugin::get_multi_edit_values();
1646 if(in_array("macro",$this->multi_boxes)){
1647 $ret['macro'] = $this->macro;
1648 $ret['macroarray'] = $this->macroarray;
1649 $ret['macros'] = $this->macros;
1650 }
1651 return($ret);
1652 }
1653 }
1655 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1656 ?>