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 $ldap= $this->config->get_ldap_link();
143 $ldap->cd($this->config->current['BASE']);
144 $ldap->search("(objectClass=goFonHardware)", array('cn', 'description'));
145 while ($attrs= $ldap->fetch()){
146 $cn= $attrs['cn'][0];
147 if (isset($attrs['description'])){
148 $description= " - ".$attrs['description'][0];
149 } else {
150 $description= "";
151 }
152 $this->hardware_list[$cn]= "$cn$description";
153 }
156 /* Get available Macros
157 * Search for all Marcos that are visible and create
158 * an array with name and parameters
159 */
160 $ldap->search("(&(objectClass=goFonMacro)(goFonMacroVisible=1))", array("*"));
162 /* Add none for no macro*/
163 $this->macros['none']=_("no macro");
164 $this->macro ="none";
166 /* Fetch all Macros*/
167 while ($attrs= $ldap->fetch()){
169 /* unset Count, we don't need that here */
170 unset($attrs['displayName']['count']);
172 /* Parse macro data, unset count for parameterarrays */
173 if (isset($attrs['goFonMacroParameter']['count'])){
174 unset($attrs['goFonMacroParameter']['count']);
175 }
177 /* fill Selectfield variable with Macros */
178 if(isset($attrs['displayName'][0])){
179 $this->macros[$attrs['dn']] = $attrs['displayName'][0]." (".$attrs['cn'][0].")";
180 }else{
181 $this->macros[$attrs['dn']] = _("undefined");
182 }
184 /* Go through available parameters and parse all attributes, like parametername, type, default ...*/
185 if((isset($attrs['goFonMacroParameter']))&&(is_array($attrs['goFonMacroParameter']))){
187 foreach($attrs['goFonMacroParameter'] as $pkey=>$pval){
188 /* Split Data in readable values, by delimiter ! */
189 $data = split("!",$attrs['goFonMacroParameter'][$pkey]);
191 /* Set all attrs */
192 $id = $data[0];
193 $this->macroarray[$attrs['dn']][$id]['var'] ="var".$id;
194 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
195 $this->macroarray[$attrs['dn']][$id]['id'] =$id;
196 $this->macroarray[$attrs['dn']][$id]['name'] =$data[1];
197 $this->macroarray[$attrs['dn']][$id]['type'] =$data[2];
198 $this->macroarray[$attrs['dn']][$id]['default']=$data[3];
199 if($data[2] == "bool"){
200 $this->macroarray[$attrs['dn']][$id]['choosen']=$data[3];
201 }
202 }//foreach
203 }//is_array
204 }//while
207 /* Parse used Macro
208 * If we have a macro selected, parse it and set values
209 * in $this->macroarray[$this->macro].
210 */
211 $tmp = split("!",$this->goFonMacro);
212 if(is_array($tmp)){
214 /* First value is the macroname */
215 $this->macro = $tmp[0];
217 /* Macroname saved, delete that index */
218 unset($tmp[0]);
220 /* Check if makro has been removed */
221 if(!isset($this->macros[$this->macro])){
222 $this->macrostillavailable = false;
223 }else{
224 $this->macrostillavailable = true;
225 }
227 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
228 foreach($tmp as $var){
230 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
231 $varar = split("#",$var);
233 /* Only insert if the parameter still exists */
234 if(isset($this->macroarray[$this->macro][$varar[0]])){
235 /* Assign value */
236 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
237 }
238 }
239 }
242 /* Colorize phones
243 * Used phones will be colored in grey,
244 * so we must detect which phones are currently in use.
245 */
246 $ldap->cd($this->config->current['BASE']);
247 $ldap->search("(goFonHardware=*)",array('cn','dn','goFonHardware'));
248 while($attrs = $ldap->fetch()){
249 $cn = $attrs['goFonHardware'][0];
250 if(isset($this->hardware_list[$cn])){
251 $this->used_hardware[$cn]= $cn;
252 }
253 }
254 $this->hardware_list["automatic"]= _("automatic");
255 ksort($this->hardware_list);
256 $this->a_old_telenums = $this->phoneNumbers;
258 /* Get voicemail PIN from MySQL DB
259 * Because every user can change his PIN directly from the phone
260 * without any update to the ldap
261 * This means, the PIN in the DB is up to date
262 */
263 // Connect to DB server
264 if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
265 $r_con = @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
266 if($r_con){
267 $r_db = @mysql_select_db($cur_cfg['DB'],$r_con);
269 $query_tmp = "SELECT ".$cur_cfg['VOICE_TABLE'].".password FROM ".$cur_cfg['VOICE_TABLE'].", ".
270 $cur_cfg['SIP_TABLE']." WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'";
272 $vp = mysql_fetch_row(mysql_query($query_tmp));
273 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
274 if((isset($vp[0]))&&(!empty($vp[0]))){
275 $this->goFonPINVoice = $vp[0];
276 }
277 }
278 }
279 $this->lastmacro=$this->macro;
281 if(is_callable("mysql_close")&&(isset($r_con))&&($r_con)){
282 @mysql_close($r_con) ;
283 }
284 }
287 /* This function generates the Database entries.
288 * The Parameter 'save' could be true or false.
289 * false - means only testing no database transactions.
290 * true - write database entries.
291 *
292 * 'sip_users','voice_mail' and 'extensions' table entries will be created.
293 *
294 * If the phone hardware is 'automatic' the table entries will only be removed
295 * and not added.
296 */
297 function generate_mysql_entension_entries($save = false)
298 {
299 /* Check if there is at least one server available
300 * If not, return and tell the user that saving failed
301 */
302 if(!count($this->goFonHomeServers)){
303 if($save){
304 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."));
305 }
306 return(true);
307 }
309 /* Check if Mysql extension is available */
310 if(!is_callable("mysql_pconnect")){
311 if($save)
312 print_red(_("Can't save any changes to asterisk database, there is no mysql extension available."));
313 return(true);
314 }
316 /**********************
317 * Attribute Initialisation
318 **********************/
320 $old_connection = false;
322 // Get Configuration for Mysql database Server
323 $s_parameter = ""; // Contains paramter for selected Macro
324 $r_con = false; // DB connection
325 $r_db = false; // Selected DB
326 $r_res = false; // Result resource
327 $a_ldap_attrs = array(); //
329 $s_ip = NULL; // Contains ip for Sip entry
330 $s_host = NULL; // Contains host for Sip entry
331 $s_qualify = "yes"; // Qualify entry
332 $s_pin = NULL; // Entry for secret
333 $s_type = NULL; // Entry for phone type (friend , peer ..)
335 $sip_data_array = array(); // Contains complete sip entry, to generate SQL syntax
336 $i_old_key = false; // Contains index for first old phonenumber, to delete old entries corectly
337 $i_new_key = false; // Contains index for first new phonenumber, to generate new entries corectly
339 $s_sip_values = ""; // Contains string with all values for given attributes in SQL syntax
340 $s_sip_keys = ""; // Contains all needed attributes to generate sip entry in DB
342 $s_sip_key = ""; // Key for SIP entry index
343 $s_sip_val = ""; // Value for SIP entry index
345 $b_first_deleted= false; // Only delete first entry,
346 $s_telenums = ""; // for each value variable
348 $i_is_accounted = false; // Ensure that extension entry, for name to number is only once in table
350 restore_error_handler();
352 /* Prepare some basic attributes */
353 foreach($this->a_old_telenums as $tele){
354 $oldnums[]= preg_replace("/[^0-9]/","",$tele);
355 }
356 foreach($this->phoneNumbers as $tele){
357 $newnums[]= preg_replace("/[^0-9]/","",$tele);
358 }
360 /* If deletion starts from userslist, cn uid are not set */
361 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
362 $this->uid = $this->parent->by_object['user']->uid;
363 }
364 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
365 $this->cn = $this->parent->by_object['user']->cn;
366 }
367 /* Create voicemail entry
368 */
369 if((!isset($this->cn))||(empty($this->cn))){
370 $CNname= $this->uid;
371 }else{
372 $CNname= $this->cn;
373 }
375 if((isset($this->parent))&&(isset($this->parent->by_object['mailAccount']))&&($this->parent->by_object['mailAccount']->is_account==true)){
376 $s_mail = $this->parent->by_object['mailAccount']->mail;
377 }else{
378 $s_mail = "";
379 }
380 /* Get phonehardware to setup sip entry */
381 $ldap = $this->config->get_ldap_link();
382 $r_res = $ldap->search("(&(objectClass=goFonHardware)(cn=".$this->goFonHardware."))", array('*'));
383 $a_ldap_attrs = $ldap->fetch();
385 /* Check selected phone hardware, is a default IP set? */
386 if(((isset($a_ldap_attrs['goFonDefaultIP'][0]))&&($a_ldap_attrs['goFonDefaultIP'][0] != "dynamic"))){
387 $s_ip = $a_ldap_attrs['goFonDefaultIP'][0];
388 $s_host = $s_ip;
389 }else{
390 $s_ip = NULL;
391 $s_host = "dynamic";
392 }
394 // Attribute GoFonQualify set ?
395 if(isset($a_ldap_attrs['goFonQualify'])){
396 $s_qualify = $a_ldap_attrs['goFonQualify'][0];
397 }
399 // Attribute GoFonPIN set ?
400 if(isset($this->goFonPIN)){
401 $s_pin = $this->goFonPIN;
402 }
404 // Attribute GoFonType set ?
405 if(isset($a_ldap_attrs['goFonType'])){
406 $s_type = $a_ldap_attrs['goFonType'][0];
407 }
409 if(isset($a_ldap_attrs['goFonDmtfMode'][0])){
410 $sip_data_array['dtmfmode'] = $a_ldap_attrs['goFonDmtfMode'][0];
411 }else{
412 $sip_data_array['dtmfmode'] ="rfc2833";
413 }
415 /* Check if phone number is used */
416 if($this->is_number_used()){
417 $this->generate_error = $this->is_number_used();
418 return false;
419 }
423 /**********************
424 * Check Server Connection Information
425 **********************/
427 /* Create Mysql handle for the current goFonHomeServer, if possible
428 * Get configuration to old asterisk home server
429 */
430 $a_New = $this->goFonHomeServers[$this->goFonHomeServer]; // DB Configuration
431 $new_connection = @mysql_pconnect($a_New['SERVER'],$a_New['LOGIN'],$a_New['PASSWORD']);
432 if(!$new_connection){
433 $this->generate_error = sprintf(
434 _("The MySQL Server '%s' isn't reachable as user '%s'. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
435 $a_New['SERVER'],$a_New['LOGIN']);
436 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
437 return false;
438 }
439 $new_database = @mysql_select_db($a_New['DB'],$new_connection);
440 if(!$new_database){
441 $this->generate_error = sprintf(
442 _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
443 $a_New['DB'],$a_New['SERVER']);
444 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($new_connection));
445 return false;
446 }
448 /* If the home server has changed, we must remove entries from old
449 * server and add new entries in new server.
450 */
451 if($this->init_HomeServer != $this->goFonHomeServer){
453 /* Get configuration to old asterisk home server */
454 $a_Remove = $this->goFonHomeServers[$this->init_HomeServer]; // DB Configuration
456 /* Create connection to the database that contains the old entry.
457 */
458 $old_connection = @mysql_pconnect($a_Remove['SERVER'],$a_Remove['LOGIN'],$a_Remove['PASSWORD']);
459 if(!$old_connection){
460 $this->generate_error = sprintf(
461 _("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."),
462 $a_Remove['SERVER'],$a_Remove['LOGIN']);
463 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
464 return false;
465 }
466 $old_database = @mysql_select_db($a_Remove['DB'],$old_connection);
467 if(!$old_database){
468 $this->generate_error = sprintf(
469 _("Can't select database %s on %s. Abort saving entries to keep the database consistent, check GOsa log for mysql error."),
470 $a_Remove['DB'],$a_Remove['SERVER']);
471 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error($old_connection));
472 return false;
473 }
474 }
476 /* Save means that we must save changes, not only test */
477 if($save == true){
479 /**********************
480 * Remove entries from old home server
481 **********************/
483 /* Check if there is an old entry
484 * If there is an old entry, get callerid and remove voicemail and extensions
485 */
486 if($old_connection){
487 $query = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
488 $rid = mysql_query($query,$old_connection);
489 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
491 /* Old entry found, remove it */
492 $query_a = array();
493 if(mysql_affected_rows($old_connection)){
494 $result = mysql_fetch_assoc($rid);
495 $query_a[]= "DELETE FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
496 $query_a[]= "DELETE FROM ".$a_Remove['VOICE_TABLE']." WHERE customer_id='".$result['callerid']."';";
497 $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$this->uid."';";
498 foreach($oldnums as $s_telenums) {
499 $query_a[]= "DELETE FROM ".$a_Remove['EXT_TABLE']." WHERE exten='".$s_telenums."';";
500 }
502 foreach($query_a as $qry){
503 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
504 if(!mysql_query($qry,$old_connection)){
505 echo mysql_error($old_connection);
506 }
507 }
508 }
509 }
511 /**********************
512 * Update / Insert sip_users entry
513 **********************/
515 /* Set the first given phone number as callerid */
516 reset($newnums);
517 $i_new_key = key($newnums);
518 $sip_data_array['callerid'] =$newnums[$i_new_key];
519 $sip_data_array['mailbox'] =$newnums[$i_new_key];
521 /* Check if there is already an entry in sip_users for this uid */
522 $SQL_query_array = array();
523 $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n";
524 $rid = mysql_query($query,$new_connection);
525 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
526 if(mysql_affected_rows($new_connection)){
528 /**********************
529 * Update sip_users entry
530 **********************/
531 $result = mysql_fetch_assoc($rid);
532 $sip_data_array['host'] = $s_host;
533 $sip_data_array['qualify'] = $s_qualify;
534 $sip_data_array['secret'] = $this->goFonPIN;
535 $sip_data_array['type'] = $s_type ;
536 $sip_data_array['username'] = $this->uid;
537 $sip_data_array['ipaddr'] = $s_ip;
539 /* Remove not changed attributes, to avoid updating table with same values */
540 foreach($sip_data_array as $name => $value){
541 if($result[$name] == $value){
542 unset($sip_data_array[$name]);
543 }
544 }
545 /* Only update entry if there is something to uopdate */
546 if(count($sip_data_array)){
547 $query = "UPDATE ".$a_New['SIP_TABLE']." SET ";
548 foreach($sip_data_array as $key => $val){
549 $query.= "".$key."='".$val."',";
550 }
551 $query = preg_replace("/,$/","",$query);
552 $query.= " WHERE name='".$this->uid."';";
553 $SQL_query_array[] = $query;
554 }
555 } else {
557 /**********************
558 * Insert sip_users entry
559 **********************/
560 //generate SIP entry
561 $sip_data_array['id'] = "";
562 $sip_data_array['name'] = $this->uid;
563 $sip_data_array['accountcode'] = NULL;
564 $sip_data_array['amaflags'] = NULL;
565 $sip_data_array['callgroup'] = NULL;
566 $sip_data_array['canreinvite'] = "no";
567 $sip_data_array['context'] = "default";
568 $sip_data_array['defaultip'] = NULL;
569 $sip_data_array['fromuser'] = NULL;
570 $sip_data_array['fromdomain'] = NULL;
571 $sip_data_array['host'] = $s_host;
572 $sip_data_array['insecure'] = NULL;
573 $sip_data_array['language'] = NULL;
574 $sip_data_array['mailbox'] = $newnums[$i_new_key];
575 $sip_data_array['md5secret'] = NULL;
576 $sip_data_array['nat'] = "no";
577 $sip_data_array['permit'] = NULL;
578 $sip_data_array['deny'] = NULL;
579 $sip_data_array['mask'] = NULL;
580 $sip_data_array['pickupgroup'] = NULL;
581 $sip_data_array['port'] = NULL;
582 $sip_data_array['qualify'] = $s_qualify;
583 $sip_data_array['restrictcid'] = "n";
584 $sip_data_array['rtptimeout'] = NULL;
585 $sip_data_array['rtpholdtimeout']=NULL;
586 $sip_data_array['secret'] = $this->goFonPIN;
587 $sip_data_array['type'] = $s_type ;
588 $sip_data_array['username'] = $this->uid;
589 $sip_data_array['disallow'] = NULL;
590 $sip_data_array['allow'] = NULL;
591 $sip_data_array['musiconhold'] = NULL;
592 $sip_data_array['regseconds'] = NULL;
593 $sip_data_array['ipaddr'] = $s_ip;
594 $sip_data_array['regexten'] = NULL;
595 $sip_data_array['cancallforward']=NULL;
597 /* There is currently no entry for this user in the sip_users table.
598 * We should create one i
599 */
600 foreach($sip_data_array as $s_sip_key=>$s_sip_val){
601 if($s_sip_val === NULL) continue;
602 $s_sip_values.="'".$s_sip_val."',";
603 $s_sip_keys .="`".$s_sip_key."`,";
604 }
605 $s_sip_values = preg_replace("/,$/","",$s_sip_values);
606 $s_sip_keys = preg_replace("/,$/","",$s_sip_keys);
608 /* Add sip entries to mysql queries */
609 $SQL_query_array[] ="INSERT INTO ".$a_New['SIP_TABLE']." (".$s_sip_keys.") VALUES (".$s_sip_values.");";
610 }
613 /**********************
614 * Update / Insert Voice mail entry
615 **********************/
617 $customer_id = $newnums[$i_new_key];
619 $voice_data_array = array(
620 "customer_id" => $customer_id,
621 "mailbox" => $customer_id,
622 "password" => $this->goFonVoicemailPIN,
623 "fullname" => $CNname,
624 "email" => $s_mail);
626 /* Set pager number if available */
627 if(isset($this->parent->by_object['user']->pager)){
628 $voice_data_array['pager'] = $this->parent->by_object['user']->pager;
629 }
631 /* Check if there is already an entry in sip_users for this uid */
632 $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n";
633 $rid = mysql_query($query_tmp,$new_connection);
634 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
635 if(mysql_affected_rows($new_connection)){
637 /**********************
638 * Update Voice mail entry
639 **********************/
640 $result = mysql_fetch_assoc($rid) ;
642 foreach($voice_data_array as $name => $value){
643 if($result[$name] == $value){
644 unset($voice_data_array[$name]);
645 }
646 }
648 /* Only update entry if there is something to uopdate */
649 if(count($voice_data_array)){
650 $query = "UPDATE ".$a_New['VOICE_TABLE']." SET ";
651 foreach($voice_data_array as $key => $val){
652 $query.= "".$key."='".$val."',";
653 }
654 $query = preg_replace("/,$/","",$query);
655 $query.= " WHERE customer_id='".$customer_id."';";
656 $SQL_query_array[] = $query;
657 }
658 }else{
660 /**********************
661 * Insert Voice mail entry
662 **********************/
663 $voice_data_array['context'] = "default";
665 /* There is currently no voice mail entry for this user.
666 * We should create one
667 */
668 $s_voi_values = $s_voi_keys = "";
669 foreach($voice_data_array as $s_voi_key=>$s_voi_val){
670 if($s_voi_val === NULL) continue;
671 $s_voi_values.="'".$s_voi_val."',";
672 $s_voi_keys .="`".$s_voi_key."`,";
673 }
674 $s_voi_values = preg_replace("/,$/","",$s_voi_values);
675 $s_voi_keys = preg_replace("/,$/","",$s_voi_keys);
677 /* Add sip entries to mysql queries */
678 $SQL_query_array[] ="INSERT INTO ".$a_New['VOICE_TABLE']." (".$s_voi_keys.") VALUES (".$s_voi_values.");";
679 }
682 /**********************
683 * Remove/Insert extension entries
684 **********************/
686 /* Remove old entries */
687 $query = array();
688 $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
689 foreach($oldnums as $s_telenums){
690 $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
691 }
692 foreach($newnums as $s_telenums){
693 $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
694 }
695 foreach($query as $qry){
696 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
697 if(!mysql_query($qry,$new_connection)){
698 echo mysql_error($new_connection);
699 }
700 }
702 /**********************
703 * Insert extension entries
704 **********************/
706 // Get selected Macro Parameter and create parameter entry
707 if(isset($this->macroarray[$this->macro])){
708 foreach($this->macroarray[$this->macro] as $key => $val ){
709 $s_parameter .= $val['choosen']."|";
710 }
711 $s_parameter = preg_replace("/\|$/","",$s_parameter);
712 }
714 $i = 0;
715 $EXT = array();
716 if(!is_numeric($this->uid)){
717 $EXT[$i]['context'] = 'GOsa';
718 $EXT[$i]['exten'] = $this->uid;
719 $EXT[$i]['priority']= 1;
720 $EXT[$i]['app'] = "Goto";
721 $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
722 $i ++;
723 }
725 // Entension entries Hint / Dial / Goto
726 foreach($newnums as $s_telenums){
728 /* Hint Entry */
729 $EXT[$i]['context'] = 'GOsa';
730 $EXT[$i]['exten'] = $s_telenums;
731 $EXT[$i]['priority']= "Hint";
732 $EXT[$i]['app'] = 'SIP/'.$this->uid;
733 $i ++;
734 /* SetCID */
735 //$EXT[$i]['context'] = 'GOsa';
736 //$EXT[$i]['exten'] = $s_telenums;
737 //$EXT[$i]['priority']= 1;
738 //$EXT[$i]['app'] = "SetCIDName";
739 //$EXT[$i]['appdata'] = $CNname;
740 //$i ++;
742 // If no macro is selected use Dial
743 if($this->macro!="none"){
744 $macroname = preg_replace("/,.*$/","",$this->macro);
745 $macroname = preg_replace("/^.*=/","",$macroname);
746 $s_app = "Macro";$macroname;
747 $s_par = $macroname."|".$s_parameter;
748 }else{
749 $s_app = "Dial";
750 $s_par = 'SIP/'.$this->uid."|20|r";
751 }
753 $EXT[$i]['context'] = 'GOsa';
754 $EXT[$i]['exten'] = $s_telenums;
755 $EXT[$i]['priority']= 1;
756 $EXT[$i]['app'] = $s_app;
757 $EXT[$i]['appdata'] = $s_par;
758 $i ++;
759 }
761 // Append all these Entries
762 foreach($EXT as $entr){
763 $SQL_syn = "INSERT INTO ".$a_New['EXT_TABLE']." (";
764 foreach($entr as $key2 => $val2){
765 $SQL_syn.= "`".$key2."`,";
766 }
767 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
768 $SQL_syn .= ") VALUES (";
769 foreach($entr as $key2 => $val2){
770 $SQL_syn .= "'".$val2."',";
771 }
772 $SQL_syn = preg_replace("/,$/","",$SQL_syn);
773 $SQL_syn .=");\n";
775 $SQL_query_array[] =$SQL_syn;
776 $SQL_syn ="";
777 }
779 // Perform queries ...
780 if($this->goFonHardware != "automatic"){
781 foreach($SQL_query_array as $query){
782 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
783 if(!@mysql_query($query,$new_connection)){
784 print_red(_("Error while performing query:")." ".mysql_error());
785 return false;
786 }
787 }
788 }
789 }
790 @mysql_close($new_connection);
791 return true;
792 }
795 function execute()
796 {
797 /* Call parent execute */
798 plugin::execute();
800 /* Log view */
801 if($this->is_account && !$this->view_logged){
802 $this->view_logged = TRUE;
803 new log("view","users/".get_class($this),$this->dn);
804 }
806 $display = "";
807 $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
808 if(empty($this->macro)&&(!empty($this->goFonMacro))){
810 /* Go through already saved values, for a parameter */
811 $tmp = split("!",$this->goFonMacro);
813 /* it is possible that nothing has been saved yet */
814 if(is_array($tmp)){
816 /* First value is the macroname */
817 $this->macro = $tmp[0];
819 /* Macroname saved, delete that index */
820 unset($tmp[0]);
822 /* Check if macro has been removed */
823 if(!isset($this->macroarray[$this->macro])){
824 $this->macrostillavailable = false;
825 }else{
826 $this->macrostillavailable = true;
827 }
829 /* for each parametervalues ( parameterID#value like 25#twentyfive) */
830 foreach($tmp as $var){
832 /* Split this, so we have $varar[0] = parameterID $varar[1] = SelectedValue */
833 $varar = split("#",$var);
835 /* Only insert if the parameter still exists */
836 if(isset($this->macroarray[$this->macro][$varar[0]])){
837 /* Assign value */
838 $this->macroarray[$this->macro][$varar[0]]['choosen']=$varar[1];
839 }
840 }
841 }
842 }
844 /* Do we represent a valid account? */
845 if (!$this->is_account && $this->parent === NULL){
846 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
847 _("This account has no phone extensions.")."</b>";
848 $display.= back_to_main();
849 return ($display);
850 }
852 /* Do we need to flip is_account state? */
853 if (isset($_POST['modify_state'])){
854 $this->is_account= !$this->is_account;
855 }
857 /* Do we represent a valid account? */
858 if (!$this->is_account && $this->parent === NULL){
859 $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\"> <b>".
860 _("This account has no phone extensions.")."</b>";
861 $display.= back_to_main();
862 return($display);
863 }
865 $display= "";
867 /* Show tab dialog headers */
869 if (!$this->multiple_support_active && $this->parent !== NULL){
870 if ($this->is_account){
871 $display= $this->show_disable_header(_("Remove phone account"),
872 _("This account has phone features enabled. You can disable them by clicking below."));
873 } else {
874 if(empty($this->uid)){
875 $display= $this->show_enable_header(_("Create phone account"),
876 _("This account has phone features disabled. You can't enable them while no uid is set."),TRUE,TRUE);
877 }else{
878 $display= $this->show_enable_header(_("Create phone account"),
879 _("This account has phone features disabled. You can enable them by clicking below."));
880 }
881 return ($display);
882 }
883 }
884 /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
885 if(empty($this->macro)){
886 $this->macro ="none";
887 }
889 /* Prepare templating */
890 $smarty= get_smarty();
892 /* tell user that the selected plugin is no longer available */
893 if((!$this->macrostillavailable)&&($this->macro!="none")){
894 print_red(_("The macro you selected, is no longer available for you, please choose another one."));
895 }
897 /* Assing macroselectbox values */
898 $smarty->assign("macros",$this->macros);
899 $smarty->assign("macro", $this->macro);
901 /* check if there is a FON server created */
902 if(!count($this->goFonHomeServer)){
903 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."));
904 }
906 /* Create html parameter table for selected macro parameters
907 * skip if no parameters given
908 */
909 if(!isset($this->macroarray[$this->macro])){
910 $macrotab="";
911 }else{
913 $macrotab ="<table summary=\""._("Parameter")."\">";
914 /* for every single parameter-> display textfile,combo, or true false switch*/
916 foreach($this->phoneNumbers as $phonenum){
917 $tmp[] = $phonenum;
918 }
920 if($this->macro != $this->lastmacro){
921 /* Go through all params */
922 foreach($this->macroarray[$this->macro] as $key => $paras){
924 $string = $paras['default'];
926 $string=preg_replace("/%uid/i",$this->uid,$string);
928 if(isset($this->cn)){
929 $string=preg_replace("/%cn/i",$this->cn,$string);
930 }
932 for($i = 0 ; $i < 10; $i++){
933 if(isset($tmp[$i])){
934 $string = preg_replace("/%telephoneNumber_".($i+1)."/i",$tmp[$i],$string);
935 }
936 }
937 if(isset($tmp[0])){
938 $string = preg_replace("/%telephoneNumber/i",$tmp[0],$string);
939 }
940 $this->macroarray[$this->macro][$key]['choosen']=$string;
941 }
942 }
944 foreach($this->macroarray[$this->macro] as $paras){
946 /* get al vars */
947 $var = $paras['var'];
948 $name = $paras['name'];
949 $default = $paras['default'];
950 $type = $paras['type'];
951 $choosen = $paras['choosen'] ;
952 $str = $default;
954 $dis = "";
955 if(!$this->acl_is_writeable("goFonMacro",$SkipWrite)){
956 $dis = " disabled ";
957 }
959 /* in case of a combo box display a combobox with selected attr */
960 $macrotab.= "<tr>";
961 switch ($type){
963 case "combo":
964 $str= "<select name='".$var."' ".$dis." >";
965 foreach(split(":",$default) as $choice){
966 if($choosen==$choice){
967 $str.= "\n<option value='".$choice."' selected>".$choice." </option>";
968 }else{
969 $str.= "\n<option value='".$choice."'>".$choice." </option>";
970 }
971 }
972 $str.="</select>";
973 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
974 break;
976 case "bool":
977 if(!$choosen){
978 $str="\n<input type='checkbox' name='".$var."' value='1' ".$dis." >";
979 }else{
980 $str="\n<input type='checkbox' name='".$var."' value='1' checked ".$dis.">";
981 }
982 $macrotab.= "<td colspan='2'>$str ".base64_decode($name)."";
983 break;
985 case "string":
986 $str="<input name='".$var."' value='".$choosen."' ".$dis." style='width:340px;'>";
987 $macrotab.= "<td>".base64_decode($name)."</td><td>$str";
988 break;
990 }
991 $macrotab.= "</td></tr>";
993 }
994 $macrotab.="</table><input name='post_success' type='hidden' value='1'>";
995 }//is_array()
997 /* Give smarty the table */
998 $smarty->assign("macrotab",$macrotab);
1001 /* Add phone number */
1002 if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
1003 if (tests::is_phone_nr($_POST['phonenumber'])){
1004 $number= $_POST["phonenumber"];
1005 $this->phoneNumbers[$number]= $number;
1006 $this->is_modified= TRUE;
1007 } else {
1008 print_red(_("Please enter a valid phone number!"));
1009 }
1010 }
1012 /* Remove phone number */
1013 if (isset($_POST["delete_phonenumber"]) && isset($_POST["phonenumber_list"])){
1014 foreach ($_POST['phonenumber_list'] as $number){
1015 unset($this->phoneNumbers[$number]);
1016 $this->is_modified= TRUE;
1017 }
1018 }
1020 /* Assign acls */
1021 $tmp = $this->plInfo();
1022 foreach($tmp['plProvidedAcls'] as $name => $translation){
1023 $smarty->assign($name."ACL",$this->getacl($name));
1024 }
1026 /* Transfer ACL's */
1027 foreach($this->attributes as $val){
1028 if(isset($this->$val)){
1029 $smarty->assign($val,$this->$val);
1030 }else{
1031 $smarty->assign($val,"");
1032 }
1033 }
1035 /* Create home server array */
1036 $tmp = array();
1037 foreach($this->goFonHomeServers as $dn => $attrs){
1038 if(!is_numeric($dn)){
1039 $tmp[$dn] = $attrs['SERVER'];
1040 }
1041 }
1042 $smarty->assign("goFonHomeServers",$tmp);
1044 /* Fill arrays */
1045 $smarty->assign ("goFonHardware", $this->goFonHardware);
1046 if (!count($this->phoneNumbers)){
1047 $smarty->assign ("phoneNumbers", array());
1048 } else {
1049 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1050 }
1052 $dis = "";
1053 if(!$this->acl_is_writeable("goFonHardware",$SkipWrite)){
1054 $dis= " disabled ";
1055 }
1056 $hl= "<select size=\"1\" name=\"goFonHardware\" ".$dis." title=\"".
1057 _("Choose your private phone")."\">\n";
1059 foreach ($this->hardware_list as $cn => $description){
1060 if ($cn == $this->goFonHardware){
1061 $selected= "selected";
1062 } else {
1063 $selected= "";
1064 }
1065 if (isset($this->used_hardware[$cn])){
1066 $color= "style=\"color:#A0A0A0\"";
1067 } else {
1068 $color= "";
1069 }
1070 $hl.= " <option $color label=\"$cn\" value=\"$cn\" $selected>$description </option>\n";
1071 }
1072 $hl.= "</select>\n";
1073 $smarty->assign ("hardware_list", $hl);
1076 foreach($this->attributes as $attr){
1077 if(in_array($attr,$this->multi_boxes)){
1078 $smarty->assign("use_".$attr,TRUE);
1079 }else{
1080 $smarty->assign("use_".$attr,FALSE);
1081 }
1082 }
1084 /* Show main page */
1085 $this->lastmacro = $this->macro;
1086 $smarty->assign("multiple_support",$this->multiple_support_active);
1087 $display.= $smarty->fetch(get_template_path('generic.tpl', TRUE, dirname(__FILE__)));
1088 return($display);
1089 }
1092 function save_object()
1093 {
1094 $SkipWrite = (!isset($this->parent) || !$this->parent) && !session::is_set('edit');
1095 if (isset($_POST["phoneTab"])){
1097 plugin::save_object();
1099 /* Save checkbox */
1100 $tmp = preg_replace("/[^a-z]/i","",$this->goFonDeliveryMode);
1101 if($this->acl_is_writeable("goFonDeliveryMode",$SkipWrite)){
1102 if(isset($_POST['fon_to_mail']) && !preg_match("/M/",$this->goFonDeliveryMode)){
1103 $tmp .= "M";
1104 }elseif(!isset($_POST['fon_to_mail']) && preg_match("/M/",$this->goFonDeliveryMode)){
1105 $tmp = preg_replace ("/M/","",$tmp);
1106 }
1107 }
1108 $this->goFonDeliveryMode= "[".$tmp."]";
1111 /* Every macro in the select box are available */
1112 if((isset($_POST['macro']))){
1113 $this->macrostillavailable=true;
1114 }
1116 if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1117 $this->is_modified =true;
1118 }
1120 if(is_array($this->phoneNumbers)){
1121 foreach($this->phoneNumbers as $telenumms) {
1122 $nummsinorder[]=$telenumms;
1123 }
1124 }else{
1125 $nummsinorder=array("");
1126 }
1129 /* get all Postvars */
1130 if(isset($this->macroarray[$this->macro])){
1132 if($this->acl_is_writeable("goFonMarco",$SkipWrite)){
1133 foreach($this->macroarray[$this->macro] as $key => $paras){
1135 $backup = $this->macroarray[$this->macro][$key];
1137 if(isset($_POST[$paras['var']])){
1138 $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1139 }
1141 /* Checkboxes are special, they are not Posted if they are not selected, so the won't be changed with the above code
1142 We need this code below to read and save checkboxes correct
1143 */
1145 if(isset($_POST['post_success'])){
1146 if($this->macroarray[$this->macro][$key]['type']=="bool"){
1147 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1148 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1149 }else{
1150 $this->macroarray[$this->macro][$key]['choosen']=false;
1151 }
1152 }
1153 }
1154 }
1155 if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1156 $this->modified = TRUE;
1157 }
1158 }
1159 }
1160 }
1161 }
1163 function check()
1164 {
1165 /* Call common method to give check the hook */
1166 $message= plugin::check();
1168 if(!count($this->goFonHomeServers)){
1169 $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1170 }
1172 if(empty($this->goFonHomeServer)){
1173 $message[] = _("Please select a valid goFonHomeServer.");
1174 }
1176 if((strlen($this->goFonVoicemailPIN)==0)||(strlen($this->goFonVoicemailPIN)>4)){
1177 $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1178 }else{
1179 if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN)){
1180 $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1181 }
1182 }
1184 if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
1185 $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1186 }
1188 if ($this->initially_was_account != $this->is_account || $this->is_modified){
1189 if(!$this->generate_mysql_entension_entries()){
1190 $message[] = $this->generate_error;
1191 }
1192 }
1194 /* We need at least one phone number */
1195 if (count($this->phoneNumbers) == 0){
1196 $message[]= sprintf(_("You need to specify at least one phone number!"));
1197 }
1199 /* check for ! in any parameter setting*/
1200 if(isset($this->macroarray[$this->macro])){
1201 foreach($this->macroarray[$this->macro] as $val){
1202 if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1203 $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1204 }
1205 }
1206 }
1207 return ($message);
1208 }
1212 function save()
1213 {
1214 plugin::save();
1216 /* Force saving macro again
1217 * This ensures that
1218 * - the macro is available on the destiantion server.
1219 * - the macro saved is up to date on the destination server.
1220 */
1221 if(!empty($this->macro) && $this->macro != "none") {
1222 $macro_tab= new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro,"gofonmacro");
1223 $macro_tab -> save();
1224 }
1226 /* Save arrays */
1227 $tmp_numbers = array();
1228 foreach ($this->phoneNumbers as $number){
1229 $tmp_numbers[] = $number;
1230 }
1232 /* Save settings, or remove goFonMacro attribute*/
1233 if($this->macro!="none"){
1234 $this->attrs['goFonMacro']=$this->macro;
1235 if(isset($this->macroarray[$this->macro])){
1236 foreach($this->macroarray[$this->macro] as $paras) {
1237 $this->attrs['goFonMacro'].="!".$paras['id']."#".$paras['choosen'];
1238 }
1239 }
1240 }else{
1241 $this->attrs['goFonMacro']=array();
1242 }
1243 unset($this->attrs['macro']) ;
1245 $this->attrs['goFonForwarding']=array();
1247 if ($this->initially_was_account != $this->is_account || $this->is_modified){
1248 $str = $this->generate_mysql_entension_entries(true);
1249 if(empty($str)){
1250 print_red($str);
1251 }
1252 }
1254 if($this->attrs['goFonMacro']==""){
1255 $this->attrs['goFonMacro']=array();
1256 }
1258 unset($this->attrs['cn']);
1260 /* Write back to ldap */
1261 $ldap= $this->config->get_ldap_link();
1262 $ldap->cd($this->dn);
1263 $this->cleanup();
1265 /* Force saving numbers, else it will be overwriten by user account. */
1266 $this->attrs['telephoneNumber'] =$tmp_numbers;
1267 $ldap->modify ($this->attrs);
1269 /* Log last action */
1270 if($this->initially_was_account){
1271 new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1272 }else{
1273 new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1274 }
1276 show_ldap_error($ldap->get_error(), sprintf(_("Saving of user/phone account with dn '%s' failed."),$this->dn));
1278 /* Optionally execute a command after we're done */
1280 if ($this->initially_was_account == $this->is_account){
1281 if ($this->is_modified){
1282 $this->handle_post_events("modify",array("uid" => $this->uid));
1283 }
1284 } else {
1285 $this->handle_post_events("add",array("uid" => $this->uid));
1286 }
1288 }
1291 function adapt_from_template($dn)
1292 {
1293 plugin::adapt_from_template($dn);
1295 /* Assemble phone numbers */
1296 if (isset($this->attrs['telephoneNumber'])){
1297 for ($i= 0; $i<$this->attrs['telephoneNumber']['count']; $i++){
1298 $number= $this->attrs['telephoneNumber'][$i];
1299 $this->phoneNumbers[$number]= $number;
1300 }
1301 }
1302 }
1305 function remove_from_parent()
1306 {
1307 if(!$this->initially_was_account) return;
1309 foreach($this->attributes as $key=>$val){
1310 if(in_array($val,array("uid","cn"))){
1311 unset($this->attributes[$key]);
1312 unset($this->$val);
1313 }
1314 }
1315 if(count($this->goFonHomeServers) && !empty($this->init_HomeServer) && is_callable("mysql_pconnect")){
1317 // Get Configuration for initial Mysql database Server
1318 $a_SETUP = $this->goFonHomeServers[$this->init_HomeServer];
1319 $s_parameter ="";
1321 // Connect to DB server
1322 $r_con = @mysql_pconnect($a_SETUP['SERVER'],$a_SETUP['LOGIN'],$a_SETUP['PASSWORD']);
1324 // Check if we are connected correctly
1325 if(!$r_con){
1326 print_red(sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
1327 $a_SETUP['SERVER'],$a_SETUP['LOGIN']));
1328 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1329 return false;
1330 }
1332 // Select database for Extensions
1333 $db = @mysql_select_db($a_SETUP['DB'],$r_con);
1335 // Test if we have the database selected correctly
1336 if(!$db){
1337 print_red(sprintf(_("Can't select database %s on %s."),$a_SETUP['DB'],$a_SETUP['SERVER']));
1338 new log("debug","gofonreport/".get_class($this),"",array(),@mysql_error());
1339 return false;
1340 }
1342 $SQL="";
1344 /* If deletion starts from userslist, cn uid are not set */
1345 if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
1346 $this->uid = $this->parent->by_object['user']->uid;
1347 }
1349 if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
1350 $this->cn = $this->parent->by_object['user']->cn;
1351 }
1353 $first_num = false;
1354 // Delete old entries
1355 foreach($this->a_old_telenums as $s_telenums){
1356 if(!$first_num){
1357 $first_num = $s_telenums;
1358 }
1359 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$s_telenums."';\n";
1360 }
1362 $SQL[] = "DELETE FROM ".$a_SETUP['VOICE_TABLE']." WHERE customer_id='".$first_num."';";
1363 $SQL[] = "DELETE FROM ".$a_SETUP['EXT_TABLE']." WHERE exten='".$this->uid."';\n";
1364 $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
1366 foreach($SQL as $query){
1367 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
1368 if(!@mysql_query($query,$r_con)){
1369 print_red(_("Stop".mysql_error()));
1370 return false;
1371 }
1372 }
1373 }else{
1374 print_red(_("Can't remove phone account, the mysql extension is not present in php configuration."));
1375 return false;
1376 }
1378 /* unset macro attr, it will cause an error */
1379 $tmp = array_flip($this->attributes);
1380 unset($tmp['macro']);
1381 $this->attributes=array_flip($tmp);
1383 /* Cancel if there's nothing to do here */
1384 if (!$this->initially_was_account){
1385 return;
1386 }
1388 plugin::remove_from_parent();
1390 /* Just keep one phone number */
1391 if (count($this->telephoneNumber) && $this->telephoneNumber != ""){
1392 $this->attrs['telephoneNumber']= $this->telephoneNumber;
1393 } else {
1394 $this->attrs['telephoneNumber']= array();
1395 }
1398 $ldap= $this->config->get_ldap_link();
1399 $ldap->cd($this->config->current['BASE']);
1400 $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
1401 while($attr = $ldap->fetch()){
1402 if(in_array($this->dn,$attr['member'])){
1403 $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
1404 unset($new->by_object['ogroup']->memberList[$this->dn]);
1405 unset($new->by_object['ogroup']->member[$this->dn]);
1406 $new->save();
1407 print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
1408 }
1409 }
1410 $ldap->cd($this->dn);
1411 $this->cleanup();
1412 $ldap->modify ($this->attrs);
1414 new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
1415 show_ldap_error($ldap->get_error(), sprintf(_("Removing of user/phone account with dn '%s' failed."),$this->dn));
1417 /* Optionally execute a command after we're done */
1418 @mysql_close($r_con);
1419 $this->handle_post_events('remove',array("uid"=> $this->uid));
1420 }
1424 /* This function checks if the given phonenumbers are available or already in use*/
1425 function is_number_used()
1426 {
1427 $ldap= $this->config->get_ldap_link();
1428 $ldap->cd($this->config->current['BASE']);
1429 $ldap->search("(|(objectClass=goFonAccount)(objectClass=goFonQueue)(objectClass=goFonConference))", array("telephoneNumber","cn","uid"));
1430 while($attrs = $ldap->fetch()) {
1431 unset($attrs['telephoneNumber']['count']);
1432 foreach($attrs['telephoneNumber'] as $tele){
1433 if(!isset($attrs['cn'][0])) $attrs['cn'][0]=$attrs['dn'];
1434 if(!isset($attrs['uid'][0])) $attrs['uid'][0]=$attrs['dn'];
1435 $numbers[$tele]=$attrs;
1436 }
1437 }
1439 foreach($this->phoneNumbers as $num){
1440 if(!isset($this->cn)) $this->cn = "";
1442 if((isset($numbers[$num]))&&(($numbers[$num]['uid'][0]!=$this->uid))){
1443 if(isset($numbers[$num]['uid'][0])){
1444 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['uid'][0]);
1445 }else{
1446 return sprintf(_("The specified telephonenumber '%s' is already assigned to '%s'."),$num,$numbers[$num]['cn'][0]);
1447 }
1448 }
1449 }
1450 }
1453 /* Create phoneAccount part of copy & paste dialog */
1454 function getCopyDialog()
1455 {
1456 if(!$this->is_account) return("");
1457 $smarty = get_smarty();
1458 if (!count($this->phoneNumbers)){
1459 $smarty->assign ("phoneNumbers", array(""));
1460 } else {
1461 $smarty->assign ("phoneNumbers", $this->phoneNumbers);
1462 }
1464 $smarty->assign("goFonVoicemailPIN",$this->goFonVoicemailPIN);
1465 $smarty->assign("goFonPIN",$this->goFonPIN);
1467 $display= $smarty->fetch(get_template_path('paste_generic.tpl', TRUE, dirname(__FILE__)));
1468 $ret =array();
1469 $ret['string'] = $display;
1470 $ret['status'] = "";
1471 return($ret);
1472 }
1474 /* Save posts from copy & paste dialog dialog */
1475 function saveCopyDialog()
1476 {
1477 if(!$this->is_account) return;
1478 $this->execute();
1479 if(isset($_POST['goFonVoicemailPIN'])) {
1480 $this->goFonVoicemailPIN = $_POST['goFonVoicemailPIN'];
1481 }
1482 if(isset($_POST['goFonPIN'])){
1483 $this->goFonPIN = $_POST['goFonPIN'];
1484 }
1485 }
1488 function allow_remove()
1489 {
1490 /* Check if previously selected server is still available */
1491 if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
1492 return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
1493 }
1494 }
1496 /* Return plugin informations for acl handling */
1497 static function plInfo()
1498 {
1499 return (array(
1500 "plShortName" => _("Phone"),
1501 "plDescription" => _("Phone account settings"),
1502 "plSelfModify" => TRUE,
1503 "plDepends" => array("user"),
1504 "plPriority" => 7, // Position in tabs
1505 "plSection" => "personal", // This belongs to personal
1506 "plCategory" => array("gofonreport" => array("description" => _("GOfon reports"),
1507 "objectClass" => "")),
1509 "plOptions" => array(),
1511 "plProvidedAcls" => array(
1512 "telephoneNumber" => _("Telephone number"),
1513 "goFonHomeServer" => _("Home server"),
1514 "goFonMacro" => _("Macro settings"),
1515 "goFonHardware" => _("Phone hardware"),
1516 "goFonPIN" => _("Telephone pin"),
1517 "goFonVoicemailPIN" => _("Voicemail pin"))
1518 ));
1519 }
1523 function multiple_execute()
1524 {
1525 plugin::multiple_execute();
1526 return($this->execute());
1527 }
1529 function get_multi_init_values()
1530 {
1531 $ret = plugin::get_multi_init_values();
1532 $ret['phoneNumbers'] = array();
1533 foreach($this->phoneNumbers as $number){
1534 $ret['phoneNumbers'][] = $number." [".$this->attrs['cn'][0]."]";
1535 }
1536 $ret['phoneNumbers']['count'] = count($ret['phoneNumbers']);
1537 return($ret);
1538 }
1540 function init_multiple_support($attrs,$all)
1541 {
1542 plugin::init_multiple_support($attrs,$all);
1544 $this->phoneNumbers = array();
1545 if(isset($all['phoneNumbers'])){
1546 for($i = 0 ; $i < $all['phoneNumbers']['count'] ; $i++){
1547 $this->phoneNumbers[$all['phoneNumbers'][$i]] = $all['phoneNumbers'][$i];
1548 }
1549 }
1550 }
1552 function multiple_save_object()
1553 {
1554 /* Simply call parents save_object */
1555 if (isset($_POST["phoneTab"])){
1557 plugin::save_object();
1558 plugin::multiple_save_object();
1560 /* Every macro in the select box are available */
1561 if((isset($_POST['macro']))){
1562 $this->macrostillavailable=true;
1563 }
1565 if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
1566 $this->is_modified =true;
1567 }
1569 /* get all Postvars */
1570 if(isset($this->macroarray[$this->macro])){
1571 foreach($this->macroarray[$this->macro] as $key => $paras){
1572 $backup = $this->macroarray[$this->macro][$key];
1573 if(isset($_POST[$paras['var']])){
1574 $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
1575 }
1576 if(isset($_POST['post_success'])){
1577 if($this->macroarray[$this->macro][$key]['type']=="bool"){
1578 if(isset($_POST[$this->macroarray[$this->macro][$key]['var']])) {
1579 $this->macroarray[$this->macro][$key]['choosen']=$_POST[$paras['var']];
1580 }else{
1581 $this->macroarray[$this->macro][$key]['choosen']=false;
1582 }
1583 }
1584 }
1585 }
1586 if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
1587 $this->modified = TRUE;
1588 }
1589 }
1590 }
1591 }
1593 function multiple_check()
1594 {
1595 $message = plugin::multiple_check();
1597 if(!count($this->goFonHomeServers) && in_array("goFonHomeServers",$this->multi_boxes)){
1598 $message[] = _("There must be at least one server with an asterisk database to create a phone account.");
1599 }
1601 if(empty($this->goFonHomeServer) && in_array("goFonHomeServers",$this->multi_boxes)){
1602 $message[] = _("Please select a valid goFonHomeServer.");
1603 }
1605 if(in_array("goFonVoicemailPIN",$this->multi_boxes) &&
1606 ( (strlen($this->goFonVoicemailPIN)==0)||
1607 (strlen($this->goFonVoicemailPIN)>4))){
1608 $message[]=(_("Voicemail PIN must be between 1-4 characters."));
1609 }else{
1610 if(preg_match("/[^0-9]/",$this->goFonVoicemailPIN) && in_array("goFonVoicemailPIN",$this->multi_boxes) ){
1611 $message[]=(_("The specified Voicemail PIN contains invalid characters, only numeric values are allowed here."));
1612 }
1613 }
1615 if(preg_match("/[^0-9a-z]/i",$this->goFonPIN) && in_array("goFonPIN",$this->multi_boxes)){
1616 $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
1617 }
1619 /* check for ! in any parameter setting*/
1620 if(isset($this->macroarray[$this->macro]) && in_array("macro",$this->multi_boxes)){
1621 foreach($this->macroarray[$this->macro] as $val){
1622 if((strstr($val['choosen'],"!"))||(strstr($val['choosen'],"#"))){
1623 $message[] = sprintf(_("The parameter %s contains invalid char. '!,#' is used as delimiter"),$val['name']);
1624 }
1625 }
1626 }
1628 return($message);
1629 }
1631 function get_multi_edit_values()
1632 {
1633 $ret = plugin::get_multi_edit_values();
1634 if(in_array("macro",$this->multi_boxes)){
1635 $ret['macro'] = $this->macro;
1636 $ret['macroarray'] = $this->macroarray;
1637 $ret['macros'] = $this->macros;
1638 }
1639 return($ret);
1640 }
1641 }
1643 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1644 ?>