From 3a4c2f72e2b0d9736286d6561ce1b122b29407e7 Mon Sep 17 00:00:00 2001 From: frytimo Date: Sat, 2 Dec 2023 20:16:18 -0400 Subject: [PATCH] Event socket bug fix and more docs (#6823) * Add documentation to methods. Use is_resource for added type detection * Allow connect to specify timeout in microseconds with default 30,000 * Update calling mechanism for event sockets * Update project for new singleton event sockets * remove unused variable * catch errors on closing the socket --- app/access_controls/access_control_edit.php | 10 +- .../access_controls_reload.php | 15 +- app/access_controls/app_defaults.php | 10 +- .../resources/classes/access_controls.php | 15 +- app/basic_operator_panel/exec.php | 4 +- app/basic_operator_panel/index.php | 6 +- .../classes/basic_operator_panel.php | 14 +- .../resources/content.php | 9 +- app/call_broadcast/call_broadcast_send.php | 9 +- app/call_broadcast/call_broadcast_stop.php | 6 +- .../call_center_active_inc.php | 10 +- app/call_center_active/call_center_exec.php | 11 +- app/call_centers/call_center_agent_edit.php | 36 +- app/call_centers/call_center_agent_status.php | 33 +- app/call_centers/call_center_queue_edit.php | 24 +- app/call_centers/cmd.php | 11 +- .../resources/classes/call_center.php | 17 +- .../dashboard/call_center_agents.php | 20 +- .../resources/jobs/call_center_agents.php | 11 +- app/call_flows/call_flow_edit.php | 7 +- .../resources/classes/call_flows.php | 3 +- app/call_forward/call_forward_edit.php | 8 +- .../resources/classes/do_not_disturb.php | 6 +- .../classes/feature_event_notify.php | 11 +- app/call_forward/resources/jobs/dnd.php | 99 +- app/calls_active/calls_active_inc.php | 8 +- app/calls_active/calls_exec.php | 11 +- app/click_to_call/click_to_call.php | 205 +- .../conference_room_edit.php | 6 +- app/conference_centers/conference_rooms.php | 14 +- .../resources/classes/call_center_notify.php | 7 +- .../resources/classes/conference_centers.php | 8 +- app/conferences_active/conference_exec.php | 44 +- .../conference_interactive_inc.php | 8 +- .../conferences_active_inc.php | 6 +- app/devices/cmd.php | 13 +- app/dialplans/dialplan_edit.php | 10 +- app/email_queue/resources/jobs/email_send.php | 14 +- .../resources/classes/event_guard.php | 4 +- app/extensions/extension_edit.php | 4 +- app/fax/fax_outbox.php | 6 +- app/fax_queue/resources/job/fax_send.php | 9 +- app/fifo_list/fifo_exec.php | 18 +- app/fifo_list/fifo_interactive_inc.php | 6 +- app/fifo_list/fifo_list_inc.php | 6 +- app/gateways/gateway_copy.php | 4 +- app/gateways/gateway_edit.php | 12 +- app/gateways/gateways.php | 28 +- app/gateways/resources/classes/gateways.php | 72 +- app/modules/modules.php | 22 +- app/modules/resources/classes/modules.php | 29 +- .../classes/switch_music_on_hold.php | 8 +- app/number_translations/cmd.php | 10 +- app/phrases/app_defaults.php | 6 +- .../resources/classes/registrations.php | 14 +- .../resources/classes/sip_profiles.php | 24 +- app/sip_profiles/sip_profile_edit.php | 6 +- app/sip_status/cmd.php | 9 +- app/sip_status/sip_status.php | 27 +- app/switch/resources/classes/presence.php | 10 +- .../autoload_configs/event_socket.conf.xml | 2 +- .../resources/dashboard/switch_status.php | 14 +- .../resources/dashboard/system_cpu_status.php | 2 +- .../resources/dashboard/system_status.php | 7 +- app/system/system.php | 12 +- .../resources/classes/voicemail.php | 14 +- core/notifications/notification_edit.php | 6 +- core/users/user_edit.php | 10 +- resources/classes/cache.php | 48 +- resources/classes/event_socket.php | 232 ++- resources/classes/switch_settings.php | 5 +- resources/functions.php | 1662 +++++++++-------- resources/header.php | 4 +- resources/switch.php | 42 +- 74 files changed, 1620 insertions(+), 1533 deletions(-) diff --git a/app/access_controls/access_control_edit.php b/app/access_controls/access_control_edit.php index 8d85f0d3f2..352231bd72 100644 --- a/app/access_controls/access_control_edit.php +++ b/app/access_controls/access_control_edit.php @@ -118,10 +118,7 @@ $cache->delete("configuration:acl.conf"); //create the event socket connection - $fp = event_socket_create(); - if ($fp) { - event_socket_request($fp, "api reloadacl"); - } + event_socket::api("reloadacl"); //redirect the user header('Location: access_control_edit.php?id='.$id); @@ -204,10 +201,7 @@ $cache->delete("configuration:acl.conf"); //create the event socket connection - $fp = event_socket_create(); - if ($fp) { - event_socket_request($fp, "api reloadacl"); - } + event_socket::async("reloadacl"); //redirect the user if (isset($action)) { diff --git a/app/access_controls/access_controls_reload.php b/app/access_controls/access_controls_reload.php index df735ec949..ea6304338d 100644 --- a/app/access_controls/access_controls_reload.php +++ b/app/access_controls/access_controls_reload.php @@ -40,18 +40,11 @@ //set the variables $search = $_REQUEST['search'] ?? ''; -//create event socket connection - $fp = event_socket_create(); - if ($fp) { - //run the command - $result = rtrim(event_socket_request($fp, 'api reloadacl')); +//run the command + $result = rtrim(event_socket::api('reloadacl')); - //add message - message::add($result, 'alert'); - - //close the connection - fclose($fp); - } +//add message + message::add($result, 'alert'); //redirect $search = preg_replace('#[^a-zA-Z0-9_\-\.]# ', '', $search); diff --git a/app/access_controls/app_defaults.php b/app/access_controls/app_defaults.php index c43a8382d0..7cf90760f0 100644 --- a/app/access_controls/app_defaults.php +++ b/app/access_controls/app_defaults.php @@ -157,12 +157,10 @@ $cache->delete("configuration:sofia.conf:".gethostname()); //create the event socket connection - if (!$fp) { - $fp = event_socket_create(); - } + $esl = event_socket::create(); //reload the acl - event_socket_request($fp, "api reloadacl"); + event_socket::async("reloadacl"); //rescan each sip profile $sql = "select sip_profile_name from v_sip_profiles "; @@ -171,10 +169,10 @@ $sip_profiles = $database->select($sql, null, 'all'); if (is_array($sip_profiles)) { foreach ($sip_profiles as $row) { - if ($fp) { + if ($esl->is_connected()) { $command = "sofia profile '".$row['sip_profile_name']."' rescan"; //echo $command."\n"; - $result = event_socket_request($fp, "api ".$command); + $result = event_socket::api($command); //echo $result."\n"; } } diff --git a/app/access_controls/resources/classes/access_controls.php b/app/access_controls/resources/classes/access_controls.php index 56e1508106..36fae54113 100644 --- a/app/access_controls/resources/classes/access_controls.php +++ b/app/access_controls/resources/classes/access_controls.php @@ -87,10 +87,7 @@ if (!class_exists('access_controls')) { $cache->delete("configuration:acl.conf"); //create the event socket connection - $fp = event_socket_create(); - if ($fp) { - event_socket_request($fp, "api reloadacl"); - } + event_socket::async("reloadacl"); //set message message::add($text['message-delete']); @@ -146,10 +143,7 @@ if (!class_exists('access_controls')) { $cache->delete("configuration:acl.conf"); //create the event socket connection - $fp = event_socket_create(); - if ($fp) { - event_socket_request($fp, "api reloadacl"); - } + event_socket::async("reloadacl"); //set message message::add($text['message-delete']); @@ -261,10 +255,7 @@ if (!class_exists('access_controls')) { $cache->delete("configuration:acl.conf"); //create the event socket connection - $fp = event_socket_create(); - if ($fp) { - event_socket_request($fp, "api reloadacl"); - } + event_socket::async("reloadacl"); //set message message::add($text['message-copy']); diff --git a/app/basic_operator_panel/exec.php b/app/basic_operator_panel/exec.php index 7d44f13f4d..7b392c36d0 100644 --- a/app/basic_operator_panel/exec.php +++ b/app/basic_operator_panel/exec.php @@ -57,7 +57,7 @@ if (count($_GET) > 0) { $direction = trim($_GET["direction"] ?? ''); //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //allow specific commands if (!empty($switch_cmd)) { @@ -99,7 +99,7 @@ if (count($_GET) > 0) { } //run the command - $switch_result = event_socket_request($fp, 'api '.$api_cmd); + $switch_result = event_socket::api($api_cmd); /* //record stop diff --git a/app/basic_operator_panel/index.php b/app/basic_operator_panel/index.php index 2fecd9f35f..54d04a4763 100644 --- a/app/basic_operator_panel/index.php +++ b/app/basic_operator_panel/index.php @@ -97,15 +97,15 @@ //update the user_status if (is_uuid($call_center_agent_uuid)) { - $fp = event_socket_create(); + $esl = event_socket::create(); $switch_cmd .= "callcenter_config agent set status ".$call_center_agent_uuid." '".$user_status."'"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); } //update the user state if (is_uuid($call_center_agent_uuid)) { $cmd = "api callcenter_config agent set state ".$call_center_agent_uuid." Waiting"; - $response = event_socket_request($fp, $cmd); + $response = event_socket::api($cmd); } //update do not disturb diff --git a/app/basic_operator_panel/resources/classes/basic_operator_panel.php b/app/basic_operator_panel/resources/classes/basic_operator_panel.php index a68627b831..bcbff94eb6 100644 --- a/app/basic_operator_panel/resources/classes/basic_operator_panel.php +++ b/app/basic_operator_panel/resources/classes/basic_operator_panel.php @@ -86,10 +86,12 @@ if (!class_exists('basic_operator_panel')) { } //send the command - $fp = event_socket_create(); - if ($fp) { - $switch_result = event_socket_request($fp, 'api show channels as json'); + $switch_result = event_socket::api('show channels as json'); + if ($switch_result !== false) { + $fp = true; $json_array = json_decode($switch_result, true); + } else { + $fp = false; } //build the response @@ -205,8 +207,10 @@ if (!class_exists('basic_operator_panel')) { if ($fp) { if (is_uuid($field['uuid'])) { $switch_cmd = 'uuid_dump '.$field['uuid'].' json'; - $dump_result = event_socket_request($fp, 'api '.$switch_cmd); - $dump_array = json_decode($dump_result, true); + $dump_result = event_socket::api($switch_cmd); + if ($dump_result !== false) { + $dump_array = json_decode($dump_result, true); + } if (is_array($dump_array)) { foreach ($dump_array as $dump_var_name => $dump_var_value) { $array[$x][$dump_var_name] = $dump_var_value; diff --git a/app/basic_operator_panel/resources/content.php b/app/basic_operator_panel/resources/content.php index d2d300b189..bb220e1b64 100644 --- a/app/basic_operator_panel/resources/content.php +++ b/app/basic_operator_panel/resources/content.php @@ -64,9 +64,8 @@ if (!empty($groups)) { } //get the valet info -$fp = event_socket_create(); -if ($fp) { - $valet_info = event_socket_request($fp, 'api valet_info park@'.$_SESSION['domain_name']); +$valet_info = event_socket::api('valet_info park@'.$_SESSION['domain_name']); +if ($valet_info !== false) { //get an array of the valet call uuid and park numbers if (isset($valet_info)) { @@ -78,10 +77,10 @@ if ($fp) { //unset($_SESSION['valet']); foreach($valet_matches as $row) { if (!isset($_SESSION['valet']['uuid']['caller_id_name'])) { - $_SESSION['valet'][$row[1]]['caller_id_name'] = event_socket_request($fp, 'api uuid_getvar '.$row[1].' caller_id_name'); + $_SESSION['valet'][$row[1]]['caller_id_name'] = event_socket::api('uuid_getvar '.$row[1].' caller_id_name'); } if (!isset($_SESSION['valet']['uuid']['caller_id_number'])) { - $_SESSION['valet'][$row[1]]['caller_id_number'] = event_socket_request($fp, 'api uuid_getvar '.$row[1].' caller_id_number'); + $_SESSION['valet'][$row[1]]['caller_id_number'] = event_socket::api('uuid_getvar '.$row[1].' caller_id_number'); } } diff --git a/app/call_broadcast/call_broadcast_send.php b/app/call_broadcast/call_broadcast_send.php index 1280942453..89495b5c0d 100644 --- a/app/call_broadcast/call_broadcast_send.php +++ b/app/call_broadcast/call_broadcast_send.php @@ -130,7 +130,7 @@ $broadcast_name = str_replace("'", "", $broadcast_name); //create the event socket connection - $fp = event_socket_create(); + $fp = event_socket::create(); //get information over event socket if (!$fp) { @@ -196,11 +196,11 @@ //if the event socket connection is lost then re-connect if (!$fp) { - $fp = event_socket_create(); + $fp = event_socket::create(); } //method 1 - $response = trim(event_socket_request($fp, 'api '.$cmd)); + $response = trim(event_socket::command($cmd)); //method 2 //cmd_async($_SESSION['switch']['bin']['dir']."/fs_cli -x \"".$cmd."\";"); @@ -216,8 +216,7 @@ $count++; } } - fclose($fp); - + echo "
\n"; echo "\n"; echo "\n"; diff --git a/app/call_broadcast/call_broadcast_stop.php b/app/call_broadcast/call_broadcast_stop.php index e235eda429..08e3689506 100644 --- a/app/call_broadcast/call_broadcast_stop.php +++ b/app/call_broadcast/call_broadcast_stop.php @@ -45,10 +45,10 @@ else { if (is_uuid($uuid)) { //show the result if (count($_GET) > 0) { - $fp = event_socket_create(); - if ($fp) { + $fp = event_socket::create(); + if ($fp !== false) { $cmd = "sched_del ".$uuid; - $result = event_socket_request($fp, 'api '.$cmd); + $result = event_socket::api($cmd); message::add(htmlentities($result)); } } diff --git a/app/call_center_active/call_center_active_inc.php b/app/call_center_active/call_center_active_inc.php index 9729b40c72..a2b512b8be 100644 --- a/app/call_center_active/call_center_active_inc.php +++ b/app/call_center_active/call_center_active_inc.php @@ -90,10 +90,10 @@ } //create an event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //get the call center queue, agent and tiers list - if (!$fp) { + if (!$esl->is_connected()) { $msg = "
Connection to Event Socket failed.
"; echo "
\n"; echo "
\n"; @@ -117,7 +117,7 @@ //send the event socket command and get the response //callcenter_config queue list tiers [queue_name] | $switch_command = 'callcenter_config queue list tiers '.$queue_extension."@".$_SESSION["domain_name"]; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_command)); + $event_socket_str = trim(event_socket::api($switch_command)); $result = str_to_named_array($event_socket_str, '|'); //prepare the result for array_multisort @@ -139,7 +139,7 @@ //send the event socket command and get the response //callcenter_config queue list agents [queue_name] [status] | $switch_command = 'callcenter_config queue list agents '.$queue_extension."@".$_SESSION["domain_name"]; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_command)); + $event_socket_str = trim(event_socket::api($switch_command)); $agent_result = str_to_named_array($event_socket_str, '|'); //get the agents from the database @@ -280,7 +280,7 @@ //callcenter_config queue list members [queue_name] if (is_uuid($queue_uuid)) { $switch_command = 'callcenter_config queue list members '.$queue_extension."@".$_SESSION["domain_name"]; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_command)); + $event_socket_str = trim(event_socket::api($switch_command)); $result = str_to_named_array($event_socket_str, '|'); if (!is_array($result)) { unset($result); } } diff --git a/app/call_center_active/call_center_exec.php b/app/call_center_active/call_center_exec.php index cbe5e5c189..15903d3226 100644 --- a/app/call_center_active/call_center_exec.php +++ b/app/call_center_active/call_center_exec.php @@ -90,8 +90,7 @@ //run the command if (isset($switch_command)) { - $fp = event_socket_create(); - $response = event_socket_request($fp, 'api '.$switch_command); + $response = event_socket::api($switch_command); } /* @@ -134,14 +133,14 @@ //fs cmd if (!empty($switch_cmd)) { //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //ensure the connection exists - if ($fp) { + if ($esl) { //send the command - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); //set the user state $cmd = "api callcenter_config agent set state ".$username."@".$_SESSION['domain_name']." Waiting"; - $response = event_socket_request($fp, $cmd); + $response = event_socket::command($cmd); } } } diff --git a/app/call_centers/call_center_agent_edit.php b/app/call_centers/call_center_agent_edit.php index fba293e2e8..5e2ee5fce4 100644 --- a/app/call_centers/call_center_agent_edit.php +++ b/app/call_centers/call_center_agent_edit.php @@ -238,37 +238,37 @@ //add the agent //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //add the agent using event socket - if ($fp) { + if ($esl->connected()) { //add the agent - $cmd = "api callcenter_config agent add ".$call_center_agent_uuid." ".$agent_type; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config agent add ".$call_center_agent_uuid." '".$agent_type."'"; + $response = event_socket::api($cmd); usleep(200); //agent set contact - $cmd = "api callcenter_config agent set contact ".$call_center_agent_uuid." ".$agent_contact; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config agent set contact ".$call_center_agent_uuid." '".$agent_contact."'"; + $response = event_socket::api($cmd); usleep(200); //agent set status - $cmd = "api callcenter_config agent set status ".$call_center_agent_uuid." '".$agent_status."'"; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config agent set status ".$call_center_agent_uuid." '".$agent_status."'"; + $response = event_socket::api($cmd); usleep(200); //agent set reject_delay_time - $cmd = "api callcenter_config agent set reject_delay_time ".$call_center_agent_uuid." ".$agent_reject_delay_time; - $response = event_socket_request($fp, $cmd); + $cmd = 'callcenter_config agent set reject_delay_time '.$call_center_agent_uuid.' '. $agent_reject_delay_time; + $response = event_socket::api($cmd); usleep(200); //agent set busy_delay_time - $cmd = "api callcenter_config agent set busy_delay_time ".$call_center_agent_uuid." ".$agent_busy_delay_time; - $response = event_socket_request($fp, $cmd); + $cmd = 'callcenter_config agent set busy_delay_time '.$call_center_agent_uuid.' '.$agent_busy_delay_time; + $response = event_socket::api($cmd); //agent set no_answer_delay_time - $cmd = "api callcenter_config agent set no_answer_delay_time ".$call_center_agent_uuid." ".$agent_no_answer_delay_time; - $response = event_socket_request($fp, $cmd); + $cmd = 'callcenter_config agent set no_answer_delay_time '.$call_center_agent_uuid.' '.$agent_no_answer_delay_time; + $response = event_socket::api($cmd); //agent set max_no_answer - $cmd = "api callcenter_config agent set max_no_answer ".$call_center_agent_uuid." ".$agent_max_no_answer; - $response = event_socket_request($fp, $cmd); + $cmd = 'callcenter_config agent set max_no_answer '.$call_center_agent_uuid.' '.$agent_max_no_answer; + $response = event_socket::api($cmd); //agent set wrap_up_time - $cmd = "api callcenter_config agent set wrap_up_time ".$call_center_agent_uuid." ".$agent_wrap_up_time; - $response = event_socket_request($fp, $cmd); + $cmd = 'callcenter_config agent set wrap_up_time '.$call_center_agent_uuid.' '.$agent_wrap_up_time; + $response = event_socket::api($cmd); } //redirect the user diff --git a/app/call_centers/call_center_agent_status.php b/app/call_centers/call_center_agent_status.php index 04a80ec222..137e1db0cc 100644 --- a/app/call_centers/call_center_agent_status.php +++ b/app/call_centers/call_center_agent_status.php @@ -57,7 +57,7 @@ unset($sql, $parameters); //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //get the agents from the database $sql = "select * from v_call_center_agents "; @@ -70,12 +70,12 @@ //get the agent list from event socket $switch_cmd = 'callcenter_config agent list'; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $event_socket_str = trim(event_socket::api($switch_cmd)); $agent_list = csv_to_named_array($event_socket_str, '|'); //get the agent list from event socket $switch_cmd = 'callcenter_config tier list'; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $event_socket_str = trim(event_socket::api($switch_cmd)); $call_center_tiers = csv_to_named_array($event_socket_str, '|'); //get the call center queues from the database @@ -100,7 +100,7 @@ //get the queue list from event socket $switch_cmd = "callcenter_config queue list agents ".$queue_id; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $event_socket_str = trim(event_socket::api($switch_cmd)); $queue_list = csv_to_named_array($event_socket_str, '|'); $call_center_queues[$x]['queue_list'] = $queue_list; $x++; @@ -165,7 +165,7 @@ foreach($_POST['agents'] as $row) { if (!empty($row['agent_status'])) { //agent set status - if ($fp) { + if ($esl->is_connected()) { //set the user_status if (!isset($row['queue_name'])) { $array['users'][0]['user_uuid'] = $row['user_uuid'] ?? null; @@ -211,20 +211,20 @@ //set the call center status to Logged Out if (is_uuid($row['agent_uuid'])) { - $command = "api callcenter_config agent set status ".$row['agent_uuid']." 'Logged Out' "; - $response = event_socket_request($fp, $command); + $command = "callcenter_config agent set status ".$row['agent_uuid']." 'Logged Out' "; + $response = event_socket::api($command); } } else { if (is_uuid($row['agent_uuid'])) { //set the agent status - $command = "api callcenter_config agent set status ".$row['agent_uuid']." '".$agent_status."'"; - $response = event_socket_request($fp, $command); + $command = "callcenter_config agent set status ".$row['agent_uuid']." '".$agent_status."'"; + $response = event_socket::api($command); //set the agent state if ($agent_status == 'Available' || $agent_status == 'Logged Out') { - $command = "api callcenter_config agent set state ".$row['agent_uuid']." 'Waiting'"; - $response = event_socket_request($fp, $command); + $command = "callcenter_config agent set state ".$row['agent_uuid']." 'Waiting'"; + $response = event_socket::api($command); } } } @@ -247,22 +247,21 @@ if (isset($row['queue_uuid']) && $row['agent_status'] == 'Available') { //set the call center status //$command = "api callcenter_config agent set status ".$row['agent_name']."@".$_SESSION['domain_name']." '".$row['agent_status']."'"; - //$response = event_socket_request($fp, $command); + //$response = event_socket::command($command); //assign the agent to the queue if (is_uuid($row['queue_uuid']) && is_uuid($row['agent_uuid'])) { - $command = "api callcenter_config tier add ".$queue_id." ".$row['agent_uuid']." 1 1"; - //echo $command."
\n"; - $response = event_socket_request($fp, $command); + $command = "callcenter_config tier add ".$queue_id." ".$row['agent_uuid']." 1 1"; + $response = event_socket::api($command); } } //un-assign the agent from the queue if (isset($row['queue_uuid']) && $row['agent_status'] == 'Logged Out') { if (is_uuid($row['queue_uuid']) && is_uuid($row['agent_uuid'])) { - $command = "api callcenter_config tier del ".$queue_id." ".$row['agent_uuid']; + $command = "callcenter_config tier del ".$queue_id." ".$row['agent_uuid']; //echo $command."
\n"; - $response = event_socket_request($fp, $command); + $response = event_socket::api($command); } } usleep(200); diff --git a/app/call_centers/call_center_queue_edit.php b/app/call_centers/call_center_queue_edit.php index 0155f9b4b2..2bfc02e30c 100644 --- a/app/call_centers/call_center_queue_edit.php +++ b/app/call_centers/call_center_queue_edit.php @@ -160,13 +160,13 @@ //delete the agent from freeswitch //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //delete the agent over event socket - if ($fp) { + if ($esl->is_connected()) { //callcenter_config tier del [queue_name] [agent_name] if (is_numeric($queue_extension) && is_uuid($call_center_agent_uuid)) { - $cmd = "api callcenter_config tier del ".$queue_extension."@".$_SESSION['domain_name']." ".$call_center_agent_uuid; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config tier del ".$queue_extension."@".$_SESSION['domain_name']." ".$call_center_agent_uuid; + $response = event_socket::api($cmd); } } @@ -468,9 +468,9 @@ if (!empty($agent_name)) { //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //add the agent using event socket - if ($fp) { + if ($esl->is_connected()) { /* syntax: callcenter_config tier add [queue_name] [agent_name] [level] [position] callcenter_config tier set state [queue_name] [agent_name] [state] @@ -479,20 +479,20 @@ */ //add the agent if (is_numeric($queue_extension) && is_uuid($call_center_agent_uuid) && is_numeric($tier_level) && is_numeric($tier_position)) { - $cmd = "api callcenter_config tier add ".$queue_extension."@".$_SESSION["domain_name"]." ".$call_center_agent_uuid." ".$tier_level." ".$tier_position; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config tier add ".$queue_extension."@".$_SESSION["domain_name"]." ".$call_center_agent_uuid." ".$tier_level." ".$tier_position; + $response = event_socket::api($cmd); } usleep(200); //agent set level if (is_numeric($queue_extension) && is_numeric($tier_level)) { - $cmd = "api callcenter_config tier set level ".$queue_extension."@".$_SESSION["domain_name"]." ".$call_center_agent_uuid." ".$tier_level; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config tier set level ".$queue_extension."@".$_SESSION["domain_name"]." ".$call_center_agent_uuid." ".$tier_level; + $response = event_socket::api($cmd); } usleep(200); //agent set position if (is_numeric($queue_extension) && is_numeric($tier_position)) { - $cmd = "api callcenter_config tier set position ".$queue_extension."@".$_SESSION["domain_name"]." ".$tier_position; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config tier set position ".$queue_extension."@".$_SESSION["domain_name"]." ".$tier_position; + $response = event_socket::api($cmd); } usleep(200); } diff --git a/app/call_centers/cmd.php b/app/call_centers/cmd.php index 1c3fa73ca6..fd2b45aabe 100644 --- a/app/call_centers/cmd.php +++ b/app/call_centers/cmd.php @@ -70,11 +70,10 @@ //connect to event socket if (isset($queue_extension) && isset($cmd)) { - $fp = event_socket_create(); - if ($fp) { - $response = event_socket_request($fp, 'api reloadxml'); - $response = event_socket_request($fp, 'api callcenter_config queue '.$cmd. ' '.$queue_extension."@".$_SESSION["domain_name"]); - fclose($fp); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $response = event_socket::api('reloadxml'); + $response = event_socket::api('callcenter_config queue '.$cmd.' '.$queue_extension.'@'.$_SESSION['domain_name']); } else { $response = ''; @@ -85,4 +84,4 @@ $_SESSION["message"] = $response; header("Location: call_center_queues.php?savemsg=".urlencode($response)); -?> \ No newline at end of file +?> diff --git a/app/call_centers/resources/classes/call_center.php b/app/call_centers/resources/classes/call_center.php index 827adc9430..3985c9ce59 100644 --- a/app/call_centers/resources/classes/call_center.php +++ b/app/call_centers/resources/classes/call_center.php @@ -338,13 +338,13 @@ if (is_array($array) && @sizeof($array) != 0) { //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //delete the queue in the switch - if ($fp) { + if ($esl->is_connected()) { foreach ($uuids as $uuid) { - $cmd = "api callcenter_config queue unload ".$call_center_queues[$uuid]['queue_extension']."@".$_SESSION["domain_name"]; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config queue unload ".$call_center_queues[$uuid]['queue_extension']."@".$_SESSION['domain_name']; + $response = event_socket::api($cmd); } } @@ -436,13 +436,12 @@ if (is_array($array) && @sizeof($array) != 0) { //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //delete the agent in the switch - if ($fp) { + if ($esl->is_connected()) { foreach ($uuids as $uuid) { - $cmd = "api callcenter_config agent del ".$uuid; - $response = event_socket_request($fp, $cmd); + event_socket::async("callcenter_config agent del $uuid"); } } @@ -627,4 +626,4 @@ $c->queue_cc_exit_keys = ""; $c->dialplan(); */ -?> \ No newline at end of file +?> diff --git a/app/call_centers/resources/dashboard/call_center_agents.php b/app/call_centers/resources/dashboard/call_center_agents.php index a68846d34f..18fa2f2782 100644 --- a/app/call_centers/resources/dashboard/call_center_agents.php +++ b/app/call_centers/resources/dashboard/call_center_agents.php @@ -51,7 +51,7 @@ } //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //get the http post values and set them as php variables if (!empty($_POST['agents'])) { @@ -91,8 +91,8 @@ $result = $database->save($array); //send the agent status status to mod_call_center - $cmd = "api callcenter_config agent set status ".$agent_uuid." '".$agent_status."'"; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config agent set status ".$agent_uuid." '".$agent_status."'"; + $response = event_socket::api($cmd); //add or delete agents from the queue assigned by the tier foreach ($_POST['agents'] as $row) { @@ -103,21 +103,21 @@ //set the agent status to available and assign the agent to the queue with the tier if ($row['agent_status'] == 'Available') { //assign the agent to the queue - $cmd = "api callcenter_config tier add ".$row['queue_extension']."@".$_SESSION['domain_name']." ".$row['id']." 1 1"; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config tier add ".$row['queue_extension']."@".$_SESSION['domain_name']." ".$row['id']." 1 1"; + $response = event_socket::api($cmd); } //set the agent status to available and assign the agent to the queue with the tier if ($row['agent_status'] == 'On Break') { //assign the agent to the queue - $cmd = "api callcenter_config tier add ".$row['queue_extension']."@".$_SESSION['domain_name']." ".$row['id']." 1 1"; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config tier add ".$row['queue_extension']."@".$_SESSION['domain_name']." ".$row['id']." 1 1"; + $response = event_socket::api($cmd); } //un-assign the agent from the queue if ($row['agent_status'] == 'Logged Out') { - $cmd = "api callcenter_config tier del ".$row['queue_extension']."@".$_SESSION['domain_name']." ".$row['id']; - $response = event_socket_request($fp, $cmd); + $cmd = "callcenter_config tier del ".$row['queue_extension']."@".$_SESSION['domain_name']." ".$row['id']; + $response = event_socket::api($cmd); } //small sleep @@ -132,7 +132,7 @@ //get the agent list from event socket $switch_cmd = 'callcenter_config tier list'; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $event_socket_str = trim(event_socket::api($switch_cmd)); $call_center_tiers = csv_to_named_array($event_socket_str, '|'); //get the agents from the database diff --git a/app/call_centers/resources/jobs/call_center_agents.php b/app/call_centers/resources/jobs/call_center_agents.php index 29f3aca9cb..ec83d3f9b4 100644 --- a/app/call_centers/resources/jobs/call_center_agents.php +++ b/app/call_centers/resources/jobs/call_center_agents.php @@ -31,11 +31,11 @@ } //connect to event socket - $fp = event_socket_create(); + $esl = event_socket::create(); //get the agent list from event socket $switch_cmd = 'callcenter_config agent list'; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $event_socket_str = trim(event_socket::api($switch_cmd)); $agent_list = csv_to_named_array($event_socket_str, '|'); //get the agents from the database @@ -69,7 +69,7 @@ } //build the event - if ($fp) { + if ($esl->is_connected()) { $event = "sendevent PRESENCE_IN\n"; $event .= "proto: agent\n"; $event .= "from: ".$row['agent_name']."@".$row['domain_name']."\n"; @@ -104,16 +104,13 @@ } //send the event - $result = event_socket_request($fp, $event); + $result = event_socket::command($event); if (isset($debug)) { print_r($result, false); } } - //close event socket connection - fclose($fp); - /* * * * * * cd /var/www/fusionpbx && php /var/www/fusionpbx/app/call_centers/resources/jobs/call_center_agents.php */ diff --git a/app/call_flows/call_flow_edit.php b/app/call_flows/call_flow_edit.php index 7de365c31f..6dc771231f 100644 --- a/app/call_flows/call_flow_edit.php +++ b/app/call_flows/call_flow_edit.php @@ -257,8 +257,8 @@ // Update subscribed endpoints if (!empty($call_flow_feature_code)) { - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //send the event $event = "sendevent PRESENCE_IN\n"; $event .= "proto: flow\n"; @@ -274,8 +274,7 @@ } else { $event .= "answer-state: terminated\n"; } - event_socket_request($fp, $event); - fclose($fp); + event_socket::command($event); } } diff --git a/app/call_flows/resources/classes/call_flows.php b/app/call_flows/resources/classes/call_flows.php index 264d7759ce..1113548e7b 100644 --- a/app/call_flows/resources/classes/call_flows.php +++ b/app/call_flows/resources/classes/call_flows.php @@ -281,8 +281,7 @@ if (!class_exists('call_flows')) { } //send the event - $fp = event_socket_create(); - $switch_result = event_socket_request($fp, $cmd); + $switch_result = event_socket::command($cmd); } } unset($call_flows); diff --git a/app/call_forward/call_forward_edit.php b/app/call_forward/call_forward_edit.php index 119ede042a..873ce77372 100644 --- a/app/call_forward/call_forward_edit.php +++ b/app/call_forward/call_forward_edit.php @@ -399,9 +399,7 @@ $cmd .= "answer-state: confirmed\n"; //send the event - $fp = event_socket_create(); - $switch_result = event_socket_request($fp, $cmd); - unset($fp); + $switch_result = event_socket::command($cmd); } else { $presence = new presence; @@ -421,9 +419,7 @@ $cmd .= "answer-state: terminated\n"; //send the event - $fp = event_socket_create(); - $switch_result = event_socket_request($fp, $cmd); - unset($fp); + $switch_result = event_socket::command($cmd); } } } diff --git a/app/call_forward/resources/classes/do_not_disturb.php b/app/call_forward/resources/classes/do_not_disturb.php index 94226edca7..ce1523762e 100644 --- a/app/call_forward/resources/classes/do_not_disturb.php +++ b/app/call_forward/resources/classes/do_not_disturb.php @@ -39,10 +39,10 @@ if ($this->enabled == "true") { //update the call center status $user_status = "Logged Out"; - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { $switch_cmd .= "callcenter_config agent set status ".$_SESSION['username']."@".$this->domain_name." '".$user_status."'"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); } //update the database user_status diff --git a/app/call_forward/resources/classes/feature_event_notify.php b/app/call_forward/resources/classes/feature_event_notify.php index ec0afa5a0f..a9173dcb55 100644 --- a/app/call_forward/resources/classes/feature_event_notify.php +++ b/app/call_forward/resources/classes/feature_event_notify.php @@ -42,11 +42,11 @@ //feature_event method public function send_notify() { - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { // Get the SIP profiles for the extension $command = "sofia_contact */{$this->extension}@{$this->domain_name}"; - $contact_string = event_socket_request($fp, "api ".$command); + $contact_string = event_socket::api($command); // The first value in the array will be full matching text, the second one will be the array of profile matches preg_match_all('/sofia\/([^,]+)\/(?:[^,]+)/', $contact_string, $matches); if (sizeof($matches) != 2 || sizeof($matches[1]) < 1) { @@ -72,12 +72,11 @@ $event .= "forward_no_answer: " . $this->forward_no_answer_destination . "\n"; $event .= "doNotDisturbOn: " . $this->do_not_disturb . "\n"; $event .= "ringCount: " . $this->ring_count . "\n"; - event_socket_request($fp, $event); + event_socket::command($event); } - fclose($fp); } } //function - + } //class ?> diff --git a/app/call_forward/resources/jobs/dnd.php b/app/call_forward/resources/jobs/dnd.php index 98f6b8aea6..f8cd0cc2db 100644 --- a/app/call_forward/resources/jobs/dnd.php +++ b/app/call_forward/resources/jobs/dnd.php @@ -3,7 +3,7 @@ //check the permission if (defined('STDIN')) { //includes files - require_once dirname(__DIR__, 4) . "/resources/require.php"; + require_once dirname(__DIR__, 4) . "/resources/require.php"; } else { exit; @@ -31,54 +31,63 @@ exit; } -//connect to event socket - $fp = event_socket_create(); +//use global conf created from require.php + global $conf; -//get the list - $sql = "select domain_name, extension, user_context, do_not_disturb, description "; - $sql .= "from v_extensions as e, v_domains as d "; - $sql .= "where do_not_disturb = 'true' "; - $sql .= "and e.domain_uuid = d.domain_uuid "; - $sql .= "and enabled = 'true' "; - $database = new database; - $results = $database->select($sql, $parameters, 'all'); - unset($parameters); +//set the event socket connection settings + $host = $conf['switch.event_socket.host'] ?? $conf['event_socket.ip_address'] ?? '127.0.0.1'; + $port = $conf['switch.event_socket.port'] ?? $conf['event_socket.port'] ?? '8021'; + $pass = $conf['switch.event_socket.password'] ?? $conf['event_socket.password'] ?? 'ClueCon'; -//view_array($results); - foreach($results as $row) { +//connect to event socket using a lower timeout because we are on cli + $esl = event_socket::create($host, $port, $pass, 10000); - //build the event - $cmd = "sendevent PRESENCE_IN\n"; - $cmd .= "proto: sip\n"; - $cmd .= "login: ".$row['extension']."@".$row['domain_name']."\n"; - $cmd .= "from: ".$row['extension']."@".$row['domain_name']."\n"; - $cmd .= "status: Active (1 waiting)\n"; - $cmd .= "rpid: unknown\n"; - $cmd .= "event_type: presence\n"; - $cmd .= "alt_event_type: dialog\n"; - $cmd .= "event_count: 1\n"; - $cmd .= "unique-id: ".uuid()."\n"; - $cmd .= "Presence-Call-Direction: outbound\n"; - $cmd .= "answer-state: confirmed\n"; - //$cmd .= "answer-state: early\n"; - //$cmd .= "answer-state: terminated\n"; +//ensure we are connected + if ($esl->is_connected()) { - //send message to the console - if (isset($debug)) { - echo "\n"; - echo "[presence] dnd ".$row['extension']."@".$row['domain_name']."\n"; + //get the list + $sql = "select domain_name, extension, user_context, do_not_disturb, description "; + $sql .= "from v_extensions as e, v_domains as d "; + $sql .= "where do_not_disturb = 'true' "; + $sql .= "and e.domain_uuid = d.domain_uuid "; + $sql .= "and enabled = 'true' "; + $database = new database; + $results = $database->select($sql, $parameters, 'all'); + unset($parameters); + foreach ($results as $row) { + + //build the event + $cmd = "sendevent PRESENCE_IN\n"; + $cmd .= "proto: sip\n"; + $cmd .= "login: " . $row['extension'] . "@" . $row['domain_name'] . "\n"; + $cmd .= "from: " . $row['extension'] . "@" . $row['domain_name'] . "\n"; + $cmd .= "status: Active (1 waiting)\n"; + $cmd .= "rpid: unknown\n"; + $cmd .= "event_type: presence\n"; + $cmd .= "alt_event_type: dialog\n"; + $cmd .= "event_count: 1\n"; + $cmd .= "unique-id: " . uuid() . "\n"; + $cmd .= "Presence-Call-Direction: outbound\n"; + $cmd .= "answer-state: confirmed\n"; + //$cmd .= "answer-state: early\n"; + //$cmd .= "answer-state: terminated\n"; + //send message to the console + if (isset($debug)) { + echo "\n"; + echo "[presence] dnd " . $row['extension'] . "@" . $row['domain_name'] . "\n"; + } + + //send the event + $result = event_socket::command($cmd); + if (isset($debug)) { + print_r($result, false); + } } - - //send the event - $result = event_socket_request($fp, $cmd); - if (isset($debug)) { - print_r($result, false); - } - + } + else { + trigger_error("Unable to connect to FreeSWITCH using $host, $port, $password", E_USER_ERROR); } -/* -* * * * * cd /var/www/fusionpbx && php /var/www/fusionpbx/app/call_forward/resources/jobs/dnd.php -*/ - -?> + /* + * * * * * cd /var/www/fusionpbx && php /var/www/fusionpbx/app/call_forward/resources/jobs/dnd.php + */ diff --git a/app/calls_active/calls_active_inc.php b/app/calls_active/calls_active_inc.php index f7ff147e14..a6dc6307ce 100644 --- a/app/calls_active/calls_active_inc.php +++ b/app/calls_active/calls_active_inc.php @@ -52,11 +52,11 @@ $switch_cmd = 'show channels as json'; //create the event socket connection - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + $esl = event_socket::create(); //send the event socket command and get the array - if ($fp) { - $json = trim(event_socket_request($fp, 'api '.$switch_cmd)); + if ($esl->is_connected()) { + $json = trim(event_socket::api($switch_cmd)); $results = json_decode($json, "true"); } @@ -90,7 +90,7 @@ //if the connnection is available then run it and return the results - if (!$fp) { + if (!$esl) { $msg = "
".$text['confirm-socket']."
"; echo "
\n"; diff --git a/app/calls_active/calls_exec.php b/app/calls_active/calls_exec.php index 652e4393f4..7706df5b16 100644 --- a/app/calls_active/calls_exec.php +++ b/app/calls_active/calls_exec.php @@ -58,6 +58,7 @@ exit; } + $calls = []; //verify submitted call uuids if (is_array($_POST['calls']) && @sizeof($_POST['calls']) != 0) { foreach ($_POST['calls'] as $call) { @@ -71,18 +72,18 @@ } //iterate through calls - if (is_array($calls) && @sizeof($calls) != 0) { + if (count($calls) > 0) { //setup the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //execute hangup command - foreach ($calls as $call_uuid) { - $switch_result = event_socket_request($fp, 'api uuid_kill '.$call_uuid); + if ($esl->is_connected()) foreach ($calls as $call_uuid) { + event_socket::async("uuid_kill $call_uuid"); } //set message - message::add($text['message-calls_ended'].': '.@sizeof($calls),'positive'); + message::add($text['message-calls_ended'].': '.count($calls),'positive'); } diff --git a/app/click_to_call/click_to_call.php b/app/click_to_call/click_to_call.php index f612424072..93baec1d8b 100644 --- a/app/click_to_call/click_to_call.php +++ b/app/click_to_call/click_to_call.php @@ -93,124 +93,120 @@ } //create the even socket connection and send the event socket command - $fp = event_socket_create(); - if (!$fp) { - //error message - echo "
Connection to Event Socket failed.
"; - } + $esl = event_socket::create(); + if ($esl->is_connected()) { - //set call uuid - $origination_uuid = trim(event_socket_request($fp, "api create_uuid")); + //set call uuid + $origination_uuid = trim(event_socket::api("create_uuid")); - //add record path and name - if ($rec == "true") { - $record_path = $_SESSION['switch']['recordings']['dir']."/".$_SESSION['domain_name']."/archive/".date("Y")."/".date("M")."/".date("d"); - if (isset($_SESSION['recordings']['extension']['text'])) { - $record_extension = $_SESSION['recordings']['extension']['text']; - } - else { - $record_extension = 'wav'; - } - if (isset($_SESSION['recordings']['template']['text'])) { - //${year}${month}${day}-${caller_id_number}-${caller_destination}-${uuid}.${record_extension} - $record_name = $_SESSION['recordings']['template']['text']; - $record_name = str_replace('${year}', date("Y"), $record_name); - $record_name = str_replace('${month}', date("M"), $record_name); - $record_name = str_replace('${day}', date("d"), $record_name); - $record_name = str_replace('${source}', $src, $record_name); - $record_name = str_replace('${caller_id_name}', $src_cid_name, $record_name); - $record_name = str_replace('${caller_id_number}', $src_cid_number, $record_name); - $record_name = str_replace('${caller_destination}', $dest, $record_name); - $record_name = str_replace('${destination}', $dest, $record_name); - $record_name = str_replace('${uuid}', $origination_uuid, $record_name); - $record_name = str_replace('${record_extension}', $record_extension, $record_name); - } - else { - $record_name = $origination_uuid.'.'.$record_extension; - } - } - - //determine call direction - $dir = (user_exists($dest)) ? 'local' : 'outbound'; - - //define a leg - set source to display the defined caller id name and number - $source_common = "{"; - $source_common .= "click_to_call=true"; - $source_common .= ",origination_caller_id_name='".$src_cid_name."'"; - $source_common .= ",origination_caller_id_number=".$src_cid_number; - $source_common .= ",instant_ringback=true"; - $source_common .= ",ringback=".$ringback_value; - $source_common .= ",presence_id=".$src."@".$_SESSION['domains'][$domain_uuid]['domain_name']; - $source_common .= ",call_direction=".$dir; - if ($rec == "true") { - $source_common .= ",record_path='".$record_path."'"; - $source_common .= ",record_name='".$record_name."'"; - } - - if (user_exists($src)) { - //source is a local extension - $source = $source_common.$sip_auto_answer. - ",domain_uuid=".$domain_uuid. - ",domain_name=".$_SESSION['domains'][$domain_uuid]['domain_name']."}user/".$src."@".$_SESSION['domains'][$domain_uuid]['domain_name']; - } - else { - //source is an external number - $bridge_array = outbound_route_to_bridge($_SESSION['domain_uuid'], $src); - $source = $source_common."}".$bridge_array[0]; - } - unset($source_common); - - //define b leg - set destination to display the defined caller id name and number - $destination_common = " &bridge({origination_caller_id_name='".$dest_cid_name."',origination_caller_id_number=".$dest_cid_number; - if (user_exists($dest)) { - //destination is a local extension - if (strpbrk($dest, '@') != FALSE) { //sip-uri - $switch_cmd = $destination_common.",call_direction=outbound}sofia/external/".$dest.")"; - } - else { //not sip-uri - $switch_cmd = " &transfer('".$dest." XML ".$context."')"; - } - } - else { - //local extension (source) > external number (destination) - if (user_exists($src) && empty($dest_cid_number)) { - //retrieve outbound caller id from the (source) extension - $sql = "select outbound_caller_id_name, outbound_caller_id_number from v_extensions where domain_uuid = :domain_uuid and extension = :src "; - $parameters['domain_uuid'] = $_SESSION['domain_uuid']; - $parameters['src'] = $src; - $database = new database; - $result = $database->select($sql, $parameters, 'all'); - foreach ($result as &$row) { - $dest_cid_name = $row["outbound_caller_id_name"]; - $dest_cid_number = $row["outbound_caller_id_number"]; - break; //limit to 1 row + //add record path and name + if ($rec == "true") { + $record_path = $_SESSION['switch']['recordings']['dir']."/".$_SESSION['domain_name']."/archive/".date("Y")."/".date("M")."/".date("d"); + if (isset($_SESSION['recordings']['extension']['text'])) { + $record_extension = $_SESSION['recordings']['extension']['text']; + } + else { + $record_extension = 'wav'; + } + if (isset($_SESSION['recordings']['template']['text'])) { + //${year}${month}${day}-${caller_id_number}-${caller_destination}-${uuid}.${record_extension} + $record_name = $_SESSION['recordings']['template']['text']; + $record_name = str_replace('${year}', date("Y"), $record_name); + $record_name = str_replace('${month}', date("M"), $record_name); + $record_name = str_replace('${day}', date("d"), $record_name); + $record_name = str_replace('${source}', $src, $record_name); + $record_name = str_replace('${caller_id_name}', $src_cid_name, $record_name); + $record_name = str_replace('${caller_id_number}', $src_cid_number, $record_name); + $record_name = str_replace('${caller_destination}', $dest, $record_name); + $record_name = str_replace('${destination}', $dest, $record_name); + $record_name = str_replace('${uuid}', $origination_uuid, $record_name); + $record_name = str_replace('${record_extension}', $record_extension, $record_name); + } + else { + $record_name = $origination_uuid.'.'.$record_extension; } } - if (permission_exists('click_to_call_call')) { + + //determine call direction + $dir = (user_exists($dest)) ? 'local' : 'outbound'; + + //define a leg - set source to display the defined caller id name and number + $source_common = "{"; + $source_common .= "click_to_call=true"; + $source_common .= ",origination_caller_id_name='".$src_cid_name."'"; + $source_common .= ",origination_caller_id_number=".$src_cid_number; + $source_common .= ",instant_ringback=true"; + $source_common .= ",ringback=".$ringback_value; + $source_common .= ",presence_id=".$src."@".$_SESSION['domains'][$domain_uuid]['domain_name']; + $source_common .= ",call_direction=".$dir; + if ($rec == "true") { + $source_common .= ",record_path='".$record_path."'"; + $source_common .= ",record_name='".$record_name."'"; + } + + if (user_exists($src)) { + //source is a local extension + $source = $source_common.$sip_auto_answer. + ",domain_uuid=".$domain_uuid. + ",domain_name=".$_SESSION['domains'][$domain_uuid]['domain_name']."}user/".$src."@".$_SESSION['domains'][$domain_uuid]['domain_name']; + } + else { + //source is an external number + $bridge_array = outbound_route_to_bridge($_SESSION['domain_uuid'], $src); + $source = $source_common."}".$bridge_array[0]; + } + unset($source_common); + + //define b leg - set destination to display the defined caller id name and number + $destination_common = " &bridge({origination_caller_id_name='".$dest_cid_name."',origination_caller_id_number=".$dest_cid_number; + if (user_exists($dest)) { + //destination is a local extension if (strpbrk($dest, '@') != FALSE) { //sip-uri $switch_cmd = $destination_common.",call_direction=outbound}sofia/external/".$dest.")"; } else { //not sip-uri - $bridge_array = outbound_route_to_bridge($_SESSION['domain_uuid'], $dest); - //$switch_cmd = $destination_common."}".$bridge_array[0].")"; // wouldn't set cdr destination correctly, so below used instead $switch_cmd = " &transfer('".$dest." XML ".$context."')"; } } - } - unset($destination_common); - - //create the even socket connection and send the event socket command - $fp = event_socket_create(); - if (!$fp) { + else { + //local extension (source) > external number (destination) + if (user_exists($src) && empty($dest_cid_number)) { + //retrieve outbound caller id from the (source) extension + $sql = "select outbound_caller_id_name, outbound_caller_id_number from v_extensions where domain_uuid = :domain_uuid and extension = :src "; + $parameters['domain_uuid'] = $_SESSION['domain_uuid']; + $parameters['src'] = $src; + $database = new database; + $result = $database->select($sql, $parameters, 'all'); + foreach ($result as &$row) { + $dest_cid_name = $row["outbound_caller_id_name"]; + $dest_cid_number = $row["outbound_caller_id_number"]; + break; //limit to 1 row + } + } + if (permission_exists('click_to_call_call')) { + if (strpbrk($dest, '@') != FALSE) { //sip-uri + $switch_cmd = $destination_common.",call_direction=outbound}sofia/external/".$dest.")"; + } + else { //not sip-uri + $bridge_array = outbound_route_to_bridge($_SESSION['domain_uuid'], $dest); + //$switch_cmd = $destination_common."}".$bridge_array[0].")"; // wouldn't set cdr destination correctly, so below used instead + $switch_cmd = " &transfer('".$dest." XML ".$context."')"; + } + } + } + unset($destination_common); + } else { //error message echo "
Connection to Event Socket failed.
"; } - else { + + //ensure we are still connected and send the event socket command + if ($esl->is_connected()) { //display the last command - $switch_cmd = "api originate ".$source.$switch_cmd; + $switch_cmd = "originate ".$source.$switch_cmd; echo "
".escape($src)." has called ".escape($dest)."
\n"; //show the command result - $result = trim(event_socket_request($fp, $switch_cmd)); + $result = trim(event_socket::api($switch_cmd)); if (substr($result, 0,3) == "+OK") { //$uuid = substr($result, 4); if ($rec == "true") { @@ -218,12 +214,15 @@ date_default_timezone_set($_SESSION['time_zone']['system']); //create the api record command and send it over event socket if (is_uuid($origination_uuid) && file_exists($record_path)) { - $switch_cmd = "api uuid_record ".$origination_uuid." start ".$record_path."/".$record_name; + $switch_cmd = "uuid_record $origination_uuid start $record_path/$record_name"; } - $result2 = trim(event_socket_request($fp, $switch_cmd)); + $result2 = trim(event_socket::api($switch_cmd)); } } echo "

".escape($result)."

\n"; + } else { + //error message + echo "
Connection to Event Socket failed.
"; } } diff --git a/app/conference_centers/conference_room_edit.php b/app/conference_centers/conference_room_edit.php index 649aeb8746..c7fbb735d4 100644 --- a/app/conference_centers/conference_room_edit.php +++ b/app/conference_centers/conference_room_edit.php @@ -141,9 +141,9 @@ $default_voice = 'callie'; $switch_cmd = "conference ".$conference_room_uuid."@".$_SESSION['domain_name']." play ".$_SESSION['switch']['sounds']['dir']."/".$default_language."/".$default_dialect."/".$default_voice."/ivr/ivr-recording_started.wav"; //connect to event socket - $fp = event_socket_create(); - if ($fp) { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $switch_result = event_socket::api($switch_cmd); } } diff --git a/app/conference_centers/conference_rooms.php b/app/conference_centers/conference_rooms.php index f00c4829c5..a34b7ad02e 100644 --- a/app/conference_centers/conference_rooms.php +++ b/app/conference_centers/conference_rooms.php @@ -98,9 +98,9 @@ $default_voice = 'callie'; $switch_cmd = "conference ".$meeting_uuid."@".$_SESSION['domain_name']." play ".$_SESSION['switch']['sounds']['dir']."/".$default_language."/".$default_dialect."/".$default_voice."/ivr/ivr-recording_started.wav"; //connect to event socket - $fp = event_socket_create(); - if ($fp) { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $esl = event_socket::create(); + if ($esl) { + $switch_result = event_socket::api($switch_cmd); } } @@ -137,12 +137,12 @@ //get conference array $switch_cmd = "conference xml_list"; - $fp = event_socket_create(); - if (!$fp) { - //connection to even socket failed + $esl = event_socket::create(); + if (!$esl->is_connected()) { + trigger_error('Unable to connect to FreeSWITCH', E_USER_WARNING); } else { - $xml_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $xml_str = trim(event_socket::api($switch_cmd)); try { $xml = new SimpleXMLElement($xml_str, true); } diff --git a/app/conference_centers/resources/classes/call_center_notify.php b/app/conference_centers/resources/classes/call_center_notify.php index 944f6bbd91..0153776787 100644 --- a/app/conference_centers/resources/classes/call_center_notify.php +++ b/app/conference_centers/resources/classes/call_center_notify.php @@ -37,8 +37,8 @@ //feature_event method public function send_call_center_notify() { - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //send the event $event = "sendevent PRESENCE_IN\n"; $event .= "proto: agent\n"; @@ -50,9 +50,8 @@ $event .= "login: agent+".$this->agent_name."@".$this->domain_name."\n"; $event .= "unique-id: ".$this->agent_uuid."\n"; $event .= "answer-state: ".$this->answer_state."\n"; - event_socket_request($fp, $event); + event_socket::command($event); //echo $event."
"; - fclose($fp); } } //function diff --git a/app/conference_centers/resources/classes/conference_centers.php b/app/conference_centers/resources/classes/conference_centers.php index 71a3abde23..59d648cc86 100644 --- a/app/conference_centers/resources/classes/conference_centers.php +++ b/app/conference_centers/resources/classes/conference_centers.php @@ -687,10 +687,10 @@ if (!class_exists('conference_centers')) { $switch_cmd_notice = "conference ".$meeting_uuid[$uuid]."@".$_SESSION['domain_name']." play ".$_SESSION['switch']['sounds']['dir']."/".$default_language."/".$default_dialect."/".$default_voice."/ivr/ivr-recording_started.wav"; //execute api commands // if (!file_exists($recording_dir.'/'.$meeting_uuid[$uuid].'.wav')) { - $fp = event_socket_create(); - if ($fp) { -// $switch_result = event_socket_request($fp, 'api '.$switch_cmd_record); - $switch_result = event_socket_request($fp, 'api '.$switch_cmd_notice); + $esl = event_socket::create(); + if ($esl->is_connected()) { +// $switch_result = event_socket::api($switch_cmd_record); + $switch_result = event_socket::api($switch_cmd_notice); } // } } diff --git a/app/conferences_active/conference_exec.php b/app/conferences_active/conference_exec.php index 721bc0d53b..449ee70371 100644 --- a/app/conferences_active/conference_exec.php +++ b/app/conferences_active/conference_exec.php @@ -147,9 +147,9 @@ } //define an alternative kick all - function conference_end($fp, $name) { + function conference_end($name) { $switch_cmd = "conference '".$name."' xml_list"; - $xml_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $xml_str = trim(event_socket::api($switch_cmd)); try { $xml = new SimpleXMLElement($xml_str); } @@ -161,7 +161,7 @@ foreach ($xml->conference->members->member as $row) { $uuid = (string)$row->uuid; if (is_uuid($uuid)) { - $switch_result = event_socket_request($fp, 'api uuid_kill '.$uuid); + $switch_result = event_socket::api("uuid_kill $uuid"); } if ($x < 1) { usleep(500000); //500000 = 0.5 seconds @@ -188,66 +188,66 @@ } //connect to event socket - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { if ($data == "energy") { //conference 3001-example-domain.org energy 103 - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); $result_array = explode("=",$switch_result); $tmp_value = $result_array[1]; if ($direction == "up") { $tmp_value = $tmp_value + 100; } if ($direction == "down") { $tmp_value = $tmp_value - 100; } //echo "energy $tmp_value
\n"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd.' '.$tmp_value); + $switch_result = event_socket::api("$switch_cmd $tmp_value"); } elseif ($data == "volume_in") { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); $result_array = explode("=",$switch_result); $tmp_value = $result_array[1]; if ($direction == "up") { $tmp_value = $tmp_value + 1; } if ($direction == "down") { $tmp_value = $tmp_value - 1; } //echo "volume $tmp_value
\n"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd.' '.$tmp_value); + $switch_result = event_socket::api($switch_cmd.' '.$tmp_value); } elseif ($data == "volume_out") { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); $result_array = explode("=",$switch_result); $tmp_value = $result_array[1]; if ($direction == "up") { $tmp_value = $tmp_value + 1; } if ($direction == "down") { $tmp_value = $tmp_value - 1; } //echo "volume $tmp_value
\n"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd.' '.$tmp_value); + $switch_result = event_socket::api($switch_cmd.' '.$tmp_value); } elseif ($data == "record") { $recording_dir = $_SESSION['switch']['recordings']['dir'].'/'.$_SESSION['domain_name'].'/archive/'.date("Y").'/'.date("M").'/'.date("d"); - $switch_cmd .= $recording_dir."/".$uuid.".wav"; - if (!file_exists($recording_dir."/".$uuid.".wav")) { - $switch_result = event_socket_request($fp, "api ".$switch_cmd); + $switch_cmd .= $recording_dir."/{$uuid}.wav"; + if (!file_exists($switch_cmd)) { + $switch_result = event_socket::api($switch_cmd); } } elseif ($data == "norecord") { //stop recording and rename the file $recording_dir = $_SESSION['switch']['recordings']['dir'].'/'.$_SESSION['domain_name'].'/archive/'.date("Y").'/'.date("M").'/'.date("d"); $switch_cmd .= $recording_dir."/".$uuid.".wav"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); } elseif ($data == "kick") { - $switch_result = event_socket_request($fp, 'api uuid_kill '.$uuid); + $switch_result = event_socket::api("uuid_kill $uuid"); } elseif ($data == "kick all") { - //$switch_result = event_socket_request($fp, 'api '.$switch_cmd); - conference_end($fp, $name); + //$switch_result = event_socket::api($switch_cmd); + conference_end($name); } elseif ($data == "mute" || $data == "unmute" || $data == "mute non_moderator" || $data == "unmute non_moderator") { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); $switch_cmd = "uuid_setvar ".$uuid. " hand_raised false"; - event_socket_request($fp, 'api '.$switch_cmd); + event_socket::api($switch_cmd); } elseif ($data == "deaf" || $data == "undeaf" ) { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); } elseif ($data == "lock" || $data == "unlock" ) { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); } //echo "command: ".$switch_cmd." result: ".$switch_result.""; } diff --git a/app/conferences_active/conference_interactive_inc.php b/app/conferences_active/conference_interactive_inc.php index 075e3ccef8..092a4a75d8 100644 --- a/app/conferences_active/conference_interactive_inc.php +++ b/app/conferences_active/conference_interactive_inc.php @@ -61,8 +61,8 @@ $switch_cmd = "conference '".$conference_name."' xml_list"; //connect to event socket, send the command and process the results - $fp = event_socket_create(); - if (!$fp) { + $esl = event_socket::create(); + if (!$esl->is_connected()) { $msg = "
".$text['message-connection']."
"; echo "
\n"; echo "
\n"; @@ -77,7 +77,7 @@ } else { //show the content - $xml_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $xml_str = trim(event_socket::api($switch_cmd)); if (substr($xml_str, -9) == "not found") { $valid_xml = false; } @@ -188,7 +188,7 @@ $caller_id_name = urldecode($caller_id_name); $caller_id_number = $row->caller_id_number; $switch_cmd = "uuid_getvar ".$uuid. " hand_raised"; - $hand_raised = (trim(event_socket_request($fp, 'api '.$switch_cmd)) == "true") ? "true" : "false"; + $hand_raised = (trim(event_socket::api($switch_cmd)) == "true") ? "true" : "false"; //format secondsfloor(floor($fifo_duration / 60) % 60) $join_time_formatted = sprintf('%02d:%02d:%02d', floor($join_time / 3600), floor(floor($join_time / 60) % 60), $join_time % 60); $last_talking_formatted = sprintf('%02d:%02d:%02d', floor($last_talking / 3600), floor(floor($last_talking / 60) % 60), $last_talking % 60); diff --git a/app/conferences_active/conferences_active_inc.php b/app/conferences_active/conferences_active_inc.php index 3d9be0d290..e3f427db46 100644 --- a/app/conferences_active/conferences_active_inc.php +++ b/app/conferences_active/conferences_active_inc.php @@ -43,8 +43,8 @@ $text = $language->get(); //show content - $fp = event_socket_create(); - if (!$fp) { + $fp = event_socket::create(); + if (!$fp->is_connected()) { $msg = "
".$text['message-connection']."
"; echo "
\n"; echo "
\n"; @@ -58,7 +58,7 @@ echo "\n"; } else { - $xml_string = trim(event_socket_request($fp, 'api conference xml_list')); + $xml_string = trim(event_socket::api('conference xml_list')); try { $xml = new SimpleXMLElement($xml_string); } diff --git a/app/devices/cmd.php b/app/devices/cmd.php index 64bc0f37f8..e4467fb3f5 100644 --- a/app/devices/cmd.php +++ b/app/devices/cmd.php @@ -65,11 +65,11 @@ } //create the event socket connection - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { // Get the SIP profiles for the user $command = "sofia_contact */{$user}@{$domain_name}"; - $contact_string = event_socket_request($fp, "api ".$command); + $contact_string = event_socket::api($command); // The first value in the array will be full matching text, the second one will be the array of profile matches preg_match_all('/sofia\/([^,]+)\/(?:[^,]+)/', $contact_string, $matches); @@ -93,8 +93,8 @@ } //send the command - $response = event_socket_request($fp, "api {$command}"); - event_socket_request($fp, "api log notice {$command}"); + $response = event_socket::api("{$command}"); + event_socket::api("log notice {$command}"); //prepare the response $message = $text['message-command_sent']; @@ -105,9 +105,6 @@ //show the response message::add($text['label-event']." ".$message, 'positive', 3500); } - - //close the connection - fclose($fp); } //redirect the user diff --git a/app/dialplans/dialplan_edit.php b/app/dialplans/dialplan_edit.php index 3234563901..e71fe00109 100644 --- a/app/dialplans/dialplan_edit.php +++ b/app/dialplans/dialplan_edit.php @@ -89,14 +89,14 @@ //get the list of applications if (empty($_SESSION['switch']['applications']) || !is_array($_SESSION['switch']['applications'])) { - $fp = event_socket_create(); - if ($fp) { - $result = event_socket_request($fp, 'api show application'); - + $esl = event_socket::create(); + if ($esl->is_connected()) { + $result = event_socket::api('show application'); + $show_applications = explode("\n\n", $result); $raw_applications = explode("\n", $show_applications[0]); unset($result); - unset($fp); + unset($esl); $previous_application = null; foreach($raw_applications as $row) { diff --git a/app/email_queue/resources/jobs/email_send.php b/app/email_queue/resources/jobs/email_send.php index a78b9ba697..1987d72f27 100644 --- a/app/email_queue/resources/jobs/email_send.php +++ b/app/email_queue/resources/jobs/email_send.php @@ -383,11 +383,11 @@ $domain_name = $database->select($sql, $parameters, 'column'); //send the message waiting status - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //$switch_cmd .= "luarun app.lua voicemail mwi ".$voicemail_id."@".$domain_name; - $switch_cmd .= "luarun app/voicemail/resources/scripts/mwi_notify.lua ".$voicemail_id." ".$domain_name." 0 0"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_cmd .= "luarun app/voicemail/resources/scripts/mwi_notify.lua $voicemail_id $domain_name 0 0"; + $switch_result = event_socket::api($switch_cmd); echo $switch_cmd."\n"; } else { @@ -517,7 +517,7 @@ unset($mail); //save output to - //$fp = fopen(sys_get_temp_dir()."/mailer-app.log", "a"); + //$esl = fopen(sys_get_temp_dir()."/mailer-app.log", "a"); //prepare the output buffers //ob_end_clean(); @@ -532,7 +532,7 @@ //ob_end_clean(); //clean the buffer - //fwrite($fp, $content); - //fclose($fp); + //fwrite($esl, $content); + //fclose($esl); ?> diff --git a/app/event_guard/resources/classes/event_guard.php b/app/event_guard/resources/classes/event_guard.php index 5f0dd3a43c..02bafd1bc2 100644 --- a/app/event_guard/resources/classes/event_guard.php +++ b/app/event_guard/resources/classes/event_guard.php @@ -157,8 +157,8 @@ if (!class_exists('event_guard')) { $cmd = "sendevent CUSTOM\n"; $cmd .= "Event-Name: CUSTOM\n"; $cmd .= "Event-Subclass: event_guard:unblock\n"; - $fp = event_socket_create(); - $switch_result = event_socket_request($fp, $cmd); + $esl = event_socket::create(); + $switch_result = event_socket::command($cmd); //set message message::add($text['message-delete']); diff --git a/app/extensions/extension_edit.php b/app/extensions/extension_edit.php index 8b9c2c9f56..94a1727605 100644 --- a/app/extensions/extension_edit.php +++ b/app/extensions/extension_edit.php @@ -780,8 +780,8 @@ //reload acl if allowed if (permission_exists("extension_cidr")) { - $fp = event_socket_create(); - if ($fp) { event_socket_request($fp, "api reloadacl"); } + $esl = event_socket::create(); + if ($esl->is_connected()) { event_socket::api("reloadacl"); } } //check the permissions diff --git a/app/fax/fax_outbox.php b/app/fax/fax_outbox.php index 656d839c50..57af3edd2e 100644 --- a/app/fax/fax_outbox.php +++ b/app/fax/fax_outbox.php @@ -98,11 +98,11 @@ $switch_cmd = 'show channels as json'; //create the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //send the event socket command and get the array - if ($fp) { - $json = trim(event_socket_request($fp, 'api '.$switch_cmd)); + if ($esl->is_connected()) { + $json = trim($esl->api($switch_cmd)); $results = json_decode($json, "true"); } diff --git a/app/fax_queue/resources/job/fax_send.php b/app/fax_queue/resources/job/fax_send.php index 62f9d86a36..ac478d69d8 100644 --- a/app/fax_queue/resources/job/fax_send.php +++ b/app/fax_queue/resources/job/fax_send.php @@ -212,8 +212,8 @@ if ($fax_status == 'waiting' || $fax_status == 'trying' || $fax_status == 'busy') { //create event socket handle - $fp = event_socket_create(); - if (!$fp) { + $esl = event_socket::create(); + if (!$esl->is_connected()) { echo "Could not connect to event socket.\n"; exit; } @@ -297,7 +297,7 @@ //send the fax and try another route if the fax fails foreach($route_array as $route) { $fax_command = "originate {" . $dial_string . ",fax_uri=".$route."}" . $route." &txfax('".$fax_file."')"; - $fax_response = event_socket_request($fp, "api " . $fax_command); + $fax_response = event_socket::api($fax_command); $response = str_replace("\n", "", $fax_response); $response = trim(str_replace("+OK", "", $response)); if (is_uuid($response)) { @@ -311,8 +311,7 @@ echo "response: ".$response."\n"; } } - fclose($fp); - + //set the fax file name without the extension $fax_instance_id = pathinfo($fax_file, PATHINFO_FILENAME); diff --git a/app/fifo_list/fifo_exec.php b/app/fifo_list/fifo_exec.php index 6d9fd3c544..24cacc1aec 100644 --- a/app/fifo_list/fifo_exec.php +++ b/app/fifo_list/fifo_exec.php @@ -51,38 +51,38 @@ /* if ($action == "energy") { //conference 3001-example.dyndns.org energy 103 - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); $result_array = explode("=",$switch_result); $tmp_value = $result_array[1]; if ($direction == "up") { $tmp_value = $tmp_value + 100; } if ($direction == "down") { $tmp_value = $tmp_value - 100; } //echo "energy $tmp_value
\n"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd.' '.$tmp_value); + $switch_result = event_socket::api($switch_cmd.' '.$tmp_value); } if ($action == "volume_in") { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); $result_array = explode("=",$switch_result); $tmp_value = $result_array[1]; if ($direction == "up") { $tmp_value = $tmp_value + 1; } if ($direction == "down") { $tmp_value = $tmp_value - 1; } //echo "volume $tmp_value
\n"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd.' '.$tmp_value); + $switch_result = event_socket::api($switch_cmd.' '.$tmp_value); } if ($action == "volume_out") { - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); $result_array = explode("=",$switch_result); $tmp_value = $result_array[1]; if ($direction == "up") { $tmp_value = $tmp_value + 1; } if ($direction == "down") { $tmp_value = $tmp_value - 1; } //echo "volume $tmp_value
\n"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd.' '.$tmp_value); + $switch_result = event_socket::api($switch_cmd.' '.$tmp_value); } */ //connect to the event socket - //$fp = event_socket_create(); + //$esl = event_socket::create(); //send the command over event socket - //if ($fp) { - // $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + //if ($esl->is_connected()) { + // $switch_result = event_socket::api($switch_cmd); //} } diff --git a/app/fifo_list/fifo_interactive_inc.php b/app/fifo_list/fifo_interactive_inc.php index eb226ca787..9b288d9b64 100644 --- a/app/fifo_list/fifo_interactive_inc.php +++ b/app/fifo_list/fifo_interactive_inc.php @@ -57,8 +57,8 @@ $switch_cmd = 'fifo list_verbose '.$fifo_name.''; - $fp = event_socket_create(); - if (!$fp) { + $esl = event_socket::create(); + if (!$esl->is_connected()) { $msg = "
Connection to Event Socket failed.
"; echo "
\n"; echo "
\n"; @@ -73,7 +73,7 @@ } else { //send the api command over event socket - $xml_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $xml_str = trim(event_socket::api($switch_cmd)); //parse the response as xml try { diff --git a/app/fifo_list/fifo_list_inc.php b/app/fifo_list/fifo_list_inc.php index 541afa9304..28234d644e 100644 --- a/app/fifo_list/fifo_list_inc.php +++ b/app/fifo_list/fifo_list_inc.php @@ -46,9 +46,9 @@ //show the list $switch_cmd = 'fifo list'; - $fp = event_socket_create(); - if ($fp) { - $xml_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $xml_str = trim(event_socket::api($switch_cmd)); try { $xml = new SimpleXMLElement($xml_str); } diff --git a/app/gateways/gateway_copy.php b/app/gateways/gateway_copy.php index f3a542b761..5bbe51f507 100644 --- a/app/gateways/gateway_copy.php +++ b/app/gateways/gateway_copy.php @@ -143,8 +143,8 @@ save_gateway_xml(); //clear the cache - $fp = event_socket_create(); - $hostname = trim(event_socket_request($fp, 'api switchname')); + $esl = event_socket::create(); + $hostname = trim(event_socket::api('switchname')); $cache = new cache; $cache->delete("configuration:sofia.conf:".$hostname); diff --git a/app/gateways/gateway_edit.php b/app/gateways/gateway_edit.php index affe3d9c9d..1060d6cde0 100644 --- a/app/gateways/gateway_edit.php +++ b/app/gateways/gateway_edit.php @@ -227,20 +227,16 @@ save_gateway_xml(); //clear the cache - $fp = event_socket_create(); - $hostname = trim(event_socket_request($fp, 'api switchname')); + $esl = event_socket::create(); + $hostname = trim(event_socket::api('switchname')); $cache = new cache; $cache->delete("configuration:sofia.conf:".$hostname); //rescan the external profile to look for new or stopped gateways //create the event socket connection - $fp = event_socket_create(); - $tmp_cmd = 'api sofia profile external rescan'; - $response = event_socket_request($fp, $tmp_cmd); - unset($tmp_cmd); + $esl = event_socket::create(); + $response = event_socket::api('sofia profile external rescan'); usleep(1000); - //close the connection - fclose($fp); //clear the apply settings reminder $_SESSION["reload_xml"] = false; diff --git a/app/gateways/gateways.php b/app/gateways/gateways.php index bfda610cb3..a14388c6af 100644 --- a/app/gateways/gateways.php +++ b/app/gateways/gateways.php @@ -70,15 +70,15 @@ $obj->delete($gateways); } case 'start': - $fp = event_socket_create(); - if ($fp && permission_exists('gateway_edit')) { + $esl = event_socket::create(); + if ($esl && permission_exists('gateway_edit')) { $obj = new gateways; $obj->start($gateways); } break; case 'stop': - $fp = event_socket_create(); - if ($fp && permission_exists('gateway_edit')) { + $esl = event_socket::create(); + if ($esl && permission_exists('gateway_edit')) { $obj = new gateways; $obj->stop($gateways); } @@ -90,19 +90,19 @@ } //connect to event socket - $fp = event_socket_create(); + $esl = event_socket::create(); //gateway status function if (!function_exists('switch_gateway_status')) { function switch_gateway_status($gateway_uuid, $result_type = 'xml') { - global $fp; - if ($fp) { - $fp = event_socket_create(); - $cmd = 'api sofia xmlstatus gateway '.$gateway_uuid; - $response = trim(event_socket_request($fp, $cmd)); + global $esl; + if ($esl->is_connected()) { + $esl = event_socket::create(); + $cmd = 'sofia xmlstatus gateway '.$gateway_uuid; + $response = trim(event_socket::api($cmd)); if ($response == "Invalid Gateway!") { - $cmd = 'api sofia xmlstatus gateway '.strtoupper($gateway_uuid); - $response = trim(event_socket_request($fp, $cmd)); + $cmd = 'sofia xmlstatus gateway '.strtoupper($gateway_uuid); + $response = trim(event_socket::api($cmd)); } return $response; } @@ -267,7 +267,7 @@ echo "\n"; echo th_order_by('context', $text['label-context'], $order_by, $order); echo th_order_by('register', $text['label-register'], $order_by, $order); - if ($fp) { + if ($esl->is_connected()) { echo "\n"; if (permission_exists('gateway_edit')) { echo "\n"; @@ -316,7 +316,7 @@ echo " \n"; echo " \n"; echo " \n"; - if ($fp) { + if ($esl->is_connected()) { if ($row["enabled"] == "true") { $response = switch_gateway_status($row["gateway_uuid"]); if ($response == "Invalid Gateway!") { diff --git a/app/gateways/resources/classes/gateways.php b/app/gateways/resources/classes/gateways.php index cd89c5bedb..cbfba52633 100644 --- a/app/gateways/resources/classes/gateways.php +++ b/app/gateways/resources/classes/gateways.php @@ -110,23 +110,23 @@ if (!class_exists('gateways')) { if (!empty($gateways) && is_array($gateways) && @sizeof($gateways) != 0) { //create the event socket connection - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //start gateways foreach ($gateways as $gateway_uuid => $gateway) { if ($gateway['enabled'] == 'true') { //start gateways foreach ($gateways as $gateway_uuid => $gateway) { if ($gateway['enabled'] == 'true') { - $cmd = 'api sofia profile '.$gateway['profile'].' startgw '.$gateway_uuid; + $cmd = 'sofia profile '.$gateway['profile'].' startgw '.$gateway_uuid; $responses[$gateway_uuid]['gateway'] = $gateway['name']; - $responses[$gateway_uuid]['message'] = trim(event_socket_request($fp, $cmd)); + $responses[$gateway_uuid]['message'] = trim(event_socket::api($cmd)); } } //old method used to start gateways - //$cmd = 'api sofia profile '.$gateway['profile'].' rescan'; + //$cmd = 'sofia profile '.$gateway['profile'].' rescan'; //$responses[$gateway_uuid]['gateway'] = $gateway['name']; - //$responses[$gateway_uuid]['message'] = trim(event_socket_request($fp, $cmd)); + //$responses[$gateway_uuid]['message'] = trim(event_socket::api($cmd)); } } @@ -198,14 +198,14 @@ if (!class_exists('gateways')) { if (!empty($gateways) && is_array($gateways) && @sizeof($gateways) != 0) { //create the event socket connection - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //stop gateways foreach ($gateways as $gateway_uuid => $gateway) { if ($gateway['enabled'] == 'true') { - $cmd = 'api sofia profile '.$gateway['profile'].' killgw '.$gateway_uuid; + $cmd = 'sofia profile '.$gateway['profile'].' killgw '.$gateway_uuid; $responses[$gateway_uuid]['gateway'] = $gateway['name']; - $responses[$gateway_uuid]['message'] = trim(event_socket_request($fp, $cmd)); + $responses[$gateway_uuid]['message'] = trim(event_socket::api($cmd)); } } //set message @@ -274,9 +274,7 @@ if (!class_exists('gateways')) { } //create the event socket connection - if (!isset($fp)) { - $fp = event_socket_create(); - } + $esl = event_socket::create(); //loop through gateways $x = 0; @@ -294,9 +292,9 @@ if (!class_exists('gateways')) { } //send the api command to stop the gateway - if ($fp) { - $cmd = 'api sofia profile '.$gateway['profile'].' killgw '.$gateway_uuid; - $response = event_socket_request($fp, $cmd); + if ($esl->is_connected()) { + $cmd = 'sofia profile '.$gateway['profile'].' killgw '.$gateway_uuid; + $response = event_socket::api($cmd); unset($cmd); } @@ -320,20 +318,16 @@ if (!class_exists('gateways')) { save_gateway_xml(); //clear the cache - if (!$fp) { - $fp = event_socket_create(); - } - if ($fp) { - $hostname = trim(event_socket_request($fp, 'api switchname')); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $hostname = trim(event_socket::api('switchname')); $cache = new cache; $cache->delete("configuration:sofia.conf:".$hostname); } //rescan the sip profile to look for new or stopped gateways - if (!$fp) { - $fp = event_socket_create(); - } - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //get distinct profiles from gateways foreach ($gateways as $gateway) { $array[] = $gateway['profile']; @@ -342,13 +336,8 @@ if (!class_exists('gateways')) { //send the api command to rescan each profile foreach ($profiles as $profile) { - $cmd = 'api sofia profile '.$profile.' rescan'; - $response = event_socket_request($fp, $cmd); + $response = event_socket::api("sofia profile $profile rescan"); } - unset($cmd); - - //close the connection - fclose($fp); } usleep(1000); @@ -452,18 +441,16 @@ if (!class_exists('gateways')) { save_gateway_xml(); //clear the cache - $fp = event_socket_create(); - $hostname = trim(event_socket_request($fp, 'api switchname')); + $esl = event_socket::create(); + $hostname = trim(event_socket::api('switchname')); $cache = new cache; $cache->delete("configuration:sofia.conf:".$hostname); //create the event socket connection - if (!$fp) { - $fp = event_socket_create(); - } + $esl = event_socket::create(); //rescan the sip profile to look for new or stopped gateways - if ($fp) { + if ($esl->is_connected()) { //get distinct profiles from gateways foreach ($gateways as $gateway) { $array[] = $gateway['profile']; @@ -472,13 +459,8 @@ if (!class_exists('gateways')) { //send the api command to rescan each profile foreach ($profiles as $profile) { - $cmd = 'api sofia profile '.$profile.' rescan'; - $response = event_socket_request($fp, $cmd); + event_socket::api("sofia profile $profile rescan"); } - unset($cmd); - - //close the connection - fclose($fp); } usleep(1000); @@ -585,8 +567,8 @@ if (!class_exists('gateways')) { save_gateway_xml(); //clear the cache - $fp = event_socket_create(); - $hostname = trim(event_socket_request($fp, 'api switchname')); + $esl = event_socket::create(); + $hostname = trim(event_socket::api('switchname')); $cache = new cache; $cache->delete("configuration:sofia.conf:".$hostname); diff --git a/app/modules/modules.php b/app/modules/modules.php index defb1c891a..1dee38b378 100644 --- a/app/modules/modules.php +++ b/app/modules/modules.php @@ -92,17 +92,10 @@ } //connect to event socket - $fp = event_socket_create(); - -//check connection status - $esl_alive = false; - if ($fp) { - $esl_alive = true; - fclose($fp); - } + $esl = event_socket::create(); //warn if switch not running - if (!$fp) { + if (!$esl->is_connected()) { message::add($text['error-event-socket'], 'negative', 5000); } @@ -133,7 +126,7 @@ echo "
\n"; echo "
".$text['header-modules']." (".$module_count.")
\n"; echo "
\n"; - if (permission_exists('module_edit') && $modules && $fp) { + if (permission_exists('module_edit') && $modules && $esl->is_connected()) { echo button::create(['type'=>'button','label'=>$text['button-stop'],'icon'=>$_SESSION['theme']['button_icon_stop'],'onclick'=>"modal_open('modal-stop','btn_stop');"]); echo button::create(['type'=>'button','label'=>$text['button-start'],'icon'=>$_SESSION['theme']['button_icon_start'],'onclick'=>"modal_open('modal-start','btn_start');"]); } @@ -151,7 +144,7 @@ echo "
\n"; echo "
\n"; - if (permission_exists('module_edit') && !empty($modules) && $fp) { + if (permission_exists('module_edit') && !empty($modules) && $esl->is_connected()) { echo modal::create(['id'=>'modal-stop','type'=>'general','message'=>$text['confirm-stop_modules'],'actions'=>button::create(['type'=>'button','label'=>$text['button-continue'],'icon'=>'check','id'=>'btn_stop','style'=>'float: right; margin-left: 15px;','collapse'=>'never','onclick'=>"modal_close(); list_action_set('stop'); list_form_submit('form_list');"])]); echo modal::create(['id'=>'modal-start','type'=>'general','message'=>$text['confirm-start_modules'],'actions'=>button::create(['type'=>'button','label'=>$text['button-continue'],'icon'=>'check','id'=>'btn_start','style'=>'float: right; margin-left: 15px;','collapse'=>'never','onclick'=>"modal_close(); list_action_set('start'); list_form_submit('form_list');"])]); } @@ -171,7 +164,7 @@ echo "
".$text['label-proxy']."".$text['label-status']."".$text['label-action']."".escape($row["proxy"])."".escape($row["context"])."".ucwords(escape($row["register"]))."
\n"; function write_header($modifier) { - global $fp, $text, $modules, $list_row_edit_button; + global $text, $modules, $list_row_edit_button; $modifier = str_replace('/', '', $modifier); $modifier = str_replace(' ', ' ', $modifier); $modifier = str_replace(' ', '_', $modifier); @@ -185,7 +178,8 @@ } echo "\n"; echo "\n"; - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { echo "\n"; } echo "\n"; @@ -229,7 +223,7 @@ echo escape($row['module_label']); } echo " \n"; - if ($fp) { + if ($esl->is_connected()) { if ($module->active($row["module_name"])) { echo " \n"; if (permission_exists('module_edit')) { diff --git a/app/modules/resources/classes/modules.php b/app/modules/resources/classes/modules.php index de5f774974..8d6f14dd96 100644 --- a/app/modules/resources/classes/modules.php +++ b/app/modules/resources/classes/modules.php @@ -32,7 +32,7 @@ if (!class_exists('modules')) { * declare public variables */ public $dir; - public $fp; + public $esl; public $modules; public $msg; @@ -65,9 +65,8 @@ if (!class_exists('modules')) { $this->toggle_values = ['true','false']; //get the list of active modules - $this->fp = event_socket_create(); - $cmd = "api show modules as json"; - $json = event_socket_request($this->fp, $cmd); + $this->esl = event_socket::create(); + $json = $this->esl->api("show modules as json"); $this->active_modules = json_decode($json, true); } @@ -884,15 +883,14 @@ if (!class_exists('modules')) { if (is_array($modules) && @sizeof($modules) != 0) { //create the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); - if ($fp) { + if ($esl->is_connected()) { //control modules foreach ($modules as $module_uuid => $module) { if ($module['enabled'] == 'true') { - $cmd = 'api '.$action.' '.$module['name']; $responses[$module_uuid]['module'] = $module['name']; - $responses[$module_uuid]['message'] = trim(event_socket_request($fp, $cmd)); + $responses[$module_uuid]['message'] = trim(event_socket::api($action.' '.$module['name'])); } else { $responses[$module_uuid]['module'] = $module['name']; @@ -970,15 +968,14 @@ if (!class_exists('modules')) { if (is_array($array) && @sizeof($array) != 0) { //create the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //stop modules - if ($fp) { + if ($esl->is_connected()) { foreach ($modules as $module_uuid => $module) { if ($this->active($module['name'])) { - $cmd = 'api unload '.$module['name']; $responses[$module_uuid]['module'] = $module['name']; - $responses[$module_uuid]['message'] = trim(event_socket_request($fp, $cmd)); + $responses[$module_uuid]['message'] = trim(event_socket::api('unload '.$module['name'])); } } } @@ -1070,15 +1067,15 @@ if (!class_exists('modules')) { unset($array); //create the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //stop modules if active - if ($fp) { + if ($esl->is_connected()) { foreach ($modules as $module_uuid => $module) { if ($this->active($module['name'])) { - $cmd = 'api unload '.$module['name']; + $cmd = 'unload '.$module['name']; $responses[$module_uuid]['module'] = $module['name']; - $responses[$module_uuid]['message'] = trim(event_socket_request($fp, $cmd)); + $responses[$module_uuid]['message'] = trim(event_socket::api($cmd)); } } } diff --git a/app/music_on_hold/resources/classes/switch_music_on_hold.php b/app/music_on_hold/resources/classes/switch_music_on_hold.php index a83b4d60ce..99d778d5f9 100644 --- a/app/music_on_hold/resources/classes/switch_music_on_hold.php +++ b/app/music_on_hold/resources/classes/switch_music_on_hold.php @@ -147,15 +147,15 @@ if (!class_exists('switch_music_on_hold')) { public function reload() { //if the handle does not exist create it - $fp = event_socket_create(); + $esl = event_socket::create(); //if the handle still does not exist show an error message - if (!$fp) { + if (!$esl->is_connected()) { $msg = "
".$text['message-event-socket']."
"; } //send the api command to check if the module exists - if ($fp) { + if ($esl->is_connected()) { $cmd = "reload mod_local_stream"; - $switch_result = event_socket_request($fp, 'api '.$cmd); + $switch_result = event_socket::api($cmd); unset($cmd); } } diff --git a/app/number_translations/cmd.php b/app/number_translations/cmd.php index e550cfbfd7..26a65cc665 100644 --- a/app/number_translations/cmd.php +++ b/app/number_translations/cmd.php @@ -42,22 +42,20 @@ $rdr = $_GET['rdr']; //create the event socket connection - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //reloadxml if ($cmd == "api reloadxml") { - message::add(rtrim(event_socket_request($fp, $cmd)), 'alert'); + message::add(rtrim(event_socket::command($cmd)), 'alert'); unset($cmd); } //reload mod_translate if ($cmd == "api reload mod_translate") { - message::add(rtrim(event_socket_request($fp, $cmd)), 'alert'); + message::add(rtrim(event_socket::command($cmd)), 'alert'); unset($cmd); } - //close the connection - fclose($fp); } //redirect the user diff --git a/app/phrases/app_defaults.php b/app/phrases/app_defaults.php index 0adbfb19a7..10e4281890 100644 --- a/app/phrases/app_defaults.php +++ b/app/phrases/app_defaults.php @@ -142,8 +142,8 @@ if ($domains_processed == 1) { //save_phrases_xml(); //delete the phrase from memcache - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //get phrase languages $sql = "select distinct phrase_language from v_phrases order by phrase_language asc "; $database = new database; @@ -158,7 +158,7 @@ if ($domains_processed == 1) { } unset($sql, $result, $row); } - unset($fp); + unset($esl); } diff --git a/app/registrations/resources/classes/registrations.php b/app/registrations/resources/classes/registrations.php index e5497e6358..89bf18fbb2 100644 --- a/app/registrations/resources/classes/registrations.php +++ b/app/registrations/resources/classes/registrations.php @@ -60,7 +60,7 @@ if (!class_exists('registrations')) { $id = 0; //create the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //get the default settings $sql = "select sip_profile_name from v_sip_profiles "; @@ -77,7 +77,7 @@ if (!class_exists('registrations')) { //get sofia status profile information including registrations $cmd = "api sofia xmlstatus profile '".$field['sip_profile_name']."' reg"; - $xml_response = trim(event_socket_request($fp, $cmd)); + $xml_response = trim(event_socket::command($cmd)); //show an error message if ($xml_response == "Invalid Profile!") { @@ -269,10 +269,10 @@ if (!class_exists('registrations')) { unset($sql); //create the event socket connection - $fp = event_socket_create(); + $esl = event_socket::create(); //loop through registrations - if ($fp) { + if ($esl->is_connected()) { //check if registrations exist if (is_array($registrations)) { foreach ($registrations as $registration) { @@ -332,9 +332,9 @@ if (!class_exists('registrations')) { } //send the api command - if (!empty($command) && $fp) { - $response_api[$registration['user']]['command'] = event_socket_request($fp, "api ".$command); - $response_api[$registration['user']]['log'] = event_socket_request($fp, "api log notice ".$command); + if (!empty($command) && $esl->is_connected()) { + $response_api[$registration['user']]['command'] = event_socket::api($command); + $response_api[$registration['user']]['log'] = event_socket::api("log notice $command"); } } diff --git a/app/sip_profiles/resources/classes/sip_profiles.php b/app/sip_profiles/resources/classes/sip_profiles.php index 8867c47e72..82470a40dd 100644 --- a/app/sip_profiles/resources/classes/sip_profiles.php +++ b/app/sip_profiles/resources/classes/sip_profiles.php @@ -154,9 +154,9 @@ if (!class_exists('sip_profiles')) { } } if ($empty_hostname) { - $fp = event_socket_create(); - if ($fp) { - $hostnames[] = event_socket_request($fp, 'api switchname'); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $hostnames[] = event_socket::api('switchname'); } } @@ -237,9 +237,9 @@ if (!class_exists('sip_profiles')) { //get system hostname if necessary if (empty($sip_profile_hostname)) { - $fp = event_socket_create(); - if ($fp) { - $sip_profile_hostname = event_socket_request($fp, 'api switchname'); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $sip_profile_hostname = event_socket::api('switchname'); } } @@ -315,9 +315,9 @@ if (!class_exists('sip_profiles')) { //get system hostname if necessary if (empty($sip_profile_hostname)) { - $fp = event_socket_create(); - if ($fp) { - $sip_profile_hostname = event_socket_request($fp, 'api switchname'); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $sip_profile_hostname = event_socket::api('switchname'); } } @@ -403,9 +403,9 @@ if (!class_exists('sip_profiles')) { } } if ($empty_hostname) { - $fp = event_socket_create(); - if ($fp) { - $hostnames[] = event_socket_request($fp, 'api switchname'); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $hostnames[] = event_socket::api('switchname'); } } diff --git a/app/sip_profiles/sip_profile_edit.php b/app/sip_profiles/sip_profile_edit.php index aa6bfd01d9..499fcad74d 100644 --- a/app/sip_profiles/sip_profile_edit.php +++ b/app/sip_profiles/sip_profile_edit.php @@ -247,9 +247,9 @@ //get the hostname if ($sip_profile_hostname == '') { - $fp = event_socket_create(); - if ($fp) { - $sip_profile_hostname = event_socket_request($fp, 'api switchname'); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $sip_profile_hostname = event_socket::api('switchname'); } } diff --git a/app/sip_status/cmd.php b/app/sip_status/cmd.php index f11202527e..817085ba4e 100644 --- a/app/sip_status/cmd.php +++ b/app/sip_status/cmd.php @@ -91,15 +91,15 @@ } //create the event socket connection - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { //if reloadxml then run reloadacl, reloadxml and rescan the external profile for new gateways if (isset($command)) { //clear the apply settings reminder $_SESSION["reload_xml"] = false; //run the command - $result = rtrim(event_socket_request($fp, 'api '.$command)); + $result = rtrim(event_socket::api($command)); } //sofia profile @@ -109,9 +109,6 @@ else if (!empty($result)) { message::add($result, 'alert'); } - - //close the connection - fclose($fp); } //redirect the user diff --git a/app/sip_status/sip_status.php b/app/sip_status/sip_status.php index 92b30dc2cd..f3d40f5d37 100644 --- a/app/sip_status/sip_status.php +++ b/app/sip_status/sip_status.php @@ -43,8 +43,8 @@ $text = $language->get(); //create event socket - $fp = event_socket_create(); - if (!$fp) { + $esl = event_socket::create(); + if (!$esl->is_connected()) { message::add($text['error-event-socket'], 'negative', 5000); } @@ -57,8 +57,8 @@ unset($sql); //get the sip profiles - if ($fp) { - $hostname = trim(event_socket_request($fp, 'api switchname')); + if ($esl->is_connected()) { + $hostname = trim(event_socket::api('switchname')); } $sql = "select sip_profile_uuid, sip_profile_name from v_sip_profiles "; $sql .= "where sip_profile_enabled = 'true' "; @@ -80,8 +80,8 @@ //get status try { - $cmd = "api sofia xmlstatus"; - $xml_response = trim(event_socket_request($fp, $cmd)); + $cmd = "sofia xmlstatus"; + $xml_response = trim(event_socket::api($cmd)); if ($xml_response) { $xml = new SimpleXMLElement($xml_response); } @@ -91,8 +91,8 @@ message::add($message, 'negative', 5000); } try { - $cmd = "api sofia xmlstatus gateway"; - $xml_response = trim(event_socket_request($fp, $cmd)); + $cmd = "sofia xmlstatus gateway"; + $xml_response = trim(event_socket::api($cmd)); if ($xml_response) { $xml_gateways = new SimpleXMLElement($xml_response); } @@ -221,10 +221,9 @@ } //sofia status profile - if ($fp && permission_exists('system_status_sofia_status_profile')) { + if ($esl && permission_exists('system_status_sofia_status_profile')) { foreach ($sip_profiles as $sip_profile_name => $sip_profile_uuid) { - $cmd = "api sofia xmlstatus profile ".$sip_profile_name.""; - $xml_response = trim(event_socket_request($fp, $cmd)); + $xml_response = trim(event_socket::api("sofia xmlstatus profile $sip_profile_name")); if ($xml_response == "Invalid Profile!") { $xml_response = "Invalid Profile!"; $profile_state = 'stopped'; @@ -309,16 +308,14 @@ } //status - if ($fp && permission_exists('sip_status_switch_status')) { - $cmd = "api status"; - $response = event_socket_request($fp, $cmd); + if ($esl->is_connected() && permission_exists('sip_status_switch_status')) { + $response = event_socket::api("status"); echo "".$text['title-status']."\n"; echo "
"; echo "
";
 		echo trim(escape($response));
 		echo "
\n"; echo "
"; - fclose($fp); } //include the footer diff --git a/app/switch/resources/classes/presence.php b/app/switch/resources/classes/presence.php index 22f40979ac..014c04771e 100644 --- a/app/switch/resources/classes/presence.php +++ b/app/switch/resources/classes/presence.php @@ -36,10 +36,7 @@ if (!class_exists('presence')) { * @var string $presence_id */ public function active($presence_id) { - $fp = event_socket_create(); - $cmd = 'show calls as json'; - $json = event_socket_request($fp, 'api '.$cmd); - unset($fp); + $json = event_socket::api('show calls as json'); $call_array = json_decode($json, true); if (isset($call_array['rows'])) { $x = 0; @@ -65,10 +62,7 @@ if (!class_exists('presence')) { * show presence */ public function show() { - $fp = event_socket_create(); - $cmd = 'show calls as json'; - $json = event_socket_request($fp, 'api '.$cmd); - unset($fp); + $json = event_socket::api('show calls as json'); $call_array = json_decode($json, true); if (isset($call_array['rows'])) { $x = 0; diff --git a/app/switch/resources/conf/autoload_configs/event_socket.conf.xml b/app/switch/resources/conf/autoload_configs/event_socket.conf.xml index 5ea2e09788..917b4cf696 100644 --- a/app/switch/resources/conf/autoload_configs/event_socket.conf.xml +++ b/app/switch/resources/conf/autoload_configs/event_socket.conf.xml @@ -1,7 +1,7 @@ - + diff --git a/app/switch/resources/dashboard/switch_status.php b/app/switch/resources/dashboard/switch_status.php index b5275e8077..a870392d64 100644 --- a/app/switch/resources/dashboard/switch_status.php +++ b/app/switch/resources/dashboard/switch_status.php @@ -26,19 +26,19 @@ $row_style["1"] = "row_style1"; //connect to event socket - $fp = event_socket_create(); + $esl = event_socket::create(); //switch version - if (permission_exists('switch_version') && $fp) { - $switch_version = event_socket_request($fp, 'api version'); + if (permission_exists('switch_version') && $esl->is_connected()) { + $switch_version = event_socket::api('version'); preg_match("/FreeSWITCH Version (\d+\.\d+\.\d+(?:\.\d+)?).*\(.*?(\d+\w+)\s*\)/", $switch_version, $matches); $switch_version = $matches[1]; $switch_bits = $matches[2]; } //switch uptime - if (permission_exists('switch_uptime') && $fp) { - $tmp = event_socket_request($fp, 'api status'); + if (permission_exists('switch_uptime') && $esl->is_connected()) { + $tmp = event_socket::api('status'); $tmp = explode("\n", $tmp); $tmp = $tmp[0]; $tmp = explode(' ', $tmp); @@ -55,8 +55,8 @@ //channel count $channels = ''; $tr_link_channels = ''; - if (permission_exists('switch_channels') && $fp) { - $tmp = event_socket_request($fp, 'api status'); + if (permission_exists('switch_channels') && $esl->is_connected()) { + $tmp = event_socket::api('status'); $matches = Array(); preg_match("/(\d+)\s+session\(s\)\s+\-\speak/", $tmp, $matches); $channels = $matches[1] ? $matches[1] : 0; diff --git a/app/system/resources/dashboard/system_cpu_status.php b/app/system/resources/dashboard/system_cpu_status.php index 60671466c4..a2ff11ff40 100644 --- a/app/system/resources/dashboard/system_cpu_status.php +++ b/app/system/resources/dashboard/system_cpu_status.php @@ -38,7 +38,7 @@ $cpu_cores = trim($result); } if (stristr(PHP_OS, 'Linux')) { - $result = trim(shell_exec("grep -P '^processor' /proc/cpuinfo")); + $result = @trim(shell_exec("grep -P '^processor' /proc/cpuinfo")); $cpu_cores = count(explode("\n", $result)); } if ($cpu_cores > 1) { $percent_cpu = $percent_cpu / $cpu_cores; } diff --git a/app/system/resources/dashboard/system_status.php b/app/system/resources/dashboard/system_status.php index 1c4270b562..330a28dda7 100644 --- a/app/system/resources/dashboard/system_status.php +++ b/app/system/resources/dashboard/system_status.php @@ -187,8 +187,9 @@ } //channel count - if (isset($fp)) { - $tmp = event_socket_request($fp, 'api status'); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $tmp = event_socket::api('status'); $matches = Array(); preg_match("/(\d+)\s+session\(s\)\s+\-\speak/", $tmp, $matches); $channels = !empty($matches[1]) ? $matches[1] : 0; @@ -201,7 +202,7 @@ } //registration count - if (isset($fp) && file_exists($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/app/registrations/")) { + if ($esl->is_connected() && file_exists($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/app/registrations/")) { $registration = new registrations; $registrations = $registration->count(); $tr_link = "href='".PROJECT_PATH."/app/registrations/registrations.php'"; diff --git a/app/system/system.php b/app/system/system.php index b4618ba5d8..fd753477ec 100644 --- a/app/system/system.php +++ b/app/system/system.php @@ -144,9 +144,9 @@ echo " \n"; echo "\n"; - $fp = event_socket_create(); - if ($fp) { - $switch_version = event_socket_request($fp, 'api version'); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $switch_version = event_socket::api('version'); preg_match("/FreeSWITCH Version (\d+\.\d+\.\d+(?:\.\d+)?).*\(.*?(\d+\w+)\s*\)/", $switch_version, $matches); $switch_version = $matches[1]; $switch_bits = $matches[2]; @@ -544,10 +544,10 @@ $memcache_fail = false; $mod = new modules; if ($mod -> active("mod_memcache")) { - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { $switch_cmd = "memcache status verbose"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); $memcache_lines = preg_split('/\n/', $switch_result); foreach($memcache_lines as $memcache_line) { if (!empty(trim($memcache_line)) > 0 && substr_count($memcache_line, ': ')) { diff --git a/app/voicemails/resources/classes/voicemail.php b/app/voicemails/resources/classes/voicemail.php index 00c3c87374..a1e3472f4d 100644 --- a/app/voicemails/resources/classes/voicemail.php +++ b/app/voicemails/resources/classes/voicemail.php @@ -595,10 +595,10 @@ //send the message waiting status - $fp = event_socket_create(); - if ($fp) { + $esl = event_socket::create(); + if ($esl->is_connected()) { $switch_cmd = "luarun app.lua voicemail mwi ".$this->voicemail_id."@".$_SESSION['domain_name']; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); } } @@ -843,7 +843,7 @@ * range download method (helps safari play audio sources) */ private function range_download($file) { - $fp = @fopen($file, 'rb'); + $esl = @fopen($file, 'rb'); $size = filesize($file); // File size $length = $size; // Content length @@ -909,7 +909,7 @@ $start = $c_start; $end = $c_end; $length = $end - $start + 1; // Calculate new content length - fseek($fp, $start); + fseek($esl, $start); header('HTTP/1.1 206 Partial Content'); } // Notify the client the byte range we'll be outputting @@ -918,14 +918,14 @@ // Start buffered download $buffer = 1024 * 8; - while(!feof($fp) && ($p = ftell($fp)) <= $end) { + while(!feof($esl) && ($p = ftell($esl)) <= $end) { if ($p + $buffer > $end) { // In case we're only outputtin a chunk, make sure we don't // read past the length $buffer = $end - $p + 1; } set_time_limit(0); // Reset time limit for big files - echo fread($fp, $buffer); + echo fread($esl, $buffer); flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit. } diff --git a/core/notifications/notification_edit.php b/core/notifications/notification_edit.php index 04da78c647..880715d473 100644 --- a/core/notifications/notification_edit.php +++ b/core/notifications/notification_edit.php @@ -74,9 +74,9 @@ Mark J Crane $web_server = $_SERVER['SERVER_SOFTWARE']; // switch version - $fp = event_socket_create(); - if ($fp) { - $switch_result = event_socket_request($fp, 'api version'); + $esl = event_socket::create(); + if ($esl->is_connected()) { + $switch_result = event_socket::api('version'); } $switch_ver = trim($switch_result); diff --git a/core/users/user_edit.php b/core/users/user_edit.php index d4ffd4bf85..6039df8f39 100644 --- a/core/users/user_edit.php +++ b/core/users/user_edit.php @@ -573,16 +573,16 @@ //update the user_status if (isset($call_center_agent_uuid) && is_uuid($call_center_agent_uuid) && !empty($user_status)) { - $fp = event_socket_create(); + $esl = event_socket::create(); $switch_cmd = "callcenter_config agent set status ".$call_center_agent_uuid." '".$user_status."'"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $switch_result = event_socket::api($switch_cmd); } //update the user state if (isset($call_center_agent_uuid) && is_uuid($call_center_agent_uuid)) { - $fp = event_socket_create(); - $cmd = "api callcenter_config agent set state ".$call_center_agent_uuid." Waiting"; - $response = event_socket_request($fp, $cmd); + $esl = event_socket::create(); + $cmd = "callcenter_config agent set state ".$call_center_agent_uuid." Waiting"; + $response = event_socket::api($cmd); } } diff --git a/resources/classes/cache.php b/resources/classes/cache.php index 5e6ff0a654..7683c647f1 100644 --- a/resources/classes/cache.php +++ b/resources/classes/cache.php @@ -30,17 +30,15 @@ class cache { //save to memcache if ($_SESSION['cache']['method']['text'] == "memcache") { //connect to event socket - $fp = event_socket_create(); - if ($fp === false) { + $esl = event_socket::create(); + if ($esl === false) { return false; } //run the memcache $command = "memcache set ".$key." ".$value; - $result = event_socket_request($fp, 'api '.$command); + $result = event_socket::api($command); - //close event socket - fclose($fp); } //save to the file cache @@ -64,8 +62,8 @@ class cache { //cache method memcache if ($_SESSION['cache']['method']['text'] == "memcache") { // connect to event socket - $fp = event_socket_create(); - if ($fp === false) { + $esl = event_socket::create(); + if (!$esl->is_connected()) { return false; } @@ -73,10 +71,8 @@ class cache { //run the memcache $command = "memcache get ".$key; - $result = event_socket_request($fp, 'api '.$command); + $result = event_socket::api($command); - //close event socket - fclose($fp); } //get the file cache @@ -106,8 +102,8 @@ class cache { //cache method memcache if (!empty($_SESSION['cache']['method']['text']) && $_SESSION['cache']['method']['text'] == "memcache") { //connect to event socket - $fp = event_socket_create(); - if ($fp === false) { + $esl = event_socket::create(); + if ($esl === false) { return false; } @@ -117,14 +113,12 @@ class cache { $event .= "Event-Subclass: fusion::memcache\n"; $event .= "API-Command: memcache\n"; $event .= "API-Command-Argument: delete ".$key."\n"; - event_socket_request($fp, $event); + event_socket::command($event); //run the memcache $command = "memcache delete ".$key; - $result = event_socket_request($fp, 'api '.$command); + $result = event_socket::api($command); - //close event socket - fclose($fp); } //cache method file @@ -133,8 +127,8 @@ class cache { $key = str_replace(":", ".", $key); //connect to event socket - $fp = event_socket_create(); - if ($fp === false) { + $esl = event_socket::create(); + if ($esl === false) { return false; } @@ -144,7 +138,7 @@ class cache { $event .= "Event-Subclass: fusion::file\n"; $event .= "API-Command: cache\n"; $event .= "API-Command-Argument: delete ".$key."\n"; - event_socket_request($fp, $event); + event_socket::command($event); //remove the local files foreach (glob($_SESSION['cache']['location']['text'] . "/" . $key) as $file) { @@ -174,8 +168,8 @@ class cache { //cache method memcache if ($_SESSION['cache']['method']['text'] == "memcache") { // connect to event socket - $fp = event_socket_create(); - if ($fp === false) { + $esl = event_socket::create(); + if ($esl === false) { return false; } @@ -185,21 +179,19 @@ class cache { $event .= "Event-Subclass: fusion::memcache\n"; $event .= "API-Command: memcache\n"; $event .= "API-Command-Argument: flush\n"; - event_socket_request($fp, $event); + event_socket::command($event); //run the memcache $command = "memcache flush"; - $result = event_socket_request($fp, 'api '.$command); + $result = event_socket::api($command); - //close event socket - fclose($fp); } //cache method file if ($_SESSION['cache']['method']['text'] == "file") { // connect to event socket - $fp = event_socket_create(); - if ($fp === false) { + $esl = event_socket::create(); + if ($esl === false) { return false; } @@ -209,7 +201,7 @@ class cache { $event .= "Event-Subclass: fusion::file\n"; $event .= "API-Command: cache\n"; $event .= "API-Command-Argument: flush\n"; - event_socket_request($fp, $event); + event_socket::command($event); //remove the cache recursive_delete($_SESSION['cache']['location']['text']); diff --git a/resources/classes/event_socket.php b/resources/classes/event_socket.php index 13868c735d..036790f04e 100644 --- a/resources/classes/event_socket.php +++ b/resources/classes/event_socket.php @@ -42,26 +42,43 @@ class buffer { //print($b->read_line()); //print($b->read_line()); +/** + * Subscribes to the event socket of the FreeSWITCH (c) Event Socket Server + * @depends buffer::class + */ class event_socket { private $buffer; public $fp; + private static $socket = null; + + /** + * Create a new connection to the socket + * @param resource|false $fp + */ public function __construct($fp = false) { $this->buffer = new buffer; $this->fp = $fp; } + /** + * Ensures a closed connection on destruction of object + */ public function __destructor() { $this->close(); } + /** + * Read the event body from the socket + * @return string|false Content body or false if not connected or empty message + * @depends buffer::class + */ public function read_event() { - if (!$this->fp) { + if (!$this->connected()) { return false; } $b = $this->buffer; - $content_length = 0; $content = array(); while (true) { @@ -87,7 +104,7 @@ class event_socket { $str = $b->read_n($content['Content-Length']); if ($str === false) { while (true) { - if (feof($this->fp)) { + if (!$this->connected()) { break; } @@ -107,69 +124,67 @@ class event_socket { return $content; } - public function connect($host = null, $port = null, $password = null) { + /** + * Connect to the FreeSWITCH (c) event socket server + *

If the configuration is not loaded then the defaults of + * host 127.0.0.1, port of 8021, and default password of ClueCon will be used

+ * @global array $conf Global configuration used in fusionpbx/config.conf + * @param string $host Host or IP address of FreeSWITCH event socket server. Defaults to 127.0.0.1 + * @param string $port Port number of FreeSWITCH event socket server. Defaults to 8021 + * @param string $password Password of FreeSWITCH event socket server. Defaults to ClueCon + * @param int $timeout_microseconds Number of microseconds before timeout is triggered on socket + * @return bool Returns true on success or false if not connected + */ + public function connect($host = null, $port = null, $password = null, $timeout_microseconds = 30000) { global $conf; - //get the database connection settings - if (empty($host) && empty($conf['event_socket.ip_address'])) { - $host = '127.0.0.1'; - } - if (empty($port) && empty($conf['event_socket.port'])) { - $port = '8021'; - } - if (empty($password) && empty($conf['switch.event_socket.password'])) { - $password = 'ClueCon'; - } - - //set the event socket variables - if (!empty($conf['switch.event_socket.host'])) { - $host = $conf['switch.event_socket.host']; - } - if (!empty($conf['switch.event_socket.port'])) { - $port = $conf['switch.event_socket.port']; - } - if (!empty($conf['switch.event_socket.password'])) { - $password = $conf['switch.event_socket.password']; - } + //set the event socket variables in the order of + //param passed to func, conf setting, old conf setting, default + $host = $host ?? $conf['switch.event_socket.host'] ?? $conf['event_socket.ip_address'] ?? '127.0.0.1'; + $port = $port ?? $conf['switch.event_socket.port'] ?? $conf['event_socket.port'] ?? '8021'; + $password = $password ?? $conf['switch.event_socket.password'] ?? $conf['event_socket.password'] ?? 'ClueCon'; //open the socket connection - $fp = @fsockopen($host, $port, $errno, $errdesc, 3); + $this->fp = @fsockopen($host, $port, $errno, $errdesc, 3); - if (!$fp) { + if (!$this->connected()) { return false; } - socket_set_timeout($fp, 0, 30000); - socket_set_blocking($fp, true); - $this->fp = $fp; + + socket_set_timeout($this->fp, 0, $timeout_microseconds); + socket_set_blocking($this->fp, true); //wait auth request and send response - while (!feof($fp)) { - $event = $this->read_event(); - if(@$event['Content-Type'] == 'auth/request'){ - fputs($fp, "auth $password\n\n"); - break; - } + while ($this->connected()) { + $event = $this->read_event(); + if(($event['Content-Type'] ?? '') === 'auth/request'){ + fputs($this->fp, "auth $password\n\n"); + break; } + } //wait auth response - while (!feof($fp)) { - $event = $this->read_event(); - if (@$event['Content-Type'] == 'command/reply') { - if (@$event['Reply-Text'] == '+OK accepted') { - return $fp; - } - $this->fp = false; - fclose($fp); - return false; + while ($this->connected()) { + $event = $this->read_event(); + if (($event['Content-Type'] ?? '') === 'command/reply') { + if (($event['Reply-Text'] ?? '') === '+OK accepted') { + break; + } else { + $this->close(); } } + } - return false; + return $this->connected(); } - public function connected() { - if (!$this->fp) { + /** + * Tests if connected to the FreeSWITCH Event Socket Server + * @return bool Returns true when connected or false when not connected + */ + public function connected(): bool { + if (!is_resource($this->fp)) { //not connected to the socket return false; } @@ -177,14 +192,27 @@ class event_socket { //not connected to the socket return false; } - else { - //connected to the socket - return true; - } + //connected to the socket + return true; } + /** + * alias of connected + * @return bool + */ + public function is_connected(): bool { + return $this->connected(); + } + + /** + * Send a command to the FreeSWITCH Event Socket Server + *

Multi-line commands can be sent when separated by '\n'

+ * @param string $cmd Command to send through the socket + * @return mixed Returns the response from FreeSWITCH or false if not connected + * @depends read_event() + */ public function request($cmd) { - if (!$this->fp) { + if (!$this->connected()) { return false; } @@ -202,42 +230,90 @@ class event_socket { return $event; } + /** + * Sets the current socket resource returning the old + * @param resource|bool $fp Sets the current FreeSWITCH resource + * @return mixed Returns the original resource + * @deprecated since version 5.1 + */ public function reset_fp($fp = false){ $tmp = $this->fp; $this->fp = $fp; return $tmp; } + /** + * Closes the socket + */ public function close() { - if ($this->fp) { - fclose($this->fp); - $this->fp = false; + //fp is public access so ensure it is a resource before closing it + if (is_resource($this->fp)) { + try { + fclose($this->fp); + } catch (\Exception $t) { + //report it + trigger_error("event_socket failed to close socket", E_USER_WARNING); + } + } else { + //log an error if fp was set to something other than a resource + if ($this->fp !== false) { + trigger_error("event_socket not a resource", E_USER_ERROR); + } } + //force fp to be false + $this->fp = false; + } + + /** + * Create uses a singleton design to return a connected socket to the FreeSWITCH Event Socket Layer + * @global array $conf Global configuration used in config.conf + * @param string $host Host or IP address of FreeSWITCH event socket server. Defaults to 127.0.0.1 + * @param string $port Port number of FreeSWITCH event socket server. Defaults to 8021 + * @param string $password Password of FreeSWITCH event socket server. Defaults to ClueCon + * @param int $timeout_microseconds Number of microseconds before timeout is triggered on socket + * @return self + */ + public static function create($host = null, $port = null, $password = null, $timeout_microseconds = 30000): self { + //create the event socket object + if (self::$socket === null) { + self::$socket = new event_socket(); + } + //attempt to connect it + if(!self::$socket->connected()) { + self::$socket->connect($host, $port, $password, $timeout_microseconds); + } + return self::$socket; + } + + /** + * Sends a command on the socket blocking for a response + * @param string $cmd + * @return string|false Response from server or false if failed + */ + public static function command(string $cmd) { + return self::create()->request($cmd); + } + + /** + * Sends an API command on the socket + * @param string $api_cmd + * @return string|false Response from server or false if failed + */ + public static function api(string $api_cmd) { + return self::command('api '.$api_cmd); + } + + /** + * Sends an API command to FreeSWITCH using asynchronous (non-blocking) mode + * @param string $cmd API command to send + * @returns string $job_id the Job ID for tracking completion status + */ + public static function async(string $cmd) { + return self::command('bgapi '.$cmd); } } -/* -function event_socket_create($host, $port, $password) { - $esl = new event_socket; - if ($esl->connect($host, $port, $password)) { - return $esl->reset_fp(); - } - return false; -} - -function event_socket_request($fp, $cmd) { - $esl = new event_socket($fp); - $result = $esl->request($cmd); - $esl->reset_fp(); - return $result; -} -*/ - -// $esl = new event_socket; -// $esl->connect('127.0.0.1', 8021, 'ClueCon'); +// $esl = event_socket::create('127.0.0.1', 8021, 'ClueCon'); // print($esl->request('api sofia status')); -// $fp = event_socket_create('127.0.0.1', 8021, 'ClueCon'); -// print(event_socket_request($fp, 'api sofia status')); - ?> diff --git a/resources/classes/switch_settings.php b/resources/classes/switch_settings.php index 186dde3098..0843b4a6cb 100644 --- a/resources/classes/switch_settings.php +++ b/resources/classes/switch_settings.php @@ -51,9 +51,8 @@ if (!class_exists('switch_settings')) { } //connect to event socket - $esl = new event_socket; - $esl->connect($this->event_socket_ip_address, $this->event_socket_port, $this->event_socket_password); - + $esl = event_socket::create($this->event_socket_ip_address, $this->event_socket_port, $this->event_socket_password); + //run the api command $result = $esl->request('api global_getvar'); diff --git a/resources/functions.php b/resources/functions.php index 4f8b129f32..3994c6a713 100644 --- a/resources/functions.php +++ b/resources/functions.php @@ -1,102 +1,111 @@ - Portions created by the Initial Developer are Copyright (C) 2008-2022 - the Initial Developer. All Rights Reserved. + The Original Code is FusionPBX - Contributor(s): - Mark J Crane - Luis Daniel Lucio Quiroz -*/ + The Initial Developer of the Original Code is + Mark J Crane + Portions created by the Initial Developer are Copyright (C) 2008-2022 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Luis Daniel Lucio Quiroz + */ if (!function_exists('mb_strtoupper')) { + function mb_strtoupper($string) { return strtoupper($string); } + } if (!function_exists('check_float')) { + function check_float($string) { - $string = str_replace(",",".",$string ?? ''); + $string = str_replace(",", ".", $string ?? ''); return trim($string); } + } if (!function_exists('check_str')) { + function check_str($string, $trim = true) { global $db_type, $db; //when code in db is urlencoded the ' does not need to be modified if ($db_type == "sqlite") { if (function_exists('sqlite_escape_string')) { $string = sqlite_escape_string($string); - } - else { - $string = str_replace("'","''",$string); + } else { + $string = str_replace("'", "''", $string); } } if ($db_type == "pgsql") { - $string = str_replace("'","''",$string); + $string = str_replace("'", "''", $string); } if ($db_type == "mysql") { - if(function_exists('mysql_real_escape_string')){ + if (function_exists('mysql_real_escape_string')) { $tmp_str = mysql_real_escape_string($string); - } - else { + } else { $tmp_str = mysqli_real_escape_string($db, $string); } if (!empty($tmp_str)) { $string = $tmp_str; - } - else { + } else { $search = array("\x00", "\n", "\r", "\\", "'", "\"", "\x1a"); - $replace = array("\\x00", "\\n", "\\r", "\\\\" ,"\'", "\\\"", "\\\x1a"); + $replace = array("\\x00", "\\n", "\\r", "\\\\", "\'", "\\\"", "\\\x1a"); $string = str_replace($search, $replace, $string); } } $string = ($trim) ? trim($string) : $string; return $string; } + } if (!function_exists('check_sql')) { + function check_sql($string) { return trim($string); //remove white space } + } if (!function_exists('check_cidr')) { + function check_cidr($cidr, $ip_address) { if (isset($cidr) && !empty($cidr)) { - list ($subnet, $mask) = explode ('/', $cidr); - return ( ip2long ($ip_address) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet); - } - else { + list ($subnet, $mask) = explode('/', $cidr); + return ( ip2long($ip_address) & ~((1 << (32 - $mask)) - 1) ) == ip2long($subnet); + } else { return false; } } + } if (!function_exists('fix_postback')) { + function fix_postback($post_array) { foreach ($post_array as $index => $value) { - if (is_array($value)) { fix_postback($value); } - else { + if (is_array($value)) { + fix_postback($value); + } else { $value = str_replace('"', """, $value); $value = str_replace("'", "'", $value); $post_array[$index] = $value; @@ -104,17 +113,18 @@ } return $post_array; } + } if (!function_exists('uuid')) { + function uuid() { $uuid = null; if (PHP_OS === 'FreeBSD') { $uuid = trim(shell_exec("uuid -v 4")); if (is_uuid($uuid)) { return $uuid; - } - else { + } else { echo "Please install the following package.\n"; echo "pkg install ossp-uuid\n"; exit; @@ -124,13 +134,11 @@ $uuid = trim(file_get_contents('/proc/sys/kernel/random/uuid')); if (is_uuid($uuid)) { return $uuid; - } - else { + } else { $uuid = trim(shell_exec("uuidgen")); if (is_uuid($uuid)) { return $uuid; - } - else { + } else { echo "Please install the uuidgen.\n"; exit; } @@ -140,160 +148,174 @@ $uuid = trim(com_create_guid(), '{}'); if (is_uuid($uuid)) { return $uuid; - } - else { + } else { echo "The com_create_guid() function failed to create a uuid.\n"; exit; } } } + } if (!function_exists('is_uuid')) { + function is_uuid($str) { $is_uuid = false; if (gettype($str) == 'string') { if (substr_count($str, '-') != 0 && strlen($str) == 36) { $regex = '/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i'; $is_uuid = preg_match($regex, $str); - } - else if (strlen(preg_replace("#[^a-fA-F0-9]#", '', $str)) == 32) { + } else if (strlen(preg_replace("#[^a-fA-F0-9]#", '', $str)) == 32) { $regex = '/^[0-9A-F]{32}$/i'; $is_uuid = preg_match($regex, $str); } } return $is_uuid; } + } if (!function_exists('is_xml')) { + function is_xml($string) { - $pattern = '/^<\?xml(?:\s+[^>]+\s*)?\?>\s*<(\w+)>.*<\/\1>\s*$/s'; - return preg_match($pattern, $string) === 1; + $pattern = '/^<\?xml(?:\s+[^>]+\s*)?\?>\s*<(\w+)>.*<\/\1>\s*$/s'; + return preg_match($pattern, $string) === 1; } + } if (!function_exists('recursive_copy')) { if (file_exists('/bin/cp')) { + function recursive_copy($source, $destination, $options = '') { if (strtoupper(substr(PHP_OS, 0, 3)) === 'SUN') { //copy -R recursive, preserve attributes for SUN - $cmd = 'cp -Rp '.$source.'/* '.$destination; - } - else { + $cmd = 'cp -Rp ' . $source . '/* ' . $destination; + } else { //copy -R recursive, -L follow symbolic links, -p preserve attributes for other Posix systemss - $cmd = 'cp -RLp '.$options.' '.$source.'/* '.$destination; + $cmd = 'cp -RLp ' . $options . ' ' . $source . '/* ' . $destination; } - exec ($cmd); + exec($cmd); } - } - elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + + } elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + function recursive_copy($source, $destination, $options = '') { $source = normalize_path_to_os($source); $destination = normalize_path_to_os($destination); exec("xcopy /E /Y \"$source\" \"$destination\""); } - } - else { + + } else { + function recursive_copy($source, $destination, $options = '') { $dir = opendir($source); if (!$dir) { - throw new Exception("recursive_copy() source directory '".$source."' does not exist."); + throw new Exception("recursive_copy() source directory '" . $source . "' does not exist."); } if (!is_dir($destination)) { - if (!mkdir($destination,02770,true)) { - throw new Exception("recursive_copy() failed to create destination directory '".$destination."'"); + if (!mkdir($destination, 02770, true)) { + throw new Exception("recursive_copy() failed to create destination directory '" . $destination . "'"); } } - while(false !== ( $file = readdir($dir)) ) { + while (false !== ( $file = readdir($dir))) { if (( $file != '.' ) && ( $file != '..' )) { - if ( is_dir($source . '/' . $file) ) { - recursive_copy($source . '/' . $file,$destination . '/' . $file); - } - else { - copy($source . '/' . $file,$destination . '/' . $file); + if (is_dir($source . '/' . $file)) { + recursive_copy($source . '/' . $file, $destination . '/' . $file); + } else { + copy($source . '/' . $file, $destination . '/' . $file); } } } closedir($dir); } + } } if (!function_exists('recursive_delete')) { if (file_exists('/usr/bin/find')) { + function recursive_delete($directory) { if (isset($directory) && strlen($directory) > 8) { - exec('/usr/bin/find '.$directory.'/* -name "*" -delete'); + exec('/usr/bin/find ' . $directory . '/* -name "*" -delete'); //exec('rm -Rf '.$directory.'/*'); clearstatcache(); } } - } - elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + + } elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + function recursive_delete($directory) { $directory = normalize_path_to_os($directory); //$this->write_debug("del /S /F /Q \"$dir\""); exec("del /S /F /Q \"$directory\""); clearstatcache(); } - } - else { + + } else { + function recursive_delete($directory) { foreach (glob($directory) as $file) { if (is_dir($file)) { //$this->write_debug("rm dir: ".$file); recursive_delete("$file/*"); rmdir($file); - } - else { + } else { //$this->write_debug("delete file: ".$file); unlink($file); } } clearstatcache(); } + } } if (!function_exists('if_group')) { + function if_group($group) { //set default false - $result = false; + $result = false; //search for the permission - if (count($_SESSION["groups"]) > 0) { - foreach($_SESSION["groups"] as $row) { - if ($row['group_name'] == $group) { - $result = true; - break; - } + if (count($_SESSION["groups"]) > 0) { + foreach ($_SESSION["groups"] as $row) { + if ($row['group_name'] == $group) { + $result = true; + break; } } + } //return the result - return $result; + return $result; } + } //check if the permission exists if (!function_exists('permission_exists')) { + function permission_exists($permission_name, $operator = 'or') { $permission = new permissions; return $permission->exists($permission_name); } + } if (!function_exists('if_group_member')) { + function if_group_member($group_members, $group) { - if (stripos($group_members, "||".$group."||") === false) { + if (stripos($group_members, "||" . $group . "||") === false) { return false; //group does not exist - } - else { + } else { return true; //group exists } } + } if (!function_exists('superadmin_list')) { + function superadmin_list() { global $domain_uuid; $sql = "select * from v_user_groups "; @@ -304,26 +326,29 @@ if (is_array($result) && @sizeof($result) != 0) { foreach ($result as $field) { //get the list of superadmins - $superadmin_list .= $field['user_uuid']."||"; + $superadmin_list .= $field['user_uuid'] . "||"; } } unset($sql, $result, $field); return $superadmin_list; } + } if (!function_exists('if_superadmin')) { + function if_superadmin($superadmin_list, $user_uuid) { - if (stripos($superadmin_list, "||".$user_uuid."||") === false) { + if (stripos($superadmin_list, "||" . $user_uuid . "||") === false) { return false; - } - else { + } else { return true; //user_uuid exists } } + } if (!function_exists('html_select_other')) { + function html_select_other($table_name, $field_name, $sql_where_optional, $field_current_value, $sql_order_by = null, $label_other = 'Other...') { //html select other: build a select box from distinct items in db with option for other global $domain_uuid; @@ -332,40 +357,42 @@ $html = "
".$text['label-label']."".$text['label-status']."".$text['label-action']."".$text['label-enabled']."".$text['label-running']."
\n"; $html .= "\n"; - $html .= "\n"; - $html .= "\n"; $html .= "\n"; $html .= "
\n"; + $html .= "\n"; $html .= "\n"; - $html .= "\n"; $html .= "\n"; - $sql = "select distinct(".$field_name.") as ".$field_name." "; - $sql .= "from ".$table_name." ".$sql_where_optional." "; - $sql .= "order by ".(!empty($sql_order_by) ? $sql_order_by : $field_name.' asc'); + $sql = "select distinct(" . $field_name . ") as " . $field_name . " "; + $sql .= "from " . $table_name . " " . $sql_where_optional . " "; + $sql .= "order by " . (!empty($sql_order_by) ? $sql_order_by : $field_name . ' asc'); $database = new database; $result = $database->select($sql, null, 'all'); if (is_array($result) && @sizeof($result) != 0) { - foreach($result as $field) { + foreach ($result as $field) { if (!empty($field[$field_name])) { - $html .= "\n"; + $html .= "\n"; } } } unset($sql, $result, $field); $html .= "\n"; - $html .= "\n"; + $html .= "\n"; $html .= "\n"; $html .= "\n"; - $html .= "\n"; + $html .= "\n"; + $html .= "\n"; $html .= "
"; return $html; } + } if (!function_exists('html_select')) { + function html_select($table_name, $field_name, $sql_where_optional, $field_current_value, $field_value = '', $style = '', $on_change = '') { //html select: build a select box from distinct items in db global $domain_uuid; @@ -373,28 +400,27 @@ $table_name = preg_replace("#[^a-zA-Z0-9_]#", "", $table_name); $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name); $field_value = preg_replace("#[^a-zA-Z0-9_]#", "", $field_value); - + if (!empty($field_value)) { - $html .= "\n"; $html .= " \n"; - $sql = "select distinct(".$field_name.") as ".$field_name.", ".$field_value." from ".$table_name." ".$sql_where_optional." order by ".$field_name." asc "; - } - else { - $html .= "\n"; $html .= " \n"; - $sql = "select distinct(".$field_name.") as ".$field_name." from ".$table_name." ".$sql_where_optional." "; + $sql = "select distinct(" . $field_name . ") as " . $field_name . " from " . $table_name . " " . $sql_where_optional . " "; } $database = new database; $result = $database->select($sql, null, 'all'); if (is_array($result) && @sizeof($result) != 0) { - foreach($result as $field) { + foreach ($result as $field) { if (!empty($field[$field_name])) { $selected = $field_current_value == $field[$field_name] ? "selected='selected'" : null; $array_key = empty($field_value) ? $field_name : $field_value; - $html .= "\n"; + $html .= "\n"; } } } @@ -403,13 +429,17 @@ return $html; } + } if (!function_exists('th_order_by')) { + //html table header order by function th_order_by($field_name, $column_title, $order_by, $order, $app_uuid = '', $css = '', $http_get_params = '', $description = '') { global $text; - if (is_uuid($app_uuid) > 0) { $app_uuid = "&app_uuid=".urlencode($app_uuid); } // accomodate need to pass app_uuid where necessary (inbound/outbound routes lists) + if (is_uuid($app_uuid) > 0) { + $app_uuid = "&app_uuid=" . urlencode($app_uuid); + } // accomodate need to pass app_uuid where necessary (inbound/outbound routes lists) $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name); $field_value = preg_replace("#[^a-zA-Z0-9_]#", "", $field_value ?? ''); @@ -425,9 +455,8 @@ $value = urldecode($array['1']); if ($key == 'order_by' && !empty($value)) { //validate order by - $sanitized_parameters .= "&order_by=". preg_replace('#[^a-zA-Z0-9_\-]#', '', $value); - } - else if ($key == 'order' && !empty($value)) { + $sanitized_parameters .= "&order_by=" . preg_replace('#[^a-zA-Z0-9_\-]#', '', $value); + } else if ($key == 'order' && !empty($value)) { //validate order switch ($value) { case 'asc': @@ -437,43 +466,41 @@ $sanitized_parameters .= "&order=desc"; break; } - } - else if (!empty($value) && is_numeric($value)) { - $sanitized_parameters .= "&".$key."=".$value; - } - else { - $sanitized_parameters .= "&".$key."=".urlencode($value); + } else if (!empty($value) && is_numeric($value)) { + $sanitized_parameters .= "&" . $key . "=" . $value; + } else { + $sanitized_parameters .= "&" . $key . "=" . urlencode($value); } } } } } - $html = ""; + $html = ""; $description = empty($description) ? '' : $description . ', '; if (empty($order_by)) { $order = 'asc'; } if ($order_by == $field_name) { if ($order == "asc") { - $description .= $text['label-order'].' '.$text['label-descending']; - $html .= "".escape($column_title).""; + $description .= $text['label-order'] . ' ' . $text['label-descending']; + $html .= "" . escape($column_title) . ""; + } else { + $description .= $text['label-order'] . ' ' . $text['label-ascending']; + $html .= "" . escape($column_title) . ""; } - else { - $description .= $text['label-order'].' '.$text['label-ascending']; - $html .= "".escape($column_title).""; - } - } - else { - $description .= $text['label-order'].' '.$text['label-ascending']; - $html .= "".escape($column_title).""; + } else { + $description .= $text['label-order'] . ' ' . $text['label-ascending']; + $html .= "" . escape($column_title) . ""; } $html .= ""; return $html; } + } if (!function_exists('get_ext')) { + function get_ext($filename) { preg_match('/[^?]*/', $filename, $matches); $string = $matches[0]; @@ -481,24 +508,26 @@ $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE); // check if there is any extension - if(count($pattern) == 1){ + if (count($pattern) == 1) { //echo 'No File Extension Present'; return ''; } - if(count($pattern) > 1) { - $filenamepart = $pattern[count($pattern)-1][0]; + if (count($pattern) > 1) { + $filenamepart = $pattern[count($pattern) - 1][0]; preg_match('/[^?]*/', $filenamepart, $matches); return $matches[0]; } } + //echo "ext: ".get_ext('test.txt'); } if (!function_exists('file_upload')) { + function file_upload($field = '', $file_type = '', $dest_dir = '') { - $uploadtempdir = $_ENV["TEMP"]."\\"; + $uploadtempdir = $_ENV["TEMP"] . "\\"; ini_set('upload_tmp_dir', $uploadtempdir); $tmp_name = $_FILES[$field]["tmp_name"]; @@ -507,7 +536,7 @@ $file_size = $_FILES[$field]["size"]; $file_ext = get_ext($file_name); $file_name_orig = $file_name; - $file_name_base = substr($file_name, 0, (strlen($file_name) - (strlen($file_ext)+1))); + $file_name_base = substr($file_name, 0, (strlen($file_name) - (strlen($file_ext) + 1))); //$dest_dir = '/tmp'; if ($file_size == 0) { @@ -544,16 +573,15 @@ } //find unique filename: check if file exists if it does then increment the filename - $i = 1; - while( file_exists($dest_dir.'/'.$file_name)) { - if (!empty($file_ext)) { - $file_name = $file_name_base . $i .'.'. $file_ext; - } - else { - $file_name = $file_name_orig . $i; - } - $i++; + $i = 1; + while (file_exists($dest_dir . '/' . $file_name)) { + if (!empty($file_ext)) { + $file_name = $file_name_base . $i . '.' . $file_ext; + } else { + $file_name = $file_name_orig . $i; } + $i++; + } //echo "file_type: ".$file_type."
\n"; //echo "tmp_name: ".$tmp_name."
\n"; @@ -562,51 +590,62 @@ //echo "file_name_orig: ".$file_name_orig."
\n"; //echo "file_name_base: ".$file_name_base."
\n"; //echo "dest_dir: ".$dest_dir."
\n"; - //move the file to upload directory //bool move_uploaded_file ( string $filename, string $destination ) - if (move_uploaded_file($tmp_name, $dest_dir.'/'.$file_name)) { - return $file_name; - } - else { - echo "File upload failed! Here's some debugging info:\n"; - return false; - } - exit; - + if (move_uploaded_file($tmp_name, $dest_dir . '/' . $file_name)) { + return $file_name; + } else { + echo "File upload failed! Here's some debugging info:\n"; + return false; + } + exit; } + } if (!function_exists('sys_get_temp_dir')) { + function sys_get_temp_dir() { - if ($temp = getenv('TMP')) { return $temp; } - if ($temp = getenv('TEMP')) { return $temp; } - if ($temp = getenv('TMPDIR')) { return $temp; } - $temp = tempnam(__FILE__,''); + if ($temp = getenv('TMP')) { + return $temp; + } + if ($temp = getenv('TEMP')) { + return $temp; + } + if ($temp = getenv('TMPDIR')) { + return $temp; + } + $temp = tempnam(__FILE__, ''); if (file_exists($temp)) { unlink($temp); return dirname($temp); } return null; } + } //echo realpath(sys_get_temp_dir()); if (!function_exists('normalize_path')) { + //don't use DIRECTORY_SEPARATOR as it will change on a per platform basis and we need consistency function normalize_path($path) { - return str_replace(array('/','\\'), '/', $path); + return str_replace(array('/', '\\'), '/', $path); } + } if (!function_exists('normalize_path_to_os')) { + function normalize_path_to_os($path) { - return str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $path); + return str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path); } + } if (!function_exists('username_exists')) { + function username_exists($username) { global $domain_uuid; $sql = "select count(*) from v_users "; @@ -618,165 +657,159 @@ $num_rows = $database->select($sql, $parameters, 'column'); return $num_rows > 0 ? true : false; } + } if (!function_exists('add_extension_user')) { + function add_extension_user($extension_uuid, $username) { global $domain_uuid; //get the user_uuid by using the username - $sql = "select user_uuid from v_users "; + $sql = "select user_uuid from v_users "; + $sql .= "where domain_uuid = :domain_uuid "; + $sql .= "and username = :username "; + $parameters['domain_uuid'] = $domain_uuid; + $parameters['username'] = $username; + $database = new database; + $user_uuid = $database->select($sql, $parameters, 'column'); + unset($sql, $parameters); + + if (is_uuid($user_uuid)) { + //check if the user_uuid exists in v_extension_users + $sql = "select count(*) from v_extension_users "; $sql .= "where domain_uuid = :domain_uuid "; - $sql .= "and username = :username "; + $sql .= "and user_uuid = :user_uuid "; $parameters['domain_uuid'] = $domain_uuid; - $parameters['username'] = $username; + $parameters['user_uuid'] = $user_uuid; $database = new database; - $user_uuid = $database->select($sql, $parameters, 'column'); + $num_rows = $database->select($sql, $parameters, 'column'); unset($sql, $parameters); - if (is_uuid($user_uuid)) { - //check if the user_uuid exists in v_extension_users - $sql = "select count(*) from v_extension_users "; - $sql .= "where domain_uuid = :domain_uuid "; - $sql .= "and user_uuid = :user_uuid "; - $parameters['domain_uuid'] = $domain_uuid; - $parameters['user_uuid'] = $user_uuid; - $database = new database; - $num_rows = $database->select($sql, $parameters, 'column'); - unset($sql, $parameters); - - //assign the extension to the user - if ($num_rows == 0) { - //build insert array - $extension_user_uuid = uuid(); - $array['extension_users'][$x]['extension_user_uuid'] = $extension_user_uuid; - $array['extension_users'][$x]['domain_uuid'] = $domain_uuid; - $array['extension_users'][$x]['extension_uuid'] = $extension_uuid; - $array['extension_users'][$x]['user_uuid'] = $row["user_uuid"]; - //grant temporary permissions - $p = new permissions; - $p->add('extension_user_add', 'temp'); - //execute insert - $database = new database; - $database->app_name = 'function-add_extension_user'; - $database->app_uuid = 'e68d9689-2769-e013-28fa-6214bf47fca3'; - $database->save($array); - unset($array); - //revoke temporary permissions - $p->delete('extension_user_add', 'temp'); - } + //assign the extension to the user + if ($num_rows == 0) { + //build insert array + $extension_user_uuid = uuid(); + $array['extension_users'][$x]['extension_user_uuid'] = $extension_user_uuid; + $array['extension_users'][$x]['domain_uuid'] = $domain_uuid; + $array['extension_users'][$x]['extension_uuid'] = $extension_uuid; + $array['extension_users'][$x]['user_uuid'] = $row["user_uuid"]; + //grant temporary permissions + $p = new permissions; + $p->add('extension_user_add', 'temp'); + //execute insert + $database = new database; + $database->app_name = 'function-add_extension_user'; + $database->app_uuid = 'e68d9689-2769-e013-28fa-6214bf47fca3'; + $database->save($array); + unset($array); + //revoke temporary permissions + $p->delete('extension_user_add', 'temp'); } + } } + } if (!function_exists('user_add')) { + function user_add($username, $password, $user_email = '') { global $domain_uuid; - if (empty($username)) { return false; } - if (empty($password)) { return false; } + if (empty($username)) { + return false; + } + if (empty($password)) { + return false; + } if (!username_exists($username)) { //build user insert array - $user_uuid = uuid(); - $salt = generate_password('20', '4'); - $array['users'][0]['user_uuid'] = $user_uuid; - $array['users'][0]['domain_uuid'] = $domain_uuid; - $array['users'][0]['username'] = $username; - $array['users'][0]['password'] = md5($salt.$password); - $array['users'][0]['salt'] = $salt; - if (valid_email($user_email)) { - $array['users'][0]['user_email'] = $user_email; - } - $array['users'][0]['add_date'] = 'now()'; - $array['users'][0]['add_user'] = $_SESSION["username"]; + $user_uuid = uuid(); + $salt = generate_password('20', '4'); + $array['users'][0]['user_uuid'] = $user_uuid; + $array['users'][0]['domain_uuid'] = $domain_uuid; + $array['users'][0]['username'] = $username; + $array['users'][0]['password'] = md5($salt . $password); + $array['users'][0]['salt'] = $salt; + if (valid_email($user_email)) { + $array['users'][0]['user_email'] = $user_email; + } + $array['users'][0]['add_date'] = 'now()'; + $array['users'][0]['add_user'] = $_SESSION["username"]; //build user group insert array - $user_group_uuid = uuid(); - $array['user_groups'][0]['user_group_uuid'] = $user_group_uuid; - $array['user_groups'][0]['domain_uuid'] = $domain_uuid; - $array['user_groups'][0]['group_name'] = 'user'; - $array['user_groups'][0]['user_uuid'] = $user_uuid; + $user_group_uuid = uuid(); + $array['user_groups'][0]['user_group_uuid'] = $user_group_uuid; + $array['user_groups'][0]['domain_uuid'] = $domain_uuid; + $array['user_groups'][0]['group_name'] = 'user'; + $array['user_groups'][0]['user_uuid'] = $user_uuid; //grant temporary permissions - $p = new permissions; - $p->add('user_add', 'temp'); - $p->add('user_group_add', 'temp'); + $p = new permissions; + $p->add('user_add', 'temp'); + $p->add('user_group_add', 'temp'); //execute insert - $database = new database; - $database->app_name = 'function-user_add'; - $database->app_uuid = '15a8d74b-ac7e-4468-add4-3e6ebdcb8e22'; - $database->save($array); - unset($array); + $database = new database; + $database->app_name = 'function-user_add'; + $database->app_uuid = '15a8d74b-ac7e-4468-add4-3e6ebdcb8e22'; + $database->save($array); + unset($array); //revoke temporary permissions - $p->delete('user_add', 'temp'); - $p->delete('user_group_add', 'temp'); + $p->delete('user_add', 'temp'); + $p->delete('user_group_add', 'temp'); } } + } -function switch_module_is_running($fp, $mod) { - if (!$fp) { - //if the handle does not exist create it - $fp = event_socket_create(); - //if the handle still does not exist show an error message - if (!$fp) { - $msg = "
Connection to Event Socket failed.
"; - } - } - if ($fp) { - //send the api command to check if the module exists - $switchcmd = "module_exists $mod"; - $switch_result = event_socket_request($fp, 'api '.$switchcmd); - unset($switchcmd); - if (trim($switch_result) == "true") { - return true; + function switch_module_is_running($mod, event_socket $esl = null) { + //if the object does not exist create it + if ($esl === null) { + $esl = event_socket::create(); } - else { + //if we are not connected to freeswitch show an error message + if (!$esl->is_connected()) { return false; } + //send the api command to check if the module exists + $switch_result = event_socket::api("module_exists $mod"); + return (trim($switch_result) == "true"); } - else { - return false; - } -} -//switch_module_is_running('mod_spidermonkey'); +//print (switch_module_is_running('mod_spidermonkey') ? "true" : "false"); //format a number (n) replace with a number (r) remove the number -function format_string($format, $data) { - //nothing to do so return - if(empty($format)) - return $data; - - //preset values - $x=0; - $tmp = ''; + function format_string($format, $data) { + //nothing to do so return + if (empty($format)) + return $data; - //count the characters - $format_count = substr_count($format, 'x'); - $format_count = $format_count + substr_count($format, 'R'); - $format_count = $format_count + substr_count($format, 'r'); + //preset values + $x = 0; + $tmp = ''; - //format the string if it matches - if ($format_count == strlen($data)) { - for ($i = 0; $i <= strlen($format); $i++) { - $tmp_format = strtolower(substr($format, $i, 1)); - if ($tmp_format == 'x') { - $tmp .= substr($data, $x, 1); - $x++; - } - elseif ($tmp_format == 'r') { - $x++; - } - else { - $tmp .= $tmp_format; + //count the characters + $format_count = substr_count($format, 'x'); + $format_count = $format_count + substr_count($format, 'R'); + $format_count = $format_count + substr_count($format, 'r'); + + //format the string if it matches + if ($format_count == strlen($data)) { + for ($i = 0; $i <= strlen($format); $i++) { + $tmp_format = strtolower(substr($format, $i, 1)); + if ($tmp_format == 'x') { + $tmp .= substr($data, $x, 1); + $x++; + } elseif ($tmp_format == 'r') { + $x++; + } else { + $tmp .= $tmp_format; + } } } + if (empty($tmp)) { + return $data; + } else { + return $tmp; + } } - if (empty($tmp)) { - return $data; - } - else { - return $tmp; - } -} //get the format and use it to format the phone number function format_phone($phone_number) { @@ -799,7 +832,7 @@ function format_string($format, $data) { //format seconds into hh:mm:ss function format_hours($seconds) { - $seconds = (int)$seconds; //convert seconds to an integer + $seconds = (int) $seconds; //convert seconds to an integer $hours = floor($seconds / 3600); $minutes = floor(floor($seconds / 60) % 60); $seconds = $seconds % 60; @@ -810,144 +843,143 @@ function format_string($format, $data) { function http_user_agent($info = '') { //set default values - $user_agent = $_SERVER['HTTP_USER_AGENT']; - $browser_name = 'Unknown'; - $platform = 'Unknown'; - $version = ''; - $mobile = false; + $user_agent = $_SERVER['HTTP_USER_AGENT']; + $browser_name = 'Unknown'; + $platform = 'Unknown'; + $version = ''; + $mobile = false; //get the platform - if (preg_match('/linux/i', $user_agent)) { - $platform = 'Linux'; - } - elseif (preg_match('/macintosh|mac os x/i', $user_agent)) { - $platform = 'Apple'; - } - elseif (preg_match('/windows|win32/i', $user_agent)) { - $platform = 'Windows'; - } + if (preg_match('/linux/i', $user_agent)) { + $platform = 'Linux'; + } elseif (preg_match('/macintosh|mac os x/i', $user_agent)) { + $platform = 'Apple'; + } elseif (preg_match('/windows|win32/i', $user_agent)) { + $platform = 'Windows'; + } //set mobile to true or false - if (preg_match('/mobile/i', $user_agent)) { - $platform = 'Mobile'; - $mobile = true; - } - elseif (preg_match('/android/i', $user_agent)) { - $platform = 'Android'; - $mobile = true; - } + if (preg_match('/mobile/i', $user_agent)) { + $platform = 'Mobile'; + $mobile = true; + } elseif (preg_match('/android/i', $user_agent)) { + $platform = 'Android'; + $mobile = true; + } //get the name of the useragent - if (preg_match('/MSIE/i',$user_agent) || preg_match('/Trident/i',$user_agent)) { - $browser_name = 'Internet Explorer'; - $browser_name_short = 'MSIE'; - } - elseif (preg_match('/Firefox/i',$user_agent)) { - $browser_name = 'Mozilla Firefox'; - $browser_name_short = 'Firefox'; - } - elseif (preg_match('/Chrome/i',$user_agent)) { - $browser_name = 'Google Chrome'; - $browser_name_short = 'Chrome'; - } - elseif (preg_match('/Safari/i',$user_agent)) { - $browser_name = 'Apple Safari'; - $browser_name_short = 'Safari'; - } - elseif (preg_match('/Opera/i',$user_agent)) { - $browser_name = 'Opera'; - $browser_name_short = 'Opera'; - } - elseif (preg_match('/Netscape/i',$user_agent)) { - $browser_name = 'Netscape'; - $browser_name_short = 'Netscape'; - } - else { - $browser_name = 'Unknown'; - $browser_name_short = 'Unknown'; - } + if (preg_match('/MSIE/i', $user_agent) || preg_match('/Trident/i', $user_agent)) { + $browser_name = 'Internet Explorer'; + $browser_name_short = 'MSIE'; + } elseif (preg_match('/Firefox/i', $user_agent)) { + $browser_name = 'Mozilla Firefox'; + $browser_name_short = 'Firefox'; + } elseif (preg_match('/Chrome/i', $user_agent)) { + $browser_name = 'Google Chrome'; + $browser_name_short = 'Chrome'; + } elseif (preg_match('/Safari/i', $user_agent)) { + $browser_name = 'Apple Safari'; + $browser_name_short = 'Safari'; + } elseif (preg_match('/Opera/i', $user_agent)) { + $browser_name = 'Opera'; + $browser_name_short = 'Opera'; + } elseif (preg_match('/Netscape/i', $user_agent)) { + $browser_name = 'Netscape'; + $browser_name_short = 'Netscape'; + } else { + $browser_name = 'Unknown'; + $browser_name_short = 'Unknown'; + } //finally get the correct version number - $known = array('Version', $browser_name_short, 'other'); - $pattern = '#(?' . join('|', $known) . ')[/ ]+(?[0-9.|a-zA-Z.]*)#'; - if (!preg_match_all($pattern, $user_agent, $matches)) { - //we have no matching number just continue - } + $known = array('Version', $browser_name_short, 'other'); + $pattern = '#(?' . join('|', $known) . ')[/ ]+(?[0-9.|a-zA-Z.]*)#'; + if (!preg_match_all($pattern, $user_agent, $matches)) { + //we have no matching number just continue + } //see how many we have - $i = count($matches['browser']); - if ($i != 1) { - //we will have two since we are not using 'other' argument yet - //see if version is before or after the name - if (strripos($user_agent,"Version") < strripos($user_agent,$browser_name_short)) { - $version= $matches['version'][0]; - } - else { - $version= $matches['version'][1]; - } - } - else { - $version= $matches['version'][0]; + $i = count($matches['browser']); + if ($i != 1) { + //we will have two since we are not using 'other' argument yet + //see if version is before or after the name + if (strripos($user_agent, "Version") < strripos($user_agent, $browser_name_short)) { + $version = $matches['version'][0]; + } else { + $version = $matches['version'][1]; } + } else { + $version = $matches['version'][0]; + } //check if we have a number - if ($version == null || $version == "") { $version = "?"; } + if ($version == null || $version == "") { + $version = "?"; + } //return the data - switch ($info) { - case "agent": return $user_agent; break; - case "name": return $browser_name; break; - case "name_short": return $browser_name_short; break; - case "version": return $version; break; - case "platform": return $platform; break; - case "mobile": return $mobile; break; - case "pattern": return $pattern; break; - default : - return array( - 'user_agent' => $user_agent, - 'name' => $browser_name, - 'name_short' => $browser_name_short, - 'version' => $version, - 'platform' => $platform, - 'mobile' => $mobile, - 'pattern' => $pattern - ); - } + switch ($info) { + case "agent": return $user_agent; + break; + case "name": return $browser_name; + break; + case "name_short": return $browser_name_short; + break; + case "version": return $version; + break; + case "platform": return $platform; + break; + case "mobile": return $mobile; + break; + case "pattern": return $pattern; + break; + default : + return array( + 'user_agent' => $user_agent, + 'name' => $browser_name, + 'name_short' => $browser_name_short, + 'version' => $version, + 'platform' => $platform, + 'mobile' => $mobile, + 'pattern' => $pattern + ); + } } //tail php function for non posix systems - function tail($file, $num_to_get=10) { - $fp = fopen($file, 'r'); + function tail($file, $num_to_get = 10) { + $esl = fopen($file, 'r'); $position = filesize($file); $chunklen = 4096; - if($position-$chunklen<=0) { - fseek($fp,0); + if ($position - $chunklen <= 0) { + fseek($esl, 0); + } else { + fseek($esl, $position - $chunklen); } - else { - fseek($fp, $position-$chunklen); - } - $data="";$ret="";$lc=0; - while($chunklen > 0) { - $data = fread($fp, $chunklen); - $dl=strlen($data); - for($i=$dl-1;$i>=0;$i--){ - if($data[$i]=="\n"){ - if($lc==0 && $ret!="")$lc++; + $data = ""; + $ret = ""; + $lc = 0; + while ($chunklen > 0) { + $data = fread($esl, $chunklen); + $dl = strlen($data); + for ($i = $dl - 1; $i >= 0; $i--) { + if ($data[$i] == "\n") { + if ($lc == 0 && $ret != "") + $lc++; $lc++; - if($lc>$num_to_get)return $ret; + if ($lc > $num_to_get) + return $ret; } - $ret=$data[$i].$ret; + $ret = $data[$i] . $ret; } - if($position-$chunklen<=0){ - fseek($fp,0); - $chunklen=$chunklen-abs($position-$chunklen); - } - else { - fseek($fp, $position-$chunklen); + if ($position - $chunklen <= 0) { + fseek($esl, 0); + $chunklen = $chunklen - abs($position - $chunklen); + } else { + fseek($esl, $position - $chunklen); } $position = $position - $chunklen; } - fclose($fp); return $ret; } @@ -959,12 +991,20 @@ function format_string($format, $data) { $length = (is_numeric($_SESSION["users"]["password_length"]["numeric"])) ? $_SESSION["users"]["password_length"]["numeric"] : 20; $strength = (is_numeric($_SESSION["users"]["password_strength"]["numeric"])) ? $_SESSION["users"]["password_strength"]["numeric"] : 4; } - if ($strength >= 1) { $chars .= "0123456789"; } - if ($strength >= 2) { $chars .= "abcdefghijkmnopqrstuvwxyz"; } - if ($strength >= 3) { $chars .= "ABCDEFGHIJKLMNPQRSTUVWXYZ"; } - if ($strength >= 4) { $chars .= "!^$%*?."; } + if ($strength >= 1) { + $chars .= "0123456789"; + } + if ($strength >= 2) { + $chars .= "abcdefghijkmnopqrstuvwxyz"; + } + if ($strength >= 3) { + $chars .= "ABCDEFGHIJKLMNPQRSTUVWXYZ"; + } + if ($strength >= 4) { + $chars .= "!^$%*?."; + } for ($i = 0; $i < $length; $i++) { - $password .= $chars[random_int(0, strlen($chars)-1)]; + $password .= $chars[random_int(0, strlen($chars) - 1)]; } return $password; } @@ -985,26 +1025,25 @@ function format_string($format, $data) { $req['uppercase'] = ($_SESSION['user']['password_uppercase']['boolean'] == 'true') ? true : false; $req['special'] = ($_SESSION['user']['password_special']['boolean'] == 'true') ? true : false; } - if (is_numeric($req['length']) && $req['length'] != 0 && !preg_match_all('$\S*(?=\S{'.$req['length'].',})\S*$', $password)) { // length - $msg_errors[] = $req['length'].'+ '.$text['label-characters']; + if (is_numeric($req['length']) && $req['length'] != 0 && !preg_match_all('$\S*(?=\S{' . $req['length'] . ',})\S*$', $password)) { // length + $msg_errors[] = $req['length'] . '+ ' . $text['label-characters']; } if ($req['number'] && !preg_match_all('$\S*(?=\S*[\d])\S*$', $password)) { //number - $msg_errors[] = '1+ '.$text['label-numbers']; + $msg_errors[] = '1+ ' . $text['label-numbers']; } if ($req['lowercase'] && !preg_match_all('$\S*(?=\S*[a-z])\S*$', $password)) { //lowercase - $msg_errors[] = '1+ '.$text['label-lowercase_letters']; + $msg_errors[] = '1+ ' . $text['label-lowercase_letters']; } if ($req['uppercase'] && !preg_match_all('$\S*(?=\S*[A-Z])\S*$', $password)) { //uppercase - $msg_errors[] = '1+ '.$text['label-uppercase_letters']; + $msg_errors[] = '1+ ' . $text['label-uppercase_letters']; } if ($req['special'] && !preg_match_all('$\S*(?=\S*[\W])\S*$', $password)) { //special - $msg_errors[] = '1+ '.$text['label-special_characters']; + $msg_errors[] = '1+ ' . $text['label-special_characters']; } if (is_array($msg_errors) && sizeof($msg_errors) > 0) { - message::add($_SESSION["message"] = $text['message-password_requirements'].': '.implode(', ', $msg_errors), 'negative', 6000); + message::add($_SESSION["message"] = $text['message-password_requirements'] . ': ' . implode(', ', $msg_errors), 'negative', 6000); return false; - } - else { + } else { return true; } } @@ -1013,38 +1052,41 @@ function format_string($format, $data) { //based on Wez Furlong do_post_request if (!function_exists('send_http_request')) { + function send_http_request($url, $data, $method = "POST", $optional_headers = null) { $params = array('http' => array( - 'method' => $method, - 'content' => $data - )); + 'method' => $method, + 'content' => $data + )); if ($optional_headers !== null) { $params['http']['header'] = $optional_headers; } $ctx = stream_context_create($params); - $fp = @fopen($url, 'rb', false, $ctx); - if (!$fp) { + $esl = @fopen($url, 'rb', false, $ctx); + if (!$esl) { throw new Exception("Problem with $url, $php_errormsg"); } - $response = @stream_get_contents($fp); + $response = @stream_get_contents($esl); if ($response === false) { throw new Exception("Problem reading data from $url, $php_errormsg"); } return $response; } + } //convert the string to a named array - if(!function_exists('csv_to_named_array')) { + if (!function_exists('csv_to_named_array')) { + function csv_to_named_array($tmp_str, $tmp_delimiter) { - $tmp_array = explode ("\n", $tmp_str); + $tmp_array = explode("\n", $tmp_str); $result = array(); if (trim(strtoupper($tmp_array[0])) !== "+OK") { - $tmp_field_name_array = explode ($tmp_delimiter, $tmp_array[0]); + $tmp_field_name_array = explode($tmp_delimiter, $tmp_array[0]); $x = 0; foreach ($tmp_array as $row) { if ($x > 0) { - $tmp_field_value_array = explode ($tmp_delimiter, $tmp_array[$x]); + $tmp_field_value_array = explode($tmp_delimiter, $tmp_array[$x]); $y = 0; foreach ($tmp_field_value_array as $tmp_value) { $tmp_name = $tmp_field_name_array[$y]; @@ -1060,72 +1102,75 @@ function format_string($format, $data) { } return $result; } + } -function get_time_zone_offset($remote_tz, $origin_tz = 'UTC') { - $origin_dtz = new DateTimeZone($origin_tz); - $remote_dtz = new DateTimeZone($remote_tz); - $origin_dt = new DateTime("now", $origin_dtz); - $remote_dt = new DateTime("now", $remote_dtz); - $offset = $remote_dtz->getOffset($remote_dt) - $origin_dtz->getOffset($origin_dt); - return $offset; -} + function get_time_zone_offset($remote_tz, $origin_tz = 'UTC') { + $origin_dtz = new DateTimeZone($origin_tz); + $remote_dtz = new DateTimeZone($remote_tz); + $origin_dt = new DateTime("now", $origin_dtz); + $remote_dt = new DateTime("now", $remote_dtz); + $offset = $remote_dtz->getOffset($remote_dt) - $origin_dtz->getOffset($origin_dt); + return $offset; + } -function number_pad($number,$n) { - return str_pad((int) $number,$n,"0",STR_PAD_LEFT); -} + function number_pad($number, $n) { + return str_pad((int) $number, $n, "0", STR_PAD_LEFT); + } // validate email address syntax - if(!function_exists('valid_email')) { + if (!function_exists('valid_email')) { + function valid_email($email) { return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? true : false; } + } //function to convert hexidecimal color value to rgb string/array value if (!function_exists('hex_to_rgb')) { + function hex_to_rgb($hex, $delim = '') { $hex = str_replace("#", "", $hex); if (strlen($hex) == 3) { - $r = hexdec(substr($hex,0,1).substr($hex,0,1)); - $g = hexdec(substr($hex,1,1).substr($hex,1,1)); - $b = hexdec(substr($hex,2,1).substr($hex,2,1)); - } - else { - $r = hexdec(substr($hex,0,2)); - $g = hexdec(substr($hex,2,2)); - $b = hexdec(substr($hex,4,2)); + $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1)); + $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1)); + $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1)); + } else { + $r = hexdec(substr($hex, 0, 2)); + $g = hexdec(substr($hex, 2, 2)); + $b = hexdec(substr($hex, 4, 2)); } $rgb = array($r, $g, $b); if (!empty($delim)) { return implode($delim, $rgb); // return rgb delimited string - } - else { + } else { return $rgb; // return array of rgb values } } + } //function to get a color's luminence level -- dependencies: rgb_to_hsl() if (!function_exists('get_color_luminence')) { + function get_color_luminence($color) { //convert hex to rgb if (substr_count($color, ',') == 0) { $color = str_replace(' ', '', $color); $color = str_replace('#', '', $color); if (strlen($color) == 3) { - $r = hexdec(substr($color,0,1).substr($color,0,1)); - $g = hexdec(substr($color,1,1).substr($color,1,1)); - $b = hexdec(substr($color,2,1).substr($color,2,1)); + $r = hexdec(substr($color, 0, 1) . substr($color, 0, 1)); + $g = hexdec(substr($color, 1, 1) . substr($color, 1, 1)); + $b = hexdec(substr($color, 2, 1) . substr($color, 2, 1)); + } else { + $r = hexdec(substr($color, 0, 2)); + $g = hexdec(substr($color, 2, 2)); + $b = hexdec(substr($color, 4, 2)); } - else { - $r = hexdec(substr($color,0,2)); - $g = hexdec(substr($color,2,2)); - $b = hexdec(substr($color,4,2)); - } - $color = $r.','.$g.','.$b; + $color = $r . ',' . $g . ',' . $b; } //color to array, pop alpha @@ -1141,22 +1186,24 @@ function number_pad($number,$n) { //return luminence value return (is_array($hsl) && is_numeric($hsl[2])) ? $hsl[2] : null; } + } //function to lighten or darken a hexidecimal, rgb, or rgba color value by a percentage -- dependencies: rgb_to_hsl(), hsl_to_rgb() if (!function_exists('color_adjust')) { + function color_adjust($color, $percent) { /* - USAGE - 20% Lighter - color_adjust('#3f4265', 0.2); - color_adjust('234,120,6,0.3', 0.2); - 20% Darker - color_adjust('#3f4265', -0.2); // - color_adjust('rgba(234,120,6,0.3)', -0.2); - RETURNS - Same color format provided (hex in = hex out, rgb(a) in = rgb(a) out) - */ + USAGE + 20% Lighter + color_adjust('#3f4265', 0.2); + color_adjust('234,120,6,0.3', 0.2); + 20% Darker + color_adjust('#3f4265', -0.2); // + color_adjust('rgba(234,120,6,0.3)', -0.2); + RETURNS + Same color format provided (hex in = hex out, rgb(a) in = rgb(a) out) + */ //convert hex to rgb if (substr_count($color, ',') == 0) { @@ -1166,16 +1213,15 @@ function number_pad($number,$n) { $hash = '#'; } if (strlen($color) == 3) { - $r = hexdec(substr($color,0,1).substr($color,0,1)); - $g = hexdec(substr($color,1,1).substr($color,1,1)); - $b = hexdec(substr($color,2,1).substr($color,2,1)); + $r = hexdec(substr($color, 0, 1) . substr($color, 0, 1)); + $g = hexdec(substr($color, 1, 1) . substr($color, 1, 1)); + $b = hexdec(substr($color, 2, 1) . substr($color, 2, 1)); + } else { + $r = hexdec(substr($color, 0, 2)); + $g = hexdec(substr($color, 2, 2)); + $b = hexdec(substr($color, 4, 2)); } - else { - $r = hexdec(substr($color,0,2)); - $g = hexdec(substr($color,2,2)); - $b = hexdec(substr($color,4,2)); - } - $color = $r.','.$g.','.$b; + $color = $r . ',' . $g . ',' . $b; } //color to array, pop alpha @@ -1203,25 +1249,33 @@ function number_pad($number,$n) { $hex = ''; for ($i = 0; $i <= 2; $i++) { $hex_color = dechex($color[$i]); - if (strlen($hex_color) == 1) { $hex_color = '0'.$hex_color; } + if (strlen($hex_color) == 1) { + $hex_color = '0' . $hex_color; + } $hex .= $hex_color; } - return $hash.$hex; - } - else { //rgb(a) + return $hash . $hex; + } else { //rgb(a) $rgb = implode(',', $color); - if (!empty($alpha)) { $rgb .= ','.$alpha; $a = 'a'; } - if ($wrapper) { $rgb = 'rgb'.($a ?? '').'('.$rgb.')'; } + if (!empty($alpha)) { + $rgb .= ',' . $alpha; + $a = 'a'; + } + if ($wrapper) { + $rgb = 'rgb' . ($a ?? '') . '(' . $rgb . ')'; + } return $rgb; } } return $color; } + } //function to convert an rgb color array to an hsl color array if (!function_exists('rgb_to_hsl')) { + function rgb_to_hsl($r, $g, $b) { $r /= 255; $g /= 255; @@ -1237,13 +1291,14 @@ function number_pad($number,$n) { if ($d == 0) { $h = $s = 0; // achromatic - } - else { + } else { $s = $d / (1 - abs((2 * $l) - 1)); - switch($max){ + switch ($max) { case $r: $h = 60 * fmod((($g - $b) / $d), 6); - if ($b > $g) { $h += 360; } + if ($b > $g) { + $h += 360; + } break; case $g: $h = 60 * (($b - $r) / $d + 2); @@ -1256,11 +1311,13 @@ function number_pad($number,$n) { return array(round($h, 2), round($s, 2), round($l, 2)); } + } //function to convert an hsl color array to an rgb color array if (!function_exists('hsl_to_rgb')) { - function hsl_to_rgb($h, $s, $l){ + + function hsl_to_rgb($h, $s, $l) { $r; $g; $b; @@ -1273,28 +1330,23 @@ function number_pad($number,$n) { $r = $c; $g = $x; $b = 0; - } - else if ($h < 120) { + } else if ($h < 120) { $r = $x; $g = $c; $b = 0; - } - else if ($h < 180) { + } else if ($h < 180) { $r = 0; $g = $c; $b = $x; - } - else if ($h < 240) { + } else if ($h < 240) { $r = 0; $g = $x; $b = $c; - } - else if ($h < 300) { + } else if ($h < 300) { $r = $x; $g = 0; $b = $c; - } - else { + } else { $r = $c; $g = 0; $b = $x; @@ -1304,83 +1356,97 @@ function number_pad($number,$n) { $g = ($g + $m) * 255; $b = ($b + $m) * 255; - if ($r > 255) { $r = 255; } - if ($g > 255) { $g = 255; } - if ($b > 255) { $b = 255; } + if ($r > 255) { + $r = 255; + } + if ($g > 255) { + $g = 255; + } + if ($b > 255) { + $b = 255; + } - if ($r < 0) { $r = 0; } - if ($g < 0) { $g = 0; } - if ($b < 0) { $b = 0; } + if ($r < 0) { + $r = 0; + } + if ($g < 0) { + $g = 0; + } + if ($b < 0) { + $b = 0; + } return array(floor($r), floor($g), floor($b)); } + } //function to send email if (!function_exists('send_email')) { + function send_email($email_recipients, $email_subject, $email_body, &$email_error = '', $email_from_address = '', $email_from_name = '', $email_priority = 3, $email_debug_level = 0, $email_attachments = '', $email_read_confirmation = false) { /* - RECIPIENTS NOTE: + RECIPIENTS NOTE: - Pass in a single email address... + Pass in a single email address... - user@domain.com + user@domain.com - Pass in a comma or semi-colon delimited string of e-mail addresses... + Pass in a comma or semi-colon delimited string of e-mail addresses... - user@domain.com,user2@domain2.com,user3@domain3.com - user@domain.com;user2@domain2.com;user3@domain3.com + user@domain.com,user2@domain2.com,user3@domain3.com + user@domain.com;user2@domain2.com;user3@domain3.com - Pass in a simple array of email addresses... + Pass in a simple array of email addresses... - Array ( - [0] => user@domain.com - [1] => user2@domain2.com - [2] => user3@domain3.com - ) + Array ( + [0] => user@domain.com + [1] => user2@domain2.com + [2] => user3@domain3.com + ) - Pass in a multi-dimentional array of addresses (delivery, address, name)... + Pass in a multi-dimentional array of addresses (delivery, address, name)... - Array ( - [0] => Array ( - [delivery] => to - [address] => user@domain.com - [name] => user 1 - ) - [1] => Array ( - [delivery] => cc - [address] => user2@domain2.com - [name] => user 2 - ) - [2] => Array ( - [delivery] => bcc - [address] => user3@domain3.com - [name] => user 3 - ) - ) + Array ( + [0] => Array ( + [delivery] => to + [address] => user@domain.com + [name] => user 1 + ) + [1] => Array ( + [delivery] => cc + [address] => user2@domain2.com + [name] => user 2 + ) + [2] => Array ( + [delivery] => bcc + [address] => user3@domain3.com + [name] => user 3 + ) + ) - ATTACHMENTS NOTE: + ATTACHMENTS NOTE: - Pass in as many files as necessary in an array in the following format... + Pass in as many files as necessary in an array in the following format... - Array ( - [0] => Array ( - [type] => file (or 'path') - [name] => filename.ext - [value] => /folder/filename.ext - ) - [1] => Array ( - [type] => string - [name] => filename.ext - [value] => (string of file contents - if base64, will be decoded automatically) - ) - ) + Array ( + [0] => Array ( + [type] => file (or 'path') + [name] => filename.ext + [value] => /folder/filename.ext + ) + [1] => Array ( + [type] => string + [name] => filename.ext + [value] => (string of file contents - if base64, will be decoded automatically) + ) + ) - ERROR RESPONSE: + ERROR RESPONSE: - Error messages are stored in the variable passed into $email_error BY REFERENCE + Error messages are stored in the variable passed into $email_error BY REFERENCE - */ + */ //add the email recipients $address_found = false; @@ -1396,8 +1462,7 @@ function number_pad($number,$n) { $recipients = $email_recipient["address"]; $address_found = true; } - } - else if (!empty($email_recipient) && valid_email($email_recipient)) { // check if recipient value is simply (only) an address + } else if (!empty($email_recipient) && valid_email($email_recipient)) { // check if recipient value is simply (only) an address $email_recipients = $email_recipient; $address_found = true; } @@ -1425,45 +1490,54 @@ function number_pad($number,$n) { $email->debug_level = 3; $sent = $email->send(); //$email_error = $email->email_error; - } + } //encrypt a string if (!function_exists('encrypt')) { + function encrypt($key, $data) { $encryption_key = base64_decode($key); $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv); - return base64_encode($encrypted.'::'.$iv); + return base64_encode($encrypted . '::' . $iv); } + } //decrypt a string if (!function_exists('decrypt')) { + function decrypt($key, $data) { $encryption_key = base64_decode($key); list($encrypted_data, $iv) = explode('::', base64_decode($data), 2); return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv); } + } //json detection if (!function_exists('is_json')) { + function is_json($str) { return is_string($str) && is_array(json_decode($str, true)) ? true : false; } + } //mac detection if (!function_exists('is_mac')) { + function is_mac($str) { return preg_match('/([a-fA-F0-9]{2}[:|\-]?){6}/', $str) == 1 && strlen(preg_replace("#[^a-fA-F0-9]#", '', $str)) == 12 ? true : false; } + } //detect if php is running as command line interface if (!function_exists('is_cli')) { + function is_cli() { if (defined('STDIN')) { return true; @@ -1473,37 +1547,42 @@ function number_pad($number,$n) { } return false; } + } //format device address if (!function_exists('format_device_address')) { + function format_device_address($str, $delim = '-', $case = 'lower') { - if (empty($str)) { return false; } + if (empty($str)) { + return false; + } $str = preg_replace("#[^a-fA-F0-9]#", '', $str); //remove formatting, if any if (is_mac($str)) { $str = join($delim, str_split($str, 2)); - } - else if (is_uuid($str)) { - $str = substr($str, 0, 8).'-'.substr($str, 8, 4).'-'.substr($str, 12, 4).'-'.substr($str, 16, 4).'-'.substr($str, 20, 12); + } else if (is_uuid($str)) { + $str = substr($str, 0, 8) . '-' . substr($str, 8, 4) . '-' . substr($str, 12, 4) . '-' . substr($str, 16, 4) . '-' . substr($str, 20, 12); } $str = $case == 'upper' ? strtoupper($str) : strtolower($str); return $str; } + } //transparent gif if (!function_exists('img_spacer')) { + function img_spacer($width = '1px', $height = '1px', $custom = null) { - return ""; + return ""; } + } //lower case function lower_case($string) { if (function_exists('mb_strtolower')) { return mb_strtolower($string, 'UTF-8'); - } - else { + } else { return strtolower($string); } } @@ -1512,93 +1591,97 @@ function number_pad($number,$n) { function upper_case($string) { if (function_exists('mb_strtoupper')) { return mb_strtoupper($string, 'UTF-8'); - } - else { + } else { return strtoupper($string); } } //write javascript function that detects select key combinations to perform designated actions if (!function_exists('key_press')) { + function key_press($key, $direction = 'up', $subject = 'document', $exceptions = array(), $prompt = null, $action = null, $script_wrapper = true) { //determine key code - switch (strtolower($key)) { - case 'escape': - $key_code = '(e.which == 27)'; - break; - case 'delete': - $key_code = '(e.which == 46)'; - break; - case 'enter': - $key_code = '(e.which == 13)'; - break; - case 'backspace': - $key_code = '(e.which == 8)'; - break; - case 'space': - $key_code = '(e.which == 32)'; - break; - case 'ctrl+s': - $key_code = '(((e.which == 115 || e.which == 83) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - case 'ctrl+q': - $key_code = '(((e.which == 113 || e.which == 81) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - case 'ctrl+a': - $key_code = '(((e.which == 97 || e.which == 65) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - case 'ctrl+c': - $key_code = '(((e.which == 99 || e.which == 67) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - case 'ctrl+enter': - $key_code = '(((e.which == 13 || e.which == 10) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - default: - return; - } + switch (strtolower($key)) { + case 'escape': + $key_code = '(e.which == 27)'; + break; + case 'delete': + $key_code = '(e.which == 46)'; + break; + case 'enter': + $key_code = '(e.which == 13)'; + break; + case 'backspace': + $key_code = '(e.which == 8)'; + break; + case 'space': + $key_code = '(e.which == 32)'; + break; + case 'ctrl+s': + $key_code = '(((e.which == 115 || e.which == 83) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + case 'ctrl+q': + $key_code = '(((e.which == 113 || e.which == 81) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + case 'ctrl+a': + $key_code = '(((e.which == 97 || e.which == 65) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + case 'ctrl+c': + $key_code = '(((e.which == 99 || e.which == 67) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + case 'ctrl+enter': + $key_code = '(((e.which == 13 || e.which == 10) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + default: + return; + } //filter direction - switch ($direction) { - case 'down': $direction = 'keydown'; break; - case 'press': $direction = 'keypress'; break; - case 'up': $direction = 'keyup'; break; - } + switch ($direction) { + case 'down': $direction = 'keydown'; + break; + case 'press': $direction = 'keypress'; + break; + case 'up': $direction = 'keyup'; + break; + } //check for element exceptions - if (is_array($exceptions)) { - if (sizeof($exceptions) > 0) { - $exceptions = "!$(e.target).is('".implode(',', $exceptions)."') && "; - } + if (is_array($exceptions)) { + if (sizeof($exceptions) > 0) { + $exceptions = "!$(e.target).is('" . implode(',', $exceptions) . "') && "; } + } //quote if selector is id or class - $subject = ($subject != 'window' && $subject != 'document') ? "'".$subject."'" : $subject; + $subject = ($subject != 'window' && $subject != 'document') ? "'" . $subject . "'" : $subject; //output script - echo "\n\n\n"; - if ($script_wrapper) { - echo "\n"; - } - echo "\n\n\n"; + echo "\n\n\n"; + if ($script_wrapper) { + echo "\n"; + } + echo "\n\n\n"; } + } //format border radius values if (!function_exists('format_border_radius')) { + function format_border_radius($radius_value, $default = 5) { $radius_value = (!empty($radius_value)) ? $radius_value : $default; $br_a = explode(' ', $radius_value); @@ -1606,8 +1689,7 @@ function number_pad($number,$n) { if (substr_count($br, '%') > 0) { $br_b[$index]['number'] = str_replace('%', '', $br); $br_b[$index]['unit'] = '%'; - } - else { + } else { $br_b[$index]['number'] = str_replace('px', '', strtolower($br)); $br_b[$index]['unit'] = 'px'; } @@ -1622,8 +1704,7 @@ function number_pad($number,$n) { $br['tr']['u'] = $br_b[1]['unit']; $br['br']['u'] = $br_b[2]['unit']; $br['bl']['u'] = $br_b[3]['unit']; - } - else if (sizeof($br_b) == 2) { + } else if (sizeof($br_b) == 2) { $br['tl']['n'] = $br_b[0]['number']; $br['tr']['n'] = $br_b[0]['number']; $br['br']['n'] = $br_b[1]['number']; @@ -1632,8 +1713,7 @@ function number_pad($number,$n) { $br['tr']['u'] = $br_b[0]['unit']; $br['br']['u'] = $br_b[1]['unit']; $br['bl']['u'] = $br_b[1]['unit']; - } - else { + } else { $br['tl']['n'] = $br_b[0]['number']; $br['tr']['n'] = $br_b[0]['number']; $br['br']['n'] = $br_b[0]['number']; @@ -1647,58 +1727,58 @@ function number_pad($number,$n) { return $br; //array } + } //converts a string to a regular expression if (!function_exists('string_to_regex')) { - function string_to_regex($string, $prefix='') { + + function string_to_regex($string, $prefix = '') { $original_string = $string; //escape the plus - if (substr($string, 0, 1) == "+") { - $string = "^\\+(".substr($string, 1).")$"; - } + if (substr($string, 0, 1) == "+") { + $string = "^\\+(" . substr($string, 1) . ")$"; + } //add prefix - if (!empty($prefix)) { - if (!empty($prefix) && strlen($prefix) < 4) { - $plus = (substr($string, 0, 1) == "+") ? '' : '\+?'; - $prefix = $plus.$prefix.'?'; - } - else { - $prefix = '(?:'.$prefix.')?'; - } + if (!empty($prefix)) { + if (!empty($prefix) && strlen($prefix) < 4) { + $plus = (substr($string, 0, 1) == "+") ? '' : '\+?'; + $prefix = $plus . $prefix . '?'; + } else { + $prefix = '(?:' . $prefix . ')?'; } + } //convert N,X,Z syntax to regex - if (preg_match('/^[NnXxZz]+$/', $original_string)) { - $string = str_ireplace("N", "[2-9]", $string); - $string = str_ireplace("X", "[0-9]", $string); - $string = str_ireplace("Z", "[1-9]", $string); - } + if (preg_match('/^[NnXxZz]+$/', $original_string)) { + $string = str_ireplace("N", "[2-9]", $string); + $string = str_ireplace("X", "[0-9]", $string); + $string = str_ireplace("Z", "[1-9]", $string); + } //add ^ to the start of the string if missing - if (substr($string, 0, 1) != "^") { - $string = "^".$string; - } + if (substr($string, 0, 1) != "^") { + $string = "^" . $string; + } //add $ to the end of the string if missing - if (substr($string, -1) != "$") { - $string = $string."$"; - } + if (substr($string, -1) != "$") { + $string = $string . "$"; + } //add the round brackets - if (!strstr($string, '(')) { - if (strstr($string, '^')) { - $string = str_replace("^", "^".$prefix."(", $string); - } - else { - $string = '^('.$string; - } - if (strstr($string, '$')) { - $string = str_replace("$", ")$", $string); - } - else { - $string = $string.')$'; - } + if (!strstr($string, '(')) { + if (strstr($string, '^')) { + $string = str_replace("^", "^" . $prefix . "(", $string); + } else { + $string = '^(' . $string; } + if (strstr($string, '$')) { + $string = str_replace("$", ")$", $string); + } else { + $string = $string . ')$'; + } + } //return the result - return $string; + return $string; } + //$string = "+12089068227"; echo $string." ".string_to_regex($string)."\n"; //$string = "12089068227"; echo $string." ".string_to_regex($string)."\n"; //$string = "2089068227"; echo $string." ".string_to_regex($string)."\n"; @@ -1714,18 +1794,19 @@ function number_pad($number,$n) { //dynamically load available web fonts if (!function_exists('get_available_fonts')) { + function get_available_fonts($sort = 'alpha') { if (!empty($_SESSION['theme']['font_source_key']['text'])) { if (!is_array($_SESSION['fonts_available']) || sizeof($_SESSION['fonts_available']) == 0) { /* - sort options: - alpha - alphabetically - date - by date added (most recent font added or updated first) - popularity - by popularity (most popular family first) - style - by number of styles available (family with most styles first) - trending - by families seeing growth in usage (family seeing the most growth first) - */ - $google_api_url = 'https://www.googleapis.com/webfonts/v1/webfonts?key='.$_SESSION['theme']['font_source_key']['text'].'&sort='.$sort; + sort options: + alpha - alphabetically + date - by date added (most recent font added or updated first) + popularity - by popularity (most popular family first) + style - by number of styles available (family with most styles first) + trending - by families seeing growth in usage (family seeing the most growth first) + */ + $google_api_url = 'https://www.googleapis.com/webfonts/v1/webfonts?key=' . $_SESSION['theme']['font_source_key']['text'] . '&sort=' . $sort; $response = file_get_contents($google_api_url); if (!empty($response)) { $data = json_decode($response, true); @@ -1739,39 +1820,42 @@ function number_pad($number,$n) { unset($fonts); } return (is_array($_SESSION['fonts_available']) && sizeof($_SESSION['fonts_available']) > 0) ? $_SESSION['fonts_available'] : array(); - } - else { + } else { return false; } } + } //dynamically import web fonts (by reading static css file) if (!function_exists('import_fonts')) { + function import_fonts($file_to_parse, $line_styles_begin = null) { /* - This function reads the contents of $file_to_parse, beginning at $line_styles_begin (if set), - and attempts to parse the specified google fonts used. The assumption is that each curly brace - will be on its own line, each CSS style (attribute: value;) will be on its own line, a single - Google Fonts name will be used per selector, and that it will be surrounded by SINGLE quotes, - as shown in the example below: + This function reads the contents of $file_to_parse, beginning at $line_styles_begin (if set), + and attempts to parse the specified google fonts used. The assumption is that each curly brace + will be on its own line, each CSS style (attribute: value;) will be on its own line, a single + Google Fonts name will be used per selector, and that it will be surrounded by SINGLE quotes, + as shown in the example below: - .class_name { - font-family: 'Google Font'; - font-weight: 300; - font-style: italic; - } + .class_name { + font-family: 'Google Font'; + font-weight: 300; + font-style: italic; + } - If the CSS styles are formatted as described, the necessary @import string should be generated - correctly. - */ + If the CSS styles are formatted as described, the necessary @import string should be generated + correctly. + */ - $file = file_get_contents($_SERVER["DOCUMENT_ROOT"].$file_to_parse); + $file = file_get_contents($_SERVER["DOCUMENT_ROOT"] . $file_to_parse); $lines = explode("\n", $file); $style_counter = 0; foreach ($lines as $line_number => $line) { - if (!empty($line_styles_begin) && $line_number < $line_styles_begin - 1) { continue; } + if (!empty($line_styles_begin) && $line_number < $line_styles_begin - 1) { + continue; + } if (substr_count($line, "{") > 0) { $style_lines[$style_counter]['begins'] = $line_number; } @@ -1785,7 +1869,7 @@ function number_pad($number,$n) { if (is_array($style_lines) && sizeof($style_lines) > 0) { foreach ($style_lines as $index => $style_line) { - for ($l = $style_line['begins']+1; $l < $style_line['ends']; $l++) { + for ($l = $style_line['begins'] + 1; $l < $style_line['ends']; $l++) { $tmp[] = $lines[$l]; } $style_groups[] = $tmp; @@ -1799,7 +1883,7 @@ function number_pad($number,$n) { foreach ($style_group as $style_index => $style) { $tmp = explode(':', $style); $attribute = trim($tmp[0]); - $value = trim(trim($tmp[1]),';'); + $value = trim(trim($tmp[1]), ';'); $style_array[$attribute] = $value; } $style_groups[$style_group_index] = $style_array; @@ -1811,14 +1895,14 @@ function number_pad($number,$n) { $style_value = $style_group['font-family']; if (substr_count($style_value, "'") > 0) { //determine font - $font_begin = strpos($style_value, "'")+1; - $font_end = strpos($style_value, "'", $font_begin); - $font_name = substr($style_value, $font_begin, $font_end - $font_begin); + $font_begin = strpos($style_value, "'") + 1; + $font_end = strpos($style_value, "'", $font_begin); + $font_name = substr($style_value, $font_begin, $font_end - $font_begin); //determine modifiers - $weight = (is_numeric($style_group['font-weight']) || strtolower($style_group['font-weight']) == 'bold') ? strtolower($style_group['font-weight']) : null; - $italic = (strtolower($style_group['font-style']) == 'italic') ? 'italic' : null; + $weight = (is_numeric($style_group['font-weight']) || strtolower($style_group['font-weight']) == 'bold') ? strtolower($style_group['font-weight']) : null; + $italic = (strtolower($style_group['font-style']) == 'italic') ? 'italic' : null; //add font to array - $fonts[$font_name][] = $weight.$italic; + $fonts[$font_name][] = $weight . $italic; } } //echo "\n\n/*".print_r($fonts, true)."*/\n\n"; @@ -1828,24 +1912,23 @@ function number_pad($number,$n) { $modifiers = array_unique($modifiers); $import_font_string = str_replace(' ', '+', $font_name); if (is_array($modifiers) && sizeof($modifiers) > 0) { - $import_font_string .= ':'.implode(',', $modifiers); + $import_font_string .= ':' . implode(',', $modifiers); } $import_fonts[] = $import_font_string; } //echo "\n\n/*".print_r($import_fonts, true)."*/\n\n"; - $import_string = "@import url(//fonts.googleapis.com/css?family=".implode('|', $import_fonts).");"; - echo $import_string."\n"; + $import_string = "@import url(//fonts.googleapis.com/css?family=" . implode('|', $import_fonts) . ");"; + echo $import_string . "\n"; } - } - } - } + } //retrieve array of countries if (!function_exists('get_countries')) { + function get_countries() { $sql = "select * from v_countries order by country asc"; $database = new database; @@ -1854,39 +1937,36 @@ function number_pad($number,$n) { return is_array($result) && @sizeof($result) != 0 ? $result : false; } + } //make directory with event socket function event_socket_mkdir($dir) { //connect to fs - $fp = event_socket_create(); - if (!$fp) { - return false; - } - //send the mkdir command to freeswitch - if ($fp) { - //build and send the mkdir command to freeswitch - $switch_cmd = "lua mkdir.lua ".escapeshellarg($dir); - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); - fclose($fp); - //check result - if (trim($switch_result) == "-ERR no reply") { - return true; - } - } - //can not create directory + $esl = event_socket::create(); + if (!$esl->is_connected()) { return false; + } + //send the mkdir command to freeswitch + //build and send the mkdir command to freeswitch + $switch_cmd = "lua mkdir.lua " . escapeshellarg($dir); + $switch_result = event_socket::api($switch_cmd); + //check result + if (trim($switch_result) == "-ERR no reply") { + return true; + } + + //can not create directory + return false; } //escape user data function escape($string) { if (is_string($string)) { return htmlentities($string, ENT_QUOTES | ENT_HTML5, 'UTF-8'); - } - elseif (is_numeric($string)) { + } elseif (is_numeric($string)) { return $string; - } - else { + } else { $string = (array) $string; if (isset($string[0])) { return htmlentities($string[0], ENT_QUOTES | ENT_HTML5, 'UTF-8'); @@ -1897,20 +1977,22 @@ function number_pad($number,$n) { //output pre-formatted array keys and values if (!function_exists('view_array')) { + function view_array($array, $exit = true, $return = false) { - $html = "
".print_r($array, true).'

'; + $html = "
" . print_r($array, true) . '

'; if ($return) { return $html; - } - else { + } else { echo $html; } $exit and exit(); } + } //format db date and/or time to local date and/or time if (!function_exists('format_when_local')) { + function format_when_local($when, $format = 'dt', $include_seconds = false) { if (!empty($when)) { // determine when format @@ -1918,11 +2000,9 @@ function number_pad($number,$n) { $tmp = explode(' ', $when); $date = $tmp[0]; $time = $tmp[1]; - } - else if (substr_count($when, '-') > 0) { // date only + } else if (substr_count($when, '-') > 0) { // date only $date = $when; - } - else if (substr_count($when, ':') > 0) { // time only + } else if (substr_count($when, ':') > 0) { // time only $time = $when; } unset($when, $tmp); @@ -1930,7 +2010,7 @@ function number_pad($number,$n) { // format date if (!empty($date)) { $tmp = explode('-', $date); - $date = $tmp[1].'-'.$tmp[2].'-'.$tmp[0]; + $date = $tmp[1] . '-' . $tmp[2] . '-' . $tmp[0]; } // format time @@ -1939,8 +2019,7 @@ function number_pad($number,$n) { if ($tmp[0] >= 0 && $tmp[0] <= 11) { $meridiem = 'AM'; $hour = ($tmp[0] == 0) ? 12 : $tmp[0]; - } - else { + } else { $meridiem = 'PM'; $hour = ($tmp[0] > 12) ? ($tmp[0] - 12) : $tmp[0]; } @@ -1949,24 +2028,27 @@ function number_pad($number,$n) { } // structure requested time format - $time = $hour.':'.$minute; - if ($include_seconds) { $time .= ':'.$second; } - $time .= ' '.$meridiem; + $time = $hour . ':' . $minute; + if ($include_seconds) { + $time .= ':' . $second; + } + $time .= ' ' . $meridiem; $return['d'] = $date; $return['t'] = $time; - $return['dt'] = $date.' '.$time; + $return['dt'] = $date . ' ' . $time; return $return[$format]; - } - else { + } else { return false; } } + } //define email button (src: https://buttons.cm) if (!function_exists('email_button')) { + function email_button($text = 'Click Here!', $link = URL, $bg_color = '#dddddd', $fg_color = '#000000', $radius = '') { // default button radius @@ -1980,16 +2062,15 @@ function number_pad($number,$n) { } $tmp = preg_replace("/[^0-9,.]/", '', $tmp); // remove non-numeric characters $arc = floor($tmp / 35 * 100); // calculate percentage - // create button code $btn = "