From bda6861f88c8082398d66d7f772cc42f1c3388bc Mon Sep 17 00:00:00 2001 From: "Harry G. Coin" Date: Mon, 25 Apr 2016 20:30:23 -0500 Subject: [PATCH] \r\n --> \n Cause all the .php files containing lines ending with \r\n to instead end with \n. DYI with: find fusionpbx -type f -name '*.php' -exec dos2unix '{}' \; --- app/adminer/app_menu.php | 36 +- app/backup/index.php | 514 +- .../call_center_active_inc.php | 720 +-- app/call_center_active/call_center_exec.php | 200 +- app/call_centers/app_defaults.php | 52 +- .../resources/classes/call_center.php | 446 +- app/calls/app_languages.php | 948 ++-- app/calls/app_menu.php | 40 +- app/calls/resources/classes/follow_me.php | 896 ++-- app/click_to_call/app_menu.php | 34 +- app/click_to_call/click_to_call.php | 754 +-- app/conferences/app_menu.php | 40 +- app/contacts/app_defaults.php | 436 +- app/contacts/contact_auth.php | 242 +- app/contacts/contact_import_google.php | 1352 ++--- app/contacts/contact_relation_edit.php | 684 +-- app/contacts/contact_relations.php | 224 +- app/contacts/contact_timer.php | 720 +-- app/contacts/contact_timer_inc.php | 112 +- .../functions/google_get_contacts.php | 226 +- .../resources/functions/google_get_groups.php | 106 +- app/devices/app_defaults.php | 106 +- app/devices/app_languages.php | 4694 ++++++++--------- app/devices/device_copy.php | 320 +- app/devices/device_profile_copy.php | 320 +- app/devices/device_profile_delete.php | 150 +- app/devices/device_profile_edit.php | 1414 ++--- app/devices/device_profiles.php | 352 +- app/edit/app_defaults.php | 176 +- app/edit/app_menu.php | 176 +- app/emails/app_config.php | 186 +- app/emails/email_delete.php | 128 +- app/emails/email_view.php | 412 +- app/emails/emails.php | 542 +- app/exec/app_config.php | 84 +- app/exec/app_languages.php | 552 +- app/extensions/app_languages.php | 3122 +++++------ app/fax/app_defaults.php | 348 +- app/fax/fax_copy.php | 290 +- app/fax/fax_edit.php | 2082 ++++---- app/fax/fax_emails.php | 772 +-- app/fax/fax_file_delete.php | 204 +- app/fax/fax_files.php | 786 +-- app/fax/fax_files_remote.php | 486 +- app/fax/fax_send.php | 2206 ++++---- app/fax/resources/classes/fax.php | 494 +- .../resources/functions/object_to_array.php | 16 +- app/fax/resources/functions/parse_message.php | 290 +- app/follow_me/app_menu.php | 42 +- app/gateways/app_defaults.php | 86 +- app/meetings/app_menu.php | 22 +- app/operator_panel/index.php | 884 ++-- app/operator_panel/index_inc.php | 900 ++-- .../resources/functions/get_call_activity.php | 364 +- app/provision/app_menu.php | 22 +- app/provision/resources/classes/provision.php | 2094 ++++---- app/ring_groups/app_languages.php | 1568 +++--- app/scripts/app_defaults.php | 66 +- app/scripts/resources/classes/scripts.php | 570 +- app/services/resources/classes/lib_win.php | 454 +- app/time_conditions/app_defaults.php | 232 +- app/time_conditions/time_condition_edit.php | 2228 ++++---- app/voicemail_greetings/app_defaults.php | 244 +- app/voicemails/app_defaults.php | 192 +- app/voicemails/app_languages.php | 1428 ++--- app/voicemails/voicemail_message_toggle.php | 154 +- app/xml_cdr/app_languages.php | 2564 ++++----- app/xml_cdr/report.php | 428 +- app/xml_cdr/xml_cdr_export.php | 576 +- core/default_settings/app_defaults.php | 1128 ++-- core/default_settings/app_languages.php | 864 +-- .../default_setting_toggle.php | 142 +- .../default_settings_reload.php | 100 +- core/domain_settings/app_defaults.php | 68 +- core/domain_settings/app_languages.php | 888 ++-- core/events/resources/classes/events.php | 326 +- core/install/app_languages.php | 840 +-- core/install/index.php | 164 +- core/install/install.php | 732 +-- .../resources/classes/detect_switch.php | 338 +- .../resources/classes/global_settings.php | 426 +- .../resources/classes/install_fusionpbx.php | 1904 +++---- .../resources/classes/install_switch.php | 290 +- .../resources/classes/iso_countries.php | 502 +- .../page_parts/install_config_database.php | 550 +- .../page_parts/install_config_detail.php | 298 +- .../page_parts/install_event_socket.php | 272 +- .../page_parts/install_select_language.php | 128 +- core/notifications/notification_edit.php | 920 ++-- core/upgrade/index.php | 496 +- core/user_settings/app_languages.php | 2518 ++++----- core/user_settings/app_menu.php | 84 +- core/users/app_config.php | 842 +-- core/users/app_languages.php | 2144 ++++---- core/users/app_menu.php | 70 +- core/users/groupedit.php | 622 +-- resources/app_languages.php | 1494 +++--- resources/classes/cache.php | 276 +- resources/classes/config.php | 252 +- resources/classes/destinations.php | 560 +- resources/classes/event_socket.php | 390 +- resources/classes/groups.php | 380 +- resources/classes/permissions.php | 208 +- resources/classes/switch_settings.php | 572 +- resources/classes/template.php | 202 +- resources/classes/text.php | 164 +- resources/classes/users.php | 152 +- resources/countries.php | 1830 +++---- .../fpdi/filters/FilterASCIIHexDecode.php | 102 +- resources/fpdi/fpdi.php | 1388 ++--- resources/fpdi/fpdi_pdf_parser.php | 706 +-- resources/fpdi/pdf_context.php | 304 +- resources/fpdi/pdf_parser.php | 1824 +++---- .../sysplugins/smarty_internal_parsetree.php | 786 +-- .../smarty_internal_templatebase.php | 1644 +++--- .../smarty_internal_templatecompilerbase.php | 1618 +++--- .../sysplugins/smarty_internal_utility.php | 1644 +++--- themes/default/app_defaults.php | 2760 +++++----- 118 files changed, 40760 insertions(+), 40760 deletions(-) diff --git a/app/adminer/app_menu.php b/app/adminer/app_menu.php index fa1f6d0199..38d96bab49 100644 --- a/app/adminer/app_menu.php +++ b/app/adminer/app_menu.php @@ -1,19 +1,19 @@ -/app/adminer/index.php"; - $apps[$x]['menu'][0]['groups'][] = "superadmin"; - +/app/adminer/index.php"; + $apps[$x]['menu'][0]['groups'][] = "superadmin"; + ?> \ No newline at end of file diff --git a/app/backup/index.php b/app/backup/index.php index e6e98b5998..aa65e92045 100644 --- a/app/backup/index.php +++ b/app/backup/index.php @@ -1,258 +1,258 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists("backup_download")) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//download the backup - if ($_GET['a'] == "download" && permission_exists('backup_download')) { - $file_format = $_GET['file_format']; - $file_format = ($file_format != '') ? $file_format : 'tgz'; - - //build the backup file - $backup_path = ($_SESSION['server']['backup']['path'] != '') ? $_SESSION['server']['backup']['path'] : '/tmp'; - $backup_file = 'backup_'.date('Ymd_His').'.'.$file_format; - if (count($_SESSION['backup']['path']) > 0) { - //determine compression method - switch ($file_format) { - case "rar" : $cmd = 'rar a -ow -r '; break; - case "zip" : $cmd = 'zip -r '; break; - case "tbz" : $cmd = 'tar -jvcf '; break; - default : $cmd = 'tar -zvcf '; - } - $cmd .= $backup_path.'/'.$backup_file.' '; - foreach ($_SESSION['backup']['path'] as $value) { - $cmd .= $value.' '; - } - exec($cmd); - - //download the file - session_cache_limiter('public'); - if (file_exists($backup_path."/".$backup_file)) { - $fd = fopen($backup_path."/".$backup_file, 'rb'); - header("Content-Type: application/octet-stream"); - header("Content-Transfer-Encoding: binary"); - header("Content-Description: File Transfer"); - header('Content-Disposition: attachment; filename='.$backup_file); - header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 - header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past - header("Content-Length: ".filesize($backup_path."/".$backup_file)); - header("Pragma: no-cache"); - header("Expires: 0"); - ob_clean(); - fpassthru($fd); - exit; - } - else { - //set response message - $_SESSION["message"] = $text['message-backup_failed_format']; - header("Location: ".$_SERVER['PHP_SELF']); - exit; - } - } - else { - //set response message - $_SESSION["message"] = $text['message-backup_failed_paths']; - header("Location: ".$_SERVER['PHP_SELF']); - exit; - } - } - -//script a backup (cron) - if ($_GET['a'] == "script" && permission_exists('backup_download')) { - $file_format = $_GET['file_format']; - $target_type = "script"; - - $backup = new backup; - $command = $backup->command("backup", $file_format); - } - -//restore a backup - if ($_POST['a'] == "restore" && permission_exists('backup_upload')) { - - $backup_path = ($_SESSION['server']['backup']['path'] != '') ? $_SESSION['server']['backup']['path'] : '/tmp'; - $backup_file = $_FILES['backup_file']['name']; - - if (is_uploaded_file($_FILES['backup_file']['tmp_name'])) { - //move temp file to backup path - move_uploaded_file($_FILES['backup_file']['tmp_name'], $backup_path.'/'.$backup_file); - //determine file format and restore backup - $file_format = pathinfo($_FILES['backup_file']['name'], PATHINFO_EXTENSION); - $valid_format = true; - switch ($file_format) { - case "rar" : $cmd = 'rar x -ow -o+ '.$backup_path.'/'.$backup_file.' /'; break; - case "zip" : $cmd = 'umask 755; unzip -o -qq -X -K '.$backup_path.'/'.$backup_file.' -d /'; break; - case "tbz" : $cmd = 'tar -xvpjf '.$backup_path.'/'.$backup_file.' -C /'; break; - case "tgz" : $cmd = 'tar -xvpzf '.$backup_path.'/'.$backup_file.' -C /'; break; - default: $valid_format = false; - } - if (!$valid_format) { - @unlink($backup_path.'/'.$backup_file); - $_SESSION["message"] = $text['message-restore_failed_format']; - header("Location: ".$_SERVER['PHP_SELF']); - exit; - } - else { - exec($cmd); - //set response message - $_SESSION["message"] = $text['message-restore_completed']; - header("Location: ".$_SERVER['PHP_SELF']); - exit; - } - } - else { - //set response message - $_SESSION["message"] = $text['message-restore_failed_upload']; - header("Location: ".$_SERVER['PHP_SELF']); - exit; - } - } - -//add the header - require_once "resources/header.php"; - $document['title'] = $text['title-destinations']; - -// backup type switch javascript - echo ""; - -//show the content - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - } - - echo " \n"; - echo "
\n"; - - echo "".$text['header-backup']."\n"; - echo "

"; - echo $text['description-backup']."\n"; - echo "


"; - echo "\n"; - echo "\n"; - echo "\n"; - echo ""; - echo ""; - echo "\n"; - echo "\n"; - echo ""; - echo ""; - echo "\n"; - echo "\n"; - echo ""; - echo ""; - echo "
\n"; - echo " ".$text['label-source_paths']."\n"; - echo "\n"; - foreach ($_SESSION['backup']['path'] as $backup_path) { - echo $backup_path."
\n"; - } - echo "
\n"; - echo " ".$text['label-file_format']."\n"; - echo "\n"; - echo " "; - echo "
\n"; - echo " ".$text['label-target_type']."\n"; - echo "\n"; - echo " "; - echo "
"; - echo "
"; - echo "\n"; - echo "\n"; - echo "\n"; - echo ""; - echo ""; - echo "
\n"; - echo " ".$text['label-command']."\n"; - echo "\n"; - echo " "; - echo "
"; - echo "
"; - echo "
"; - echo "
"; - echo ""; - echo ""; - echo "
"; - echo "

"; - - if (permission_exists("backup_upload")) { - echo "
      \n"; - echo " ".$text['header-restore']."\n"; - echo "

"; - echo $text['description-restore']."\n"; - echo "


"; - echo "
"; - echo "
"; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo "
".$text['label-select_backup']." 
"; - echo "
"; - echo " ".$text['description-restore_warning'].""; - echo "
\n"; - echo "
"; - echo "
\n"; - echo "

"; - - //show the footer - require_once "resources/footer.php"; - + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists("backup_download")) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//download the backup + if ($_GET['a'] == "download" && permission_exists('backup_download')) { + $file_format = $_GET['file_format']; + $file_format = ($file_format != '') ? $file_format : 'tgz'; + + //build the backup file + $backup_path = ($_SESSION['server']['backup']['path'] != '') ? $_SESSION['server']['backup']['path'] : '/tmp'; + $backup_file = 'backup_'.date('Ymd_His').'.'.$file_format; + if (count($_SESSION['backup']['path']) > 0) { + //determine compression method + switch ($file_format) { + case "rar" : $cmd = 'rar a -ow -r '; break; + case "zip" : $cmd = 'zip -r '; break; + case "tbz" : $cmd = 'tar -jvcf '; break; + default : $cmd = 'tar -zvcf '; + } + $cmd .= $backup_path.'/'.$backup_file.' '; + foreach ($_SESSION['backup']['path'] as $value) { + $cmd .= $value.' '; + } + exec($cmd); + + //download the file + session_cache_limiter('public'); + if (file_exists($backup_path."/".$backup_file)) { + $fd = fopen($backup_path."/".$backup_file, 'rb'); + header("Content-Type: application/octet-stream"); + header("Content-Transfer-Encoding: binary"); + header("Content-Description: File Transfer"); + header('Content-Disposition: attachment; filename='.$backup_file); + header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 + header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past + header("Content-Length: ".filesize($backup_path."/".$backup_file)); + header("Pragma: no-cache"); + header("Expires: 0"); + ob_clean(); + fpassthru($fd); + exit; + } + else { + //set response message + $_SESSION["message"] = $text['message-backup_failed_format']; + header("Location: ".$_SERVER['PHP_SELF']); + exit; + } + } + else { + //set response message + $_SESSION["message"] = $text['message-backup_failed_paths']; + header("Location: ".$_SERVER['PHP_SELF']); + exit; + } + } + +//script a backup (cron) + if ($_GET['a'] == "script" && permission_exists('backup_download')) { + $file_format = $_GET['file_format']; + $target_type = "script"; + + $backup = new backup; + $command = $backup->command("backup", $file_format); + } + +//restore a backup + if ($_POST['a'] == "restore" && permission_exists('backup_upload')) { + + $backup_path = ($_SESSION['server']['backup']['path'] != '') ? $_SESSION['server']['backup']['path'] : '/tmp'; + $backup_file = $_FILES['backup_file']['name']; + + if (is_uploaded_file($_FILES['backup_file']['tmp_name'])) { + //move temp file to backup path + move_uploaded_file($_FILES['backup_file']['tmp_name'], $backup_path.'/'.$backup_file); + //determine file format and restore backup + $file_format = pathinfo($_FILES['backup_file']['name'], PATHINFO_EXTENSION); + $valid_format = true; + switch ($file_format) { + case "rar" : $cmd = 'rar x -ow -o+ '.$backup_path.'/'.$backup_file.' /'; break; + case "zip" : $cmd = 'umask 755; unzip -o -qq -X -K '.$backup_path.'/'.$backup_file.' -d /'; break; + case "tbz" : $cmd = 'tar -xvpjf '.$backup_path.'/'.$backup_file.' -C /'; break; + case "tgz" : $cmd = 'tar -xvpzf '.$backup_path.'/'.$backup_file.' -C /'; break; + default: $valid_format = false; + } + if (!$valid_format) { + @unlink($backup_path.'/'.$backup_file); + $_SESSION["message"] = $text['message-restore_failed_format']; + header("Location: ".$_SERVER['PHP_SELF']); + exit; + } + else { + exec($cmd); + //set response message + $_SESSION["message"] = $text['message-restore_completed']; + header("Location: ".$_SERVER['PHP_SELF']); + exit; + } + } + else { + //set response message + $_SESSION["message"] = $text['message-restore_failed_upload']; + header("Location: ".$_SERVER['PHP_SELF']); + exit; + } + } + +//add the header + require_once "resources/header.php"; + $document['title'] = $text['title-destinations']; + +// backup type switch javascript + echo ""; + +//show the content + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + } + + echo " \n"; + echo "
\n"; + + echo "".$text['header-backup']."\n"; + echo "

"; + echo $text['description-backup']."\n"; + echo "


"; + echo "\n"; + echo "\n"; + echo "\n"; + echo ""; + echo ""; + echo "\n"; + echo "\n"; + echo ""; + echo ""; + echo "\n"; + echo "\n"; + echo ""; + echo ""; + echo "
\n"; + echo " ".$text['label-source_paths']."\n"; + echo "\n"; + foreach ($_SESSION['backup']['path'] as $backup_path) { + echo $backup_path."
\n"; + } + echo "
\n"; + echo " ".$text['label-file_format']."\n"; + echo "\n"; + echo " "; + echo "
\n"; + echo " ".$text['label-target_type']."\n"; + echo "\n"; + echo " "; + echo "
"; + echo "
"; + echo "\n"; + echo "\n"; + echo "\n"; + echo ""; + echo ""; + echo "
\n"; + echo " ".$text['label-command']."\n"; + echo "\n"; + echo " "; + echo "
"; + echo "
"; + echo "
"; + echo "
"; + echo ""; + echo ""; + echo "
"; + echo "

"; + + if (permission_exists("backup_upload")) { + echo "
      \n"; + echo " ".$text['header-restore']."\n"; + echo "

"; + echo $text['description-restore']."\n"; + echo "


"; + echo "
"; + echo "
"; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo "
".$text['label-select_backup']." 
"; + echo "
"; + echo " ".$text['description-restore_warning'].""; + echo "
\n"; + echo "
"; + echo "
\n"; + echo "

"; + + //show the footer + require_once "resources/footer.php"; + ?> \ No newline at end of file diff --git a/app/call_center_active/call_center_active_inc.php b/app/call_center_active/call_center_active_inc.php index cf4904454f..e09165227b 100644 --- a/app/call_center_active/call_center_active_inc.php +++ b/app/call_center_active/call_center_active_inc.php @@ -1,360 +1,360 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - James Rose -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('call_center_active_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get the queue_name and set it as a variable - $queue_name = $_GET[queue_name].'@'. $_SESSION['domains'][$domain_uuid]['domain_name']; - -//convert the string to a named array - function str_to_named_array($tmp_str, $tmp_delimiter) { - $tmp_array = explode ("\n", $tmp_str); - $result = ''; - if (trim(strtoupper($tmp_array[0])) != "+OK") { - $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]); - $y = 0; - foreach ($tmp_field_value_array as $tmp_value) { - $tmp_name = $tmp_field_name_array[$y]; - if (trim(strtoupper($tmp_value)) != "+OK") { - $result[$x][$tmp_name] = $tmp_value; - } - $y++; - } - } - $x++; - } - unset($row); - } - return $result; - } - -//alternate the color of the row - $c = 0; - $row_style["0"] = "row_style0"; - $row_style["1"] = "row_style1"; - -//create an event socket connection - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - -//get the call center queue, agent and tiers list - if (!$fp) { - $msg = "
Connection to Event Socket failed.
"; - echo "
\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "
Message
$msg
\n"; - echo "
\n"; - } - else { - - //get the agent list - - //show the title - echo "".$text['header-agents']."
\n"; - echo $text['description-agents']."

\n"; - - //send the event socket command and get the response - //callcenter_config queue list tiers [queue_name] | - $switch_cmd = 'callcenter_config queue list tiers '.$queue_name; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); - $result = str_to_named_array($event_socket_str, '|'); - - //prepare the result for array_multisort - $x = 0; - foreach ($result as $row) { - $tier_result[$x]['level'] = $row['level']; - $tier_result[$x]['position'] = $row['position']; - $tier_result[$x]['agent'] = $row['agent']; - $tier_result[$x]['state'] = trim($row['state']); - $tier_result[$x]['queue'] = $row['queue']; - $x++; - } - - //sort the array //SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING - array_multisort($tier_result, SORT_ASC); - - //send the event socket command and get the response - //callcenter_config queue list agents [queue_name] [status] | - $switch_cmd = 'callcenter_config queue list agents '.$queue_name; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); - $agent_result = str_to_named_array($event_socket_str, '|'); - - //list the agents - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - if (permission_exists('call_center_active_options')) { - echo "\n"; - } - echo "\n"; - foreach ($tier_result as $tier_row) { - //$queue = $tier_row['queue']; - //$queue = str_replace('@'.$_SESSION['domain_name'], '', $queue); - $agent = $tier_row['agent']; - //$agent = str_replace('@'.$_SESSION['domain_name'], '', $agent); - $tier_state = $tier_row['state']; - $tier_level = $tier_row['level']; - $tier_position = $tier_row['position']; - - foreach ($agent_result as $agent_row) { - if ($tier_row['agent'] == $agent_row['name']) { - $name = $agent_row['name']; - $name = str_replace('@'.$_SESSION['domain_name'], '', $name); - //$system = $agent_row['system']; - $a_uuid = $agent_row['uuid']; - //$type = $agent_row['type']; - $contact = $agent_row['contact']; - $a_exten = preg_replace("/user\//", "", $contact); - $a_exten = preg_replace("/@.*/", "", $a_exten); - $a_exten = preg_replace("/{.*}/", "", $a_exten); - $status = $agent_row['status']; - $state = $agent_row['state']; - $max_no_answer = $agent_row['max_no_answer']; - $wrap_up_time = $agent_row['wrap_up_time']; - $reject_delay_time = $agent_row['reject_delay_time']; - $busy_delay_time = $agent_row['busy_delay_time']; - $last_bridge_start = $agent_row['last_bridge_start']; - $last_bridge_end = $agent_row['last_bridge_end']; - //$last_offered_call = $agent_row['last_offered_call']; - $last_status_change = $agent_row['last_status_change']; - $no_answer_count = $agent_row['no_answer_count']; - $calls_answered = $agent_row['calls_answered']; - $talk_time = $agent_row['talk_time']; - $ready_time = $agent_row['ready_time']; - - $last_offered_call_seconds = time() - $last_offered_call; - $last_offered_call_length_hour = floor($last_offered_call_seconds/3600); - $last_offered_call_length_min = floor($last_offered_call_seconds/60 - ($last_offered_call_length_hour * 60)); - $last_offered_call_length_sec = $last_offered_call_seconds - (($last_offered_call_length_hour * 3600) + ($last_offered_call_length_min * 60)); - $last_offered_call_length_min = sprintf("%02d", $last_offered_call_length_min); - $last_offered_call_length_sec = sprintf("%02d", $last_offered_call_length_sec); - $last_offered_call_length = $last_offered_call_length_hour.':'.$last_offered_call_length_min.':'.$last_offered_call_length_sec; - - $last_status_change_seconds = time() - $last_status_change; - $last_status_change_length_hour = floor($last_status_change_seconds/3600); - $last_status_change_length_min = floor($last_status_change_seconds/60 - ($last_status_change_length_hour * 60)); - $last_status_change_length_sec = $last_status_change_seconds - (($last_status_change_length_hour * 3600) + ($last_status_change_length_min * 60)); - $last_status_change_length_min = sprintf("%02d", $last_status_change_length_min); - $last_status_change_length_sec = sprintf("%02d", $last_status_change_length_sec); - $last_status_change_length = $last_status_change_length_hour.':'.$last_status_change_length_min.':'.$last_status_change_length_sec; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if (permission_exists('call_center_active_options')) { - - echo ""; - } - } - } - echo "\n"; - - if ($c==0) { $c=1; } else { $c=0; } - } - echo "
".$text['label-name']."".$text['label-extension']."".$text['label-status']."".$text['label-state']."".$text['label-status_change']."".$text['label-missed']."".$text['label-answered']."".$text['label-tier_state']."".$text['label-tier_level']."".$text['label-tier_position']."".$text['label-options']."
".$name."".$a_exten."".$status."".$state."".$last_status_change_length."".$no_answer_count."".$calls_answered."".$tier_state."".$tier_level."".$tier_position.""; - - //need to check state to so only waiting gets call, and trying/answer gets eavesdrop - if ($tier_state == "Offering" || $tier_state == "Active Inbound") { - $orig_command="{origination_caller_id_name=eavesdrop,origination_caller_id_number=".$a_exten."}user/".$_SESSION['user']['extension'][0]['user']."@".$_SESSION['domain_name']." %26eavesdrop(".$a_uuid.")"; - - //debug - //echo $orig_command; - //echo " log_cmd \n"; - echo " ".$text['label-eavesdrop']." \n"; - - $xfer_command = $a_uuid." -bleg ".$_SESSION['user']['extension'][0]['user']." XML ".$_SESSION['domain_name']; - //$xfer_command = $a_uuid." ".$_SESSION['user']['extension'][0]['user']." XML default"; - $xfer_command = urlencode($xfer_command); - echo " ".$text['label-transfer']." \n"; - } - else { - $orig_call="{origination_caller_id_name=c2c-".urlencode($name).",origination_caller_id_number=".$a_exten."}user/".$_SESSION['user']['extension'][0]['user']."@".$_SESSION['domain_name']." %26bridge(user/".$a_exten."@".$_SESSION['domain_name'].")"; - echo " ".$text['label-call']." \n"; - } - echo "
\n\n"; - - //add vertical spacing - echo "
"; - echo "
"; - echo "
"; - echo "
"; - - - //get the queue list - //send the event socket command and get the response - //callcenter_config queue list members [queue_name] - $switch_cmd = 'callcenter_config queue list members '.$queue_name; - $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); - $result = str_to_named_array($event_socket_str, '|'); - - //show the title - $q_waiting=0; - $q_trying=0; - $q_answered=0; - - echo "\n"; - echo " \n"; - echo " \n"; - echo " "; - echo " \n"; - echo "
".$text['label-queue'].": ".ucfirst($_GET[queue_name])."
\n"; - echo " ".$text['description-queue']."
\n"; - echo "
"; - foreach ($result as $row) { - $state = $row['state']; - $q_trying += ($state == "Trying") ? 1 : 0; - $q_waiting += ($state == "Waiting") ? 1 : 0; - $q_answered += ($state == "Answered") ? 1 : 0; - } - echo " ".$text['label-waiting'].": ".$q_waiting."   "; - echo " ".$text['label-trying'].": ".$q_trying."    "; - echo " ".$text['label-answered'].": ".$q_answered.""; - echo "
\n"; - echo "
\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - //echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - if ((if_group("admin") || if_group("superadmin"))) { - echo "\n"; - } - echo "\n"; - echo "\n"; - - foreach ($result as $row) { - $queue = $row['queue']; - $system = $row['system']; - $uuid = $row['uuid']; - $session_uuid = $row['session_uuid']; - $caller_number = $row['cid_number']; - $caller_name = $row['cid_name']; - $system_epoch = $row['system_epoch']; - $joined_epoch = $row['joined_epoch']; - $rejoined_epoch = $row['rejoined_epoch']; - $bridge_epoch = $row['bridge_epoch']; - $abandoned_epoch = $row['abandoned_epoch']; - $base_score = $row['base_score']; - $skill_score = $row['skill_score']; - $serving_agent = $row['serving_agent']; - $serving_system = $row['serving_system']; - $state = $row['state']; - $joined_seconds = time() - $joined_epoch; - $joined_length_hour = floor($joined_seconds/3600); - $joined_length_min = floor($joined_seconds/60 - ($joined_length_hour * 60)); - $joined_length_sec = $joined_seconds - (($joined_length_hour * 3600) + ($joined_length_min * 60)); - $joined_length_min = sprintf("%02d", $joined_length_min); - $joined_length_sec = sprintf("%02d", $joined_length_sec); - $joined_length = $joined_length_hour.':'.$joined_length_min.':'.$joined_length_sec; - - //$system_seconds = time() - $system_epoch; - //$system_length_hour = floor($system_seconds/3600); - //$system_length_min = floor($system_seconds/60 - ($system_length_hour * 60)); - //$system_length_sec = $system_seconds - (($system_length_hour * 3600) + ($system_length_min * 60)); - //$system_length_min = sprintf("%02d", $system_length_min); - //$system_length_sec = sprintf("%02d", $system_length_sec); - //$system_length = $system_length_hour.':'.$system_length_min.':'.$system_length_sec; - - echo "\n"; - echo "\n"; - //echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - if (if_group("admin") || if_group("superadmin")) { - echo ""; - } - echo "\n"; - echo "\n"; - if ($c==0) { $c=1; } else { $c=0; } - } - echo "
".$text['label-time']."".$text['label-system']."".$text['label-name']."".$text['label-number']."".$text['label-status']."".$text['label-options']."".$text['label-agent']."
".$joined_length."".$system_length."".$caller_name." ".$caller_number." ".$state.""; - if ($state != "Abandoned") { - $q_caller_number = urlencode($caller_number); - $orig_command="{origination_caller_id_name=eavesdrop,origination_caller_id_number=".$q_caller_number."}user/".$_SESSION['user']['extension'][0]['user']."@".$_SESSION['domain_name']." %26eavesdrop(".$session_uuid.")"; - - //debug - //echo $orig_command; - //echo " log_cmd \n"; - - echo " ".$text['label-eavesdrop']." \n"; - } - else { - echo " "; - } - echo "".$serving_agent." 
\n"; - - //add vertical spacing - echo "
\n"; - echo "
\n"; - echo "
\n"; - - - } -?> + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + James Rose +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('call_center_active_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get the queue_name and set it as a variable + $queue_name = $_GET[queue_name].'@'. $_SESSION['domains'][$domain_uuid]['domain_name']; + +//convert the string to a named array + function str_to_named_array($tmp_str, $tmp_delimiter) { + $tmp_array = explode ("\n", $tmp_str); + $result = ''; + if (trim(strtoupper($tmp_array[0])) != "+OK") { + $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]); + $y = 0; + foreach ($tmp_field_value_array as $tmp_value) { + $tmp_name = $tmp_field_name_array[$y]; + if (trim(strtoupper($tmp_value)) != "+OK") { + $result[$x][$tmp_name] = $tmp_value; + } + $y++; + } + } + $x++; + } + unset($row); + } + return $result; + } + +//alternate the color of the row + $c = 0; + $row_style["0"] = "row_style0"; + $row_style["1"] = "row_style1"; + +//create an event socket connection + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + +//get the call center queue, agent and tiers list + if (!$fp) { + $msg = "
Connection to Event Socket failed.
"; + echo "
\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "
Message
$msg
\n"; + echo "
\n"; + } + else { + + //get the agent list + + //show the title + echo "".$text['header-agents']."
\n"; + echo $text['description-agents']."

\n"; + + //send the event socket command and get the response + //callcenter_config queue list tiers [queue_name] | + $switch_cmd = 'callcenter_config queue list tiers '.$queue_name; + $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $result = str_to_named_array($event_socket_str, '|'); + + //prepare the result for array_multisort + $x = 0; + foreach ($result as $row) { + $tier_result[$x]['level'] = $row['level']; + $tier_result[$x]['position'] = $row['position']; + $tier_result[$x]['agent'] = $row['agent']; + $tier_result[$x]['state'] = trim($row['state']); + $tier_result[$x]['queue'] = $row['queue']; + $x++; + } + + //sort the array //SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING + array_multisort($tier_result, SORT_ASC); + + //send the event socket command and get the response + //callcenter_config queue list agents [queue_name] [status] | + $switch_cmd = 'callcenter_config queue list agents '.$queue_name; + $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $agent_result = str_to_named_array($event_socket_str, '|'); + + //list the agents + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + if (permission_exists('call_center_active_options')) { + echo "\n"; + } + echo "\n"; + foreach ($tier_result as $tier_row) { + //$queue = $tier_row['queue']; + //$queue = str_replace('@'.$_SESSION['domain_name'], '', $queue); + $agent = $tier_row['agent']; + //$agent = str_replace('@'.$_SESSION['domain_name'], '', $agent); + $tier_state = $tier_row['state']; + $tier_level = $tier_row['level']; + $tier_position = $tier_row['position']; + + foreach ($agent_result as $agent_row) { + if ($tier_row['agent'] == $agent_row['name']) { + $name = $agent_row['name']; + $name = str_replace('@'.$_SESSION['domain_name'], '', $name); + //$system = $agent_row['system']; + $a_uuid = $agent_row['uuid']; + //$type = $agent_row['type']; + $contact = $agent_row['contact']; + $a_exten = preg_replace("/user\//", "", $contact); + $a_exten = preg_replace("/@.*/", "", $a_exten); + $a_exten = preg_replace("/{.*}/", "", $a_exten); + $status = $agent_row['status']; + $state = $agent_row['state']; + $max_no_answer = $agent_row['max_no_answer']; + $wrap_up_time = $agent_row['wrap_up_time']; + $reject_delay_time = $agent_row['reject_delay_time']; + $busy_delay_time = $agent_row['busy_delay_time']; + $last_bridge_start = $agent_row['last_bridge_start']; + $last_bridge_end = $agent_row['last_bridge_end']; + //$last_offered_call = $agent_row['last_offered_call']; + $last_status_change = $agent_row['last_status_change']; + $no_answer_count = $agent_row['no_answer_count']; + $calls_answered = $agent_row['calls_answered']; + $talk_time = $agent_row['talk_time']; + $ready_time = $agent_row['ready_time']; + + $last_offered_call_seconds = time() - $last_offered_call; + $last_offered_call_length_hour = floor($last_offered_call_seconds/3600); + $last_offered_call_length_min = floor($last_offered_call_seconds/60 - ($last_offered_call_length_hour * 60)); + $last_offered_call_length_sec = $last_offered_call_seconds - (($last_offered_call_length_hour * 3600) + ($last_offered_call_length_min * 60)); + $last_offered_call_length_min = sprintf("%02d", $last_offered_call_length_min); + $last_offered_call_length_sec = sprintf("%02d", $last_offered_call_length_sec); + $last_offered_call_length = $last_offered_call_length_hour.':'.$last_offered_call_length_min.':'.$last_offered_call_length_sec; + + $last_status_change_seconds = time() - $last_status_change; + $last_status_change_length_hour = floor($last_status_change_seconds/3600); + $last_status_change_length_min = floor($last_status_change_seconds/60 - ($last_status_change_length_hour * 60)); + $last_status_change_length_sec = $last_status_change_seconds - (($last_status_change_length_hour * 3600) + ($last_status_change_length_min * 60)); + $last_status_change_length_min = sprintf("%02d", $last_status_change_length_min); + $last_status_change_length_sec = sprintf("%02d", $last_status_change_length_sec); + $last_status_change_length = $last_status_change_length_hour.':'.$last_status_change_length_min.':'.$last_status_change_length_sec; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if (permission_exists('call_center_active_options')) { + + echo ""; + } + } + } + echo "\n"; + + if ($c==0) { $c=1; } else { $c=0; } + } + echo "
".$text['label-name']."".$text['label-extension']."".$text['label-status']."".$text['label-state']."".$text['label-status_change']."".$text['label-missed']."".$text['label-answered']."".$text['label-tier_state']."".$text['label-tier_level']."".$text['label-tier_position']."".$text['label-options']."
".$name."".$a_exten."".$status."".$state."".$last_status_change_length."".$no_answer_count."".$calls_answered."".$tier_state."".$tier_level."".$tier_position.""; + + //need to check state to so only waiting gets call, and trying/answer gets eavesdrop + if ($tier_state == "Offering" || $tier_state == "Active Inbound") { + $orig_command="{origination_caller_id_name=eavesdrop,origination_caller_id_number=".$a_exten."}user/".$_SESSION['user']['extension'][0]['user']."@".$_SESSION['domain_name']." %26eavesdrop(".$a_uuid.")"; + + //debug + //echo $orig_command; + //echo " log_cmd \n"; + echo " ".$text['label-eavesdrop']." \n"; + + $xfer_command = $a_uuid." -bleg ".$_SESSION['user']['extension'][0]['user']." XML ".$_SESSION['domain_name']; + //$xfer_command = $a_uuid." ".$_SESSION['user']['extension'][0]['user']." XML default"; + $xfer_command = urlencode($xfer_command); + echo " ".$text['label-transfer']." \n"; + } + else { + $orig_call="{origination_caller_id_name=c2c-".urlencode($name).",origination_caller_id_number=".$a_exten."}user/".$_SESSION['user']['extension'][0]['user']."@".$_SESSION['domain_name']." %26bridge(user/".$a_exten."@".$_SESSION['domain_name'].")"; + echo " ".$text['label-call']." \n"; + } + echo "
\n\n"; + + //add vertical spacing + echo "
"; + echo "
"; + echo "
"; + echo "
"; + + + //get the queue list + //send the event socket command and get the response + //callcenter_config queue list members [queue_name] + $switch_cmd = 'callcenter_config queue list members '.$queue_name; + $event_socket_str = trim(event_socket_request($fp, 'api '.$switch_cmd)); + $result = str_to_named_array($event_socket_str, '|'); + + //show the title + $q_waiting=0; + $q_trying=0; + $q_answered=0; + + echo "\n"; + echo " \n"; + echo " \n"; + echo " "; + echo " \n"; + echo "
".$text['label-queue'].": ".ucfirst($_GET[queue_name])."
\n"; + echo " ".$text['description-queue']."
\n"; + echo "
"; + foreach ($result as $row) { + $state = $row['state']; + $q_trying += ($state == "Trying") ? 1 : 0; + $q_waiting += ($state == "Waiting") ? 1 : 0; + $q_answered += ($state == "Answered") ? 1 : 0; + } + echo " ".$text['label-waiting'].": ".$q_waiting."   "; + echo " ".$text['label-trying'].": ".$q_trying."    "; + echo " ".$text['label-answered'].": ".$q_answered.""; + echo "
\n"; + echo "
\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + //echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + if ((if_group("admin") || if_group("superadmin"))) { + echo "\n"; + } + echo "\n"; + echo "\n"; + + foreach ($result as $row) { + $queue = $row['queue']; + $system = $row['system']; + $uuid = $row['uuid']; + $session_uuid = $row['session_uuid']; + $caller_number = $row['cid_number']; + $caller_name = $row['cid_name']; + $system_epoch = $row['system_epoch']; + $joined_epoch = $row['joined_epoch']; + $rejoined_epoch = $row['rejoined_epoch']; + $bridge_epoch = $row['bridge_epoch']; + $abandoned_epoch = $row['abandoned_epoch']; + $base_score = $row['base_score']; + $skill_score = $row['skill_score']; + $serving_agent = $row['serving_agent']; + $serving_system = $row['serving_system']; + $state = $row['state']; + $joined_seconds = time() - $joined_epoch; + $joined_length_hour = floor($joined_seconds/3600); + $joined_length_min = floor($joined_seconds/60 - ($joined_length_hour * 60)); + $joined_length_sec = $joined_seconds - (($joined_length_hour * 3600) + ($joined_length_min * 60)); + $joined_length_min = sprintf("%02d", $joined_length_min); + $joined_length_sec = sprintf("%02d", $joined_length_sec); + $joined_length = $joined_length_hour.':'.$joined_length_min.':'.$joined_length_sec; + + //$system_seconds = time() - $system_epoch; + //$system_length_hour = floor($system_seconds/3600); + //$system_length_min = floor($system_seconds/60 - ($system_length_hour * 60)); + //$system_length_sec = $system_seconds - (($system_length_hour * 3600) + ($system_length_min * 60)); + //$system_length_min = sprintf("%02d", $system_length_min); + //$system_length_sec = sprintf("%02d", $system_length_sec); + //$system_length = $system_length_hour.':'.$system_length_min.':'.$system_length_sec; + + echo "\n"; + echo "\n"; + //echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + if (if_group("admin") || if_group("superadmin")) { + echo ""; + } + echo "\n"; + echo "\n"; + if ($c==0) { $c=1; } else { $c=0; } + } + echo "
".$text['label-time']."".$text['label-system']."".$text['label-name']."".$text['label-number']."".$text['label-status']."".$text['label-options']."".$text['label-agent']."
".$joined_length."".$system_length."".$caller_name." ".$caller_number." ".$state.""; + if ($state != "Abandoned") { + $q_caller_number = urlencode($caller_number); + $orig_command="{origination_caller_id_name=eavesdrop,origination_caller_id_number=".$q_caller_number."}user/".$_SESSION['user']['extension'][0]['user']."@".$_SESSION['domain_name']." %26eavesdrop(".$session_uuid.")"; + + //debug + //echo $orig_command; + //echo " log_cmd \n"; + + echo " ".$text['label-eavesdrop']." \n"; + } + else { + echo " "; + } + echo "".$serving_agent." 
\n"; + + //add vertical spacing + echo "
\n"; + echo "
\n"; + echo "
\n"; + + + } +?> diff --git a/app/call_center_active/call_center_exec.php b/app/call_center_active/call_center_exec.php index 6134b3472f..6c3d1ba1e8 100644 --- a/app/call_center_active/call_center_exec.php +++ b/app/call_center_active/call_center_exec.php @@ -1,100 +1,100 @@ -0) { - $switch_cmd = trim($_GET["cmd"]); - $action = trim(check_str($_GET["action"])); - $data = trim(check_str($_GET["data"])); - $username = trim(check_str($_GET["username"])); - } - -//authorized commands - if (stristr($switch_cmd, 'user_status') == true) { - //authorized; - } elseif (stristr($switch_cmd, 'callcenter_config') == true) { - //authorized; - } elseif (stristr($switch_cmd, 'eavesdrop') == true) { - //authorized; - } elseif (stristr($switch_cmd, 'bridge') == true) { - //authorized; - } elseif (stristr($switch_cmd, 'uuid_transfer') == true) { - //authorized; - } else { - //not found. this command is not authorized - echo "access denied"; - exit; - } - -//set the username - if (if_group("admin") || if_group("superadmin")) { - //use the username that was provided - } - else { - $username = $_SESSION['username']; - } - -//get to php variables - if (count($_GET)>0) { - if ($action == "user_status") { - $user_status = $data; - $sql = "update v_users set "; - $sql .= "user_status = '".trim($user_status, "'")."' "; - $sql .= "where domain_uuid = '$domain_uuid' "; - $sql .= "and username = '".$username."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - } - - //fs cmd - if (strlen($switch_cmd) > 0) { - //setup the event socket connection - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - //ensure the connection exists - if ($fp) { - //send the command - $switch_result = event_socket_request($fp, '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); - } - } - } - -?> +0) { + $switch_cmd = trim($_GET["cmd"]); + $action = trim(check_str($_GET["action"])); + $data = trim(check_str($_GET["data"])); + $username = trim(check_str($_GET["username"])); + } + +//authorized commands + if (stristr($switch_cmd, 'user_status') == true) { + //authorized; + } elseif (stristr($switch_cmd, 'callcenter_config') == true) { + //authorized; + } elseif (stristr($switch_cmd, 'eavesdrop') == true) { + //authorized; + } elseif (stristr($switch_cmd, 'bridge') == true) { + //authorized; + } elseif (stristr($switch_cmd, 'uuid_transfer') == true) { + //authorized; + } else { + //not found. this command is not authorized + echo "access denied"; + exit; + } + +//set the username + if (if_group("admin") || if_group("superadmin")) { + //use the username that was provided + } + else { + $username = $_SESSION['username']; + } + +//get to php variables + if (count($_GET)>0) { + if ($action == "user_status") { + $user_status = $data; + $sql = "update v_users set "; + $sql .= "user_status = '".trim($user_status, "'")."' "; + $sql .= "where domain_uuid = '$domain_uuid' "; + $sql .= "and username = '".$username."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + } + + //fs cmd + if (strlen($switch_cmd) > 0) { + //setup the event socket connection + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + //ensure the connection exists + if ($fp) { + //send the command + $switch_result = event_socket_request($fp, '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); + } + } + } + +?> diff --git a/app/call_centers/app_defaults.php b/app/call_centers/app_defaults.php index f34a3c0be0..9a9aadea29 100644 --- a/app/call_centers/app_defaults.php +++ b/app/call_centers/app_defaults.php @@ -1,27 +1,27 @@ - - Portions created by the Initial Developer are Copyright (C) 2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - + + Portions created by the Initial Developer are Copyright (C) 2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + ?> \ 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 23723497ed..60293c56a8 100644 --- a/app/call_centers/resources/classes/call_center.php +++ b/app/call_centers/resources/classes/call_center.php @@ -1,224 +1,224 @@ - - Copyright (C) 2015 - All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -/** - * cache class provides an abstracted cache - * - * @method string dialplan - builds the dialplan for call center - */ -//define the call center class - if (!class_exists('call_center')) { - class call_center { - /** - * define the variables - */ - public $domain_uuid; - public $call_center_queue_uuid; - public $dialplan_uuid; - public $queue_name; - public $queue_description; - public $destination_number; - - /** - * Called when the object is created - */ - public function __construct() { - //place holder - } - - /** - * Called when there are no references to a particular object - * unset the variables used in the class - */ - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - /** - * Add a dialplan for call center - * @var string $domain_uuid the multi-tenant id - * @var string $value string to be cached - */ - public function dialplan() { - - //delete previous dialplan - if (strlen($this->dialplan_uuid) > 0) { - //delete the previous dialplan - $sql = "delete from v_dialplans "; - $sql .= "where dialplan_uuid = '".$this->dialplan_uuid."' "; - $sql .= "and domain_uuid = '".$this->domain_uuid."' "; - $this->db->exec($sql); - - $sql = "delete from v_dialplan_details "; - $sql .= "where dialplan_uuid = '".$this->dialplan_uuid."' "; - $sql .= "and domain_uuid = '".$this->domain_uuid."' "; - $this->db->exec($sql); - unset($sql); - } - unset($prep_statement); - - //build the dialplan array - $dialplan["app_uuid"] = "95788e50-9500-079e-2807-fd530b0ea370"; - $dialplan["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_name"] = ($this->queue_name != '') ? $this->queue_name : format_phone($this->destination_number); - $dialplan["dialplan_number"] = $this->destination_number; - $dialplan["dialplan_context"] = $_SESSION['context']; - $dialplan["dialplan_continue"] = "false"; - $dialplan["dialplan_order"] = "210"; - $dialplan["dialplan_enabled"] = "true"; - $dialplan["dialplan_description"] = $this->queue_description; - $dialplan_detail_order = 10; - - //add the public condition - $y = 1; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "condition"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "\${caller_id_name}"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "^([^#]+#)(.*)$"; - $dialplan["dialplan_details"][$y]["dialplan_detail_break"] = "never"; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "caller_id_name=$2"; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "condition"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "destination_number"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "^".$this->destination_number."\$"; - $dialplan["dialplan_details"][$y]["dialplan_detail_break"] = ""; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "answer"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = ""; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "hangup_after_bridge=true"; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - if (strlen($this->queue_cid_prefix) > 0) { - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "effective_caller_id_name=".$this->queue_cid_prefix."#\${caller_id_name}"; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - } - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "callcenter"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = $this->queue_name.'@'.$_SESSION["domain_name"]; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - if (strlen($this->queue_timeout_action) > 0) { - $action_array = explode(":",$this->queue_timeout_action); - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = $action_array[0]; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = substr($this->queue_timeout_action, strlen($action_array[0])+1, strlen($this->queue_timeout_action)); - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - } - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "hangup"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = ""; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - - //add the dialplan permission - $p = new permissions; - $p->add("dialplan_add", 'temp'); - $p->add("dialplan_detail_add", 'temp'); - $p->add("dialplan_edit", 'temp'); - $p->add("dialplan_detail_edit", 'temp'); - - //save the dialplan - $orm = new orm; - $orm->name('dialplans'); - $orm->save($dialplan); - $dialplan_response = $orm->message; - $this->dialplan_uuid = $dialplan_response['uuid']; - - //if new dialplan uuid then update the call center queue - $sql = "update v_call_center_queues "; - $sql .= "set dialplan_uuid = '".$this->dialplan_uuid."' "; - $sql .= "where call_center_queue_uuid = '".$this->call_center_queue_uuid."' "; - $sql .= "and domain_uuid = '".$this->domain_uuid."' "; - $this->db->exec($sql); - unset($sql); - - //remove the temporary permission - $p->delete("dialplan_add", 'temp'); - $p->delete("dialplan_detail_add", 'temp'); - $p->delete("dialplan_edit", 'temp'); - $p->delete("dialplan_detail_edit", 'temp'); - - //synchronize the xml config - save_dialplan_xml(); - - //clear the cache - $cache = new cache; - $cache->delete("dialplan:".$_SESSION['context']); - - //return the dialplan_uuid - return $dialplan_response; - - } - } - } - -/* -$o = new call_center; -$c->domain_uuid = ""; -$c->dialplan_uuid = ""; -$c->queue_name = ""; -$c->queue_cid_prefix = ""; -$c->queue_timeout_action = ""; -$c->queue_description = ""; -$c->destination_number = ""; -$c->dialplan(); -*/ - + + Copyright (C) 2015 + All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +/** + * cache class provides an abstracted cache + * + * @method string dialplan - builds the dialplan for call center + */ +//define the call center class + if (!class_exists('call_center')) { + class call_center { + /** + * define the variables + */ + public $domain_uuid; + public $call_center_queue_uuid; + public $dialplan_uuid; + public $queue_name; + public $queue_description; + public $destination_number; + + /** + * Called when the object is created + */ + public function __construct() { + //place holder + } + + /** + * Called when there are no references to a particular object + * unset the variables used in the class + */ + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + /** + * Add a dialplan for call center + * @var string $domain_uuid the multi-tenant id + * @var string $value string to be cached + */ + public function dialplan() { + + //delete previous dialplan + if (strlen($this->dialplan_uuid) > 0) { + //delete the previous dialplan + $sql = "delete from v_dialplans "; + $sql .= "where dialplan_uuid = '".$this->dialplan_uuid."' "; + $sql .= "and domain_uuid = '".$this->domain_uuid."' "; + $this->db->exec($sql); + + $sql = "delete from v_dialplan_details "; + $sql .= "where dialplan_uuid = '".$this->dialplan_uuid."' "; + $sql .= "and domain_uuid = '".$this->domain_uuid."' "; + $this->db->exec($sql); + unset($sql); + } + unset($prep_statement); + + //build the dialplan array + $dialplan["app_uuid"] = "95788e50-9500-079e-2807-fd530b0ea370"; + $dialplan["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_name"] = ($this->queue_name != '') ? $this->queue_name : format_phone($this->destination_number); + $dialplan["dialplan_number"] = $this->destination_number; + $dialplan["dialplan_context"] = $_SESSION['context']; + $dialplan["dialplan_continue"] = "false"; + $dialplan["dialplan_order"] = "210"; + $dialplan["dialplan_enabled"] = "true"; + $dialplan["dialplan_description"] = $this->queue_description; + $dialplan_detail_order = 10; + + //add the public condition + $y = 1; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "condition"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "\${caller_id_name}"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "^([^#]+#)(.*)$"; + $dialplan["dialplan_details"][$y]["dialplan_detail_break"] = "never"; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "caller_id_name=$2"; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "condition"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "destination_number"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "^".$this->destination_number."\$"; + $dialplan["dialplan_details"][$y]["dialplan_detail_break"] = ""; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "answer"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = ""; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "hangup_after_bridge=true"; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + if (strlen($this->queue_cid_prefix) > 0) { + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "effective_caller_id_name=".$this->queue_cid_prefix."#\${caller_id_name}"; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + } + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "callcenter"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = $this->queue_name.'@'.$_SESSION["domain_name"]; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + if (strlen($this->queue_timeout_action) > 0) { + $action_array = explode(":",$this->queue_timeout_action); + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = $action_array[0]; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = substr($this->queue_timeout_action, strlen($action_array[0])+1, strlen($this->queue_timeout_action)); + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + } + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "hangup"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = ""; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "2"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + + //add the dialplan permission + $p = new permissions; + $p->add("dialplan_add", 'temp'); + $p->add("dialplan_detail_add", 'temp'); + $p->add("dialplan_edit", 'temp'); + $p->add("dialplan_detail_edit", 'temp'); + + //save the dialplan + $orm = new orm; + $orm->name('dialplans'); + $orm->save($dialplan); + $dialplan_response = $orm->message; + $this->dialplan_uuid = $dialplan_response['uuid']; + + //if new dialplan uuid then update the call center queue + $sql = "update v_call_center_queues "; + $sql .= "set dialplan_uuid = '".$this->dialplan_uuid."' "; + $sql .= "where call_center_queue_uuid = '".$this->call_center_queue_uuid."' "; + $sql .= "and domain_uuid = '".$this->domain_uuid."' "; + $this->db->exec($sql); + unset($sql); + + //remove the temporary permission + $p->delete("dialplan_add", 'temp'); + $p->delete("dialplan_detail_add", 'temp'); + $p->delete("dialplan_edit", 'temp'); + $p->delete("dialplan_detail_edit", 'temp'); + + //synchronize the xml config + save_dialplan_xml(); + + //clear the cache + $cache = new cache; + $cache->delete("dialplan:".$_SESSION['context']); + + //return the dialplan_uuid + return $dialplan_response; + + } + } + } + +/* +$o = new call_center; +$c->domain_uuid = ""; +$c->dialplan_uuid = ""; +$c->queue_name = ""; +$c->queue_cid_prefix = ""; +$c->queue_timeout_action = ""; +$c->queue_description = ""; +$c->destination_number = ""; +$c->dialplan(); +*/ + ?> \ No newline at end of file diff --git a/app/calls/app_languages.php b/app/calls/app_languages.php index 776259af03..a1f22aa83a 100644 --- a/app/calls/app_languages.php +++ b/app/calls/app_languages.php @@ -1,475 +1,475 @@ - \ No newline at end of file diff --git a/app/calls/app_menu.php b/app/calls/app_menu.php index 765a8262e3..5c213167ef 100644 --- a/app/calls/app_menu.php +++ b/app/calls/app_menu.php @@ -1,21 +1,21 @@ - \ No newline at end of file diff --git a/app/calls/resources/classes/follow_me.php b/app/calls/resources/classes/follow_me.php index a5bd693380..741514241d 100644 --- a/app/calls/resources/classes/follow_me.php +++ b/app/calls/resources/classes/follow_me.php @@ -1,448 +1,448 @@ - - Copyright (C) 2010 - 2014 - All Rights Reserved. - - Contributor(s): - Mark J Crane - Luis Daniel Lucio Quiroz - Salvatore Caruso - Riccardo Granchi - Errol Samuels -*/ -include "root.php"; - -//define the follow me class - class follow_me { - public $domain_uuid; - public $db_type; - public $follow_me_uuid; - public $cid_name_prefix; - public $cid_number_prefix; - public $accountcode; - public $follow_me_enabled; - public $follow_me_caller_id_uuid; - public $follow_me_ignore_busy; - public $outbound_caller_id_name; - public $outbound_caller_id_number; - private $extension; - private $toll_allow; - - public $destination_data_1; - public $destination_type_1; - public $destination_delay_1; - public $destination_prompt_1; - public $destination_timeout_1; - - public $destination_data_2; - public $destination_type_2; - public $destination_delay_2; - public $destination_prompt_2; - public $destination_timeout_2; - - public $destination_data_3; - public $destination_type_3; - public $destination_delay_3; - public $destination_prompt_3; - public $destination_timeout_3; - - public $destination_data_4; - public $destination_type_4; - public $destination_delay_4; - public $destination_prompt_4; - public $destination_timeout_4; - - public $destination_data_5; - public $destination_type_5; - public $destination_delay_5; - public $destination_prompt_5; - public $destination_timeout_5; - - public $destination_timeout = 0; - public $destination_order = 1; - - public function add() { - //set the global variable - global $db; - - //add a new follow me - $sql = "insert into v_follow_me "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "follow_me_uuid, "; - $sql .= "cid_name_prefix, "; - if (strlen($this->cid_number_prefix) > 0) { - $sql .= "cid_number_prefix, "; - } - $sql .= "follow_me_caller_id_uuid, "; - $sql .= "follow_me_enabled, "; - $sql .= "follow_me_ignore_busy "; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'$this->domain_uuid', "; - $sql .= "'$this->follow_me_uuid', "; - $sql .= "'$this->cid_name_prefix', "; - if (strlen($this->cid_number_prefix) > 0) { - $sql .= "'$this->cid_number_prefix', "; - } - if (strlen($this->follow_me_caller_id_uuid) > 0) { - $sql .= "'$this->follow_me_caller_id_uuid', "; - } - else { - $sql .= 'null, '; - } - $sql .= "'$this->follow_me_enabled', "; - $sql .= "'$this->follow_me_ignore_busy' "; - $sql .= ")"; - if ($v_debug) { - echo $sql."
"; - } - $db->exec(check_sql($sql)); - unset($sql); - $this->follow_me_destinations(); - } //end function - - public function update() { - //set the global variable - global $db; - //update follow me table - $sql = "update v_follow_me set "; - $sql .= "follow_me_enabled = '$this->follow_me_enabled', "; - $sql .= "follow_me_ignore_busy = '$this->follow_me_ignore_busy', "; - $sql .= "cid_name_prefix = '$this->cid_name_prefix', "; - if (strlen($this->follow_me_caller_id_uuid) > 0) { - $sql .= "follow_me_caller_id_uuid = '$this->follow_me_caller_id_uuid', "; - } - else { - $sql .= "follow_me_caller_id_uuid = null, "; - } - $sql .= "cid_number_prefix = '$this->cid_number_prefix' "; - $sql .= "where domain_uuid = '$this->domain_uuid' "; - $sql .= "and follow_me_uuid = '$this->follow_me_uuid' "; - $db->exec(check_sql($sql)); - unset($sql); - $this->follow_me_destinations(); - } //end function - - public function follow_me_destinations() { - //set the global variable - global $db; - - //prepare insert statement - $stmt = $db->prepare( - "insert into v_follow_me_destinations(" - . "follow_me_destination_uuid," - . "domain_uuid," - . "follow_me_uuid," - . "follow_me_destination," - . "follow_me_timeout," - . "follow_me_delay," - . "follow_me_prompt," - . "follow_me_order" - . ")values(?,?,?,?,?,?,?,?)" - ); - - //delete related follow me destinations - $sql = "delete from v_follow_me_destinations where follow_me_uuid = '$this->follow_me_uuid' "; - $db->exec(check_sql($sql)); - - //insert the follow me destinations - if (strlen($this->destination_data_1) > 0) { - $stmt->execute(array( - uuid(), - $this->domain_uuid, - $this->follow_me_uuid, - $this->destination_data_1, - $this->destination_timeout_1, - $this->destination_delay_1, - $this->destination_prompt_1, - '1' - )); - $this->destination_order++; - } - if (strlen($this->destination_data_2) > 0) { - $stmt->execute(array( - uuid(), - $this->domain_uuid, - $this->follow_me_uuid, - $this->destination_data_2, - $this->destination_timeout_2, - $this->destination_delay_2, - $this->destination_prompt_2, - '2' - )); - $this->destination_order++; - } - if (strlen($this->destination_data_3) > 0) { - $stmt->execute(array( - uuid(), - $this->domain_uuid, - $this->follow_me_uuid, - $this->destination_data_3, - $this->destination_timeout_3, - $this->destination_delay_3, - $this->destination_prompt_3, - '3' - )); - $this->destination_order++; - } - if (strlen($this->destination_data_4) > 0) { - $stmt->execute(array( - uuid(), - $this->domain_uuid, - $this->follow_me_uuid, - $this->destination_data_4, - $this->destination_timeout_4, - $this->destination_delay_4, - $this->destination_prompt_4, - '4' - )); - $this->destination_order++; - } - if (strlen($this->destination_data_5) > 0) { - $stmt->execute(array( - uuid(), - $this->domain_uuid, - $this->follow_me_uuid, - $this->destination_data_5, - $this->destination_timeout_5, - $this->destination_delay_5, - $this->destination_prompt_5, - '5' - )); - $this->destination_order++; - } - unset($stmt); - } //function - - public function set() { - //set the global variable - global $db; - - //determine whether to update the dial string - $sql = "select * from v_extensions "; - $sql .= "where domain_uuid = '".$this->domain_uuid."' "; - $sql .= "and extension_uuid = '".$this->extension_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) > 0) { - foreach ($result as &$row) { - $this->extension = $row["extension"]; - $this->accountcode = $row["accountcode"]; - $this->toll_allow = $row["toll_allow"]; - $this->outbound_caller_id_name = $row["outbound_caller_id_name"]; - $this->outbound_caller_id_number = $row["outbound_caller_id_number"]; - } - } - - //determine whether to update the dial string - $sql = "select * from v_follow_me "; - $sql .= "where domain_uuid = '".$this->domain_uuid."' "; - $sql .= "and follow_me_uuid = '".$this->follow_me_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) > 0) { - foreach ($result as &$row) { - $follow_me_uuid = $row["follow_me_uuid"]; - $this->cid_name_prefix = $row["cid_name_prefix"]; - $this->cid_number_prefix = $row["cid_number_prefix"]; - } - } - unset ($prep_statement); - - //add follow me - if (strlen($follow_me_uuid) == 0) { - $this->add(); - } - - //set the extension dial string - $sql = "select * from v_follow_me_destinations "; - $sql .= "where follow_me_uuid = '".$this->follow_me_uuid."' "; - $sql .= "order by follow_me_order asc "; - $prep_statement_2 = $db->prepare(check_sql($sql)); - $prep_statement_2->execute(); - $result = $prep_statement_2->fetchAll(PDO::FETCH_NAMED); - $dial_string = "{"; - if ($this->follow_me_ignore_busy != 'true') { - $dial_string .= "fail_on_single_reject=USER_BUSY,"; - } - $dial_string .= "instant_ringback=true,"; - $dial_string .= "ignore_early_media=true"; - $dial_string .= ",domain_uuid=".$_SESSION['domain_uuid']; - $dial_string .= ",sip_invite_domain=".$_SESSION['domain_name']; - $dial_string .= ",domain_name=".$_SESSION['domain_name']; - $dial_string .= ",domain=".$_SESSION['domain_name']; - $dial_string .= ",extension_uuid=".$this->extension_uuid; - $dial_string .= ",group_confirm_key=exec,group_confirm_file=lua confirm.lua"; - - $dial_string_caller_id_name = "\${caller_id_name}"; - $dial_string_caller_id_number = "\${caller_id_number}"; - - if (strlen($this->follow_me_caller_id_uuid) > 0){ - $sql_caller = "select destination_number, destination_description, destination_caller_id_number, destination_caller_id_name from v_destinations where domain_uuid = '$this->domain_uuid' and destination_type = 'inbound' and destination_uuid = '$this->follow_me_caller_id_uuid'"; - $prep_statement_caller = $db->prepare($sql_caller); - if ($prep_statement_caller) { - $prep_statement_caller->execute(); - $row_caller = $prep_statement_caller->fetch(PDO::FETCH_ASSOC); - - $caller_id_number = $row_caller['destination_caller_id_number']; - if(strlen($caller_id_number) == 0){ - $caller_id_number = $row_caller['destination_number']; - } - $caller_id_name = $row_caller['destination_caller_id_name']; - if(strlen($caller_id_name) == 0){ - $caller_id_name = $row_caller['destination_description']; - } - - if (strlen($caller_id_name) > 0) { - $dial_string_caller_id_name = $caller_id_name; - } - if (strlen($caller_id_number) > 0) { - $dial_string_caller_id_number = $caller_id_number; - } - } - } - - if (strlen($this->cid_name_prefix) > 0) { - $dial_string .= ",origination_caller_id_name=".$this->cid_name_prefix."$dial_string_caller_id_name"; - } - else { - $dial_string .= ",origination_caller_id_name=$dial_string_caller_id_name"; - } - - if (strlen($this->cid_number_prefix) > 0) { - //$dial_string .= ",origination_caller_id_number=".$this->cid_number_prefix.""; - $dial_string .= ",origination_caller_id_number=".$this->cid_number_prefix."$dial_string_caller_id_number"; - } - else { - $dial_string .= ",origination_caller_id_number=$dial_string_caller_id_number"; - } - - if (strlen($this->accountcode) > 0) { - $dial_string .= ",sip_h_X-accountcode=".$this->accountcode; - $dial_string .= ",accountcode=".$this->accountcode; - } - $dial_string .= ",toll_allow='".$this->toll_allow."'"; - $dial_string .= "}"; - $x = 0; - foreach ($result as &$row) { - if ($x > 0) { - $dial_string .= ","; - } - if (extension_exists($row["follow_me_destination"])) { - //set the dial string - if (strlen($_SESSION['domain']['dial_string']['text']) == 0) { - $dial_string .= "["; - $dial_string .= "outbound_caller_id_number=$dial_string_caller_id_number,"; - $dial_string .= "presence_id=".$row["follow_me_destination"]."@".$_SESSION['domain_name'].","; - if ($row["follow_me_prompt"] == "1") { - $dial_string .= "group_confirm_key=exec,group_confirm_file=lua confirm.lua,confirm=true,"; - } - $dial_string .= "leg_delay_start=".$row["follow_me_delay"].","; - $dial_string .= "leg_timeout=".$row["follow_me_timeout"]."]"; - $dial_string .= "\${sofia_contact(".$row["follow_me_destination"]."@".$_SESSION['domain_name'].")}"; - } - else { - $replace_value = $row["follow_me_destination"]; - if ($row["follow_me_prompt"] == "1") { - $replace_value .= "[group_confirm_key=exec,group_confirm_file=lua confirm.lua,confirm=true]"; - } - $local_dial_string = $_SESSION['domain']['dial_string']['text']; - $local_dial_string = str_replace("\${dialed_user}", $replace_value, $local_dial_string); - $local_dial_string = str_replace("\${dialed_domain}", $_SESSION['domain_name'], $local_dial_string); - $local_dial_string = str_replace("\${call_timeout}", $row["follow_me_timeout"], $local_dial_string); - $local_dial_string = str_replace("\${leg_timeout}", $row["follow_me_timeout"], $local_dial_string); - $dial_string .= $local_dial_string; - } - } - else { - $dial_string .= "["; - if ($_SESSION['cdr']['follow_me_fix']['boolean'] == "true"){ - $dial_string .= "outbound_caller_id_name=".$this->outbound_caller_id_name; - $dial_string .= ",outbound_caller_id_number=".$this->outbound_caller_id_number; - $dial_string .= ",origination_caller_id_name=".$this->outbound_caller_id_name; - $dial_string .= ",origination_caller_id_number=".$this->outbound_caller_id_number; - } - else{ - $dial_string .= "outbound_caller_id_number=$dial_string_caller_id_number"; - } - $dial_string .= ",presence_id=".$this->extension."@".$_SESSION['domain_name']; - if ($row["follow_me_prompt"] == "1") { - $dial_string .= ",group_confirm_key=exec,group_confirm_file=lua confirm.lua,confirm=true,"; - } - $dial_string .= ",leg_delay_start=".$row["follow_me_delay"]; - $dial_string .= ",leg_timeout=".$row["follow_me_timeout"]."]"; - if (is_numeric($row["follow_me_destination"])) { - if ($_SESSION['domain']['bridge']['text'] == "outbound" || $_SESSION['domain']['bridge']['text'] == "bridge") { - $bridge = outbound_route_to_bridge ($_SESSION['domain_uuid'], $row["follow_me_destination"]); - $dial_string .= $bridge[0]; - } - elseif ($_SESSION['domain']['bridge']['text'] == "loopback") { - $dial_string .= "loopback/".$row["follow_me_destination"]."/".$_SESSION['domain_name']; - } - elseif ($_SESSION['domain']['bridge']['text'] == "lcr") { - $dial_string .= "lcr/".$_SESSION['lcr']['profile']['text']."/".$_SESSION['domain_name']."/".$row["follow_me_destination"]; - } - else { - $dial_string .= "loopback/".$row["follow_me_destination"]."/".$_SESSION['domain_name']; - } - } - else { - $dial_string .= $row["follow_me_destination"]; - } - } - $x++; - } - $this->dial_string = $dial_string; - - $sql = "update v_follow_me set "; - $sql .= "dial_string = '".$this->dial_string."' "; - $sql .= "where domain_uuid = '".$this->domain_uuid."' "; - $sql .= "and follow_me_uuid = '".$this->follow_me_uuid."' "; - if ($this->debug) { - echo $sql."
"; - } - $db->exec($sql); - unset($sql); - - //is follow me enabled - $dial_string = ''; - if ($this->follow_me_enabled == "true") { - $dial_string = $this->dial_string; - } - - $sql = "update v_extensions set "; - $sql .= "dial_string = '".check_str($dial_string)."', "; - $sql .= "dial_domain = '".$_SESSION['domain_name']."' "; - $sql .= "where domain_uuid = '".$this->domain_uuid."' "; - $sql .= "and follow_me_uuid = '".$this->follow_me_uuid."' "; - if ($this->debug) { - echo $sql."
"; - } - $db->exec($sql); - unset($sql); - - } //function - } //class - -?> + + Copyright (C) 2010 - 2014 + All Rights Reserved. + + Contributor(s): + Mark J Crane + Luis Daniel Lucio Quiroz + Salvatore Caruso + Riccardo Granchi + Errol Samuels +*/ +include "root.php"; + +//define the follow me class + class follow_me { + public $domain_uuid; + public $db_type; + public $follow_me_uuid; + public $cid_name_prefix; + public $cid_number_prefix; + public $accountcode; + public $follow_me_enabled; + public $follow_me_caller_id_uuid; + public $follow_me_ignore_busy; + public $outbound_caller_id_name; + public $outbound_caller_id_number; + private $extension; + private $toll_allow; + + public $destination_data_1; + public $destination_type_1; + public $destination_delay_1; + public $destination_prompt_1; + public $destination_timeout_1; + + public $destination_data_2; + public $destination_type_2; + public $destination_delay_2; + public $destination_prompt_2; + public $destination_timeout_2; + + public $destination_data_3; + public $destination_type_3; + public $destination_delay_3; + public $destination_prompt_3; + public $destination_timeout_3; + + public $destination_data_4; + public $destination_type_4; + public $destination_delay_4; + public $destination_prompt_4; + public $destination_timeout_4; + + public $destination_data_5; + public $destination_type_5; + public $destination_delay_5; + public $destination_prompt_5; + public $destination_timeout_5; + + public $destination_timeout = 0; + public $destination_order = 1; + + public function add() { + //set the global variable + global $db; + + //add a new follow me + $sql = "insert into v_follow_me "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "follow_me_uuid, "; + $sql .= "cid_name_prefix, "; + if (strlen($this->cid_number_prefix) > 0) { + $sql .= "cid_number_prefix, "; + } + $sql .= "follow_me_caller_id_uuid, "; + $sql .= "follow_me_enabled, "; + $sql .= "follow_me_ignore_busy "; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'$this->domain_uuid', "; + $sql .= "'$this->follow_me_uuid', "; + $sql .= "'$this->cid_name_prefix', "; + if (strlen($this->cid_number_prefix) > 0) { + $sql .= "'$this->cid_number_prefix', "; + } + if (strlen($this->follow_me_caller_id_uuid) > 0) { + $sql .= "'$this->follow_me_caller_id_uuid', "; + } + else { + $sql .= 'null, '; + } + $sql .= "'$this->follow_me_enabled', "; + $sql .= "'$this->follow_me_ignore_busy' "; + $sql .= ")"; + if ($v_debug) { + echo $sql."
"; + } + $db->exec(check_sql($sql)); + unset($sql); + $this->follow_me_destinations(); + } //end function + + public function update() { + //set the global variable + global $db; + //update follow me table + $sql = "update v_follow_me set "; + $sql .= "follow_me_enabled = '$this->follow_me_enabled', "; + $sql .= "follow_me_ignore_busy = '$this->follow_me_ignore_busy', "; + $sql .= "cid_name_prefix = '$this->cid_name_prefix', "; + if (strlen($this->follow_me_caller_id_uuid) > 0) { + $sql .= "follow_me_caller_id_uuid = '$this->follow_me_caller_id_uuid', "; + } + else { + $sql .= "follow_me_caller_id_uuid = null, "; + } + $sql .= "cid_number_prefix = '$this->cid_number_prefix' "; + $sql .= "where domain_uuid = '$this->domain_uuid' "; + $sql .= "and follow_me_uuid = '$this->follow_me_uuid' "; + $db->exec(check_sql($sql)); + unset($sql); + $this->follow_me_destinations(); + } //end function + + public function follow_me_destinations() { + //set the global variable + global $db; + + //prepare insert statement + $stmt = $db->prepare( + "insert into v_follow_me_destinations(" + . "follow_me_destination_uuid," + . "domain_uuid," + . "follow_me_uuid," + . "follow_me_destination," + . "follow_me_timeout," + . "follow_me_delay," + . "follow_me_prompt," + . "follow_me_order" + . ")values(?,?,?,?,?,?,?,?)" + ); + + //delete related follow me destinations + $sql = "delete from v_follow_me_destinations where follow_me_uuid = '$this->follow_me_uuid' "; + $db->exec(check_sql($sql)); + + //insert the follow me destinations + if (strlen($this->destination_data_1) > 0) { + $stmt->execute(array( + uuid(), + $this->domain_uuid, + $this->follow_me_uuid, + $this->destination_data_1, + $this->destination_timeout_1, + $this->destination_delay_1, + $this->destination_prompt_1, + '1' + )); + $this->destination_order++; + } + if (strlen($this->destination_data_2) > 0) { + $stmt->execute(array( + uuid(), + $this->domain_uuid, + $this->follow_me_uuid, + $this->destination_data_2, + $this->destination_timeout_2, + $this->destination_delay_2, + $this->destination_prompt_2, + '2' + )); + $this->destination_order++; + } + if (strlen($this->destination_data_3) > 0) { + $stmt->execute(array( + uuid(), + $this->domain_uuid, + $this->follow_me_uuid, + $this->destination_data_3, + $this->destination_timeout_3, + $this->destination_delay_3, + $this->destination_prompt_3, + '3' + )); + $this->destination_order++; + } + if (strlen($this->destination_data_4) > 0) { + $stmt->execute(array( + uuid(), + $this->domain_uuid, + $this->follow_me_uuid, + $this->destination_data_4, + $this->destination_timeout_4, + $this->destination_delay_4, + $this->destination_prompt_4, + '4' + )); + $this->destination_order++; + } + if (strlen($this->destination_data_5) > 0) { + $stmt->execute(array( + uuid(), + $this->domain_uuid, + $this->follow_me_uuid, + $this->destination_data_5, + $this->destination_timeout_5, + $this->destination_delay_5, + $this->destination_prompt_5, + '5' + )); + $this->destination_order++; + } + unset($stmt); + } //function + + public function set() { + //set the global variable + global $db; + + //determine whether to update the dial string + $sql = "select * from v_extensions "; + $sql .= "where domain_uuid = '".$this->domain_uuid."' "; + $sql .= "and extension_uuid = '".$this->extension_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) > 0) { + foreach ($result as &$row) { + $this->extension = $row["extension"]; + $this->accountcode = $row["accountcode"]; + $this->toll_allow = $row["toll_allow"]; + $this->outbound_caller_id_name = $row["outbound_caller_id_name"]; + $this->outbound_caller_id_number = $row["outbound_caller_id_number"]; + } + } + + //determine whether to update the dial string + $sql = "select * from v_follow_me "; + $sql .= "where domain_uuid = '".$this->domain_uuid."' "; + $sql .= "and follow_me_uuid = '".$this->follow_me_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) > 0) { + foreach ($result as &$row) { + $follow_me_uuid = $row["follow_me_uuid"]; + $this->cid_name_prefix = $row["cid_name_prefix"]; + $this->cid_number_prefix = $row["cid_number_prefix"]; + } + } + unset ($prep_statement); + + //add follow me + if (strlen($follow_me_uuid) == 0) { + $this->add(); + } + + //set the extension dial string + $sql = "select * from v_follow_me_destinations "; + $sql .= "where follow_me_uuid = '".$this->follow_me_uuid."' "; + $sql .= "order by follow_me_order asc "; + $prep_statement_2 = $db->prepare(check_sql($sql)); + $prep_statement_2->execute(); + $result = $prep_statement_2->fetchAll(PDO::FETCH_NAMED); + $dial_string = "{"; + if ($this->follow_me_ignore_busy != 'true') { + $dial_string .= "fail_on_single_reject=USER_BUSY,"; + } + $dial_string .= "instant_ringback=true,"; + $dial_string .= "ignore_early_media=true"; + $dial_string .= ",domain_uuid=".$_SESSION['domain_uuid']; + $dial_string .= ",sip_invite_domain=".$_SESSION['domain_name']; + $dial_string .= ",domain_name=".$_SESSION['domain_name']; + $dial_string .= ",domain=".$_SESSION['domain_name']; + $dial_string .= ",extension_uuid=".$this->extension_uuid; + $dial_string .= ",group_confirm_key=exec,group_confirm_file=lua confirm.lua"; + + $dial_string_caller_id_name = "\${caller_id_name}"; + $dial_string_caller_id_number = "\${caller_id_number}"; + + if (strlen($this->follow_me_caller_id_uuid) > 0){ + $sql_caller = "select destination_number, destination_description, destination_caller_id_number, destination_caller_id_name from v_destinations where domain_uuid = '$this->domain_uuid' and destination_type = 'inbound' and destination_uuid = '$this->follow_me_caller_id_uuid'"; + $prep_statement_caller = $db->prepare($sql_caller); + if ($prep_statement_caller) { + $prep_statement_caller->execute(); + $row_caller = $prep_statement_caller->fetch(PDO::FETCH_ASSOC); + + $caller_id_number = $row_caller['destination_caller_id_number']; + if(strlen($caller_id_number) == 0){ + $caller_id_number = $row_caller['destination_number']; + } + $caller_id_name = $row_caller['destination_caller_id_name']; + if(strlen($caller_id_name) == 0){ + $caller_id_name = $row_caller['destination_description']; + } + + if (strlen($caller_id_name) > 0) { + $dial_string_caller_id_name = $caller_id_name; + } + if (strlen($caller_id_number) > 0) { + $dial_string_caller_id_number = $caller_id_number; + } + } + } + + if (strlen($this->cid_name_prefix) > 0) { + $dial_string .= ",origination_caller_id_name=".$this->cid_name_prefix."$dial_string_caller_id_name"; + } + else { + $dial_string .= ",origination_caller_id_name=$dial_string_caller_id_name"; + } + + if (strlen($this->cid_number_prefix) > 0) { + //$dial_string .= ",origination_caller_id_number=".$this->cid_number_prefix.""; + $dial_string .= ",origination_caller_id_number=".$this->cid_number_prefix."$dial_string_caller_id_number"; + } + else { + $dial_string .= ",origination_caller_id_number=$dial_string_caller_id_number"; + } + + if (strlen($this->accountcode) > 0) { + $dial_string .= ",sip_h_X-accountcode=".$this->accountcode; + $dial_string .= ",accountcode=".$this->accountcode; + } + $dial_string .= ",toll_allow='".$this->toll_allow."'"; + $dial_string .= "}"; + $x = 0; + foreach ($result as &$row) { + if ($x > 0) { + $dial_string .= ","; + } + if (extension_exists($row["follow_me_destination"])) { + //set the dial string + if (strlen($_SESSION['domain']['dial_string']['text']) == 0) { + $dial_string .= "["; + $dial_string .= "outbound_caller_id_number=$dial_string_caller_id_number,"; + $dial_string .= "presence_id=".$row["follow_me_destination"]."@".$_SESSION['domain_name'].","; + if ($row["follow_me_prompt"] == "1") { + $dial_string .= "group_confirm_key=exec,group_confirm_file=lua confirm.lua,confirm=true,"; + } + $dial_string .= "leg_delay_start=".$row["follow_me_delay"].","; + $dial_string .= "leg_timeout=".$row["follow_me_timeout"]."]"; + $dial_string .= "\${sofia_contact(".$row["follow_me_destination"]."@".$_SESSION['domain_name'].")}"; + } + else { + $replace_value = $row["follow_me_destination"]; + if ($row["follow_me_prompt"] == "1") { + $replace_value .= "[group_confirm_key=exec,group_confirm_file=lua confirm.lua,confirm=true]"; + } + $local_dial_string = $_SESSION['domain']['dial_string']['text']; + $local_dial_string = str_replace("\${dialed_user}", $replace_value, $local_dial_string); + $local_dial_string = str_replace("\${dialed_domain}", $_SESSION['domain_name'], $local_dial_string); + $local_dial_string = str_replace("\${call_timeout}", $row["follow_me_timeout"], $local_dial_string); + $local_dial_string = str_replace("\${leg_timeout}", $row["follow_me_timeout"], $local_dial_string); + $dial_string .= $local_dial_string; + } + } + else { + $dial_string .= "["; + if ($_SESSION['cdr']['follow_me_fix']['boolean'] == "true"){ + $dial_string .= "outbound_caller_id_name=".$this->outbound_caller_id_name; + $dial_string .= ",outbound_caller_id_number=".$this->outbound_caller_id_number; + $dial_string .= ",origination_caller_id_name=".$this->outbound_caller_id_name; + $dial_string .= ",origination_caller_id_number=".$this->outbound_caller_id_number; + } + else{ + $dial_string .= "outbound_caller_id_number=$dial_string_caller_id_number"; + } + $dial_string .= ",presence_id=".$this->extension."@".$_SESSION['domain_name']; + if ($row["follow_me_prompt"] == "1") { + $dial_string .= ",group_confirm_key=exec,group_confirm_file=lua confirm.lua,confirm=true,"; + } + $dial_string .= ",leg_delay_start=".$row["follow_me_delay"]; + $dial_string .= ",leg_timeout=".$row["follow_me_timeout"]."]"; + if (is_numeric($row["follow_me_destination"])) { + if ($_SESSION['domain']['bridge']['text'] == "outbound" || $_SESSION['domain']['bridge']['text'] == "bridge") { + $bridge = outbound_route_to_bridge ($_SESSION['domain_uuid'], $row["follow_me_destination"]); + $dial_string .= $bridge[0]; + } + elseif ($_SESSION['domain']['bridge']['text'] == "loopback") { + $dial_string .= "loopback/".$row["follow_me_destination"]."/".$_SESSION['domain_name']; + } + elseif ($_SESSION['domain']['bridge']['text'] == "lcr") { + $dial_string .= "lcr/".$_SESSION['lcr']['profile']['text']."/".$_SESSION['domain_name']."/".$row["follow_me_destination"]; + } + else { + $dial_string .= "loopback/".$row["follow_me_destination"]."/".$_SESSION['domain_name']; + } + } + else { + $dial_string .= $row["follow_me_destination"]; + } + } + $x++; + } + $this->dial_string = $dial_string; + + $sql = "update v_follow_me set "; + $sql .= "dial_string = '".$this->dial_string."' "; + $sql .= "where domain_uuid = '".$this->domain_uuid."' "; + $sql .= "and follow_me_uuid = '".$this->follow_me_uuid."' "; + if ($this->debug) { + echo $sql."
"; + } + $db->exec($sql); + unset($sql); + + //is follow me enabled + $dial_string = ''; + if ($this->follow_me_enabled == "true") { + $dial_string = $this->dial_string; + } + + $sql = "update v_extensions set "; + $sql .= "dial_string = '".check_str($dial_string)."', "; + $sql .= "dial_domain = '".$_SESSION['domain_name']."' "; + $sql .= "where domain_uuid = '".$this->domain_uuid."' "; + $sql .= "and follow_me_uuid = '".$this->follow_me_uuid."' "; + if ($this->debug) { + echo $sql."
"; + } + $db->exec($sql); + unset($sql); + + } //function + } //class + +?> diff --git a/app/click_to_call/app_menu.php b/app/click_to_call/app_menu.php index d535063892..a91e5dc13d 100644 --- a/app/click_to_call/app_menu.php +++ b/app/click_to_call/app_menu.php @@ -1,18 +1,18 @@ - \ No newline at end of file diff --git a/app/click_to_call/click_to_call.php b/app/click_to_call/click_to_call.php index 9150f0cb37..b411727faa 100644 --- a/app/click_to_call/click_to_call.php +++ b/app/click_to_call/click_to_call.php @@ -1,377 +1,377 @@ - - James Rose - -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('click_to_call_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//include the header - require_once "resources/header.php"; - -if (is_array($_REQUEST) && !empty($_REQUEST['src']) && !empty($_REQUEST['dest'])) { - //retrieve submitted variables - $src = check_str($_REQUEST['src']); - $src_cid_name = check_str($_REQUEST['src_cid_name']); - $src_cid_number = check_str($_REQUEST['src_cid_number']); - - $dest = check_str($_REQUEST['dest']); - $dest_cid_name = check_str($_REQUEST['dest_cid_name']); - $dest_cid_number = check_str($_REQUEST['dest_cid_number']); - - $auto_answer = check_str($_REQUEST['auto_answer']); //true,false - $rec = check_str($_REQUEST['rec']); //true,false - $ringback = check_str($_REQUEST['ringback']); - $context = $_SESSION['context']; - - //clean up variable values - $src = str_replace(array('.','(',')','-',' '), '', $src); - $dest = (strpbrk($dest, '@') != FALSE) ? str_replace(array('(',')',' '), '', $dest) : str_replace(array('.','(',')','-',' '), '', $dest); //don't strip periods or dashes in sip-uri calls, only phone numbers - - //adjust variable values - $sip_auto_answer = ($auto_answer == "true") ? ",sip_auto_answer=true" : null; - - //mozilla thunderbird TBDialout workaround (seems it can only handle the first %NUM%) - $dest = ($dest == "%NUM%") ? $src_cid_number : $dest; - - //translate ringback - switch ($ringback) { - case "music": $ringback_value = "\'local_stream://moh\'"; break; - case "uk-ring": $ringback_value = "\'%(400,200,400,450);%(400,2200,400,450)\'"; break; - case "fr-ring": $ringback_value = "\'%(1500,3500,440.0,0.0)\'"; break; - case "pt-ring": $ringback_value = "\'%(1000,5000,400.0,0.0)\'"; break; - case "rs-ring": $ringback_value = "\'%(1000,4000,425.0,0.0)\'"; break; - case "it-ring": $ringback_value = "\'%(1000,4000,425.0,0.0)\'"; break; - case "us-ring": - default: - $ringback = 'us-ring'; - $ringback_value = "\'%(2000,4000,440.0,480.0)\'"; - } - - //determine call direction - $dir = (strlen($dest) < 7) ? 'local' : 'outbound'; - - //define a leg - set source to display the defined caller id name and number - $source_common = "{". - "click_to_call=true". - ",origination_caller_id_name='".$src_cid_name."'". - ",origination_caller_id_number=".$src_cid_number. - ",instant_ringback=true". - ",ringback=".$ringback_value. - ",presence_id=".$src."@".$_SESSION['domains'][$domain_uuid]['domain_name']. - ",call_direction=".$dir; - if (strlen($src) < 7) { - //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 (strlen($dest) < 7) { - //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 (strlen($src) < 7 && strlen($dest_cid_number) == 0) { - //retrieve outbound caller id from the (source) extension - $sql = "select outbound_caller_id_name, outbound_caller_id_number from v_extensions where domain_uuid = '".$_SESSION['domain_uuid']."' and extension = '".$src."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - 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 - } - unset ($prep_statement); - } - 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); - - //create the even socket connection and send the event socket command - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if (!$fp) { - //error message - echo "
Connection to Event Socket failed.
"; - } - else { - //display the last command - $switch_cmd = "api originate ".$source.$switch_cmd; - echo "
".$switch_cmd."

".$src." has called ".$dest."
\n"; - //show the command result - $result = trim(event_socket_request($fp, $switch_cmd)); - if (substr($result, 0,3) == "+OK") { - $uuid = substr($result, 4); - if ($rec == "true") { - //use the server's time zone to ensure it matches the time zone used by freeswitch - date_default_timezone_set($_SESSION['time_zone']['system']); - //create the api record command and send it over event socket - $switch_cmd = "api uuid_record ".$uuid." start ".$_SESSION['switch']['recordings']['dir']."/".$_SESSION['domain_name']."/archive/".date("Y")."/".date("M")."/".date("d")."/".$uuid.".wav"; - $result2 = trim(event_socket_request($fp, $switch_cmd)); - } - } - echo "

".$result."

\n"; - } -} - -//show html form - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " \n"; - echo " ".$text['label-click2call']."\n"; - echo " \n"; - echo " \n"; - echo "  \n"; - echo "
\n"; - echo " \n"; - echo " ".$text['desc-click2call']."\n"; - echo " \n"; - echo "
"; - - echo "
"; - - echo "
\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - - echo" \n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo " \n"; - echo "\n"; - echo "
".$text['label-src-caller-id-nam']."\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['desc-src-caller-id-nam']."\n"; - echo "
".$text['label-src-caller-id-num']."\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['desc-src-caller-id-num']."\n"; - echo "
".$text['label-dest-caller-id-nam']."\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['desc-dest-caller-id-nam']."\n"; - echo "
".$text['label-dest-caller-id-num']."\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['desc-dest-caller-id-num']."\n"; - echo "
".$text['label-src-num']."\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['desc-src-num']."\n"; - echo "
".$text['label-dest-num']."\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['desc-dest-num']."\n"; - echo "
\n"; - echo " ".$text['label-auto-answer']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['desc-auto-answer']."\n"; - echo "
\n"; - echo " ".$text['label-record']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['desc-record']."\n"; - echo "
\n"; - echo " ".$text['label-ringback']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['desc-ringback']."\n"; - echo "
\n"; - echo "
"; - echo " \n"; - echo "
\n"; - echo "

"; - echo "
"; - -//show the footer - require_once "resources/footer.php"; -?> + + James Rose + +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('click_to_call_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//include the header + require_once "resources/header.php"; + +if (is_array($_REQUEST) && !empty($_REQUEST['src']) && !empty($_REQUEST['dest'])) { + //retrieve submitted variables + $src = check_str($_REQUEST['src']); + $src_cid_name = check_str($_REQUEST['src_cid_name']); + $src_cid_number = check_str($_REQUEST['src_cid_number']); + + $dest = check_str($_REQUEST['dest']); + $dest_cid_name = check_str($_REQUEST['dest_cid_name']); + $dest_cid_number = check_str($_REQUEST['dest_cid_number']); + + $auto_answer = check_str($_REQUEST['auto_answer']); //true,false + $rec = check_str($_REQUEST['rec']); //true,false + $ringback = check_str($_REQUEST['ringback']); + $context = $_SESSION['context']; + + //clean up variable values + $src = str_replace(array('.','(',')','-',' '), '', $src); + $dest = (strpbrk($dest, '@') != FALSE) ? str_replace(array('(',')',' '), '', $dest) : str_replace(array('.','(',')','-',' '), '', $dest); //don't strip periods or dashes in sip-uri calls, only phone numbers + + //adjust variable values + $sip_auto_answer = ($auto_answer == "true") ? ",sip_auto_answer=true" : null; + + //mozilla thunderbird TBDialout workaround (seems it can only handle the first %NUM%) + $dest = ($dest == "%NUM%") ? $src_cid_number : $dest; + + //translate ringback + switch ($ringback) { + case "music": $ringback_value = "\'local_stream://moh\'"; break; + case "uk-ring": $ringback_value = "\'%(400,200,400,450);%(400,2200,400,450)\'"; break; + case "fr-ring": $ringback_value = "\'%(1500,3500,440.0,0.0)\'"; break; + case "pt-ring": $ringback_value = "\'%(1000,5000,400.0,0.0)\'"; break; + case "rs-ring": $ringback_value = "\'%(1000,4000,425.0,0.0)\'"; break; + case "it-ring": $ringback_value = "\'%(1000,4000,425.0,0.0)\'"; break; + case "us-ring": + default: + $ringback = 'us-ring'; + $ringback_value = "\'%(2000,4000,440.0,480.0)\'"; + } + + //determine call direction + $dir = (strlen($dest) < 7) ? 'local' : 'outbound'; + + //define a leg - set source to display the defined caller id name and number + $source_common = "{". + "click_to_call=true". + ",origination_caller_id_name='".$src_cid_name."'". + ",origination_caller_id_number=".$src_cid_number. + ",instant_ringback=true". + ",ringback=".$ringback_value. + ",presence_id=".$src."@".$_SESSION['domains'][$domain_uuid]['domain_name']. + ",call_direction=".$dir; + if (strlen($src) < 7) { + //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 (strlen($dest) < 7) { + //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 (strlen($src) < 7 && strlen($dest_cid_number) == 0) { + //retrieve outbound caller id from the (source) extension + $sql = "select outbound_caller_id_name, outbound_caller_id_number from v_extensions where domain_uuid = '".$_SESSION['domain_uuid']."' and extension = '".$src."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + 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 + } + unset ($prep_statement); + } + 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); + + //create the even socket connection and send the event socket command + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if (!$fp) { + //error message + echo "
Connection to Event Socket failed.
"; + } + else { + //display the last command + $switch_cmd = "api originate ".$source.$switch_cmd; + echo "
".$switch_cmd."

".$src." has called ".$dest."
\n"; + //show the command result + $result = trim(event_socket_request($fp, $switch_cmd)); + if (substr($result, 0,3) == "+OK") { + $uuid = substr($result, 4); + if ($rec == "true") { + //use the server's time zone to ensure it matches the time zone used by freeswitch + date_default_timezone_set($_SESSION['time_zone']['system']); + //create the api record command and send it over event socket + $switch_cmd = "api uuid_record ".$uuid." start ".$_SESSION['switch']['recordings']['dir']."/".$_SESSION['domain_name']."/archive/".date("Y")."/".date("M")."/".date("d")."/".$uuid.".wav"; + $result2 = trim(event_socket_request($fp, $switch_cmd)); + } + } + echo "

".$result."

\n"; + } +} + +//show html form + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " \n"; + echo " ".$text['label-click2call']."\n"; + echo " \n"; + echo " \n"; + echo "  \n"; + echo "
\n"; + echo " \n"; + echo " ".$text['desc-click2call']."\n"; + echo " \n"; + echo "
"; + + echo "
"; + + echo "
\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + + echo" \n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo " \n"; + echo "\n"; + echo "
".$text['label-src-caller-id-nam']."\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['desc-src-caller-id-nam']."\n"; + echo "
".$text['label-src-caller-id-num']."\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['desc-src-caller-id-num']."\n"; + echo "
".$text['label-dest-caller-id-nam']."\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['desc-dest-caller-id-nam']."\n"; + echo "
".$text['label-dest-caller-id-num']."\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['desc-dest-caller-id-num']."\n"; + echo "
".$text['label-src-num']."\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['desc-src-num']."\n"; + echo "
".$text['label-dest-num']."\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['desc-dest-num']."\n"; + echo "
\n"; + echo " ".$text['label-auto-answer']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['desc-auto-answer']."\n"; + echo "
\n"; + echo " ".$text['label-record']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['desc-record']."\n"; + echo "
\n"; + echo " ".$text['label-ringback']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['desc-ringback']."\n"; + echo "
\n"; + echo "
"; + echo " \n"; + echo "
\n"; + echo "

"; + echo "
"; + +//show the footer + require_once "resources/footer.php"; +?> diff --git a/app/conferences/app_menu.php b/app/conferences/app_menu.php index 022999190f..7ac4e3842d 100644 --- a/app/conferences/app_menu.php +++ b/app/conferences/app_menu.php @@ -1,21 +1,21 @@ - \ No newline at end of file diff --git a/app/contacts/app_defaults.php b/app/contacts/app_defaults.php index 5a03ed8ea4..16d0eb5fcd 100644 --- a/app/contacts/app_defaults.php +++ b/app/contacts/app_defaults.php @@ -1,219 +1,219 @@ -db = $db; - $obj->db_type = $db_type; - $obj->schema(); - $field_exists = $obj->column_exists($db_name, 'v_contact_phones', 'phone_type'); //check if field exists - if ($field_exists) { - //add multi-lingual support - $language = new text; - $text = $language->get(); - - // populate phone_type_* values - $sql = "update v_contact_phones set phone_type_voice = '1' "; - $sql .= "where phone_type = 'home' "; - $sql .= "or phone_type = 'work' "; - $sql .= "or phone_type = 'voice' "; - $sql .= "or phone_type = 'voicemail' "; - $sql .= "or phone_type = 'cell' "; - $sql .= "or phone_type = 'pcs' "; - $db->exec(check_sql($sql)); - unset($sql); - - $sql = "update v_contact_phones set phone_type_fax = '1' where phone_type = 'fax'"; - $db->exec(check_sql($sql)); - unset($sql); - - $sql = "update v_contact_phones set phone_type_video = '1' where phone_type = 'video'"; - $db->exec(check_sql($sql)); - unset($sql); - - $sql = "update v_contact_phones set phone_type_text = '1' where phone_type = 'cell' or phone_type = 'pager'"; - $db->exec(check_sql($sql)); - unset($sql); - - // migrate phone_type values to phone_label, correct case and make multilingual where appropriate - $default_phone_types = array('home','work','pref','voice','fax','msg','cell','pager','modem','car','isdn','video','pcs'); - $default_phone_labels = array($text['option-home'],$text['option-work'],'Pref','Voice',$text['option-fax'],$text['option-voicemail'],$text['option-mobile'],$text['option-pager'],'Modem','Car','ISDN','Video','PCS'); - foreach ($default_phone_types as $index => $old) { - $new = $default_phone_labels[$index]; - $sql = "update v_contact_phones set phone_label = '".$new."' where phone_type = '".$old."'"; - $db->exec(check_sql($sql)); - unset($sql); - } - - // empty phone_type field to prevent confusion in the future - $sql = "update v_contact_phones set phone_type = null"; - $db->exec(check_sql($sql)); - unset($sql); - } - unset($obj); - - //populate primary email from deprecated field in v_contact table - $obj = new schema; - $obj->db = $db; - $obj->db_type = $db_type; - $obj->schema(); - $field_exists = $obj->column_exists($db_name, 'v_contacts', 'contact_email'); //check if field exists - if ($field_exists) { - // get email records - $sql = "select * from v_contacts where contact_email is not null and contact_email != ''"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - unset ($prep_statement, $sql); - if ($result_count > 0) { - foreach($result as $row) { - $sql = "insert into v_contact_emails "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "contact_email_uuid, "; - $sql .= "email_primary, "; - $sql .= "email_address"; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$row['domain_uuid']."', "; - $sql .= "'".$row['contact_uuid']."', "; - $sql .= "'".uuid()."', "; - $sql .= "1, "; - $sql .= "'".$row['contact_email']."' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - - //verify and remove value from old field - $sql2 = "select email_address from v_contact_emails "; - $sql2 .= "where domain_uuid = '".$row['domain_uuid']."' "; - $sql2 .= "and contact_uuid = '".$row['contact_uuid']."' "; - $sql2 .= "and email_address = '".$row['contact_email']."' "; - $prep_statement2 = $db->prepare(check_sql($sql2)); - $prep_statement2->execute(); - $result2 = $prep_statement2->fetchAll(PDO::FETCH_NAMED); - $result_count2 = count($result2); - if ($result_count2 > 0) { - $sql3 = "update v_contacts set contact_email = '' "; - $sql3 .= "where domain_uuid = '".$row['domain_uuid']."' "; - $sql3 .= "and contact_uuid = '".$row['contact_uuid']."' "; - $prep_statement3 = $db->prepare(check_sql($sql3)); - $prep_statement3->execute(); - unset($sql3, $prep_statement3); - } - unset($sql2, $result2, $prep_statement2); - } - } - } - unset($obj); - - //populate primary url from deprecated field in v_contact table - $obj = new schema; - $obj->db = $db; - $obj->db_type = $db_type; - $obj->schema(); - $field_exists = $obj->column_exists($db_name, 'v_contacts', 'contact_url'); //check if field exists - if ($field_exists) { - // get email records - $sql = "select * from v_contacts where contact_url is not null and contact_url != ''"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - unset ($prep_statement, $sql); - if ($result_count > 0) { - foreach($result as $row) { - $sql = "insert into v_contact_urls "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "contact_url_uuid, "; - $sql .= "url_primary, "; - $sql .= "url_address"; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$row['domain_uuid']."', "; - $sql .= "'".$row['contact_uuid']."', "; - $sql .= "'".uuid()."', "; - $sql .= "1, "; - $sql .= "'".$row['contact_url']."' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - - //verify and remove value from old field - $sql2 = "select url_address from v_contact_urls "; - $sql2 .= "where domain_uuid = '".$row['domain_uuid']."' "; - $sql2 .= "and contact_uuid = '".$row['contact_uuid']."' "; - $sql2 .= "and url_address = '".$row['contact_url']."' "; - $prep_statement2 = $db->prepare(check_sql($sql2)); - $prep_statement2->execute(); - $result2 = $prep_statement2->fetchAll(PDO::FETCH_NAMED); - $result_count2 = count($result2); - if ($result_count2 > 0) { - $sql3 = "update v_contacts set contact_url = '' "; - $sql3 .= "where domain_uuid = '".$row['domain_uuid']."' "; - $sql3 .= "and contact_uuid = '".$row['contact_uuid']."' "; - $prep_statement3 = $db->prepare(check_sql($sql3)); - $prep_statement3->execute(); - unset($sql3, $prep_statement3); - } - unset($sql2, $result2, $prep_statement2); - } - } - } - unset($obj); - - //set [name]_primary fields to 0 where null - $name_tables = array('phones','addresses','emails','urls'); - $name_fields = array('phone','address','email','url'); - foreach ($name_tables as $name_index => $name_table) { - $sql = "update v_contact_".$name_table." set ".$name_fields[$name_index]."_primary = 0 "; - $sql .= "where ".$name_fields[$name_index]."_primary is null "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - unset($sql, $prep_statement); - } - unset($name_tables, $name_fields); - - //move the users from the contact groups table into the contact users table - $sql = "select * from v_contact_groups "; - $sql .= "where group_uuid in (select user_uuid from v_users) "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $sql = "insert into v_contact_users "; - $sql .= "( "; - $sql .= "contact_user_uuid, "; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "user_uuid "; - $sql .= ") "; - $sql .= "values "; - $sql .= "( "; - $sql .= "'".uuid()."', "; - $sql .= "'".$row["domain_uuid"]."', "; - $sql .= "'".$row["contact_uuid"]."', "; - $sql .= "'".$row["group_uuid"]."' "; - $sql .= ");"; - //echo $sql."\n"; - $db->exec($sql); - unset($sql); - - $sql = "delete from v_contact_groups "; - $sql .= "where contact_group_uuid = '".$row["contact_group_uuid"]."';"; - //echo $sql."\n"; - $db->exec($sql); - unset($sql); - } - unset ($prep_statement); - -} - +db = $db; + $obj->db_type = $db_type; + $obj->schema(); + $field_exists = $obj->column_exists($db_name, 'v_contact_phones', 'phone_type'); //check if field exists + if ($field_exists) { + //add multi-lingual support + $language = new text; + $text = $language->get(); + + // populate phone_type_* values + $sql = "update v_contact_phones set phone_type_voice = '1' "; + $sql .= "where phone_type = 'home' "; + $sql .= "or phone_type = 'work' "; + $sql .= "or phone_type = 'voice' "; + $sql .= "or phone_type = 'voicemail' "; + $sql .= "or phone_type = 'cell' "; + $sql .= "or phone_type = 'pcs' "; + $db->exec(check_sql($sql)); + unset($sql); + + $sql = "update v_contact_phones set phone_type_fax = '1' where phone_type = 'fax'"; + $db->exec(check_sql($sql)); + unset($sql); + + $sql = "update v_contact_phones set phone_type_video = '1' where phone_type = 'video'"; + $db->exec(check_sql($sql)); + unset($sql); + + $sql = "update v_contact_phones set phone_type_text = '1' where phone_type = 'cell' or phone_type = 'pager'"; + $db->exec(check_sql($sql)); + unset($sql); + + // migrate phone_type values to phone_label, correct case and make multilingual where appropriate + $default_phone_types = array('home','work','pref','voice','fax','msg','cell','pager','modem','car','isdn','video','pcs'); + $default_phone_labels = array($text['option-home'],$text['option-work'],'Pref','Voice',$text['option-fax'],$text['option-voicemail'],$text['option-mobile'],$text['option-pager'],'Modem','Car','ISDN','Video','PCS'); + foreach ($default_phone_types as $index => $old) { + $new = $default_phone_labels[$index]; + $sql = "update v_contact_phones set phone_label = '".$new."' where phone_type = '".$old."'"; + $db->exec(check_sql($sql)); + unset($sql); + } + + // empty phone_type field to prevent confusion in the future + $sql = "update v_contact_phones set phone_type = null"; + $db->exec(check_sql($sql)); + unset($sql); + } + unset($obj); + + //populate primary email from deprecated field in v_contact table + $obj = new schema; + $obj->db = $db; + $obj->db_type = $db_type; + $obj->schema(); + $field_exists = $obj->column_exists($db_name, 'v_contacts', 'contact_email'); //check if field exists + if ($field_exists) { + // get email records + $sql = "select * from v_contacts where contact_email is not null and contact_email != ''"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + unset ($prep_statement, $sql); + if ($result_count > 0) { + foreach($result as $row) { + $sql = "insert into v_contact_emails "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "contact_email_uuid, "; + $sql .= "email_primary, "; + $sql .= "email_address"; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$row['domain_uuid']."', "; + $sql .= "'".$row['contact_uuid']."', "; + $sql .= "'".uuid()."', "; + $sql .= "1, "; + $sql .= "'".$row['contact_email']."' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + + //verify and remove value from old field + $sql2 = "select email_address from v_contact_emails "; + $sql2 .= "where domain_uuid = '".$row['domain_uuid']."' "; + $sql2 .= "and contact_uuid = '".$row['contact_uuid']."' "; + $sql2 .= "and email_address = '".$row['contact_email']."' "; + $prep_statement2 = $db->prepare(check_sql($sql2)); + $prep_statement2->execute(); + $result2 = $prep_statement2->fetchAll(PDO::FETCH_NAMED); + $result_count2 = count($result2); + if ($result_count2 > 0) { + $sql3 = "update v_contacts set contact_email = '' "; + $sql3 .= "where domain_uuid = '".$row['domain_uuid']."' "; + $sql3 .= "and contact_uuid = '".$row['contact_uuid']."' "; + $prep_statement3 = $db->prepare(check_sql($sql3)); + $prep_statement3->execute(); + unset($sql3, $prep_statement3); + } + unset($sql2, $result2, $prep_statement2); + } + } + } + unset($obj); + + //populate primary url from deprecated field in v_contact table + $obj = new schema; + $obj->db = $db; + $obj->db_type = $db_type; + $obj->schema(); + $field_exists = $obj->column_exists($db_name, 'v_contacts', 'contact_url'); //check if field exists + if ($field_exists) { + // get email records + $sql = "select * from v_contacts where contact_url is not null and contact_url != ''"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + unset ($prep_statement, $sql); + if ($result_count > 0) { + foreach($result as $row) { + $sql = "insert into v_contact_urls "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "contact_url_uuid, "; + $sql .= "url_primary, "; + $sql .= "url_address"; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$row['domain_uuid']."', "; + $sql .= "'".$row['contact_uuid']."', "; + $sql .= "'".uuid()."', "; + $sql .= "1, "; + $sql .= "'".$row['contact_url']."' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + + //verify and remove value from old field + $sql2 = "select url_address from v_contact_urls "; + $sql2 .= "where domain_uuid = '".$row['domain_uuid']."' "; + $sql2 .= "and contact_uuid = '".$row['contact_uuid']."' "; + $sql2 .= "and url_address = '".$row['contact_url']."' "; + $prep_statement2 = $db->prepare(check_sql($sql2)); + $prep_statement2->execute(); + $result2 = $prep_statement2->fetchAll(PDO::FETCH_NAMED); + $result_count2 = count($result2); + if ($result_count2 > 0) { + $sql3 = "update v_contacts set contact_url = '' "; + $sql3 .= "where domain_uuid = '".$row['domain_uuid']."' "; + $sql3 .= "and contact_uuid = '".$row['contact_uuid']."' "; + $prep_statement3 = $db->prepare(check_sql($sql3)); + $prep_statement3->execute(); + unset($sql3, $prep_statement3); + } + unset($sql2, $result2, $prep_statement2); + } + } + } + unset($obj); + + //set [name]_primary fields to 0 where null + $name_tables = array('phones','addresses','emails','urls'); + $name_fields = array('phone','address','email','url'); + foreach ($name_tables as $name_index => $name_table) { + $sql = "update v_contact_".$name_table." set ".$name_fields[$name_index]."_primary = 0 "; + $sql .= "where ".$name_fields[$name_index]."_primary is null "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + unset($sql, $prep_statement); + } + unset($name_tables, $name_fields); + + //move the users from the contact groups table into the contact users table + $sql = "select * from v_contact_groups "; + $sql .= "where group_uuid in (select user_uuid from v_users) "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $sql = "insert into v_contact_users "; + $sql .= "( "; + $sql .= "contact_user_uuid, "; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "user_uuid "; + $sql .= ") "; + $sql .= "values "; + $sql .= "( "; + $sql .= "'".uuid()."', "; + $sql .= "'".$row["domain_uuid"]."', "; + $sql .= "'".$row["contact_uuid"]."', "; + $sql .= "'".$row["group_uuid"]."' "; + $sql .= ");"; + //echo $sql."\n"; + $db->exec($sql); + unset($sql); + + $sql = "delete from v_contact_groups "; + $sql .= "where contact_group_uuid = '".$row["contact_group_uuid"]."';"; + //echo $sql."\n"; + $db->exec($sql); + unset($sql); + } + unset ($prep_statement); + +} + ?> \ No newline at end of file diff --git a/app/contacts/contact_auth.php b/app/contacts/contact_auth.php index e07d2bf177..d2410d12a6 100644 --- a/app/contacts/contact_auth.php +++ b/app/contacts/contact_auth.php @@ -1,122 +1,122 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2013 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('contact_add')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -/* -echo "bang!"; -exit; -*/ - -//add multi-lingual support - $language = new text; - $text = $language->get(); - - -$_SESSION['contact_auth']['source'] = ($_SESSION['contact_auth']['source'] == '') ? $_REQUEST['source'] : $_SESSION['contact_auth']['source']; -$_SESSION['contact_auth']['target'] = ($_SESSION['contact_auth']['target'] == '') ? $_REQUEST['target'] : $_SESSION['contact_auth']['target']; - - -//google api authentication -if ($_SESSION['contact_auth']['source'] == 'google') { - - if ($_REQUEST['error']) { - $_SESSION['message'] = ($text['message-'.$_REQUEST['error']] != '') ? $text['message-'.$_REQUEST['error']] : $_REQUEST['error']; - $_SESSION['message_mood'] = 'negative'; - header("Location: ".$_SESSION['contact_auth']['referer']); - unset($_SESSION['contact_auth']); - exit; - } - - if (isset($_REQUEST['signout'])) { - unset($_SESSION['contact_auth']['token']); - $_SESSION['message'] = $text['message-google_signed_out']; - header("Location: https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=".(($_SERVER["HTTPS"] == "on") ? "https" : "http")."://".$_SERVER['HTTP_HOST'].PROJECT_PATH."/app/contacts/".$_SESSION['contact_auth']['referer']); - exit; - } - - if ($_GET['code'] == '') { - header("Location: https://accounts.google.com/o/oauth2/auth?client_id=".$_SESSION['contact']['google_oauth_client_id']['text']."&redirect_uri=".(($_SERVER["HTTPS"] == "on") ? "https" : "http")."://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."&scope=https://www.google.com/m8/feeds/&response_type=code"); - exit; - } - else { - $auth_code = $_GET["code"]; - } - - /*******************************************************************************************/ - // request access token - - $fields = array( - 'code' => urlencode($auth_code), - 'client_id' => urlencode($_SESSION['contact']['google_oauth_client_id']['text']), - 'client_secret' => urlencode($_SESSION['contact']['google_oauth_client_secret']['text']), - 'redirect_uri' => urlencode((($_SERVER["HTTPS"] == "on") ? "https" : "http")."://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']), - 'grant_type' => urlencode('authorization_code') - ); - - foreach($fields as $key => $value) { - $post_fields[] = $key.'='.$value; - } - $post_fields = implode("&", $post_fields); - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token'); - curl_setopt($curl, CURLOPT_POST, 5); - curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); - $result = curl_exec($curl); - curl_close($curl); - - $response = json_decode($result); - $access_token = $response->access_token; - - if ($access_token != '') { - // redirect to target script - $_SESSION['contact_auth']['token'] = $access_token; - header("Location: ".$_SESSION['contact_auth']['target']); - exit; - } - -} -else { - - $_SESSION['message'] = $text['message-access_denied']; - $_SESSION['message_mood'] = 'negative'; - header("Location: ".$_SESSION['contact_auth']['referer']); - unset($_SESSION['contact_auth']); - exit; - -} + + Portions created by the Initial Developer are Copyright (C) 2008-2013 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('contact_add')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +/* +echo "bang!"; +exit; +*/ + +//add multi-lingual support + $language = new text; + $text = $language->get(); + + +$_SESSION['contact_auth']['source'] = ($_SESSION['contact_auth']['source'] == '') ? $_REQUEST['source'] : $_SESSION['contact_auth']['source']; +$_SESSION['contact_auth']['target'] = ($_SESSION['contact_auth']['target'] == '') ? $_REQUEST['target'] : $_SESSION['contact_auth']['target']; + + +//google api authentication +if ($_SESSION['contact_auth']['source'] == 'google') { + + if ($_REQUEST['error']) { + $_SESSION['message'] = ($text['message-'.$_REQUEST['error']] != '') ? $text['message-'.$_REQUEST['error']] : $_REQUEST['error']; + $_SESSION['message_mood'] = 'negative'; + header("Location: ".$_SESSION['contact_auth']['referer']); + unset($_SESSION['contact_auth']); + exit; + } + + if (isset($_REQUEST['signout'])) { + unset($_SESSION['contact_auth']['token']); + $_SESSION['message'] = $text['message-google_signed_out']; + header("Location: https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=".(($_SERVER["HTTPS"] == "on") ? "https" : "http")."://".$_SERVER['HTTP_HOST'].PROJECT_PATH."/app/contacts/".$_SESSION['contact_auth']['referer']); + exit; + } + + if ($_GET['code'] == '') { + header("Location: https://accounts.google.com/o/oauth2/auth?client_id=".$_SESSION['contact']['google_oauth_client_id']['text']."&redirect_uri=".(($_SERVER["HTTPS"] == "on") ? "https" : "http")."://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']."&scope=https://www.google.com/m8/feeds/&response_type=code"); + exit; + } + else { + $auth_code = $_GET["code"]; + } + + /*******************************************************************************************/ + // request access token + + $fields = array( + 'code' => urlencode($auth_code), + 'client_id' => urlencode($_SESSION['contact']['google_oauth_client_id']['text']), + 'client_secret' => urlencode($_SESSION['contact']['google_oauth_client_secret']['text']), + 'redirect_uri' => urlencode((($_SERVER["HTTPS"] == "on") ? "https" : "http")."://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']), + 'grant_type' => urlencode('authorization_code') + ); + + foreach($fields as $key => $value) { + $post_fields[] = $key.'='.$value; + } + $post_fields = implode("&", $post_fields); + + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token'); + curl_setopt($curl, CURLOPT_POST, 5); + curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); + $result = curl_exec($curl); + curl_close($curl); + + $response = json_decode($result); + $access_token = $response->access_token; + + if ($access_token != '') { + // redirect to target script + $_SESSION['contact_auth']['token'] = $access_token; + header("Location: ".$_SESSION['contact_auth']['target']); + exit; + } + +} +else { + + $_SESSION['message'] = $text['message-access_denied']; + $_SESSION['message_mood'] = 'negative'; + header("Location: ".$_SESSION['contact_auth']['referer']); + unset($_SESSION['contact_auth']); + exit; + +} ?> \ No newline at end of file diff --git a/app/contacts/contact_import_google.php b/app/contacts/contact_import_google.php index 6a5f9ce7ab..23f2c44e29 100644 --- a/app/contacts/contact_import_google.php +++ b/app/contacts/contact_import_google.php @@ -1,677 +1,677 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2013 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -require_once "resources/functions/google_get_groups.php"; -require_once "resources/functions/google_get_contacts.php"; - -if (permission_exists('contact_add')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//handle import -if ($_POST['a'] == 'import') { - if (sizeof($_POST['group_id']) > 0) { - //get contact ids for those in the submitted groups - if (sizeof($_SESSION['contact_auth']['google']) > 0) { - foreach ($_SESSION['contact_auth']['google'] as $contact['id'] => $contact) { - foreach ($contact['groups'] as $contact_group['id'] => $meh) { - if (in_array($contact_group['id'], $_POST['group_id'])) { - $import_ids[] = $contact['id']; - } - } - } - } - } - - if (sizeof($_POST['contact_id']) > 0) { - foreach ($_POST['contact_id'] as $contact_id) { - $import_ids[] = $contact_id; - } - } - - //iterate selected contact ids, insert contact into database - $contacts_imported = 0; - $contacts_skipped = 0; - $contacts_replaced = 0; - - if (sizeof($import_ids) > 0) { - - $import_ids = array_unique($import_ids); - foreach ($import_ids as $contact_id) { - - //check for duplicate contact (already exists, previously imported, etc) - $sql = "select contact_uuid from v_contact_settings "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and contact_setting_category = 'google' "; - $sql .= "and contact_setting_subcategory = 'id' "; - $sql .= "and contact_setting_value = '".$contact_id."' "; - $sql .= "and contact_setting_enabled = 'true' "; - $prep_statement = $db->prepare($sql); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_ASSOC); - if ($result['contact_uuid'] != '') { - $duplicate_exists = true; - $duplicate_contact_uuid = $result['contact_uuid']; - } - else { - $duplicate_exists = false; - } - unset($sql, $prep_statement, $result); - - //skip importing contact - if ($duplicate_exists && $_POST['import_duplicates'] == 'skip') { - $contacts_skipped++; - continue; - } - //replace contact (delete before inserts below) - else if ($duplicate_exists && $_POST['import_duplicates'] == 'replace') { - $contact_uuid = $duplicate_contact_uuid; - $included = true; - require_once "contact_delete.php"; - unset($contact_uuid, $duplicate_contact_uuid); - $contacts_replaced++; - } - - //extract contact record from array using contact id - $contact = $_SESSION['contact_auth']['google'][$contact_id]; - - //insert contact - $contact_uuid = uuid(); - $sql = "insert into v_contacts "; - $sql .= "( "; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "contact_type, "; - $sql .= "contact_organization, "; - $sql .= "contact_name_prefix, "; - $sql .= "contact_name_given, "; - $sql .= "contact_name_middle, "; - $sql .= "contact_name_family, "; - $sql .= "contact_name_suffix, "; - $sql .= "contact_nickname, "; - $sql .= "contact_title, "; - $sql .= "contact_category, "; - $sql .= "contact_note "; - $sql .= ") "; - $sql .= "values "; - $sql .= "( "; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'".$contact_uuid."', "; - $sql .= "'".check_str($_POST['import_type'])."', "; - $sql .= "'".check_str($contact['organization'])."', "; - $sql .= "'".check_str($contact['name_prefix'])."', "; - $sql .= "'".check_str($contact['name_given'])."', "; - $sql .= "'".check_str($contact['name_middle'])."', "; - $sql .= "'".check_str($contact['name_family'])."', "; - $sql .= "'".check_str($contact['name_suffix'])."', "; - $sql .= "'".check_str($contact['nickname'])."', "; - $sql .= "'".check_str($contact['title'])."', "; - $sql .= "'".check_str($_POST['import_category'])."', "; - $sql .= "'".check_str($contact['notes'])."' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - - //set sharing - if ($_POST['import_shared'] != 'true') { - $sql = "insert into v_contact_groups "; - $sql .= "( "; - $sql .= "contact_group_uuid, "; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "group_uuid "; - $sql .= ") "; - $sql .= "values "; - $sql .= "( "; - $sql .= "'".uuid()."', "; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'".$contact_uuid."', "; - $sql .= "'".$_SESSION["user_uuid"]."' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - } - - //insert emails - if ($_POST['import_fields']['email'] && sizeof($contact['emails']) > 0) { - foreach ($contact['emails'] as $contact_email) { - $sql = "insert into v_contact_emails "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "contact_email_uuid, "; - $sql .= "email_label, "; - $sql .= "email_address, "; - $sql .= "email_primary "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'".$contact_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= "'".check_str($contact_email['label'])."', "; - $sql .= "'".check_str($contact_email['address'])."', "; - $sql .= (($contact_email['primary']) ? 1 : 0)." "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - } - } - - //insert numbers - if ($_POST['import_fields']['number'] && sizeof($contact['numbers']) > 0) { - foreach ($contact['numbers'] as $contact_number) { - $sql = "insert into v_contact_phones "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "contact_phone_uuid, "; - $sql .= "phone_type_voice, "; - $sql .= "phone_type_fax, "; - $sql .= "phone_label, "; - $sql .= "phone_number, "; - $sql .= "phone_primary "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$contact_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= ((substr_count(strtoupper($contact_number['label']), strtoupper($text['label-fax'])) == 0) ? 1 : 'null').", "; - $sql .= ((substr_count(strtoupper($contact_number['label']), strtoupper($text['label-fax'])) != 0) ? 1 : 'null').", "; - $sql .= "'".check_str($contact_number['label'])."', "; - $sql .= "'".check_str($contact_number['number'])."', "; - $sql .= ((sizeof($contact['numbers']) == 1) ? 1 : 0)." "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - } - } - - //insert urls - if ($_POST['import_fields']['url'] && sizeof($contact['urls']) > 0) { - foreach ($contact['urls'] as $contact_url) { - $sql = "insert into v_contact_urls "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "contact_url_uuid, "; - $sql .= "url_label, "; - $sql .= "url_address, "; - $sql .= "url_primary "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'".$contact_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= "'".check_str($contact_url['label'])."', "; - $sql .= "'".check_str($contact_url['url'])."', "; - $sql .= ((sizeof($contact['urls']) == 1) ? 1 : 0)." "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - } - } - - //insert addresses - if ($_POST['import_fields']['address'] && sizeof($contact['addresses']) > 0) { - foreach ($contact['addresses'] as $contact_address) { - $sql = "insert into v_contact_addresses "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "contact_address_uuid, "; - $sql .= "address_type, "; - $sql .= "address_label, "; - $sql .= "address_street, "; - $sql .= "address_extended, "; - $sql .= "address_community, "; - $sql .= "address_locality, "; - $sql .= "address_region, "; - $sql .= "address_postal_code, "; - $sql .= "address_country, "; - $sql .= "address_primary "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'".$contact_uuid."', "; - $sql .= "'".uuid()."', "; - if (substr_count(strtoupper($contact_address['label']), strtoupper($text['option-home'])) != 0) { - $sql .= "'home', "; // vcard address type - } - else if (substr_count(strtoupper($contact_address['label']), strtoupper($text['option-work'])) != 0) { - $sql .= "'work', "; // vcard address type - } - else { - $sql .= "'', "; - } - $sql .= "'".check_str($contact_address['label'])."', "; - $sql .= "'".check_str($contact_address['street'])."', "; - $sql .= "'".check_str($contact_address['extended'])."', "; - $sql .= "'".check_str($contact_address['community'])."', "; - $sql .= "'".check_str($contact_address['locality'])."', "; - $sql .= "'".check_str($contact_address['region'])."', "; - $sql .= "'".check_str($contact_address['postal_code'])."', "; - $sql .= "'".check_str($contact_address['country'])."', "; - $sql .= ((sizeof($contact['addresses']) == 1) ? 1 : 0)." "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - } - } - - //add google contact id, etag and updated date to contact settings - $contact['updated'] = str_replace('T', ' ', $contact['updated']); - $contact['updated'] = str_replace('Z', '', $contact['updated']); - $sql = "insert into v_contact_settings "; - $sql .= "("; - $sql .= "contact_setting_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "domain_uuid, "; - $sql .= "contact_setting_category, "; - $sql .= "contact_setting_subcategory, "; - $sql .= "contact_setting_name, "; - $sql .= "contact_setting_value, "; - $sql .= "contact_setting_order, "; - $sql .= "contact_setting_enabled "; - $sql .= ") "; - $sql .= "values "; - $sql .= "('".uuid()."', '".$contact_uuid."', '".$_SESSION['domain_uuid']."', 'sync', 'source', 'array', 'google', 0, 'true' )"; - $sql .= ",('".uuid()."', '".$contact_uuid."', '".$_SESSION['domain_uuid']."', 'google', 'id', 'text', '".check_str($contact_id)."', 0, 'true' )"; - $sql .= ",('".uuid()."', '".$contact_uuid."', '".$_SESSION['domain_uuid']."', 'google', 'updated', 'date', '".check_str($contact['updated'])."', 0, 'true' )"; - $sql .= ",('".uuid()."', '".$contact_uuid."', '".$_SESSION['domain_uuid']."', 'google', 'etag', 'text', '".check_str($contact['etag'])."', 0, 'true' )"; - $db->exec(check_sql($sql)); - unset($sql); - - $contacts_imported++; - - } - - $message = $text['message-contacts_imported']." ".$contacts_imported; - if ($contacts_replaced > 0) { $message .= " (".$text['message_contacts_imported_replaced']." ".$contacts_replaced.")"; } - if ($contacts_skipped > 0) { $message .= ", ".$text['message_contacts_imported_skipped']." ".$contacts_skipped; } - $_SESSION["message"] = $message; - header("Location: contacts.php"); - exit; - - } - else { - - // no contacts imported - $_SESSION['message_mood'] = 'negative'; - $_SESSION["message"] = $text['message-contacts_imported']." ".$contacts_imported; - - } -} - -//******************************************************************************************* - -//check if authenticated -if ($_SESSION['contact_auth']['token'] == '') { - $_SESSION['contact_auth']['referer'] = substr($_SERVER["HTTP_REFERER"], strrpos($_SERVER["HTTP_REFERER"],'/')+1); - header("Location: contact_auth.php?source=google&target=".substr($_SERVER["PHP_SELF"], strrpos($_SERVER["PHP_SELF"],'/')+1)); - exit; -} - -unset($_SESSION['contact_auth']['source'], $_SESSION['contact_auth']['target']); - -//get groups & contacts -$groups = google_get_groups($_SESSION['contact_auth']['token']); -$contacts = google_get_contacts($_SESSION['contact_auth']['token'], 1000); - -//store in session variable for use on import -$_SESSION['contact_auth']['google'] = $contacts; - -//include the header -$document['title'] = $text['title-contacts_import_google']; -require_once "resources/header.php"; - -echo ""; -echo " "; -echo " "; -echo " "; -echo " "; -echo " "; -echo " "; -echo "
"; -echo " "; -echo " "; -echo " "; -echo "
".$_SESSION['contact_auth']['name']." (".$_SESSION['contact_auth']['email'].")"."
"; -echo "".$text['header-contacts_import_google'].""; -echo "

"; -echo $text['description-contacts_import_google']; -echo "


"; - -$row_style["0"] = "row_style0"; -$row_style["1"] = "row_style1"; - -echo "
\n"; -echo "\n"; - -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "
\n"; -echo " ".$text['label-import_fields']."\n"; -echo "\n"; -echo "  ".$text['label-contact_name']." \n"; -echo "  ".$text['label-contact_organization']." \n"; -echo "  \n"; -echo "  \n"; -echo "  \n"; -echo " \n"; -echo "
\n"; -echo $text['description-import_fields']."\n"; -echo "
\n"; -echo " ".$text['label-contact_type']."\n"; -echo "\n"; -if (is_array($_SESSION["contact"]["type"])) { - sort($_SESSION["contact"]["type"]); - echo " \n"; -} -else { - echo " \n"; -} -echo "
\n"; -echo $text['description-contact_type_import']."\n"; -echo "
\n"; -echo " ".$text['label-contact_category']."\n"; -echo "\n"; -if (is_array($_SESSION["contact"]["category"])) { - sort($_SESSION["contact"]["category"]); - echo " \n"; -} -else { - echo " \n"; -} -echo "
\n"; -echo $text['description-contact_category_import']."\n"; -echo "
\n"; -echo " ".$text['label-shared']."\n"; -echo "\n"; -echo " \n"; -echo "
\n"; -echo $text['description-shared_import']."\n"; -echo "
\n"; -echo " ".$text['label-import_duplicates']."\n"; -echo "\n"; -echo " \n"; -echo "
\n"; -echo $text['description-import_duplicates']."\n"; -echo "
"; -echo "

"; - -//display groups -echo "".$text['label-groups'].""; -echo "

"; - -echo "\n"; -echo "\n"; -echo " "; -echo " \n"; -echo "\n"; - -//determine contact count in groups -foreach ($contacts as $contact) { - foreach ($contact['groups'] as $group_id => $meh) { - $groups[$group_id]['count']++; - } -} - -$c = 0; -foreach ($groups as $group['id'] => $group) { - if ($group['count'] > 0) { - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - $c=($c)?0:1; - } -} -echo "
 ".$text['label-contact_name']."
".$group['name']." (".$group['count'].")
\n"; -echo "
"; - -echo "
"; - -echo "
"; - -//display contacts -echo "".$text['header-contacts'].""; -echo "

"; - -echo "\n"; -echo "\n"; -echo " "; -echo " \n"; -echo " \n"; -echo " \n"; -echo " \n"; -echo " \n"; -echo " \n"; -echo " \n"; -echo "\n"; -$c = 0; -foreach ($contacts as $contact['id'] => $contact) { - $contact_ids[] = $contact['id']; - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "\n"; - $c=($c)?0:1; -} -echo "
".$text['label-contact_name']."".$text['label-contact_organization']."".$text['label-contact_email']."".$text['label-phone_number']."".$text['label-contact_url']."".$text['label-address_address']."".$text['label-group']."
"; - $contact_name[] = $contact['name_prefix']; - $contact_name[] = $contact['name_given']; - $contact_name[] = $contact['name_middle']; - $contact_name[] = $contact['name_family']; - $contact_name[] = $contact['name_suffix']; - echo " ".implode(' ', $contact_name)." "; - unset($contact_name); - echo " "; - echo " ".(($contact['title']) ? $contact['title']."
" : null).$contact['organization']." "; - echo "
"; - if (sizeof($contact['emails']) > 0) { - foreach ($contact['emails'] as $contact_email) { - $contact_emails[] = "".$contact_email['label'].": ".$contact_email['address'].""; - } - echo implode('
', $contact_emails); - unset($contact_emails); - } else { echo " "; } - echo "
"; - if (sizeof($contact['numbers']) > 0) { - foreach ($contact['numbers'] as $contact_number) { - $contact_number_part = "".$contact_number['label'].": "; - if (substr_count(strtoupper($contact_number['label']), 'FAX') == 0) { - $contact_number_part .= ""; - } - $contact_number_part .= format_phone($contact_number['number']); - if (substr_count(strtoupper($contact_number['label']), 'FAX') == 0) { - $contact_number_part .= ""; - } - $contact_numbers[] = $contact_number_part; - unset($contact_number_part); - } - echo implode('
', $contact_numbers); - unset($contact_numbers); - } else { echo " "; } - echo "
"; - if (sizeof($contact['urls']) > 0) { - foreach ($contact['urls'] as $contact_url) { - $contact_urls[] = "".$contact_url['label'].": ".str_replace("http://", "", str_replace("https://", "", $contact_url['url'])).""; - } - echo implode('
', $contact_urls); - unset($contact_urls); - } else { echo " "; } - echo "
"; - if (sizeof($contact['addresses']) > 0) { - foreach ($contact['addresses'] as $contact_address) { - if ($contact_address['street'] != '') { $contact_address_parts[] = $contact_address['street']; } - if ($contact_address['extended'] != '') { $contact_address_parts[] = $contact_address['extended']; } - if ($contact_address['community'] != '') { $contact_address_parts[] = $contact_address['community']; } - if ($contact_address['locality'] != '') { $contact_address_parts[] = $contact_address['locality']; } - if ($contact_address['region'] != '') { $contact_address_parts[] = $contact_address['region']; } - if ($contact_address['postal_code'] != '') { $contact_address_parts[] = $contact_address['postal_code']; } - if ($contact_address['country'] != '') { $contact_address_parts[] = $contact_address['country']; } - $contact_addresses[] = "".$contact_address['label'].": ".implode(', ', $contact_address_parts); - unset($contact_address_parts); - } - echo implode('
', $contact_addresses); - unset($contact_addresses); - } else { echo " "; } - echo "
"; - foreach ($contact['groups'] as $contact_group['id'] => $contact_group['name']) { - $contact_groups[] = $contact_group['name']; - } - echo " ".implode('
', $contact_groups); - unset($contact_groups); - echo "
\n"; -echo "
"; - -echo "
"; - -echo "
"; -echo "

"; - -// check or uncheck all contact checkboxes -if (sizeof($contact_ids) > 0) { - echo "\n"; -} - -/* -echo "
";
-print_r($contacts);
-echo "
"; -echo "

"; - -echo "
"; -echo "

SOURCE JSON DECODED ARRAY...

";
-print_r($records);
-echo "
"; -*/ - -//include the footer -require_once "resources/footer.php"; - - - - -// used above -function curl_file_get_contents($url) { - $curl = curl_init(); - $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)'; - - curl_setopt($curl, CURLOPT_URL, $url); //The URL to fetch. This can also be set when initializing a session with curl_init(). - curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. - curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); //The number of seconds to wait while trying to connect. - curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request. - curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header. - curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect. - curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute. - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //To stop cURL from verifying the peer's certificate. - - $contents = curl_exec($curl); - curl_close($curl); - return $contents; -} + + Portions created by the Initial Developer are Copyright (C) 2008-2013 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +require_once "resources/functions/google_get_groups.php"; +require_once "resources/functions/google_get_contacts.php"; + +if (permission_exists('contact_add')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//handle import +if ($_POST['a'] == 'import') { + if (sizeof($_POST['group_id']) > 0) { + //get contact ids for those in the submitted groups + if (sizeof($_SESSION['contact_auth']['google']) > 0) { + foreach ($_SESSION['contact_auth']['google'] as $contact['id'] => $contact) { + foreach ($contact['groups'] as $contact_group['id'] => $meh) { + if (in_array($contact_group['id'], $_POST['group_id'])) { + $import_ids[] = $contact['id']; + } + } + } + } + } + + if (sizeof($_POST['contact_id']) > 0) { + foreach ($_POST['contact_id'] as $contact_id) { + $import_ids[] = $contact_id; + } + } + + //iterate selected contact ids, insert contact into database + $contacts_imported = 0; + $contacts_skipped = 0; + $contacts_replaced = 0; + + if (sizeof($import_ids) > 0) { + + $import_ids = array_unique($import_ids); + foreach ($import_ids as $contact_id) { + + //check for duplicate contact (already exists, previously imported, etc) + $sql = "select contact_uuid from v_contact_settings "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and contact_setting_category = 'google' "; + $sql .= "and contact_setting_subcategory = 'id' "; + $sql .= "and contact_setting_value = '".$contact_id."' "; + $sql .= "and contact_setting_enabled = 'true' "; + $prep_statement = $db->prepare($sql); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_ASSOC); + if ($result['contact_uuid'] != '') { + $duplicate_exists = true; + $duplicate_contact_uuid = $result['contact_uuid']; + } + else { + $duplicate_exists = false; + } + unset($sql, $prep_statement, $result); + + //skip importing contact + if ($duplicate_exists && $_POST['import_duplicates'] == 'skip') { + $contacts_skipped++; + continue; + } + //replace contact (delete before inserts below) + else if ($duplicate_exists && $_POST['import_duplicates'] == 'replace') { + $contact_uuid = $duplicate_contact_uuid; + $included = true; + require_once "contact_delete.php"; + unset($contact_uuid, $duplicate_contact_uuid); + $contacts_replaced++; + } + + //extract contact record from array using contact id + $contact = $_SESSION['contact_auth']['google'][$contact_id]; + + //insert contact + $contact_uuid = uuid(); + $sql = "insert into v_contacts "; + $sql .= "( "; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "contact_type, "; + $sql .= "contact_organization, "; + $sql .= "contact_name_prefix, "; + $sql .= "contact_name_given, "; + $sql .= "contact_name_middle, "; + $sql .= "contact_name_family, "; + $sql .= "contact_name_suffix, "; + $sql .= "contact_nickname, "; + $sql .= "contact_title, "; + $sql .= "contact_category, "; + $sql .= "contact_note "; + $sql .= ") "; + $sql .= "values "; + $sql .= "( "; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'".$contact_uuid."', "; + $sql .= "'".check_str($_POST['import_type'])."', "; + $sql .= "'".check_str($contact['organization'])."', "; + $sql .= "'".check_str($contact['name_prefix'])."', "; + $sql .= "'".check_str($contact['name_given'])."', "; + $sql .= "'".check_str($contact['name_middle'])."', "; + $sql .= "'".check_str($contact['name_family'])."', "; + $sql .= "'".check_str($contact['name_suffix'])."', "; + $sql .= "'".check_str($contact['nickname'])."', "; + $sql .= "'".check_str($contact['title'])."', "; + $sql .= "'".check_str($_POST['import_category'])."', "; + $sql .= "'".check_str($contact['notes'])."' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + + //set sharing + if ($_POST['import_shared'] != 'true') { + $sql = "insert into v_contact_groups "; + $sql .= "( "; + $sql .= "contact_group_uuid, "; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "group_uuid "; + $sql .= ") "; + $sql .= "values "; + $sql .= "( "; + $sql .= "'".uuid()."', "; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'".$contact_uuid."', "; + $sql .= "'".$_SESSION["user_uuid"]."' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + } + + //insert emails + if ($_POST['import_fields']['email'] && sizeof($contact['emails']) > 0) { + foreach ($contact['emails'] as $contact_email) { + $sql = "insert into v_contact_emails "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "contact_email_uuid, "; + $sql .= "email_label, "; + $sql .= "email_address, "; + $sql .= "email_primary "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'".$contact_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= "'".check_str($contact_email['label'])."', "; + $sql .= "'".check_str($contact_email['address'])."', "; + $sql .= (($contact_email['primary']) ? 1 : 0)." "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + } + } + + //insert numbers + if ($_POST['import_fields']['number'] && sizeof($contact['numbers']) > 0) { + foreach ($contact['numbers'] as $contact_number) { + $sql = "insert into v_contact_phones "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "contact_phone_uuid, "; + $sql .= "phone_type_voice, "; + $sql .= "phone_type_fax, "; + $sql .= "phone_label, "; + $sql .= "phone_number, "; + $sql .= "phone_primary "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$contact_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= ((substr_count(strtoupper($contact_number['label']), strtoupper($text['label-fax'])) == 0) ? 1 : 'null').", "; + $sql .= ((substr_count(strtoupper($contact_number['label']), strtoupper($text['label-fax'])) != 0) ? 1 : 'null').", "; + $sql .= "'".check_str($contact_number['label'])."', "; + $sql .= "'".check_str($contact_number['number'])."', "; + $sql .= ((sizeof($contact['numbers']) == 1) ? 1 : 0)." "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + } + } + + //insert urls + if ($_POST['import_fields']['url'] && sizeof($contact['urls']) > 0) { + foreach ($contact['urls'] as $contact_url) { + $sql = "insert into v_contact_urls "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "contact_url_uuid, "; + $sql .= "url_label, "; + $sql .= "url_address, "; + $sql .= "url_primary "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'".$contact_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= "'".check_str($contact_url['label'])."', "; + $sql .= "'".check_str($contact_url['url'])."', "; + $sql .= ((sizeof($contact['urls']) == 1) ? 1 : 0)." "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + } + } + + //insert addresses + if ($_POST['import_fields']['address'] && sizeof($contact['addresses']) > 0) { + foreach ($contact['addresses'] as $contact_address) { + $sql = "insert into v_contact_addresses "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "contact_address_uuid, "; + $sql .= "address_type, "; + $sql .= "address_label, "; + $sql .= "address_street, "; + $sql .= "address_extended, "; + $sql .= "address_community, "; + $sql .= "address_locality, "; + $sql .= "address_region, "; + $sql .= "address_postal_code, "; + $sql .= "address_country, "; + $sql .= "address_primary "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'".$contact_uuid."', "; + $sql .= "'".uuid()."', "; + if (substr_count(strtoupper($contact_address['label']), strtoupper($text['option-home'])) != 0) { + $sql .= "'home', "; // vcard address type + } + else if (substr_count(strtoupper($contact_address['label']), strtoupper($text['option-work'])) != 0) { + $sql .= "'work', "; // vcard address type + } + else { + $sql .= "'', "; + } + $sql .= "'".check_str($contact_address['label'])."', "; + $sql .= "'".check_str($contact_address['street'])."', "; + $sql .= "'".check_str($contact_address['extended'])."', "; + $sql .= "'".check_str($contact_address['community'])."', "; + $sql .= "'".check_str($contact_address['locality'])."', "; + $sql .= "'".check_str($contact_address['region'])."', "; + $sql .= "'".check_str($contact_address['postal_code'])."', "; + $sql .= "'".check_str($contact_address['country'])."', "; + $sql .= ((sizeof($contact['addresses']) == 1) ? 1 : 0)." "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + } + } + + //add google contact id, etag and updated date to contact settings + $contact['updated'] = str_replace('T', ' ', $contact['updated']); + $contact['updated'] = str_replace('Z', '', $contact['updated']); + $sql = "insert into v_contact_settings "; + $sql .= "("; + $sql .= "contact_setting_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "domain_uuid, "; + $sql .= "contact_setting_category, "; + $sql .= "contact_setting_subcategory, "; + $sql .= "contact_setting_name, "; + $sql .= "contact_setting_value, "; + $sql .= "contact_setting_order, "; + $sql .= "contact_setting_enabled "; + $sql .= ") "; + $sql .= "values "; + $sql .= "('".uuid()."', '".$contact_uuid."', '".$_SESSION['domain_uuid']."', 'sync', 'source', 'array', 'google', 0, 'true' )"; + $sql .= ",('".uuid()."', '".$contact_uuid."', '".$_SESSION['domain_uuid']."', 'google', 'id', 'text', '".check_str($contact_id)."', 0, 'true' )"; + $sql .= ",('".uuid()."', '".$contact_uuid."', '".$_SESSION['domain_uuid']."', 'google', 'updated', 'date', '".check_str($contact['updated'])."', 0, 'true' )"; + $sql .= ",('".uuid()."', '".$contact_uuid."', '".$_SESSION['domain_uuid']."', 'google', 'etag', 'text', '".check_str($contact['etag'])."', 0, 'true' )"; + $db->exec(check_sql($sql)); + unset($sql); + + $contacts_imported++; + + } + + $message = $text['message-contacts_imported']." ".$contacts_imported; + if ($contacts_replaced > 0) { $message .= " (".$text['message_contacts_imported_replaced']." ".$contacts_replaced.")"; } + if ($contacts_skipped > 0) { $message .= ", ".$text['message_contacts_imported_skipped']." ".$contacts_skipped; } + $_SESSION["message"] = $message; + header("Location: contacts.php"); + exit; + + } + else { + + // no contacts imported + $_SESSION['message_mood'] = 'negative'; + $_SESSION["message"] = $text['message-contacts_imported']." ".$contacts_imported; + + } +} + +//******************************************************************************************* + +//check if authenticated +if ($_SESSION['contact_auth']['token'] == '') { + $_SESSION['contact_auth']['referer'] = substr($_SERVER["HTTP_REFERER"], strrpos($_SERVER["HTTP_REFERER"],'/')+1); + header("Location: contact_auth.php?source=google&target=".substr($_SERVER["PHP_SELF"], strrpos($_SERVER["PHP_SELF"],'/')+1)); + exit; +} + +unset($_SESSION['contact_auth']['source'], $_SESSION['contact_auth']['target']); + +//get groups & contacts +$groups = google_get_groups($_SESSION['contact_auth']['token']); +$contacts = google_get_contacts($_SESSION['contact_auth']['token'], 1000); + +//store in session variable for use on import +$_SESSION['contact_auth']['google'] = $contacts; + +//include the header +$document['title'] = $text['title-contacts_import_google']; +require_once "resources/header.php"; + +echo ""; +echo " "; +echo " "; +echo " "; +echo " "; +echo " "; +echo " "; +echo "
"; +echo " "; +echo " "; +echo " "; +echo "
".$_SESSION['contact_auth']['name']." (".$_SESSION['contact_auth']['email'].")"."
"; +echo "".$text['header-contacts_import_google'].""; +echo "

"; +echo $text['description-contacts_import_google']; +echo "


"; + +$row_style["0"] = "row_style0"; +$row_style["1"] = "row_style1"; + +echo "
\n"; +echo "\n"; + +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "
\n"; +echo " ".$text['label-import_fields']."\n"; +echo "\n"; +echo "  ".$text['label-contact_name']." \n"; +echo "  ".$text['label-contact_organization']." \n"; +echo "  \n"; +echo "  \n"; +echo "  \n"; +echo " \n"; +echo "
\n"; +echo $text['description-import_fields']."\n"; +echo "
\n"; +echo " ".$text['label-contact_type']."\n"; +echo "\n"; +if (is_array($_SESSION["contact"]["type"])) { + sort($_SESSION["contact"]["type"]); + echo " \n"; +} +else { + echo " \n"; +} +echo "
\n"; +echo $text['description-contact_type_import']."\n"; +echo "
\n"; +echo " ".$text['label-contact_category']."\n"; +echo "\n"; +if (is_array($_SESSION["contact"]["category"])) { + sort($_SESSION["contact"]["category"]); + echo " \n"; +} +else { + echo " \n"; +} +echo "
\n"; +echo $text['description-contact_category_import']."\n"; +echo "
\n"; +echo " ".$text['label-shared']."\n"; +echo "\n"; +echo " \n"; +echo "
\n"; +echo $text['description-shared_import']."\n"; +echo "
\n"; +echo " ".$text['label-import_duplicates']."\n"; +echo "\n"; +echo " \n"; +echo "
\n"; +echo $text['description-import_duplicates']."\n"; +echo "
"; +echo "

"; + +//display groups +echo "".$text['label-groups'].""; +echo "

"; + +echo "\n"; +echo "\n"; +echo " "; +echo " \n"; +echo "\n"; + +//determine contact count in groups +foreach ($contacts as $contact) { + foreach ($contact['groups'] as $group_id => $meh) { + $groups[$group_id]['count']++; + } +} + +$c = 0; +foreach ($groups as $group['id'] => $group) { + if ($group['count'] > 0) { + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + $c=($c)?0:1; + } +} +echo "
 ".$text['label-contact_name']."
".$group['name']." (".$group['count'].")
\n"; +echo "
"; + +echo "
"; + +echo "
"; + +//display contacts +echo "".$text['header-contacts'].""; +echo "

"; + +echo "\n"; +echo "\n"; +echo " "; +echo " \n"; +echo " \n"; +echo " \n"; +echo " \n"; +echo " \n"; +echo " \n"; +echo " \n"; +echo "\n"; +$c = 0; +foreach ($contacts as $contact['id'] => $contact) { + $contact_ids[] = $contact['id']; + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "\n"; + $c=($c)?0:1; +} +echo "
".$text['label-contact_name']."".$text['label-contact_organization']."".$text['label-contact_email']."".$text['label-phone_number']."".$text['label-contact_url']."".$text['label-address_address']."".$text['label-group']."
"; + $contact_name[] = $contact['name_prefix']; + $contact_name[] = $contact['name_given']; + $contact_name[] = $contact['name_middle']; + $contact_name[] = $contact['name_family']; + $contact_name[] = $contact['name_suffix']; + echo " ".implode(' ', $contact_name)." "; + unset($contact_name); + echo " "; + echo " ".(($contact['title']) ? $contact['title']."
" : null).$contact['organization']." "; + echo "
"; + if (sizeof($contact['emails']) > 0) { + foreach ($contact['emails'] as $contact_email) { + $contact_emails[] = "".$contact_email['label'].": ".$contact_email['address'].""; + } + echo implode('
', $contact_emails); + unset($contact_emails); + } else { echo " "; } + echo "
"; + if (sizeof($contact['numbers']) > 0) { + foreach ($contact['numbers'] as $contact_number) { + $contact_number_part = "".$contact_number['label'].": "; + if (substr_count(strtoupper($contact_number['label']), 'FAX') == 0) { + $contact_number_part .= ""; + } + $contact_number_part .= format_phone($contact_number['number']); + if (substr_count(strtoupper($contact_number['label']), 'FAX') == 0) { + $contact_number_part .= ""; + } + $contact_numbers[] = $contact_number_part; + unset($contact_number_part); + } + echo implode('
', $contact_numbers); + unset($contact_numbers); + } else { echo " "; } + echo "
"; + if (sizeof($contact['urls']) > 0) { + foreach ($contact['urls'] as $contact_url) { + $contact_urls[] = "".$contact_url['label'].": ".str_replace("http://", "", str_replace("https://", "", $contact_url['url'])).""; + } + echo implode('
', $contact_urls); + unset($contact_urls); + } else { echo " "; } + echo "
"; + if (sizeof($contact['addresses']) > 0) { + foreach ($contact['addresses'] as $contact_address) { + if ($contact_address['street'] != '') { $contact_address_parts[] = $contact_address['street']; } + if ($contact_address['extended'] != '') { $contact_address_parts[] = $contact_address['extended']; } + if ($contact_address['community'] != '') { $contact_address_parts[] = $contact_address['community']; } + if ($contact_address['locality'] != '') { $contact_address_parts[] = $contact_address['locality']; } + if ($contact_address['region'] != '') { $contact_address_parts[] = $contact_address['region']; } + if ($contact_address['postal_code'] != '') { $contact_address_parts[] = $contact_address['postal_code']; } + if ($contact_address['country'] != '') { $contact_address_parts[] = $contact_address['country']; } + $contact_addresses[] = "".$contact_address['label'].": ".implode(', ', $contact_address_parts); + unset($contact_address_parts); + } + echo implode('
', $contact_addresses); + unset($contact_addresses); + } else { echo " "; } + echo "
"; + foreach ($contact['groups'] as $contact_group['id'] => $contact_group['name']) { + $contact_groups[] = $contact_group['name']; + } + echo " ".implode('
', $contact_groups); + unset($contact_groups); + echo "
\n"; +echo "
"; + +echo "
"; + +echo "
"; +echo "

"; + +// check or uncheck all contact checkboxes +if (sizeof($contact_ids) > 0) { + echo "\n"; +} + +/* +echo "
";
+print_r($contacts);
+echo "
"; +echo "

"; + +echo "
"; +echo "

SOURCE JSON DECODED ARRAY...

";
+print_r($records);
+echo "
"; +*/ + +//include the footer +require_once "resources/footer.php"; + + + + +// used above +function curl_file_get_contents($url) { + $curl = curl_init(); + $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)'; + + curl_setopt($curl, CURLOPT_URL, $url); //The URL to fetch. This can also be set when initializing a session with curl_init(). + curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); //The number of seconds to wait while trying to connect. + curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request. + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header. + curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect. + curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute. + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //To stop cURL from verifying the peer's certificate. + + $contents = curl_exec($curl); + curl_close($curl); + return $contents; +} ?> \ No newline at end of file diff --git a/app/contacts/contact_relation_edit.php b/app/contacts/contact_relation_edit.php index bd01d13a93..6774247b0b 100644 --- a/app/contacts/contact_relation_edit.php +++ b/app/contacts/contact_relation_edit.php @@ -1,342 +1,342 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - Luis Daniel Lucio Quiroz -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('contact_relation_edit') || permission_exists('contact_relation_add')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//action add or update - if (isset($_REQUEST["id"])) { - $action = "update"; - $contact_relation_uuid = check_str($_REQUEST["id"]); - } - else { - $action = "add"; - } - -//get the contact uuid - if (strlen($_GET["contact_uuid"]) > 0) { - $contact_uuid = check_str($_GET["contact_uuid"]); - } - -//get http post variables and set them to php variables - if (count($_POST)>0) { - $relation_label = check_str($_POST["relation_label"]); - $relation_label_custom = check_str($_POST["relation_label_custom"]); - $relation_contact_uuid = check_str($_POST["relation_contact_uuid"]); - $relation_reciprocal = check_str($_POST["relation_reciprocal"]); - $relation_reciprocal_label = check_str($_POST["relation_reciprocal_label"]); - $relation_reciprocal_label_custom = check_str($_POST["relation_reciprocal_label_custom"]); - - //use custom label(s), if set - $relation_label = ($relation_label_custom != '') ? $relation_label_custom : $relation_label; - $relation_reciprocal_label = ($relation_reciprocal_label_custom != '') ? $relation_reciprocal_label_custom : $relation_reciprocal_label; - } - -//process the form data - if (count($_POST) > 0 && strlen($_POST["persistformvar"]) == 0) { - - //set the uuid - if ($action == "update") { - $contact_relation_uuid = check_str($_POST["contact_relation_uuid"]); - } - - //check for all required data - $msg = ''; - if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) { - require_once "resources/header.php"; - require_once "resources/persist_form_var.php"; - echo "
\n"; - echo "
\n"; - echo $msg."
"; - echo "
\n"; - persistformvar($_POST); - echo "
\n"; - require_once "resources/footer.php"; - return; - } - - //add or update the database - if ($_POST["persistformvar"] != "true") { - - //update last modified - $sql = "update v_contacts set "; - $sql .= "last_mod_date = now(), "; - $sql .= "last_mod_user = '".$_SESSION['username']."' "; - $sql .= "where domain_uuid = '".$domain_uuid."' "; - $sql .= "and contact_uuid = '".$contact_uuid."' "; - $db->exec(check_sql($sql)); - unset($sql); - - if ($action == "add") { - $contact_relation_uuid = uuid(); - $sql = "insert into v_contact_relations "; - $sql .= "("; - $sql .= "contact_relation_uuid, "; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "relation_label, "; - $sql .= "relation_contact_uuid "; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$contact_relation_uuid."', "; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'".$contact_uuid."', "; - $sql .= "'".$relation_label."', "; - $sql .= "'".$relation_contact_uuid."' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - - if ($relation_reciprocal) { - $contact_relation_uuid = uuid(); - $sql = "insert into v_contact_relations "; - $sql .= "("; - $sql .= "contact_relation_uuid, "; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "relation_label, "; - $sql .= "relation_contact_uuid "; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$contact_relation_uuid."', "; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'".$relation_contact_uuid."', "; - $sql .= "'".$relation_reciprocal_label."', "; - $sql .= "'".$contact_uuid."' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - } - - $_SESSION["message"] = $text['message-add']; - header("Location: contact_edit.php?id=".$contact_uuid); - return; - } //if ($action == "add") - - if ($action == "update") { - $sql = "update v_contact_relations set "; - $sql .= "relation_label = '".$relation_label."', "; - $sql .= "relation_contact_uuid = '".$relation_contact_uuid."' "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and contact_relation_uuid = '".$contact_relation_uuid."'"; - $db->exec(check_sql($sql)); - unset($sql); - - $_SESSION["message"] = $text['message-update']; - header("Location: contact_edit.php?id=".$contact_uuid); - return; - } //if ($action == "update") - } //if ($_POST["persistformvar"] != "true") - } //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) - -//pre-populate the form - if (count($_GET) > 0 && $_POST["persistformvar"] != "true") { - $contact_relation_uuid = $_GET["id"]; - $sql = "select * from v_contact_relations "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and contact_relation_uuid = '".$contact_relation_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $relation_label = $row["relation_label"]; - $relation_contact_uuid = $row["relation_contact_uuid"]; - break; //limit to 1 row - } - unset ($prep_statement); - } - -//show the header - $document['title'] = $text['title-contact_relation']; - require_once "resources/header.php"; - -//javascript to toggle input/select boxes - echo ""; - -//show the content - echo "
\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "
"; - echo " ".$text['header-contact_relation'].""; - echo ""; - echo " "; - echo " \n"; - echo "
\n"; - echo "
\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if ($action == 'add') { - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "
\n"; - echo " ".$text['label-contact_relation_label']."\n"; - echo "\n"; - if (is_array($_SESSION["contact"]["relation_label"])) { - sort($_SESSION["contact"]["relation_label"]); - foreach($_SESSION["contact"]["relation_label"] as $row) { - $relation_label_options[] = ""; - } - $relation_label_found = (in_array($relation_label, $_SESSION["contact"]["relation_label"])) ? true : false; - } - else { - $selected[$relation_label] = "selected"; - $default_labels[] = $text['label-contact_relation_option_parent']; - $default_labels[] = $text['label-contact_relation_option_child']; - $default_labels[] = $text['label-contact_relation_option_employee']; - $default_labels[] = $text['label-contact_relation_option_member']; - $default_labels[] = $text['label-contact_relation_option_associate']; - $default_labels[] = $text['label-contact_relation_option_other']; - foreach ($default_labels as $default_label) { - $relation_label_options[] = ""; - } - $relation_label_found = (in_array($relation_label, $default_labels)) ? true : false; - } - echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo $text['description-relation_label']."\n"; - echo "
\n"; - echo " ".$text['label-contact_relation_contact']."\n"; - echo "\n"; - $sql = "select contact_uuid, contact_organization, contact_name_given, contact_name_family from v_contacts "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and contact_uuid <> '".$contact_uuid."' "; - $sql .= "order by contact_organization desc, contact_name_given asc, contact_name_family asc "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - echo "\n"; -// echo "
\n"; -// echo $text['description-related_contact']."\n"; - echo "
\n"; - echo " ".$text['label-contact_relation_reciprocal']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['description-contact_relation_reciprocal']."\n"; - echo "
\n"; - - echo "\n"; - - echo "\n"; - } - - echo " \n"; - echo " \n"; - echo " "; - echo "
\n"; - echo "
\n"; - echo " \n"; - if ($action == "update") { - echo " \n"; - } - echo " \n"; - echo "
"; - echo "

"; - echo "
"; - -//include the footer - require_once "resources/footer.php"; -?> + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Luis Daniel Lucio Quiroz +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('contact_relation_edit') || permission_exists('contact_relation_add')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//action add or update + if (isset($_REQUEST["id"])) { + $action = "update"; + $contact_relation_uuid = check_str($_REQUEST["id"]); + } + else { + $action = "add"; + } + +//get the contact uuid + if (strlen($_GET["contact_uuid"]) > 0) { + $contact_uuid = check_str($_GET["contact_uuid"]); + } + +//get http post variables and set them to php variables + if (count($_POST)>0) { + $relation_label = check_str($_POST["relation_label"]); + $relation_label_custom = check_str($_POST["relation_label_custom"]); + $relation_contact_uuid = check_str($_POST["relation_contact_uuid"]); + $relation_reciprocal = check_str($_POST["relation_reciprocal"]); + $relation_reciprocal_label = check_str($_POST["relation_reciprocal_label"]); + $relation_reciprocal_label_custom = check_str($_POST["relation_reciprocal_label_custom"]); + + //use custom label(s), if set + $relation_label = ($relation_label_custom != '') ? $relation_label_custom : $relation_label; + $relation_reciprocal_label = ($relation_reciprocal_label_custom != '') ? $relation_reciprocal_label_custom : $relation_reciprocal_label; + } + +//process the form data + if (count($_POST) > 0 && strlen($_POST["persistformvar"]) == 0) { + + //set the uuid + if ($action == "update") { + $contact_relation_uuid = check_str($_POST["contact_relation_uuid"]); + } + + //check for all required data + $msg = ''; + if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) { + require_once "resources/header.php"; + require_once "resources/persist_form_var.php"; + echo "
\n"; + echo "
\n"; + echo $msg."
"; + echo "
\n"; + persistformvar($_POST); + echo "
\n"; + require_once "resources/footer.php"; + return; + } + + //add or update the database + if ($_POST["persistformvar"] != "true") { + + //update last modified + $sql = "update v_contacts set "; + $sql .= "last_mod_date = now(), "; + $sql .= "last_mod_user = '".$_SESSION['username']."' "; + $sql .= "where domain_uuid = '".$domain_uuid."' "; + $sql .= "and contact_uuid = '".$contact_uuid."' "; + $db->exec(check_sql($sql)); + unset($sql); + + if ($action == "add") { + $contact_relation_uuid = uuid(); + $sql = "insert into v_contact_relations "; + $sql .= "("; + $sql .= "contact_relation_uuid, "; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "relation_label, "; + $sql .= "relation_contact_uuid "; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$contact_relation_uuid."', "; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'".$contact_uuid."', "; + $sql .= "'".$relation_label."', "; + $sql .= "'".$relation_contact_uuid."' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + + if ($relation_reciprocal) { + $contact_relation_uuid = uuid(); + $sql = "insert into v_contact_relations "; + $sql .= "("; + $sql .= "contact_relation_uuid, "; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "relation_label, "; + $sql .= "relation_contact_uuid "; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$contact_relation_uuid."', "; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'".$relation_contact_uuid."', "; + $sql .= "'".$relation_reciprocal_label."', "; + $sql .= "'".$contact_uuid."' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + } + + $_SESSION["message"] = $text['message-add']; + header("Location: contact_edit.php?id=".$contact_uuid); + return; + } //if ($action == "add") + + if ($action == "update") { + $sql = "update v_contact_relations set "; + $sql .= "relation_label = '".$relation_label."', "; + $sql .= "relation_contact_uuid = '".$relation_contact_uuid."' "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and contact_relation_uuid = '".$contact_relation_uuid."'"; + $db->exec(check_sql($sql)); + unset($sql); + + $_SESSION["message"] = $text['message-update']; + header("Location: contact_edit.php?id=".$contact_uuid); + return; + } //if ($action == "update") + } //if ($_POST["persistformvar"] != "true") + } //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) + +//pre-populate the form + if (count($_GET) > 0 && $_POST["persistformvar"] != "true") { + $contact_relation_uuid = $_GET["id"]; + $sql = "select * from v_contact_relations "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and contact_relation_uuid = '".$contact_relation_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $relation_label = $row["relation_label"]; + $relation_contact_uuid = $row["relation_contact_uuid"]; + break; //limit to 1 row + } + unset ($prep_statement); + } + +//show the header + $document['title'] = $text['title-contact_relation']; + require_once "resources/header.php"; + +//javascript to toggle input/select boxes + echo ""; + +//show the content + echo "
\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "
"; + echo " ".$text['header-contact_relation'].""; + echo ""; + echo " "; + echo " \n"; + echo "
\n"; + echo "
\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if ($action == 'add') { + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "
\n"; + echo " ".$text['label-contact_relation_label']."\n"; + echo "\n"; + if (is_array($_SESSION["contact"]["relation_label"])) { + sort($_SESSION["contact"]["relation_label"]); + foreach($_SESSION["contact"]["relation_label"] as $row) { + $relation_label_options[] = ""; + } + $relation_label_found = (in_array($relation_label, $_SESSION["contact"]["relation_label"])) ? true : false; + } + else { + $selected[$relation_label] = "selected"; + $default_labels[] = $text['label-contact_relation_option_parent']; + $default_labels[] = $text['label-contact_relation_option_child']; + $default_labels[] = $text['label-contact_relation_option_employee']; + $default_labels[] = $text['label-contact_relation_option_member']; + $default_labels[] = $text['label-contact_relation_option_associate']; + $default_labels[] = $text['label-contact_relation_option_other']; + foreach ($default_labels as $default_label) { + $relation_label_options[] = ""; + } + $relation_label_found = (in_array($relation_label, $default_labels)) ? true : false; + } + echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo $text['description-relation_label']."\n"; + echo "
\n"; + echo " ".$text['label-contact_relation_contact']."\n"; + echo "\n"; + $sql = "select contact_uuid, contact_organization, contact_name_given, contact_name_family from v_contacts "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and contact_uuid <> '".$contact_uuid."' "; + $sql .= "order by contact_organization desc, contact_name_given asc, contact_name_family asc "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + echo "\n"; +// echo "
\n"; +// echo $text['description-related_contact']."\n"; + echo "
\n"; + echo " ".$text['label-contact_relation_reciprocal']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['description-contact_relation_reciprocal']."\n"; + echo "
\n"; + + echo "\n"; + + echo "\n"; + } + + echo " \n"; + echo " \n"; + echo " "; + echo "
\n"; + echo "
\n"; + echo " \n"; + if ($action == "update") { + echo " \n"; + } + echo " \n"; + echo "
"; + echo "

"; + echo "
"; + +//include the footer + require_once "resources/footer.php"; +?> diff --git a/app/contacts/contact_relations.php b/app/contacts/contact_relations.php index 9158017223..b91d0b75d7 100644 --- a/app/contacts/contact_relations.php +++ b/app/contacts/contact_relations.php @@ -1,113 +1,113 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('contact_relation_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//show the content - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "
".$text['header-contact_relations']." 
\n"; - - //get the related contacts - $sql = "select "; - $sql .= "cr.contact_relation_uuid, "; - $sql .= "cr.relation_label, "; - $sql .= "c.contact_uuid, "; - $sql .= "c.contact_organization, "; - $sql .= "c.contact_name_given, "; - $sql .= "c.contact_name_family "; - $sql .= "from "; - $sql .= "v_contact_relations as cr, "; - $sql .= "v_contacts as c "; - $sql .= "where "; - $sql .= "cr.relation_contact_uuid = c.contact_uuid "; - $sql .= "and cr.domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and cr.contact_uuid = '".$contact_uuid."' "; - $sql .= "order by "; - $sql .= "c.contact_organization desc, "; - $sql .= "c.contact_name_given asc, "; - $sql .= "c.contact_name_family asc "; - //echo $sql."

"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - unset ($prep_statement, $sql); - - $c = 0; - $row_style["0"] = "row_style0"; - $row_style["1"] = "row_style1"; - - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if ($result_count > 0) { - foreach($result as $row) { - if (permission_exists('contact_relation_edit')) { - $tr_link = "href='contact_relation_edit.php?contact_uuid=".$row['contact_uuid']."&id=".$row['contact_relation_uuid']."' "; - } - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "\n"; - $c = ($c) ? 0 : 1; - } //end foreach - unset($sql, $result, $row_count); - } //end if results - - echo "
".$text['label-contact_relation_label']."".$text['label-contact_relation_organization']."".$text['label-contact_relation_name'].""; - if (permission_exists('contact_relation_add')) { - echo "$v_link_label_add"; - } - echo "
".$row['relation_label']." "; - if (permission_exists('contact_relation_edit')) { - echo "$v_link_label_edit"; - } - if (permission_exists('contact_relation_delete')) { - echo "$v_link_label_delete"; - } - echo "
"; - + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('contact_relation_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//show the content + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "
".$text['header-contact_relations']." 
\n"; + + //get the related contacts + $sql = "select "; + $sql .= "cr.contact_relation_uuid, "; + $sql .= "cr.relation_label, "; + $sql .= "c.contact_uuid, "; + $sql .= "c.contact_organization, "; + $sql .= "c.contact_name_given, "; + $sql .= "c.contact_name_family "; + $sql .= "from "; + $sql .= "v_contact_relations as cr, "; + $sql .= "v_contacts as c "; + $sql .= "where "; + $sql .= "cr.relation_contact_uuid = c.contact_uuid "; + $sql .= "and cr.domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and cr.contact_uuid = '".$contact_uuid."' "; + $sql .= "order by "; + $sql .= "c.contact_organization desc, "; + $sql .= "c.contact_name_given asc, "; + $sql .= "c.contact_name_family asc "; + //echo $sql."

"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + unset ($prep_statement, $sql); + + $c = 0; + $row_style["0"] = "row_style0"; + $row_style["1"] = "row_style1"; + + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if ($result_count > 0) { + foreach($result as $row) { + if (permission_exists('contact_relation_edit')) { + $tr_link = "href='contact_relation_edit.php?contact_uuid=".$row['contact_uuid']."&id=".$row['contact_relation_uuid']."' "; + } + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "\n"; + $c = ($c) ? 0 : 1; + } //end foreach + unset($sql, $result, $row_count); + } //end if results + + echo "
".$text['label-contact_relation_label']."".$text['label-contact_relation_organization']."".$text['label-contact_relation_name'].""; + if (permission_exists('contact_relation_add')) { + echo "$v_link_label_add"; + } + echo "
".$row['relation_label']." "; + if (permission_exists('contact_relation_edit')) { + echo "$v_link_label_edit"; + } + if (permission_exists('contact_relation_delete')) { + echo "$v_link_label_delete"; + } + echo "
"; + ?> \ No newline at end of file diff --git a/app/contacts/contact_timer.php b/app/contacts/contact_timer.php index cf9ead4ea1..ed10f58821 100644 --- a/app/contacts/contact_timer.php +++ b/app/contacts/contact_timer.php @@ -1,361 +1,361 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (!permission_exists('contact_time_add')) { echo "access denied"; exit; } - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get contact uuid - $domain_uuid = check_str($_REQUEST['domain_uuid']); - $contact_uuid = check_str($_REQUEST['contact_uuid']); - -//get posted variables & set time status - if (sizeof($_POST) > 0) { - $contact_time_uuid = check_str($_POST['contact_time_uuid']); - $contact_uuid = check_str($_POST['contact_uuid']); - $time_action = check_str($_POST['time_action']); - $time_description = check_str($_POST['time_description']); - - if ($time_description == 'Description...') { unset($time_description); } - - if ($time_action == 'start') { - $contact_time_uuid = uuid(); - $sql = "insert into v_contact_times "; - $sql .= "( "; - $sql .= "domain_uuid, "; - $sql .= "contact_time_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "user_uuid, "; - $sql .= "time_start, "; - $sql .= "time_description "; - $sql .= ") "; - $sql .= "values "; - $sql .= "( "; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$contact_time_uuid."', "; - $sql .= "'".$contact_uuid."', "; - $sql .= "'".$_SESSION["user"]["user_uuid"]."', "; - $sql .= "'".date("Y-m-d H:i:s")."', "; - $sql .= "'".$time_description."' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - } - if ($time_action == 'stop') { - $sql = "update v_contact_times "; - $sql .= "set "; - $sql .= "time_stop = '".date("Y-m-d H:i:s")."', "; - $sql .= "time_description = '".$time_description."' "; - $sql .= "where "; - $sql .= "contact_time_uuid = '".$contact_time_uuid."' "; - $sql .= "and domain_uuid = '".$domain_uuid."' "; - $sql .= "and contact_uuid = '".$contact_uuid."' "; - $sql .= "and user_uuid = '".$_SESSION["user"]["user_uuid"]."' "; - $db->exec(check_sql($sql)); - unset($sql); - } - header("Location: contact_timer.php?domain_uuid=".$domain_uuid."&contact_uuid=".$contact_uuid); - } - -//get contact details - $sql = "select "; - $sql .= "contact_organization, "; - $sql .= "contact_name_given, "; - $sql .= "contact_name_family, "; - $sql .= "contact_nickname "; - $sql .= "from v_contacts "; - $sql .= "where domain_uuid = '".$domain_uuid."' "; - $sql .= "and contact_uuid = '".$contact_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_NAMED); - if (sizeof($result) > 0) { - $contact_organization = $result["contact_organization"]; - $contact_name_given = $result["contact_name_given"]; - $contact_name_family = $result["contact_name_family"]; - $contact_nickname = $result["contact_nickname"]; - } - else { - exit; - } - unset ($sql, $prep_statement, $result); - -//determine timer state and action - $sql = "select "; - $sql .= "contact_time_uuid, "; - $sql .= "time_description "; - $sql .= "from v_contact_times "; - $sql .= "where domain_uuid = '".$domain_uuid."' "; - $sql .= "and user_uuid = '".$_SESSION['user']['user_uuid']."' "; - $sql .= "and contact_uuid = '".$contact_uuid."' "; - $sql .= "and time_start is not null "; - $sql .= "and time_stop is null "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_NAMED); - if (sizeof($result) > 0) { - $contact_time_uuid = $result["contact_time_uuid"]; - $time_description = $result["time_description"]; - } - unset ($sql, $prep_statement, $result); - - $timer_state = ($contact_time_uuid != '') ? 'running' : 'stopped'; - $timer_action = ($timer_state == 'running') ? 'stop' : 'start'; - -//determine contact name to display - if ($contact_nickname != '') { - $contact = $contact_nickname; - } - else if ($contact_name_given != '') { - $contact = $contact_name_given; - } - if ($contact_name_family != '') { - $contact .= ($contact != '') ? ' '.$contact_name_family : $contact_name_family; - } - if ($contact_organization != '') { - $contact .= ($contact != '') ? ', '.$contact_organization : $contact_organization; - } -?> - - - - <?php echo $text['label-time_timer']; ?>: <?php echo $contact; ?> - - - - - - - <?php echo $text['label-time_timer']; ?> - -

- -

- -

-
00:00:00
-
-
- - - - - - - - -
- - - -
-
-
- - - - - -
-
- + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (!permission_exists('contact_time_add')) { echo "access denied"; exit; } + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get contact uuid + $domain_uuid = check_str($_REQUEST['domain_uuid']); + $contact_uuid = check_str($_REQUEST['contact_uuid']); + +//get posted variables & set time status + if (sizeof($_POST) > 0) { + $contact_time_uuid = check_str($_POST['contact_time_uuid']); + $contact_uuid = check_str($_POST['contact_uuid']); + $time_action = check_str($_POST['time_action']); + $time_description = check_str($_POST['time_description']); + + if ($time_description == 'Description...') { unset($time_description); } + + if ($time_action == 'start') { + $contact_time_uuid = uuid(); + $sql = "insert into v_contact_times "; + $sql .= "( "; + $sql .= "domain_uuid, "; + $sql .= "contact_time_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "user_uuid, "; + $sql .= "time_start, "; + $sql .= "time_description "; + $sql .= ") "; + $sql .= "values "; + $sql .= "( "; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$contact_time_uuid."', "; + $sql .= "'".$contact_uuid."', "; + $sql .= "'".$_SESSION["user"]["user_uuid"]."', "; + $sql .= "'".date("Y-m-d H:i:s")."', "; + $sql .= "'".$time_description."' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + } + if ($time_action == 'stop') { + $sql = "update v_contact_times "; + $sql .= "set "; + $sql .= "time_stop = '".date("Y-m-d H:i:s")."', "; + $sql .= "time_description = '".$time_description."' "; + $sql .= "where "; + $sql .= "contact_time_uuid = '".$contact_time_uuid."' "; + $sql .= "and domain_uuid = '".$domain_uuid."' "; + $sql .= "and contact_uuid = '".$contact_uuid."' "; + $sql .= "and user_uuid = '".$_SESSION["user"]["user_uuid"]."' "; + $db->exec(check_sql($sql)); + unset($sql); + } + header("Location: contact_timer.php?domain_uuid=".$domain_uuid."&contact_uuid=".$contact_uuid); + } + +//get contact details + $sql = "select "; + $sql .= "contact_organization, "; + $sql .= "contact_name_given, "; + $sql .= "contact_name_family, "; + $sql .= "contact_nickname "; + $sql .= "from v_contacts "; + $sql .= "where domain_uuid = '".$domain_uuid."' "; + $sql .= "and contact_uuid = '".$contact_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_NAMED); + if (sizeof($result) > 0) { + $contact_organization = $result["contact_organization"]; + $contact_name_given = $result["contact_name_given"]; + $contact_name_family = $result["contact_name_family"]; + $contact_nickname = $result["contact_nickname"]; + } + else { + exit; + } + unset ($sql, $prep_statement, $result); + +//determine timer state and action + $sql = "select "; + $sql .= "contact_time_uuid, "; + $sql .= "time_description "; + $sql .= "from v_contact_times "; + $sql .= "where domain_uuid = '".$domain_uuid."' "; + $sql .= "and user_uuid = '".$_SESSION['user']['user_uuid']."' "; + $sql .= "and contact_uuid = '".$contact_uuid."' "; + $sql .= "and time_start is not null "; + $sql .= "and time_stop is null "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_NAMED); + if (sizeof($result) > 0) { + $contact_time_uuid = $result["contact_time_uuid"]; + $time_description = $result["time_description"]; + } + unset ($sql, $prep_statement, $result); + + $timer_state = ($contact_time_uuid != '') ? 'running' : 'stopped'; + $timer_action = ($timer_state == 'running') ? 'stop' : 'start'; + +//determine contact name to display + if ($contact_nickname != '') { + $contact = $contact_nickname; + } + else if ($contact_name_given != '') { + $contact = $contact_name_given; + } + if ($contact_name_family != '') { + $contact .= ($contact != '') ? ' '.$contact_name_family : $contact_name_family; + } + if ($contact_organization != '') { + $contact .= ($contact != '') ? ', '.$contact_organization : $contact_organization; + } +?> + + + + <?php echo $text['label-time_timer']; ?>: <?php echo $contact; ?> + + + + + + + <?php echo $text['label-time_timer']; ?> + +

+ +

+ +

+
00:00:00
+
+
+ + + + + + + + +
+ + + +
+
+
+ + + + + +
+
+ \ No newline at end of file diff --git a/app/contacts/contact_timer_inc.php b/app/contacts/contact_timer_inc.php index fd1ca82214..ae1d0b8738 100644 --- a/app/contacts/contact_timer_inc.php +++ b/app/contacts/contact_timer_inc.php @@ -1,57 +1,57 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (!permission_exists('contact_time_add')) { echo "access denied"; exit; } - -//get contact and time uuids - $domain_uuid = check_str($_REQUEST['domain_uuid']); - $contact_uuid = check_str($_REQUEST['contact_uuid']); - $contact_time_uuid = check_str($_REQUEST['contact_time_uuid']); - -//get time quantity - $sql = "select "; - $sql .= "time_start "; - $sql .= "from v_contact_times "; - $sql .= "where domain_uuid = '".$domain_uuid."' "; - $sql .= "and contact_time_uuid = '".$contact_time_uuid."' "; - $sql .= "and user_uuid = '".$_SESSION['user']['user_uuid']."' "; - $sql .= "and contact_uuid = '".$contact_uuid."' "; - $sql .= "and time_start is not null "; - $sql .= "and time_stop is null "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_NAMED); - if (sizeof($result) > 0) { - $time_start = strtotime($result["time_start"]); - $time_now = strtotime(date("Y-m-d H:i:s")); - $time_diff = gmdate("H:i:s", ($time_now - $time_start)); - echo $time_diff; - echo ""; - } - unset ($sql, $prep_statement, $result); + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (!permission_exists('contact_time_add')) { echo "access denied"; exit; } + +//get contact and time uuids + $domain_uuid = check_str($_REQUEST['domain_uuid']); + $contact_uuid = check_str($_REQUEST['contact_uuid']); + $contact_time_uuid = check_str($_REQUEST['contact_time_uuid']); + +//get time quantity + $sql = "select "; + $sql .= "time_start "; + $sql .= "from v_contact_times "; + $sql .= "where domain_uuid = '".$domain_uuid."' "; + $sql .= "and contact_time_uuid = '".$contact_time_uuid."' "; + $sql .= "and user_uuid = '".$_SESSION['user']['user_uuid']."' "; + $sql .= "and contact_uuid = '".$contact_uuid."' "; + $sql .= "and time_start is not null "; + $sql .= "and time_stop is null "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_NAMED); + if (sizeof($result) > 0) { + $time_start = strtotime($result["time_start"]); + $time_now = strtotime(date("Y-m-d H:i:s")); + $time_diff = gmdate("H:i:s", ($time_now - $time_start)); + echo $time_diff; + echo ""; + } + unset ($sql, $prep_statement, $result); ?> \ No newline at end of file diff --git a/app/contacts/resources/functions/google_get_contacts.php b/app/contacts/resources/functions/google_get_contacts.php index d54dab08e6..0e2fb6c1e8 100644 --- a/app/contacts/resources/functions/google_get_contacts.php +++ b/app/contacts/resources/functions/google_get_contacts.php @@ -1,114 +1,114 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2013 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -function google_get_contacts($token, $max_results = 50) { - //global $records; - global $groups; - - //$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&oauth_token='.$_SESSION['contact_auth']['token']; // all contacts as xml - //$url = 'https://www.google.com/m8/feeds/contacts/default/full/78967d550d3fdd99?alt=json&v=3.0&oauth_token='.$_SESSION['contact_auth']['token']; // single contact - $url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$token; // all contacts as json - $xml_response = curl_file_get_contents($url); - $records = json_decode($xml_response, true); - - //check for authentication errors (logged out of google account, or app access permission revoked, etc) - if ($records['error']['code']) { - header("Location: contact_auth.php?source=google&target=".substr($_SERVER["PHP_SELF"], strrpos($_SERVER["PHP_SELF"],'/')+1)); - exit; - } - - //create new array of contacts - foreach($records['feed']['entry'] as $contact['number'] => $contact) { - $contact_id = substr($contact['id']['$t'], strrpos($contact['id']['$t'], "/")+1); - $contacts[$contact_id]['etag'] = $contact['gd$etag']; - $contacts[$contact_id]['updated'] = $contact['updated']['$t']; - $contacts[$contact_id]['name_prefix'] = $contact['gd$name']['gd$namePrefix']['$t']; - $contacts[$contact_id]['name_given'] = $contact['gd$name']['gd$givenName']['$t']; - $contacts[$contact_id]['name_middle'] = $contact['gd$name']['gd$additionalName']['$t']; - $contacts[$contact_id]['name_family'] = $contact['gd$name']['gd$familyName']['$t']; - $contacts[$contact_id]['name_suffix'] = $contact['gd$name']['gd$nameSuffix']['$t']; - $contacts[$contact_id]['nickname'] = $contact['gContact$nickname']['$t']; - $contacts[$contact_id]['title'] = $contact['gd$organization'][0]['gd$orgTitle']['$t']; - $contacts[$contact_id]['organization'] = $contact['gd$organization'][0]['gd$orgName']['$t']; - foreach ($contact['gd$email'] as $contact_email['number'] => $contact_email) { - if ($contact_email['label']) { - $contact_email_label = $contact_email['label']; - } - else { - $contact_email_label = substr($contact_email['rel'], strpos($contact_email['rel'], "#")+1); - $contact_email_label = ucwords(str_replace("_", " ", $contact_email_label)); - } - $contacts[$contact_id]['emails'][$contact_email['number']]['label'] = $contact_email_label; - $contacts[$contact_id]['emails'][$contact_email['number']]['address'] = $contact_email['address']; - $contacts[$contact_id]['emails'][$contact_email['number']]['primary'] = ($contact_email['primary']) ? 1 : 0; - } - foreach ($contact['gd$phoneNumber'] as $contact_phone['number'] => $contact_phone) { - if ($contact_phone['label']) { - $contact_phone_label = $contact_phone['label']; - } - else { - $contact_phone_label = substr($contact_phone['rel'], strpos($contact_phone['rel'], "#")+1); - $contact_phone_label = ucwords(str_replace("_", " ", $contact_phone_label)); - } - $contacts[$contact_id]['numbers'][$contact_phone['number']]['label'] = $contact_phone_label; - $contacts[$contact_id]['numbers'][$contact_phone['number']]['number'] = preg_replace('{\D}', '', $contact_phone['$t']); - } - foreach ($contact['gContact$website'] as $contact_website['number'] => $contact_website) { - $contact_website_label = ($contact_website['label']) ? $contact_website['label'] : ucwords(str_replace("_", " ", $contact_website['rel'])); - $contacts[$contact_id]['urls'][$contact_website['number']]['label'] = $contact_website_label; - $contacts[$contact_id]['urls'][$contact_website['number']]['url'] = $contact_website['href']; - } - foreach ($contact['gd$structuredPostalAddress'] as $contact_address['number'] => $contact_address) { - if ($contact_address['label']) { - $contact_address_label = $contact_address['label']; - } - else { - $contact_address_label = substr($contact_address['rel'], strpos($contact_address['rel'], "#")+1); - $contact_address_label = ucwords(str_replace("_", " ", $contact_address_label)); - } - $contacts[$contact_id]['addresses'][$contact_address['number']]['label'] = $contact_address_label; - $contacts[$contact_id]['addresses'][$contact_address['number']]['street'] = $contact_address['gd$street']['$t']; - $contacts[$contact_id]['addresses'][$contact_address['number']]['extended'] = $contact_address['gd$pobox']['$t']; - $contacts[$contact_id]['addresses'][$contact_address['number']]['community'] = $contact_address['gd$neighborhood']['$t']; - $contacts[$contact_id]['addresses'][$contact_address['number']]['locality'] = $contact_address['gd$city']['$t']; - $contacts[$contact_id]['addresses'][$contact_address['number']]['region'] = $contact_address['gd$region']['$t']; - $contacts[$contact_id]['addresses'][$contact_address['number']]['postal_code'] = $contact_address['gd$postcode']['$t']; - $contacts[$contact_id]['addresses'][$contact_address['number']]['country'] = $contact_address['gd$country']['$t']; - } - foreach ($contact['gContact$groupMembershipInfo'] as $contact_group['number'] => $contact_group) { - $contact_group_id = substr($contact_group['href'], strrpos($contact_group['href'], "/")+1); - $contacts[$contact_id]['groups'][$contact_group_id] = $groups[$contact_group_id]['name']; - } - $contacts[$contact_id]['notes'] = $contact['content']['$t']; - } - - //set account holder info - $_SESSION['contact_auth']['name'] = $records['feed']['author'][0]['name']['$t']; - $_SESSION['contact_auth']['email'] = $records['feed']['author'][0]['email']['$t']; - - return $contacts; -} + + Portions created by the Initial Developer are Copyright (C) 2008-2013 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +function google_get_contacts($token, $max_results = 50) { + //global $records; + global $groups; + + //$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&oauth_token='.$_SESSION['contact_auth']['token']; // all contacts as xml + //$url = 'https://www.google.com/m8/feeds/contacts/default/full/78967d550d3fdd99?alt=json&v=3.0&oauth_token='.$_SESSION['contact_auth']['token']; // single contact + $url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$token; // all contacts as json + $xml_response = curl_file_get_contents($url); + $records = json_decode($xml_response, true); + + //check for authentication errors (logged out of google account, or app access permission revoked, etc) + if ($records['error']['code']) { + header("Location: contact_auth.php?source=google&target=".substr($_SERVER["PHP_SELF"], strrpos($_SERVER["PHP_SELF"],'/')+1)); + exit; + } + + //create new array of contacts + foreach($records['feed']['entry'] as $contact['number'] => $contact) { + $contact_id = substr($contact['id']['$t'], strrpos($contact['id']['$t'], "/")+1); + $contacts[$contact_id]['etag'] = $contact['gd$etag']; + $contacts[$contact_id]['updated'] = $contact['updated']['$t']; + $contacts[$contact_id]['name_prefix'] = $contact['gd$name']['gd$namePrefix']['$t']; + $contacts[$contact_id]['name_given'] = $contact['gd$name']['gd$givenName']['$t']; + $contacts[$contact_id]['name_middle'] = $contact['gd$name']['gd$additionalName']['$t']; + $contacts[$contact_id]['name_family'] = $contact['gd$name']['gd$familyName']['$t']; + $contacts[$contact_id]['name_suffix'] = $contact['gd$name']['gd$nameSuffix']['$t']; + $contacts[$contact_id]['nickname'] = $contact['gContact$nickname']['$t']; + $contacts[$contact_id]['title'] = $contact['gd$organization'][0]['gd$orgTitle']['$t']; + $contacts[$contact_id]['organization'] = $contact['gd$organization'][0]['gd$orgName']['$t']; + foreach ($contact['gd$email'] as $contact_email['number'] => $contact_email) { + if ($contact_email['label']) { + $contact_email_label = $contact_email['label']; + } + else { + $contact_email_label = substr($contact_email['rel'], strpos($contact_email['rel'], "#")+1); + $contact_email_label = ucwords(str_replace("_", " ", $contact_email_label)); + } + $contacts[$contact_id]['emails'][$contact_email['number']]['label'] = $contact_email_label; + $contacts[$contact_id]['emails'][$contact_email['number']]['address'] = $contact_email['address']; + $contacts[$contact_id]['emails'][$contact_email['number']]['primary'] = ($contact_email['primary']) ? 1 : 0; + } + foreach ($contact['gd$phoneNumber'] as $contact_phone['number'] => $contact_phone) { + if ($contact_phone['label']) { + $contact_phone_label = $contact_phone['label']; + } + else { + $contact_phone_label = substr($contact_phone['rel'], strpos($contact_phone['rel'], "#")+1); + $contact_phone_label = ucwords(str_replace("_", " ", $contact_phone_label)); + } + $contacts[$contact_id]['numbers'][$contact_phone['number']]['label'] = $contact_phone_label; + $contacts[$contact_id]['numbers'][$contact_phone['number']]['number'] = preg_replace('{\D}', '', $contact_phone['$t']); + } + foreach ($contact['gContact$website'] as $contact_website['number'] => $contact_website) { + $contact_website_label = ($contact_website['label']) ? $contact_website['label'] : ucwords(str_replace("_", " ", $contact_website['rel'])); + $contacts[$contact_id]['urls'][$contact_website['number']]['label'] = $contact_website_label; + $contacts[$contact_id]['urls'][$contact_website['number']]['url'] = $contact_website['href']; + } + foreach ($contact['gd$structuredPostalAddress'] as $contact_address['number'] => $contact_address) { + if ($contact_address['label']) { + $contact_address_label = $contact_address['label']; + } + else { + $contact_address_label = substr($contact_address['rel'], strpos($contact_address['rel'], "#")+1); + $contact_address_label = ucwords(str_replace("_", " ", $contact_address_label)); + } + $contacts[$contact_id]['addresses'][$contact_address['number']]['label'] = $contact_address_label; + $contacts[$contact_id]['addresses'][$contact_address['number']]['street'] = $contact_address['gd$street']['$t']; + $contacts[$contact_id]['addresses'][$contact_address['number']]['extended'] = $contact_address['gd$pobox']['$t']; + $contacts[$contact_id]['addresses'][$contact_address['number']]['community'] = $contact_address['gd$neighborhood']['$t']; + $contacts[$contact_id]['addresses'][$contact_address['number']]['locality'] = $contact_address['gd$city']['$t']; + $contacts[$contact_id]['addresses'][$contact_address['number']]['region'] = $contact_address['gd$region']['$t']; + $contacts[$contact_id]['addresses'][$contact_address['number']]['postal_code'] = $contact_address['gd$postcode']['$t']; + $contacts[$contact_id]['addresses'][$contact_address['number']]['country'] = $contact_address['gd$country']['$t']; + } + foreach ($contact['gContact$groupMembershipInfo'] as $contact_group['number'] => $contact_group) { + $contact_group_id = substr($contact_group['href'], strrpos($contact_group['href'], "/")+1); + $contacts[$contact_id]['groups'][$contact_group_id] = $groups[$contact_group_id]['name']; + } + $contacts[$contact_id]['notes'] = $contact['content']['$t']; + } + + //set account holder info + $_SESSION['contact_auth']['name'] = $records['feed']['author'][0]['name']['$t']; + $_SESSION['contact_auth']['email'] = $records['feed']['author'][0]['email']['$t']; + + return $contacts; +} ?> \ No newline at end of file diff --git a/app/contacts/resources/functions/google_get_groups.php b/app/contacts/resources/functions/google_get_groups.php index 2af9182f3c..6f0a3e6614 100644 --- a/app/contacts/resources/functions/google_get_groups.php +++ b/app/contacts/resources/functions/google_get_groups.php @@ -1,54 +1,54 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2013 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -function google_get_groups($token) { - // retrieve groups - $url = 'https://www.google.com/m8/feeds/groups/default/full?alt=json&v=3.0&oauth_token='.$token; - $xml_response = curl_file_get_contents($url); - $records = json_decode($xml_response, true); - - //check for authentication errors - if ($records['error']['code']) { - header("Location: contact_auth.php?source=google&target=".substr($_SERVER["PHP_SELF"], strrpos($_SERVER["PHP_SELF"],'/')+1)); - exit; - } - - //create new array of groups - foreach($records['feed']['entry'] as $group['number'] => $group) { - $group_id = substr($group['id']['$t'], strrpos($group['id']['$t'], "/")+1); - $groups[$group_id]['name'] = ($group['gContact$systemGroup']['id']) ? $group['gContact$systemGroup']['id'] : $group['title']['$t']; - $groups[$group_id]['count'] = 0; - unset($group_id); - } - unset($group); - - //set account holder info - $_SESSION['contact_auth']['name'] = $records['feed']['author'][0]['name']['$t']; - $_SESSION['contact_auth']['email'] = $records['feed']['author'][0]['email']['$t']; - - return $groups; -} + + Portions created by the Initial Developer are Copyright (C) 2008-2013 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +function google_get_groups($token) { + // retrieve groups + $url = 'https://www.google.com/m8/feeds/groups/default/full?alt=json&v=3.0&oauth_token='.$token; + $xml_response = curl_file_get_contents($url); + $records = json_decode($xml_response, true); + + //check for authentication errors + if ($records['error']['code']) { + header("Location: contact_auth.php?source=google&target=".substr($_SERVER["PHP_SELF"], strrpos($_SERVER["PHP_SELF"],'/')+1)); + exit; + } + + //create new array of groups + foreach($records['feed']['entry'] as $group['number'] => $group) { + $group_id = substr($group['id']['$t'], strrpos($group['id']['$t'], "/")+1); + $groups[$group_id]['name'] = ($group['gContact$systemGroup']['id']) ? $group['gContact$systemGroup']['id'] : $group['title']['$t']; + $groups[$group_id]['count'] = 0; + unset($group_id); + } + unset($group); + + //set account holder info + $_SESSION['contact_auth']['name'] = $records['feed']['author'][0]['name']['$t']; + $_SESSION['contact_auth']['email'] = $records['feed']['author'][0]['email']['$t']; + + return $groups; +} ?> \ No newline at end of file diff --git a/app/devices/app_defaults.php b/app/devices/app_defaults.php index 3f3ff972c6..1c2ef71402 100644 --- a/app/devices/app_defaults.php +++ b/app/devices/app_defaults.php @@ -1,54 +1,54 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - - -if ($domains_processed == 1) { - //set all lines to enabled (true) where null or empty string - $sql = "update v_device_lines set "; - $sql .= "enabled = 'true' "; - $sql .= "where enabled is null "; - $sql .= "or enabled = '' "; - $db->exec(check_sql($sql)); - unset($sql); - - //set the device key vendor - $sql = "select * from v_device_keys as k, v_devices as d "; - $sql .= "where d.device_uuid = k.device_uuid "; - $sql .= "and k.device_uuid is not null "; - $sql .= "and k.device_key_vendor is null "; - $s = $db->prepare($sql); - $s->execute(); - $device_keys = $s->fetchAll(PDO::FETCH_ASSOC); - foreach ($device_keys as &$row) { - $sql = "update v_device_keys "; - $sql .= "set device_key_vendor = '".$row["device_vendor"]."' "; - $sql .= "where device_key_uuid = '".$row["device_key_uuid"]."';\n "; - $db->exec(check_sql($sql)); - } - unset($device_keys, $sql); -} - + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + + +if ($domains_processed == 1) { + //set all lines to enabled (true) where null or empty string + $sql = "update v_device_lines set "; + $sql .= "enabled = 'true' "; + $sql .= "where enabled is null "; + $sql .= "or enabled = '' "; + $db->exec(check_sql($sql)); + unset($sql); + + //set the device key vendor + $sql = "select * from v_device_keys as k, v_devices as d "; + $sql .= "where d.device_uuid = k.device_uuid "; + $sql .= "and k.device_uuid is not null "; + $sql .= "and k.device_key_vendor is null "; + $s = $db->prepare($sql); + $s->execute(); + $device_keys = $s->fetchAll(PDO::FETCH_ASSOC); + foreach ($device_keys as &$row) { + $sql = "update v_device_keys "; + $sql .= "set device_key_vendor = '".$row["device_vendor"]."' "; + $sql .= "where device_key_uuid = '".$row["device_key_uuid"]."';\n "; + $db->exec(check_sql($sql)); + } + unset($device_keys, $sql); +} + ?> \ No newline at end of file diff --git a/app/devices/app_languages.php b/app/devices/app_languages.php index 5da21fc234..1bbbc1450b 100644 --- a/app/devices/app_languages.php +++ b/app/devices/app_languages.php @@ -1,2348 +1,2348 @@ - \ No newline at end of file diff --git a/app/devices/device_copy.php b/app/devices/device_copy.php index 78f54aad6b..31f690fa30 100644 --- a/app/devices/device_copy.php +++ b/app/devices/device_copy.php @@ -1,161 +1,161 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('device_add')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//set the http get/post variable(s) to a php variable - if (isset($_REQUEST["id"]) && isset($_REQUEST["mac"])) { - $device_uuid = check_str($_REQUEST["id"]); - $mac_address_new = check_str($_REQUEST["mac"]); - $mac_address_new = preg_replace('#[^a-fA-F0-9./]#', '', $mac_address_new); - } - -//set the default - $save = true; - -//check to see if the mac address exists - if ($mac_address_new == "" || $mac_address_new == "000000000000") { - //allow duplicates to be used as templaes - } - else { - $sql = "SELECT count(*) AS num_rows FROM v_devices "; - $sql .= "WHERE device_mac_address = '".$mac_address_new."' "; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - if ($row['num_rows'] == "0") { - $save = true; - } - else { - $save = false; - $_SESSION['message'] = $text['message-duplicate']; - } - } - unset($prep_statement); - } - -//get the device - $sql = "SELECT * FROM v_devices "; - $sql .= "where device_uuid = '".$device_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $devices = $prep_statement->fetchAll(PDO::FETCH_NAMED); - -//get device lines - $sql = "SELECT * FROM v_device_lines "; - $sql .= "where device_uuid = '".$device_uuid."' "; - $sql .= "order by line_number asc "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_lines = $prep_statement->fetchAll(PDO::FETCH_NAMED); - -//get device keys - $sql = "SELECT * FROM v_device_keys "; - $sql .= "WHERE device_uuid = '".$device_uuid."' "; - $sql .= "ORDER by "; - $sql .= "CASE device_key_category "; - $sql .= "WHEN 'line' THEN 1 "; - $sql .= "WHEN 'memort' THEN 2 "; - $sql .= "WHEN 'programmable' THEN 3 "; - $sql .= "WHEN 'expansion' THEN 4 "; - $sql .= "ELSE 100 END, "; - $sql .= "cast(device_key_id as numeric) asc "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_keys = $prep_statement->fetchAll(PDO::FETCH_NAMED); - -//get device settings - $sql = "SELECT * FROM v_device_settings "; - $sql .= "WHERE device_uuid = '".$device_uuid."' "; - $sql .= "ORDER by device_setting_subcategory asc "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - -//prepare the devices array - unset($devices[0]["device_uuid"]); - -//add copy to the device description - $devices[0]["device_description"] = $text['button-copy']." ".$devices[0]["device_description"]; - -//prepare the device_lines array - $x = 0; - foreach ($device_lines as $row) { - unset($device_lines[$x]["device_uuid"]); - unset($device_lines[$x]["device_line_uuid"]); - $x++; - } - -//prepare the device_keys array - $x = 0; - foreach ($device_keys as $row) { - unset($device_keys[$x]["device_uuid"]); - unset($device_keys[$x]["device_key_uuid"]); - $x++; - } - -//prepare the device_settings array - $x = 0; - foreach ($device_settings as $row) { - unset($device_settings[$x]["device_uuid"]); - unset($device_settings[$x]["device_setting_uuid"]); - $x++; - } - -//create the device array - $device = $devices[0]; - $device["device_mac_address"] = $mac_address_new; - $device["device_lines"] = $device_lines; - $device["device_keys"] = $device_keys; - $device["device_settings"] = $device_settings; - -//copy the device - if ($save) { - $orm = new orm; - $orm->name('devices'); - $orm->save($device); - $response = $orm->message; - $_SESSION["message"] = $text['message-copy']; - } - -//redirect - header("Location: devices.php"); - return; - + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('device_add')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//set the http get/post variable(s) to a php variable + if (isset($_REQUEST["id"]) && isset($_REQUEST["mac"])) { + $device_uuid = check_str($_REQUEST["id"]); + $mac_address_new = check_str($_REQUEST["mac"]); + $mac_address_new = preg_replace('#[^a-fA-F0-9./]#', '', $mac_address_new); + } + +//set the default + $save = true; + +//check to see if the mac address exists + if ($mac_address_new == "" || $mac_address_new == "000000000000") { + //allow duplicates to be used as templaes + } + else { + $sql = "SELECT count(*) AS num_rows FROM v_devices "; + $sql .= "WHERE device_mac_address = '".$mac_address_new."' "; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + if ($row['num_rows'] == "0") { + $save = true; + } + else { + $save = false; + $_SESSION['message'] = $text['message-duplicate']; + } + } + unset($prep_statement); + } + +//get the device + $sql = "SELECT * FROM v_devices "; + $sql .= "where device_uuid = '".$device_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $devices = $prep_statement->fetchAll(PDO::FETCH_NAMED); + +//get device lines + $sql = "SELECT * FROM v_device_lines "; + $sql .= "where device_uuid = '".$device_uuid."' "; + $sql .= "order by line_number asc "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_lines = $prep_statement->fetchAll(PDO::FETCH_NAMED); + +//get device keys + $sql = "SELECT * FROM v_device_keys "; + $sql .= "WHERE device_uuid = '".$device_uuid."' "; + $sql .= "ORDER by "; + $sql .= "CASE device_key_category "; + $sql .= "WHEN 'line' THEN 1 "; + $sql .= "WHEN 'memort' THEN 2 "; + $sql .= "WHEN 'programmable' THEN 3 "; + $sql .= "WHEN 'expansion' THEN 4 "; + $sql .= "ELSE 100 END, "; + $sql .= "cast(device_key_id as numeric) asc "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_keys = $prep_statement->fetchAll(PDO::FETCH_NAMED); + +//get device settings + $sql = "SELECT * FROM v_device_settings "; + $sql .= "WHERE device_uuid = '".$device_uuid."' "; + $sql .= "ORDER by device_setting_subcategory asc "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + +//prepare the devices array + unset($devices[0]["device_uuid"]); + +//add copy to the device description + $devices[0]["device_description"] = $text['button-copy']." ".$devices[0]["device_description"]; + +//prepare the device_lines array + $x = 0; + foreach ($device_lines as $row) { + unset($device_lines[$x]["device_uuid"]); + unset($device_lines[$x]["device_line_uuid"]); + $x++; + } + +//prepare the device_keys array + $x = 0; + foreach ($device_keys as $row) { + unset($device_keys[$x]["device_uuid"]); + unset($device_keys[$x]["device_key_uuid"]); + $x++; + } + +//prepare the device_settings array + $x = 0; + foreach ($device_settings as $row) { + unset($device_settings[$x]["device_uuid"]); + unset($device_settings[$x]["device_setting_uuid"]); + $x++; + } + +//create the device array + $device = $devices[0]; + $device["device_mac_address"] = $mac_address_new; + $device["device_lines"] = $device_lines; + $device["device_keys"] = $device_keys; + $device["device_settings"] = $device_settings; + +//copy the device + if ($save) { + $orm = new orm; + $orm->name('devices'); + $orm->save($device); + $response = $orm->message; + $_SESSION["message"] = $text['message-copy']; + } + +//redirect + header("Location: devices.php"); + return; + ?> \ No newline at end of file diff --git a/app/devices/device_profile_copy.php b/app/devices/device_profile_copy.php index 1ce9628ced..3caf000f09 100644 --- a/app/devices/device_profile_copy.php +++ b/app/devices/device_profile_copy.php @@ -1,161 +1,161 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('device_add')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//set the http get/post variable(s) to a php variable - if (isset($_REQUEST["id"]) && isset($_REQUEST["mac"])) { - $device_uuid = check_str($_REQUEST["id"]); - $mac_address_new = check_str($_REQUEST["mac"]); - $mac_address_new = preg_replace('#[^a-fA-F0-9./]#', '', $mac_address_new); - } - -//set the default - $save = true; - -//check to see if the mac address exists - if ($mac_address_new == "" || $mac_address_new == "000000000000") { - //allow duplicates to be used as templaes - } - else { - $sql = "SELECT count(*) AS num_rows FROM v_devices "; - $sql .= "WHERE device_mac_address = '".$mac_address_new."' "; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - if ($row['num_rows'] == "0") { - $save = true; - } - else { - $save = false; - $_SESSION['message'] = $text['message-duplicate']; - } - } - unset($prep_statement); - } - -//get the device - $sql = "SELECT * FROM v_devices "; - $sql .= "where device_uuid = '".$device_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $devices = $prep_statement->fetchAll(PDO::FETCH_NAMED); - -//get device lines - $sql = "SELECT * FROM v_device_lines "; - $sql .= "where device_uuid = '".$device_uuid."' "; - $sql .= "order by line_number asc "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_lines = $prep_statement->fetchAll(PDO::FETCH_NAMED); - -//get device keys - $sql = "SELECT * FROM v_device_keys "; - $sql .= "WHERE device_uuid = '".$device_uuid."' "; - $sql .= "ORDER by "; - $sql .= "CASE device_key_category "; - $sql .= "WHEN 'line' THEN 1 "; - $sql .= "WHEN 'memort' THEN 2 "; - $sql .= "WHEN 'programmable' THEN 3 "; - $sql .= "WHEN 'expansion' THEN 4 "; - $sql .= "ELSE 100 END, "; - $sql .= "cast(device_key_id as numeric) asc "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_keys = $prep_statement->fetchAll(PDO::FETCH_NAMED); - -//get device settings - $sql = "SELECT * FROM v_device_settings "; - $sql .= "WHERE device_uuid = '".$device_uuid."' "; - $sql .= "ORDER by device_setting_subcategory asc "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - -//prepare the devices array - unset($devices[0]["device_uuid"]); - -//add copy to the device description - $devices[0]["device_description"] = $text['button-copy']." ".$devices[0]["device_description"]; - -//prepare the device_lines array - $x = 0; - foreach ($device_lines as $row) { - unset($device_lines[$x]["device_uuid"]); - unset($device_lines[$x]["device_line_uuid"]); - $x++; - } - -//prepare the device_keys array - $x = 0; - foreach ($device_keys as $row) { - unset($device_keys[$x]["device_uuid"]); - unset($device_keys[$x]["device_key_uuid"]); - $x++; - } - -//prepare the device_settings array - $x = 0; - foreach ($device_settings as $row) { - unset($device_settings[$x]["device_uuid"]); - unset($device_settings[$x]["device_setting_uuid"]); - $x++; - } - -//create the device array - $device = $devices[0]; - $device["device_mac_address"] = $mac_address_new; - $device["device_lines"] = $device_lines; - $device["device_keys"] = $device_keys; - $device["device_settings"] = $device_settings; - -//copy the device - if ($save) { - $orm = new orm; - $orm->name('devices'); - $orm->save($device); - $response = $orm->message; - $_SESSION["message"] = $text['message-copy']; - } - -//redirect - header("Location: devices.php"); - return; - + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('device_add')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//set the http get/post variable(s) to a php variable + if (isset($_REQUEST["id"]) && isset($_REQUEST["mac"])) { + $device_uuid = check_str($_REQUEST["id"]); + $mac_address_new = check_str($_REQUEST["mac"]); + $mac_address_new = preg_replace('#[^a-fA-F0-9./]#', '', $mac_address_new); + } + +//set the default + $save = true; + +//check to see if the mac address exists + if ($mac_address_new == "" || $mac_address_new == "000000000000") { + //allow duplicates to be used as templaes + } + else { + $sql = "SELECT count(*) AS num_rows FROM v_devices "; + $sql .= "WHERE device_mac_address = '".$mac_address_new."' "; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + if ($row['num_rows'] == "0") { + $save = true; + } + else { + $save = false; + $_SESSION['message'] = $text['message-duplicate']; + } + } + unset($prep_statement); + } + +//get the device + $sql = "SELECT * FROM v_devices "; + $sql .= "where device_uuid = '".$device_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $devices = $prep_statement->fetchAll(PDO::FETCH_NAMED); + +//get device lines + $sql = "SELECT * FROM v_device_lines "; + $sql .= "where device_uuid = '".$device_uuid."' "; + $sql .= "order by line_number asc "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_lines = $prep_statement->fetchAll(PDO::FETCH_NAMED); + +//get device keys + $sql = "SELECT * FROM v_device_keys "; + $sql .= "WHERE device_uuid = '".$device_uuid."' "; + $sql .= "ORDER by "; + $sql .= "CASE device_key_category "; + $sql .= "WHEN 'line' THEN 1 "; + $sql .= "WHEN 'memort' THEN 2 "; + $sql .= "WHEN 'programmable' THEN 3 "; + $sql .= "WHEN 'expansion' THEN 4 "; + $sql .= "ELSE 100 END, "; + $sql .= "cast(device_key_id as numeric) asc "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_keys = $prep_statement->fetchAll(PDO::FETCH_NAMED); + +//get device settings + $sql = "SELECT * FROM v_device_settings "; + $sql .= "WHERE device_uuid = '".$device_uuid."' "; + $sql .= "ORDER by device_setting_subcategory asc "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + +//prepare the devices array + unset($devices[0]["device_uuid"]); + +//add copy to the device description + $devices[0]["device_description"] = $text['button-copy']." ".$devices[0]["device_description"]; + +//prepare the device_lines array + $x = 0; + foreach ($device_lines as $row) { + unset($device_lines[$x]["device_uuid"]); + unset($device_lines[$x]["device_line_uuid"]); + $x++; + } + +//prepare the device_keys array + $x = 0; + foreach ($device_keys as $row) { + unset($device_keys[$x]["device_uuid"]); + unset($device_keys[$x]["device_key_uuid"]); + $x++; + } + +//prepare the device_settings array + $x = 0; + foreach ($device_settings as $row) { + unset($device_settings[$x]["device_uuid"]); + unset($device_settings[$x]["device_setting_uuid"]); + $x++; + } + +//create the device array + $device = $devices[0]; + $device["device_mac_address"] = $mac_address_new; + $device["device_lines"] = $device_lines; + $device["device_keys"] = $device_keys; + $device["device_settings"] = $device_settings; + +//copy the device + if ($save) { + $orm = new orm; + $orm->name('devices'); + $orm->save($device); + $response = $orm->message; + $_SESSION["message"] = $text['message-copy']; + } + +//redirect + header("Location: devices.php"); + return; + ?> \ No newline at end of file diff --git a/app/devices/device_profile_delete.php b/app/devices/device_profile_delete.php index 0e15377dc8..56963ff7f3 100644 --- a/app/devices/device_profile_delete.php +++ b/app/devices/device_profile_delete.php @@ -1,76 +1,76 @@ - - Copyright (C) 2008-2015 All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('device_profile_delete')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get the id - if (isset($_GET["id"])) { - $id = $_GET["id"]; - } - -//delete the data and subdata - if (is_uuid($id)) { - - //delete device profile keys - $sql = "delete from v_device_keys "; - $sql .= "where device_profile_uuid = '".$id."' "; - $db->exec($sql); - unset($sql); - - //delete device profile - $sql = "delete from v_device_profiles "; - $sql .= "where device_profile_uuid = '".$id."' "; - $db->exec($sql); - unset($sql); - - //remove device profile uuid from any assigned devices - $sql = "update v_devices set "; - $sql .= "device_profile_uuid = null "; - $sql .= "where device_profile_uuid = '".$id."' "; - $db->exec($sql); - unset($sql); - } - -//write the provision files - require_once "app/provision/provision_write.php"; - -//set the message and redirect the user - $_SESSION["message"] = $text['message-delete']; - header("Location: device_profiles.php"); - return; - + + Copyright (C) 2008-2015 All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('device_profile_delete')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get the id + if (isset($_GET["id"])) { + $id = $_GET["id"]; + } + +//delete the data and subdata + if (is_uuid($id)) { + + //delete device profile keys + $sql = "delete from v_device_keys "; + $sql .= "where device_profile_uuid = '".$id."' "; + $db->exec($sql); + unset($sql); + + //delete device profile + $sql = "delete from v_device_profiles "; + $sql .= "where device_profile_uuid = '".$id."' "; + $db->exec($sql); + unset($sql); + + //remove device profile uuid from any assigned devices + $sql = "update v_devices set "; + $sql .= "device_profile_uuid = null "; + $sql .= "where device_profile_uuid = '".$id."' "; + $db->exec($sql); + unset($sql); + } + +//write the provision files + require_once "app/provision/provision_write.php"; + +//set the message and redirect the user + $_SESSION["message"] = $text['message-delete']; + header("Location: device_profiles.php"); + return; + ?> \ No newline at end of file diff --git a/app/devices/device_profile_edit.php b/app/devices/device_profile_edit.php index 025a1519f5..2af5d3348e 100644 --- a/app/devices/device_profile_edit.php +++ b/app/devices/device_profile_edit.php @@ -1,708 +1,708 @@ - - Copyright (C) 2008-2015 All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; - -//check permissions - require_once "resources/check_auth.php"; - if (permission_exists('device_profile_add') || permission_exists('device_profile_edit')) { - //access granted - } - else { - echo "access denied"; - exit; - } - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//action add or update - if (isset($_REQUEST["id"])) { - $action = "update"; - $device_profile_uuid = check_str($_REQUEST["id"]); - } - else { - $action = "add"; - } - -//get http post variables and set them to php variables - if (count($_POST) > 0) { - //echo ""; exit; - $device_profile_name = check_str($_POST["device_profile_name"]); - $device_profile_enabled = check_str($_POST["device_profile_enabled"]); - $device_profile_description = check_str($_POST["device_profile_description"]); - $device_key_category = check_str($_POST["device_key_category"]); - $device_key_id = check_str($_POST["device_key_id"]); - $device_key_type = check_str($_POST["device_key_type"]); - $device_key_line = check_str($_POST["device_key_line"]); - $device_key_value = check_str($_POST["device_key_value"]); - $device_key_extension = check_str($_POST["device_key_extension"]); - $device_key_label = check_str($_POST["device_key_label"]); - - //allow the domain_uuid to be changed only with the device_profile_domain permission - if (permission_exists('device_profile_domain')) { - $domain_uuid = check_str($_POST["domain_uuid"]); - } - else { - $_POST["domain_uuid"] = $_SESSION['domain_uuid']; - } - } - -//add or update the database - if (count($_POST) > 0 && strlen($_POST["persistformvar"]) == 0) { - - //check for all required data - $msg = ''; - if (strlen($device_profile_name) == 0) { $msg .= $text['message-required'].$text['label-profile_name']."
\n"; } - if (strlen($msg) > 0) { - require_once "resources/header.php"; - require_once "resources/persist_form_var.php"; - echo "
\n"; - echo "
\n"; - echo $msg."
"; - echo "
\n"; - persistformvar($_POST); - echo "
\n"; - require_once "resources/footer.php"; - return; - } - - //add or update the database - if ($_POST["persistformvar"] != "true") { - //add domain_uuid to the array - foreach ($_POST as $key => $value) { - if (is_array($value)) { - $y = 0; - foreach ($value as $k => $v) { - if (!isset($v["domain_uuid"])) { - $_POST[$key][$y]["domain_uuid"] = $_POST["domain_uuid"]; - } - $y++; - } - } - } - - //array cleanup - $x = 0; - foreach ($_POST["device_keys"] as $row) { - //unset the empty row - if (strlen($row["device_key_category"]) == 0) { - unset($_POST["device_keys"][$x]); - } - //unset device_detail_uuid if the field has no value - if (strlen($row["device_key_uuid"]) == 0) { - unset($_POST["device_keys"][$x]["device_key_uuid"]); - } - //increment the row - $x++; - } - - //set the default - $save = true; - - //save the profile - if ($save) { - $orm = new orm; - $orm->name('device_profiles'); - if (strlen($device_profile_uuid) > 0) { - $orm->uuid($device_profile_uuid); - } - $orm->save($_POST); - $response = $orm->message; - if (strlen($response['uuid']) > 0) { - $device_profile_uuid = $response['uuid']; - } - } - - //write the provision files - if (strlen($_SESSION['provision']['path']['text']) > 0) { - require_once "app/provision/provision_write.php"; - } - - //set the message - if (!isset($_SESSION['message'])) { - if ($save) { - if ($action == "add") { - //save the message to a session variable - $_SESSION['message'] = $text['message-add']; - } - if ($action == "update") { - //save the message to a session variable - $_SESSION['message'] = $text['message-update']; - - } - //redirect the browser - header("Location: device_profile_edit.php?id=".$device_profile_uuid); - exit; - } - } - - } //if ($_POST["persistformvar"] != "true") - } //(count($_POST) > 0 && strlen($_POST["persistformvar"]) == 0) - -//pre-populate the form - if (count($_GET) > 0 && $_POST["persistformvar"] != "true") { - $orm = new orm; - $orm->name('device_profiles'); - $orm->uuid($device_profile_uuid); - $result = $orm->find()->get(); - //$message = $orm->message; - foreach ($result as &$row) { - $device_profile_name = $row["device_profile_name"]; - $device_profile_domain_uuid = $row["domain_uuid"]; - $device_profile_enabled = $row["device_profile_enabled"]; - $device_profile_description = $row["device_profile_description"]; - } - unset ($prep_statement); - } - -//set the sub array index - $x = "999"; - -//get device keys - $sql = "SELECT * FROM v_device_keys "; - $sql .= "WHERE device_profile_uuid = '".$device_profile_uuid."' "; - $sql .= "ORDER by "; - $sql .= "device_key_vendor asc, "; - $sql .= "CASE device_key_category "; - $sql .= "WHEN 'line' THEN 1 "; - $sql .= "WHEN 'memory' THEN 2 "; - $sql .= "WHEN 'programmable' THEN 3 "; - $sql .= "WHEN 'expansion' THEN 4 "; - $sql .= "ELSE 100 END, "; - if ($db_type == "mysql") { - $sql .= "device_key_id asc "; - } - else { - $sql .= "cast(device_key_id as numeric) asc "; - } - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_keys = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $device_keys[$x]['device_key_category'] = ''; - $device_keys[$x]['device_key_id'] = ''; - $device_keys[$x]['device_key_type'] = ''; - $device_keys[$x]['device_key_line'] = ''; - $device_keys[$x]['device_key_value'] = ''; - $device_keys[$x]['device_key_extension'] = ''; - $device_keys[$x]['device_key_label'] = ''; - -//show the header - require_once "resources/header.php"; - $document['title'] = $text['title-profile']; - -//javascript to change select to input and back again - ?> -\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - $vendor_count = 0; - foreach($device_keys as $row) { - if ($previous_vendor != $row['device_key_vendor']) { - $previous_vendor = $row['device_key_vendor']; - $vendor_count++; - } - } - - echo " "; - echo " "; - echo " "; - echo " "; - - if (permission_exists('device_profile_domain')) { - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - } - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo " \n"; - echo ""; - echo "
"; - echo " ".$text['header-profile'].""; - echo "

"; - echo " ".$text['description-profile']; - echo "

"; - echo "
\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " ".$text['label-profile_name']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['description-profile_name']."\n"; - echo "
".$text['label-keys'].""; - echo " \n"; - if ($vendor_count == 0) { - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - } - $x = 0; - foreach($device_keys as $row) { - //set the column names - if ($previous_device_key_vendor != $row['device_key_vendor']) { - echo " \n"; - echo " \n"; - echo " \n"; - if ($vendor_count > 1 && strlen($row['device_key_vendor']) > 0) { - echo " \n"; - } else { - echo " \n"; - } - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - } - //determine whether to hide the element - if (strlen($device_key_uuid) == 0) { - $element['hidden'] = false; - $element['visibility'] = "visibility:visible;"; - } - else { - $element['hidden'] = true; - $element['visibility'] = "visibility:hidden;"; - } - //add the primary key uuid - if (strlen($row['device_key_uuid']) > 0) { - echo " \n"; - } - //show all the rows in the array - echo "\n"; - echo "\n"; - - echo "\n"; - - echo "\n"; - - echo "\n"; - - echo "\n"; - - echo "\n"; - - echo "\n"; - echo " \n"; - //set the previous vendor - $previous_device_key_vendor = $row['device_key_vendor']; - //increment the array key - $x++; - } - echo "
".$text['label-device_key_category']."".$text['label-device_key_id']."".$text['label-device_key_type']."".$text['label-device_key_line']."".$text['label-device_key_value']."".$text['label-device_key_extension']."".$text['label-device_key_label']." 
".$text['label-device_key_category']."".$text['label-device_key_id']."".ucwords($row['device_key_vendor'])."".$text['label-device_key_type']."".$text['label-device_key_line']."".$text['label-device_key_value']."".$text['label-device_key_extension']."".$text['label-device_key_label']." 
\n"; - echo " \n"; - echo "\n"; - echo " \n"; - echo "\n"; - if (strlen($row['device_key_vendor']) > 0) { - $device_key_vendor = $row['device_key_vendor']; - } - else { - $device_key_vendor = $device_vendor; - } - ?> - - - - - - \n"; - echo "\n"; - echo " \n"; - echo "\n"; - echo " \n"; - echo "\n"; - echo " \n"; - echo "\n"; - echo " \n"; - echo "\n"; - if (strlen($row['device_key_uuid']) > 0) { - if (permission_exists('device_key_delete')) { - echo " $v_link_label_delete\n"; - } - } - echo "
\n"; - if (strlen($text['description-keys']) > 0) { - echo "
".$text['description-keys']."\n"; - } - echo "
\n"; - echo " ".$text['label-profile_domain']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['label-profile_enabled']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['description-profile_enabled']."\n"; - echo "
\n"; - echo " ".$text['label-profile_description']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['description-profile_description']."\n"; - echo "
\n"; - if ($action == "update") { - echo " \n"; - } - echo "
"; - echo " \n"; - echo "
"; - echo "

"; - echo ""; - -//show the footer - require_once "resources/footer.php"; + + Copyright (C) 2008-2015 All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; + +//check permissions + require_once "resources/check_auth.php"; + if (permission_exists('device_profile_add') || permission_exists('device_profile_edit')) { + //access granted + } + else { + echo "access denied"; + exit; + } + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//action add or update + if (isset($_REQUEST["id"])) { + $action = "update"; + $device_profile_uuid = check_str($_REQUEST["id"]); + } + else { + $action = "add"; + } + +//get http post variables and set them to php variables + if (count($_POST) > 0) { + //echo ""; exit; + $device_profile_name = check_str($_POST["device_profile_name"]); + $device_profile_enabled = check_str($_POST["device_profile_enabled"]); + $device_profile_description = check_str($_POST["device_profile_description"]); + $device_key_category = check_str($_POST["device_key_category"]); + $device_key_id = check_str($_POST["device_key_id"]); + $device_key_type = check_str($_POST["device_key_type"]); + $device_key_line = check_str($_POST["device_key_line"]); + $device_key_value = check_str($_POST["device_key_value"]); + $device_key_extension = check_str($_POST["device_key_extension"]); + $device_key_label = check_str($_POST["device_key_label"]); + + //allow the domain_uuid to be changed only with the device_profile_domain permission + if (permission_exists('device_profile_domain')) { + $domain_uuid = check_str($_POST["domain_uuid"]); + } + else { + $_POST["domain_uuid"] = $_SESSION['domain_uuid']; + } + } + +//add or update the database + if (count($_POST) > 0 && strlen($_POST["persistformvar"]) == 0) { + + //check for all required data + $msg = ''; + if (strlen($device_profile_name) == 0) { $msg .= $text['message-required'].$text['label-profile_name']."
\n"; } + if (strlen($msg) > 0) { + require_once "resources/header.php"; + require_once "resources/persist_form_var.php"; + echo "
\n"; + echo "
\n"; + echo $msg."
"; + echo "
\n"; + persistformvar($_POST); + echo "
\n"; + require_once "resources/footer.php"; + return; + } + + //add or update the database + if ($_POST["persistformvar"] != "true") { + //add domain_uuid to the array + foreach ($_POST as $key => $value) { + if (is_array($value)) { + $y = 0; + foreach ($value as $k => $v) { + if (!isset($v["domain_uuid"])) { + $_POST[$key][$y]["domain_uuid"] = $_POST["domain_uuid"]; + } + $y++; + } + } + } + + //array cleanup + $x = 0; + foreach ($_POST["device_keys"] as $row) { + //unset the empty row + if (strlen($row["device_key_category"]) == 0) { + unset($_POST["device_keys"][$x]); + } + //unset device_detail_uuid if the field has no value + if (strlen($row["device_key_uuid"]) == 0) { + unset($_POST["device_keys"][$x]["device_key_uuid"]); + } + //increment the row + $x++; + } + + //set the default + $save = true; + + //save the profile + if ($save) { + $orm = new orm; + $orm->name('device_profiles'); + if (strlen($device_profile_uuid) > 0) { + $orm->uuid($device_profile_uuid); + } + $orm->save($_POST); + $response = $orm->message; + if (strlen($response['uuid']) > 0) { + $device_profile_uuid = $response['uuid']; + } + } + + //write the provision files + if (strlen($_SESSION['provision']['path']['text']) > 0) { + require_once "app/provision/provision_write.php"; + } + + //set the message + if (!isset($_SESSION['message'])) { + if ($save) { + if ($action == "add") { + //save the message to a session variable + $_SESSION['message'] = $text['message-add']; + } + if ($action == "update") { + //save the message to a session variable + $_SESSION['message'] = $text['message-update']; + + } + //redirect the browser + header("Location: device_profile_edit.php?id=".$device_profile_uuid); + exit; + } + } + + } //if ($_POST["persistformvar"] != "true") + } //(count($_POST) > 0 && strlen($_POST["persistformvar"]) == 0) + +//pre-populate the form + if (count($_GET) > 0 && $_POST["persistformvar"] != "true") { + $orm = new orm; + $orm->name('device_profiles'); + $orm->uuid($device_profile_uuid); + $result = $orm->find()->get(); + //$message = $orm->message; + foreach ($result as &$row) { + $device_profile_name = $row["device_profile_name"]; + $device_profile_domain_uuid = $row["domain_uuid"]; + $device_profile_enabled = $row["device_profile_enabled"]; + $device_profile_description = $row["device_profile_description"]; + } + unset ($prep_statement); + } + +//set the sub array index + $x = "999"; + +//get device keys + $sql = "SELECT * FROM v_device_keys "; + $sql .= "WHERE device_profile_uuid = '".$device_profile_uuid."' "; + $sql .= "ORDER by "; + $sql .= "device_key_vendor asc, "; + $sql .= "CASE device_key_category "; + $sql .= "WHEN 'line' THEN 1 "; + $sql .= "WHEN 'memory' THEN 2 "; + $sql .= "WHEN 'programmable' THEN 3 "; + $sql .= "WHEN 'expansion' THEN 4 "; + $sql .= "ELSE 100 END, "; + if ($db_type == "mysql") { + $sql .= "device_key_id asc "; + } + else { + $sql .= "cast(device_key_id as numeric) asc "; + } + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_keys = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $device_keys[$x]['device_key_category'] = ''; + $device_keys[$x]['device_key_id'] = ''; + $device_keys[$x]['device_key_type'] = ''; + $device_keys[$x]['device_key_line'] = ''; + $device_keys[$x]['device_key_value'] = ''; + $device_keys[$x]['device_key_extension'] = ''; + $device_keys[$x]['device_key_label'] = ''; + +//show the header + require_once "resources/header.php"; + $document['title'] = $text['title-profile']; + +//javascript to change select to input and back again + ?> +\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + $vendor_count = 0; + foreach($device_keys as $row) { + if ($previous_vendor != $row['device_key_vendor']) { + $previous_vendor = $row['device_key_vendor']; + $vendor_count++; + } + } + + echo " "; + echo " "; + echo " "; + echo " "; + + if (permission_exists('device_profile_domain')) { + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + } + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo " \n"; + echo ""; + echo "
"; + echo " ".$text['header-profile'].""; + echo "

"; + echo " ".$text['description-profile']; + echo "

"; + echo "
\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " ".$text['label-profile_name']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['description-profile_name']."\n"; + echo "
".$text['label-keys'].""; + echo " \n"; + if ($vendor_count == 0) { + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + } + $x = 0; + foreach($device_keys as $row) { + //set the column names + if ($previous_device_key_vendor != $row['device_key_vendor']) { + echo " \n"; + echo " \n"; + echo " \n"; + if ($vendor_count > 1 && strlen($row['device_key_vendor']) > 0) { + echo " \n"; + } else { + echo " \n"; + } + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + } + //determine whether to hide the element + if (strlen($device_key_uuid) == 0) { + $element['hidden'] = false; + $element['visibility'] = "visibility:visible;"; + } + else { + $element['hidden'] = true; + $element['visibility'] = "visibility:hidden;"; + } + //add the primary key uuid + if (strlen($row['device_key_uuid']) > 0) { + echo " \n"; + } + //show all the rows in the array + echo "\n"; + echo "\n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + echo " \n"; + //set the previous vendor + $previous_device_key_vendor = $row['device_key_vendor']; + //increment the array key + $x++; + } + echo "
".$text['label-device_key_category']."".$text['label-device_key_id']."".$text['label-device_key_type']."".$text['label-device_key_line']."".$text['label-device_key_value']."".$text['label-device_key_extension']."".$text['label-device_key_label']." 
".$text['label-device_key_category']."".$text['label-device_key_id']."".ucwords($row['device_key_vendor'])."".$text['label-device_key_type']."".$text['label-device_key_line']."".$text['label-device_key_value']."".$text['label-device_key_extension']."".$text['label-device_key_label']." 
\n"; + echo " \n"; + echo "\n"; + echo " \n"; + echo "\n"; + if (strlen($row['device_key_vendor']) > 0) { + $device_key_vendor = $row['device_key_vendor']; + } + else { + $device_key_vendor = $device_vendor; + } + ?> + + + + + + \n"; + echo "\n"; + echo " \n"; + echo "\n"; + echo " \n"; + echo "\n"; + echo " \n"; + echo "\n"; + echo " \n"; + echo "\n"; + if (strlen($row['device_key_uuid']) > 0) { + if (permission_exists('device_key_delete')) { + echo " $v_link_label_delete\n"; + } + } + echo "
\n"; + if (strlen($text['description-keys']) > 0) { + echo "
".$text['description-keys']."\n"; + } + echo "
\n"; + echo " ".$text['label-profile_domain']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['label-profile_enabled']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['description-profile_enabled']."\n"; + echo "
\n"; + echo " ".$text['label-profile_description']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['description-profile_description']."\n"; + echo "
\n"; + if ($action == "update") { + echo " \n"; + } + echo "
"; + echo " \n"; + echo "
"; + echo "

"; + echo ""; + +//show the footer + require_once "resources/footer.php"; ?> \ No newline at end of file diff --git a/app/devices/device_profiles.php b/app/devices/device_profiles.php index 6159bf520a..52ed5f7d9e 100644 --- a/app/devices/device_profiles.php +++ b/app/devices/device_profiles.php @@ -1,177 +1,177 @@ - - Copyright (C) 2008-2012 All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('device_profile_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get the http values and set them as variables - $search = check_str($_GET["search"]); - if (isset($_GET["order_by"])) { - $order_by = check_str($_GET["order_by"]); - $order = check_str($_GET["order"]); - } - -//additional includes - require_once "resources/header.php"; - $document['title'] = $text['title-profiles']; - require_once "resources/paging.php"; - -//show the content - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
"; - echo " ".$text['header-profiles'].""; - echo "

"; - echo " ".$text['description-profiles']; - echo "
\n"; - echo "
\n"; - echo "     "; - echo " "; - echo " "; - echo "
\n"; - echo "
\n"; - echo "
"; - - //prepare to page the results - $sql = "select count(*) as num_rows from v_device_profiles "; - $sql .= "where (domain_uuid = '".$domain_uuid."' or domain_uuid is null) "; - if (strlen($search) > 0) { - $sql .= "and ("; - $sql .= " device_profile_name like '%".$search."%' "; - $sql .= " or device_profile_description like '%".$search."%' "; - $sql .= ") "; - } - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - $num_rows = ($row['num_rows'] > 0) ? $row['num_rows'] : 0; - } - - //prepare to page the results - $rows_per_page = ($_SESSION['domain']['paging']['numeric'] != '') ? $_SESSION['domain']['paging']['numeric'] : 50; - $param = ""; - $page = $_GET['page']; - if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } - list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); - $offset = $rows_per_page * $page; - - //get the list - $sql = "select * from v_device_profiles "; - $sql .= "where (domain_uuid = '".$domain_uuid."' or domain_uuid is null) "; - if (strlen($search) > 0) { - $sql .= "and ("; - $sql .= " device_profile_name like '%".$search."%' "; - $sql .= " or device_profile_description like '%".$search."%' "; - $sql .= ") "; - } - if (strlen($order_by) == 0) { - $sql .= "order by device_profile_name asc "; - } - else { - $sql .= "order by ".$order_by." ".$order." "; - } - $sql .= "limit ".$rows_per_page." offset ".$offset." "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - unset ($prep_statement, $sql); - - $c = 0; - $row_style["0"] = "row_style0"; - $row_style["1"] = "row_style1"; - - echo "\n"; - echo "\n"; - echo th_order_by('name', $text['label-profile_name'], $order_by, $order); - echo th_order_by('enabled', $text['label-profile_enabled'], $order_by, $order); - echo th_order_by('description', $text['label-profile_description'], $order_by, $order); - echo "\n"; - echo "\n"; - - if ($result_count > 0) { - foreach($result as $row) { - $tr_link = (permission_exists('device_profile_edit')) ? "href='device_profile_edit.php?id=".$row['device_profile_uuid']."'" : null; - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "\n"; - $c = ($c == 0) ? 1 : 0; - } //end foreach - unset($sql, $result, $row_count); - } //end if results - - echo "\n"; - echo "\n"; - echo "\n"; - echo "
\n"; - if (permission_exists('device_profile_add')) { - echo " ".$v_link_label_add."\n"; - } - echo "
"; - echo (permission_exists('device_profile_edit')) ? "".$row['device_profile_name']."" : $row['device_profile_name']; - echo ($row['domain_uuid'] == '') ? "    ".$text['select-global']."" : null; - echo " ".$text['label-'.$row['device_profile_enabled']]." ".$row['device_profile_description']." "; - if (permission_exists('device_profile_edit')) { - echo "".$v_link_label_edit.""; - } - if (permission_exists('device_profile_delete')) { - echo "".$v_link_label_delete.""; - } - echo "
\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
 ".$paging_controls.""; - if (permission_exists('device_profile_add')) { - echo " ".$v_link_label_add.""; - } - echo "
\n"; - echo "
"; - echo "

"; - -//include the footer - require_once "resources/footer.php"; + + Copyright (C) 2008-2012 All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('device_profile_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get the http values and set them as variables + $search = check_str($_GET["search"]); + if (isset($_GET["order_by"])) { + $order_by = check_str($_GET["order_by"]); + $order = check_str($_GET["order"]); + } + +//additional includes + require_once "resources/header.php"; + $document['title'] = $text['title-profiles']; + require_once "resources/paging.php"; + +//show the content + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
"; + echo " ".$text['header-profiles'].""; + echo "

"; + echo " ".$text['description-profiles']; + echo "
\n"; + echo "
\n"; + echo "     "; + echo " "; + echo " "; + echo "
\n"; + echo "
\n"; + echo "
"; + + //prepare to page the results + $sql = "select count(*) as num_rows from v_device_profiles "; + $sql .= "where (domain_uuid = '".$domain_uuid."' or domain_uuid is null) "; + if (strlen($search) > 0) { + $sql .= "and ("; + $sql .= " device_profile_name like '%".$search."%' "; + $sql .= " or device_profile_description like '%".$search."%' "; + $sql .= ") "; + } + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + $num_rows = ($row['num_rows'] > 0) ? $row['num_rows'] : 0; + } + + //prepare to page the results + $rows_per_page = ($_SESSION['domain']['paging']['numeric'] != '') ? $_SESSION['domain']['paging']['numeric'] : 50; + $param = ""; + $page = $_GET['page']; + if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } + list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); + $offset = $rows_per_page * $page; + + //get the list + $sql = "select * from v_device_profiles "; + $sql .= "where (domain_uuid = '".$domain_uuid."' or domain_uuid is null) "; + if (strlen($search) > 0) { + $sql .= "and ("; + $sql .= " device_profile_name like '%".$search."%' "; + $sql .= " or device_profile_description like '%".$search."%' "; + $sql .= ") "; + } + if (strlen($order_by) == 0) { + $sql .= "order by device_profile_name asc "; + } + else { + $sql .= "order by ".$order_by." ".$order." "; + } + $sql .= "limit ".$rows_per_page." offset ".$offset." "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + unset ($prep_statement, $sql); + + $c = 0; + $row_style["0"] = "row_style0"; + $row_style["1"] = "row_style1"; + + echo "\n"; + echo "\n"; + echo th_order_by('name', $text['label-profile_name'], $order_by, $order); + echo th_order_by('enabled', $text['label-profile_enabled'], $order_by, $order); + echo th_order_by('description', $text['label-profile_description'], $order_by, $order); + echo "\n"; + echo "\n"; + + if ($result_count > 0) { + foreach($result as $row) { + $tr_link = (permission_exists('device_profile_edit')) ? "href='device_profile_edit.php?id=".$row['device_profile_uuid']."'" : null; + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "\n"; + $c = ($c == 0) ? 1 : 0; + } //end foreach + unset($sql, $result, $row_count); + } //end if results + + echo "\n"; + echo "\n"; + echo "\n"; + echo "
\n"; + if (permission_exists('device_profile_add')) { + echo " ".$v_link_label_add."\n"; + } + echo "
"; + echo (permission_exists('device_profile_edit')) ? "".$row['device_profile_name']."" : $row['device_profile_name']; + echo ($row['domain_uuid'] == '') ? "    ".$text['select-global']."" : null; + echo " ".$text['label-'.$row['device_profile_enabled']]." ".$row['device_profile_description']." "; + if (permission_exists('device_profile_edit')) { + echo "".$v_link_label_edit.""; + } + if (permission_exists('device_profile_delete')) { + echo "".$v_link_label_delete.""; + } + echo "
\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
 ".$paging_controls.""; + if (permission_exists('device_profile_add')) { + echo " ".$v_link_label_add.""; + } + echo "
\n"; + echo "
"; + echo "

"; + +//include the footer + require_once "resources/footer.php"; ?> \ No newline at end of file diff --git a/app/edit/app_defaults.php b/app/edit/app_defaults.php index f830da4a39..0387dde90f 100644 --- a/app/edit/app_defaults.php +++ b/app/edit/app_defaults.php @@ -1,89 +1,89 @@ -prepare($sql); - $prep_statement->execute(); - $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - - //find the missing default settings - $x = 0; - foreach ($array as $setting) { - $found = false; - $missing[$x] = $setting; - foreach ($default_settings as $row) { - if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { - $found = true; - //remove items from the array that were found - unset($missing[$x]); - } - } - $x++; - } - - //add the missing default settings - foreach ($missing as $row) { - //add the default settings - $orm = new orm; - $orm->name('default_settings'); - $orm->save($row); - $message = $orm->message; - unset($orm); - //print_r($message); - } - unset($missing); - - //unset the array variable - unset($array); - -} - +prepare($sql); + $prep_statement->execute(); + $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + + //find the missing default settings + $x = 0; + foreach ($array as $setting) { + $found = false; + $missing[$x] = $setting; + foreach ($default_settings as $row) { + if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { + $found = true; + //remove items from the array that were found + unset($missing[$x]); + } + } + $x++; + } + + //add the missing default settings + foreach ($missing as $row) { + //add the default settings + $orm = new orm; + $orm->name('default_settings'); + $orm->save($row); + $message = $orm->message; + unset($orm); + //print_r($message); + } + unset($missing); + + //unset the array variable + unset($array); + +} + ?> \ No newline at end of file diff --git a/app/edit/app_menu.php b/app/edit/app_menu.php index 9514cd6b79..5b5866f5c9 100644 --- a/app/edit/app_menu.php +++ b/app/edit/app_menu.php @@ -1,89 +1,89 @@ - \ No newline at end of file diff --git a/app/emails/app_config.php b/app/emails/app_config.php index 273a67f124..3179fa541f 100644 --- a/app/emails/app_config.php +++ b/app/emails/app_config.php @@ -1,93 +1,93 @@ - + diff --git a/app/emails/email_delete.php b/app/emails/email_delete.php index d648b4dbcb..26d20ab2b3 100644 --- a/app/emails/email_delete.php +++ b/app/emails/email_delete.php @@ -1,65 +1,65 @@ - - Copyright (C) 2008-2015 - All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('email_delete')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get posted values, if any - $email_uuid = $_REQUEST["id"]; - - if ($email_uuid != '') { - $sql = "delete from v_emails "; - $sql .= "where email_uuid = '".$email_uuid."' "; - if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { - $sql .= ""; - } else { - $sql .= "and domain_uuid = '".$domain_uuid."' "; - } - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - unset($sql, $prep_statement); - - //set message - if ($_SESSION["message"] == '') { - $_SESSION["message"] = $text['message-delete']; - } - } - -//redirect user - header("Location: emails.php"); - + + Copyright (C) 2008-2015 + All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('email_delete')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get posted values, if any + $email_uuid = $_REQUEST["id"]; + + if ($email_uuid != '') { + $sql = "delete from v_emails "; + $sql .= "where email_uuid = '".$email_uuid."' "; + if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { + $sql .= ""; + } else { + $sql .= "and domain_uuid = '".$domain_uuid."' "; + } + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + unset($sql, $prep_statement); + + //set message + if ($_SESSION["message"] == '') { + $_SESSION["message"] = $text['message-delete']; + } + } + +//redirect user + header("Location: emails.php"); + ?> \ No newline at end of file diff --git a/app/emails/email_view.php b/app/emails/email_view.php index 95597dc9a9..9b5d91c709 100644 --- a/app/emails/email_view.php +++ b/app/emails/email_view.php @@ -1,207 +1,207 @@ - - Copyright (C) 2008-2015 - All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('email_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get email - $email_uuid = check_str($_REQUEST["id"]); - - $msg_found = false; - - if ($email_uuid != '') { - $sql = "select * from v_emails "; - $sql .= "where email_uuid = '".$email_uuid."' "; - $sql .= "and domain_uuid = '".$domain_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - unset ($prep_statement, $sql); - - if ($result_count > 0) { - foreach($result as $row) { - $sent = $row['sent_date']; - $type = $row['type']; - $status = $row['status']; - $email = $row['email']; - $msg_found = true; - break; - } - } - } - - if (!$msg_found) { - $_SESSION["message"] = $text['message-invalid_email']; - header("Location: emails.php"); - exit; - } - -//includes - require('resources/pop3/mime_parser.php'); - require('resources/pop3/rfc822_addresses.php'); - -//parse the email message - $mime = new mime_parser_class; - $mime->decode_bodies = 1; - $parameters = array('Data' => $email); - $success = $mime->Decode($parameters, $decoded); - - if ($success) { - //get the headers - $headers = json_decode($decoded[0]["Headers"]["x-headers:"], true); - $subject = $decoded[0]["Headers"]["subject:"]; - $from = $decoded[0]["Headers"]["from:"]; - $reply_to = $decoded[0]["Headers"]["reply-to:"]; - $to = $decoded[0]["Headers"]["to:"]; - $subject = $decoded[0]["Headers"]["subject:"]; - - if (substr_count($subject, '=?utf-8?B?') > 0) { - $subject = str_replace('=?utf-8?B?', '', $subject); - $subject = str_replace('?=', '', $subject); - $subject = base64_decode($subject); - } - - //get the body - $body = ''; - $content_type = $decoded[0]['Headers']['content-type:']; - if (substr($content_type, 0, 15) == "multipart/mixed" || substr($content_type, 0, 21) == "multipart/alternative") { - foreach($decoded[0]["Parts"] as $row) { - $body_content_type = $row["Headers"]["content-type:"]; - if (substr($body_content_type, 0, 9) == "text/html") { $body = $row["Body"]; } - if (substr($body_content_type, 0, 10) == "text/plain") { $body_plain = $row["Body"]; $body = $body_plain; } - } - } - else { - $content_type_array = explode(";", $content_type); - $body = $decoded[0]["Body"]; - } - - //get the attachments (if any) - foreach ($decoded[0]['Parts'] as &$parts_array) { - $content_type = $parts_array["Parts"][0]["Headers"]["content-type:"]; //audio/wav; name="msg_b64f97e0-8570-11e4-8400-35da04cdaa74.wav" - $content_transfer_encoding = $parts_array["Parts"][0]["Headers"]["content-transfer-encoding:"]; //base64 - $content_disposition = $parts_array["Parts"][0]["Headers"]["content-disposition"]; //attachment; filename="msg_b64f97e0-8570-11e4-8400-35da04cdaa74.wav" - $file_name = $parts_array["FileName"]; - $file_size = $parts_array["BodyLength"]; - } - } - else { - $_SESSION["message"] = $text['message-decoding_error'].(($mime->error != '') ? ': '.htmlspecialchars($mime->error) : null); - header("Location: emails.php"); - exit; - } - -//show the header - $document['title'] = $text['title-view_email']; - require_once "resources/header.php"; - -//show content - echo "\n"; - echo " "; - echo " "; - echo " "; - echo " "; - echo "
"; - echo " ".$text['header-view_email']."\n"; - echo " "; - echo " "; - if (permission_exists('email_download')) { - echo " "; - } - if (permission_exists('email_resend')) { - echo " "; - } - echo "
"; - echo "
\n"; - - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "
".$text['label-sent']."".$sent."
".$text['label-type']."".$text['label-type_'.$type]."
".$text['label-status']."".$text['label-status_'.$status]."
".$text['label-from']."".$from."
".$text['label-to']."".$to."
".$text['label-subject']."".$subject."
".$text['label-message'].""; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
".$text['label-attachment']."".$file_name." (".round($file_size/1024,2)." KB)
\n"; - echo "

"; - -//include the footer - require_once "resources/footer.php"; + + Copyright (C) 2008-2015 + All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('email_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get email + $email_uuid = check_str($_REQUEST["id"]); + + $msg_found = false; + + if ($email_uuid != '') { + $sql = "select * from v_emails "; + $sql .= "where email_uuid = '".$email_uuid."' "; + $sql .= "and domain_uuid = '".$domain_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + unset ($prep_statement, $sql); + + if ($result_count > 0) { + foreach($result as $row) { + $sent = $row['sent_date']; + $type = $row['type']; + $status = $row['status']; + $email = $row['email']; + $msg_found = true; + break; + } + } + } + + if (!$msg_found) { + $_SESSION["message"] = $text['message-invalid_email']; + header("Location: emails.php"); + exit; + } + +//includes + require('resources/pop3/mime_parser.php'); + require('resources/pop3/rfc822_addresses.php'); + +//parse the email message + $mime = new mime_parser_class; + $mime->decode_bodies = 1; + $parameters = array('Data' => $email); + $success = $mime->Decode($parameters, $decoded); + + if ($success) { + //get the headers + $headers = json_decode($decoded[0]["Headers"]["x-headers:"], true); + $subject = $decoded[0]["Headers"]["subject:"]; + $from = $decoded[0]["Headers"]["from:"]; + $reply_to = $decoded[0]["Headers"]["reply-to:"]; + $to = $decoded[0]["Headers"]["to:"]; + $subject = $decoded[0]["Headers"]["subject:"]; + + if (substr_count($subject, '=?utf-8?B?') > 0) { + $subject = str_replace('=?utf-8?B?', '', $subject); + $subject = str_replace('?=', '', $subject); + $subject = base64_decode($subject); + } + + //get the body + $body = ''; + $content_type = $decoded[0]['Headers']['content-type:']; + if (substr($content_type, 0, 15) == "multipart/mixed" || substr($content_type, 0, 21) == "multipart/alternative") { + foreach($decoded[0]["Parts"] as $row) { + $body_content_type = $row["Headers"]["content-type:"]; + if (substr($body_content_type, 0, 9) == "text/html") { $body = $row["Body"]; } + if (substr($body_content_type, 0, 10) == "text/plain") { $body_plain = $row["Body"]; $body = $body_plain; } + } + } + else { + $content_type_array = explode(";", $content_type); + $body = $decoded[0]["Body"]; + } + + //get the attachments (if any) + foreach ($decoded[0]['Parts'] as &$parts_array) { + $content_type = $parts_array["Parts"][0]["Headers"]["content-type:"]; //audio/wav; name="msg_b64f97e0-8570-11e4-8400-35da04cdaa74.wav" + $content_transfer_encoding = $parts_array["Parts"][0]["Headers"]["content-transfer-encoding:"]; //base64 + $content_disposition = $parts_array["Parts"][0]["Headers"]["content-disposition"]; //attachment; filename="msg_b64f97e0-8570-11e4-8400-35da04cdaa74.wav" + $file_name = $parts_array["FileName"]; + $file_size = $parts_array["BodyLength"]; + } + } + else { + $_SESSION["message"] = $text['message-decoding_error'].(($mime->error != '') ? ': '.htmlspecialchars($mime->error) : null); + header("Location: emails.php"); + exit; + } + +//show the header + $document['title'] = $text['title-view_email']; + require_once "resources/header.php"; + +//show content + echo "\n"; + echo " "; + echo " "; + echo " "; + echo " "; + echo "
"; + echo " ".$text['header-view_email']."\n"; + echo " "; + echo " "; + if (permission_exists('email_download')) { + echo " "; + } + if (permission_exists('email_resend')) { + echo " "; + } + echo "
"; + echo "
\n"; + + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "
".$text['label-sent']."".$sent."
".$text['label-type']."".$text['label-type_'.$type]."
".$text['label-status']."".$text['label-status_'.$status]."
".$text['label-from']."".$from."
".$text['label-to']."".$to."
".$text['label-subject']."".$subject."
".$text['label-message'].""; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
".$text['label-attachment']."".$file_name." (".round($file_size/1024,2)." KB)
\n"; + echo "

"; + +//include the footer + require_once "resources/footer.php"; ?> \ No newline at end of file diff --git a/app/emails/emails.php b/app/emails/emails.php index 01167495f5..8b92419bdb 100644 --- a/app/emails/emails.php +++ b/app/emails/emails.php @@ -1,271 +1,271 @@ -get(); - -//get variables used to control the order - $order_by = ($_GET["order_by"] != '') ? $_GET["order_by"] : 'sent_date'; - $order = ($_GET["order"] != '') ? $_GET["order"] : 'desc'; - -//download email - if ($_REQUEST['a'] == 'download' && permission_exists('email_download')) { - $email_uuid = check_str($_REQUEST["id"]); - - $msg_found = false; - - if ($email_uuid != '') { - $sql = "select call_uuid, email from v_emails "; - $sql .= "where email_uuid = '".$email_uuid."' "; - $sql .= "and domain_uuid = '".$domain_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - if ($result_count > 0) { - foreach($result as $row) { - $call_uuid = $row['call_uuid']; - $email = $row['email']; - $msg_found = true; - break; - } - } - unset ($prep_statement, $sql, $result, $result_count); - } - - if ($msg_found) { - header("Content-Type: message/rfc822"); - header('Content-Disposition: attachment; filename="'.$call_uuid.'.eml"'); - header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 - header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past - header("Content-Length: ".strlen($email)); - echo $email; - exit; - } - } - -//resend email - if ($_REQUEST['a'] == 'resend' && permission_exists('email_resend')) { - $email_uuid = check_str($_REQUEST["id"]); - $resend = true; - - $msg_found = false; - - if ($email_uuid != '') { - $sql = "select email from v_emails "; - $sql .= "where email_uuid = '".$email_uuid."' "; - if (!permission_exists('emails_all') || $_REQUEST['showall'] != 'true') { - $sql .= "and domain_uuid = '".$domain_uuid."' "; - } - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - if ($result_count > 0) { - foreach($result as $row) { - $email = $row['email']; - $msg_found = true; - break; - } - } - unset ($prep_statement, $sql, $result, $result_count); - } - - if ($msg_found) { - $msg = $email; - require_once "secure/v_mailto.php"; - if ($mailer_error == '') { - $_SESSION["message"] = $text['message-message_resent']; - if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { - header("Location: email_delete.php?id=".$email_uuid."&showall=true"); - } else { - header("Location: email_delete.php?id=".$email_uuid); - } - } - else { - $_SESSION["message_mood"] = 'negative'; - $_SESSION["message_delay"] = '4'; //sec - $_SESSION["message"] = $text['message-resend_failed'].": ".$mailer_error; - if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { - header("Location: emails.php?showall=true"); - } else { - header("Location: emails.php"); - } - } - } - - exit; - } - -//additional includes - $document['title'] = $text['title-emails']; - require_once "resources/header.php"; - require_once "resources/paging.php"; - -//show the content - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
"; - echo " ".$text['header-emails'].""; - echo "

"; - echo " ".$text['description-emails']; - echo "
\n"; - if (permission_exists('emails_all')) { - if ($_REQUEST['showall'] != 'true') { - echo " \n"; - } - } - echo " \n"; - echo "
\n"; - echo "
\n"; - - //prepare to page the results - $sql = "select count(*) as num_rows from v_emails "; - if (permission_exists('emails_all')) { - if ($_REQUEST['showall'] != 'true') { - $sql .= "where domain_uuid = '".$domain_uuid."' "; - } - } - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - $num_rows = ($row['num_rows'] > 0) ? $row['num_rows'] : 0; - } - - //prepare to page the results - $rows_per_page = ($_SESSION['domain']['paging']['numeric'] != '') ? $_SESSION['domain']['paging']['numeric'] : 50; - if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { - $param .= "&showall=true"; - } else { - $param = ""; - } - $page = $_GET['page']; - if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } - list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); - $offset = $rows_per_page * $page; - - //get the list - $sql = "select * from v_emails "; - if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { - $sql .= " join v_domains on v_emails.domain_uuid = v_domains.domain_uuid "; - } else { - $sql .= "where domain_uuid = '".$domain_uuid."' "; - } - if (strlen($order_by)> 0) { $sql .= "order by ".$order_by." ".$order." "; } - $sql .= "limit ".$rows_per_page." offset ".$offset." "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - unset ($prep_statement, $sql); - - $c = 0; - $row_style["0"] = "row_style0"; - $row_style["1"] = "row_style1"; - - echo "\n"; - - echo "\n"; - if ($_REQUEST['showall'] == true && permission_exists('emails_all')) { - echo th_order_by('domain_name', $text['label-domain-name'], $order_by, $order, null, null, $param); - } - echo th_order_by('sent_date', $text['label-sent'], $order_by, $order, null, null, $param); - echo th_order_by('type', $text['label-type'], $order_by, $order, null, null, $param); - echo th_order_by('status', $text['label-status'], $order_by, $order, null, null, $param); - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if ($result_count > 0) { - foreach($result as $row) { - - //get call details - $sql = "select caller_id_name, caller_id_number, destination_number from v_xml_cdr "; - $sql .= "where domain_uuid = '".$domain_uuid."' "; - $sql .= "and uuid = '".$row['call_uuid']."' "; - //echo ""; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result2 = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach($result2 as $row2) { - $caller_id_name = ($row2['caller_id_name'] != '') ? $row2['caller_id_name'] : null; - $caller_id_number = ($row2['caller_id_number'] != '') ? $row2['caller_id_number'] : null; - $destination_number = ($row2['destination_number'] != '') ? $row2['destination_number'] : null; - } - unset($prep_statement, $sql); - - $tr_link = "href='email_view.php?id=".$row['email_uuid']."'"; - echo "\n"; - if ($_REQUEST['showall'] == true && permission_exists('emails_all')) { - echo " \n"; - } - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "\n"; - if ($c==0) { $c=1; } else { $c=0; } - } //end foreach - unset($sql, $result, $row_count); - } //end if results - - echo "\n"; - echo "\n"; - echo "\n"; - - echo "
".$text['label-message']."".$text['label-reference']." 
".$sql."
".$row['domain_name'].""; - $sent_date = explode('.', $row['sent_date']); - echo $sent_date[0]; - echo " ".$text['label-type_'.$row['type']]."".$text['label-status_'.$row['status']].""; - echo "$v_link_label_view"; - if (permission_exists('email_delete')) { - echo "$v_link_label_delete"; - } - echo "
\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
 $paging_controls 
\n"; - echo "
"; - echo "

"; - -//include the footer - require_once "resources/footer.php"; -?> +get(); + +//get variables used to control the order + $order_by = ($_GET["order_by"] != '') ? $_GET["order_by"] : 'sent_date'; + $order = ($_GET["order"] != '') ? $_GET["order"] : 'desc'; + +//download email + if ($_REQUEST['a'] == 'download' && permission_exists('email_download')) { + $email_uuid = check_str($_REQUEST["id"]); + + $msg_found = false; + + if ($email_uuid != '') { + $sql = "select call_uuid, email from v_emails "; + $sql .= "where email_uuid = '".$email_uuid."' "; + $sql .= "and domain_uuid = '".$domain_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + if ($result_count > 0) { + foreach($result as $row) { + $call_uuid = $row['call_uuid']; + $email = $row['email']; + $msg_found = true; + break; + } + } + unset ($prep_statement, $sql, $result, $result_count); + } + + if ($msg_found) { + header("Content-Type: message/rfc822"); + header('Content-Disposition: attachment; filename="'.$call_uuid.'.eml"'); + header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 + header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past + header("Content-Length: ".strlen($email)); + echo $email; + exit; + } + } + +//resend email + if ($_REQUEST['a'] == 'resend' && permission_exists('email_resend')) { + $email_uuid = check_str($_REQUEST["id"]); + $resend = true; + + $msg_found = false; + + if ($email_uuid != '') { + $sql = "select email from v_emails "; + $sql .= "where email_uuid = '".$email_uuid."' "; + if (!permission_exists('emails_all') || $_REQUEST['showall'] != 'true') { + $sql .= "and domain_uuid = '".$domain_uuid."' "; + } + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + if ($result_count > 0) { + foreach($result as $row) { + $email = $row['email']; + $msg_found = true; + break; + } + } + unset ($prep_statement, $sql, $result, $result_count); + } + + if ($msg_found) { + $msg = $email; + require_once "secure/v_mailto.php"; + if ($mailer_error == '') { + $_SESSION["message"] = $text['message-message_resent']; + if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { + header("Location: email_delete.php?id=".$email_uuid."&showall=true"); + } else { + header("Location: email_delete.php?id=".$email_uuid); + } + } + else { + $_SESSION["message_mood"] = 'negative'; + $_SESSION["message_delay"] = '4'; //sec + $_SESSION["message"] = $text['message-resend_failed'].": ".$mailer_error; + if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { + header("Location: emails.php?showall=true"); + } else { + header("Location: emails.php"); + } + } + } + + exit; + } + +//additional includes + $document['title'] = $text['title-emails']; + require_once "resources/header.php"; + require_once "resources/paging.php"; + +//show the content + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
"; + echo " ".$text['header-emails'].""; + echo "

"; + echo " ".$text['description-emails']; + echo "
\n"; + if (permission_exists('emails_all')) { + if ($_REQUEST['showall'] != 'true') { + echo " \n"; + } + } + echo " \n"; + echo "
\n"; + echo "
\n"; + + //prepare to page the results + $sql = "select count(*) as num_rows from v_emails "; + if (permission_exists('emails_all')) { + if ($_REQUEST['showall'] != 'true') { + $sql .= "where domain_uuid = '".$domain_uuid."' "; + } + } + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + $num_rows = ($row['num_rows'] > 0) ? $row['num_rows'] : 0; + } + + //prepare to page the results + $rows_per_page = ($_SESSION['domain']['paging']['numeric'] != '') ? $_SESSION['domain']['paging']['numeric'] : 50; + if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { + $param .= "&showall=true"; + } else { + $param = ""; + } + $page = $_GET['page']; + if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } + list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); + $offset = $rows_per_page * $page; + + //get the list + $sql = "select * from v_emails "; + if (permission_exists('emails_all') && $_REQUEST['showall'] == 'true') { + $sql .= " join v_domains on v_emails.domain_uuid = v_domains.domain_uuid "; + } else { + $sql .= "where domain_uuid = '".$domain_uuid."' "; + } + if (strlen($order_by)> 0) { $sql .= "order by ".$order_by." ".$order." "; } + $sql .= "limit ".$rows_per_page." offset ".$offset." "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + unset ($prep_statement, $sql); + + $c = 0; + $row_style["0"] = "row_style0"; + $row_style["1"] = "row_style1"; + + echo "\n"; + + echo "\n"; + if ($_REQUEST['showall'] == true && permission_exists('emails_all')) { + echo th_order_by('domain_name', $text['label-domain-name'], $order_by, $order, null, null, $param); + } + echo th_order_by('sent_date', $text['label-sent'], $order_by, $order, null, null, $param); + echo th_order_by('type', $text['label-type'], $order_by, $order, null, null, $param); + echo th_order_by('status', $text['label-status'], $order_by, $order, null, null, $param); + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if ($result_count > 0) { + foreach($result as $row) { + + //get call details + $sql = "select caller_id_name, caller_id_number, destination_number from v_xml_cdr "; + $sql .= "where domain_uuid = '".$domain_uuid."' "; + $sql .= "and uuid = '".$row['call_uuid']."' "; + //echo ""; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result2 = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach($result2 as $row2) { + $caller_id_name = ($row2['caller_id_name'] != '') ? $row2['caller_id_name'] : null; + $caller_id_number = ($row2['caller_id_number'] != '') ? $row2['caller_id_number'] : null; + $destination_number = ($row2['destination_number'] != '') ? $row2['destination_number'] : null; + } + unset($prep_statement, $sql); + + $tr_link = "href='email_view.php?id=".$row['email_uuid']."'"; + echo "\n"; + if ($_REQUEST['showall'] == true && permission_exists('emails_all')) { + echo " \n"; + } + + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "\n"; + if ($c==0) { $c=1; } else { $c=0; } + } //end foreach + unset($sql, $result, $row_count); + } //end if results + + echo "\n"; + echo "\n"; + echo "\n"; + + echo "
".$text['label-message']."".$text['label-reference']." 
".$sql."
".$row['domain_name'].""; + $sent_date = explode('.', $row['sent_date']); + echo $sent_date[0]; + echo " ".$text['label-type_'.$row['type']]."".$text['label-status_'.$row['status']].""; + echo "$v_link_label_view"; + if (permission_exists('email_delete')) { + echo "$v_link_label_delete"; + } + echo "
\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
 $paging_controls 
\n"; + echo "
"; + echo "

"; + +//include the footer + require_once "resources/footer.php"; +?> diff --git a/app/exec/app_config.php b/app/exec/app_config.php index 4d2a439b7e..3d427c408c 100644 --- a/app/exec/app_config.php +++ b/app/exec/app_config.php @@ -1,43 +1,43 @@ - \ No newline at end of file diff --git a/app/exec/app_languages.php b/app/exec/app_languages.php index 4b093206fc..e414f28ba2 100644 --- a/app/exec/app_languages.php +++ b/app/exec/app_languages.php @@ -1,277 +1,277 @@ -PHP Manual"; -$text['description-php']['es-cl'] = "Utilice el siguiente enlace como referencia para PHP: Manual PHP"; -$text['description-php']['pt-pt'] = "Utilize a ligação seguinte como referência para o PHP: PHP Manual"; -$text['description-php']['fr-fr'] = "Utiliser le lien suivant comme référence pour le PHP: Manuel PHP"; -$text['description-php']['pt-br'] = "Utilize a ligação seguinte como referência para o PHP: PHP Manual"; -$text['description-php']['pl'] = "Aby użyć odniesienia do PHP kliknij na ten link: PHP Manual"; -$text['description-php']['sv-se'] = "Använd följande länk som en referens gällande PHP: PHP Manual"; -$text['description-php']['uk'] = "Посилання на довідку PHP: PHP Manual"; -$text['description-php']['de-at'] = "Benutzen Sie folgenden Link als PHP Referenz: \ No newline at end of file diff --git a/app/extensions/app_languages.php b/app/extensions/app_languages.php index 9c983656db..5474833890 100644 --- a/app/extensions/app_languages.php +++ b/app/extensions/app_languages.php @@ -1,1562 +1,1562 @@ - \ No newline at end of file diff --git a/app/fax/app_defaults.php b/app/fax/app_defaults.php index 9ae498c7fa..15cc71b698 100644 --- a/app/fax/app_defaults.php +++ b/app/fax/app_defaults.php @@ -1,175 +1,175 @@ -prepare($sql); - $prep_statement->execute(); - $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - - //find the missing default settings - $x = 0; - foreach ($array as $setting) { - $found = false; - $missing[$x] = $setting; - foreach ($default_settings as $row) { - if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { - $found = true; - //remove items from the array that were found - unset($missing[$x]); - } - } - $x++; - } - - //add the missing default settings - foreach ($missing as $row) { - //add the default settings - $orm = new orm; - $orm->name('default_settings'); - $orm->save($row); - $message = $orm->message; - unset($orm); - } - unset($missing); - -} - +prepare($sql); + $prep_statement->execute(); + $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + + //find the missing default settings + $x = 0; + foreach ($array as $setting) { + $found = false; + $missing[$x] = $setting; + foreach ($default_settings as $row) { + if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { + $found = true; + //remove items from the array that were found + unset($missing[$x]); + } + } + $x++; + } + + //add the missing default settings + foreach ($missing as $row) { + //add the default settings + $orm = new orm; + $orm->name('default_settings'); + $orm->save($row); + $message = $orm->message; + unset($orm); + } + unset($missing); + +} + ?> \ No newline at end of file diff --git a/app/fax/fax_copy.php b/app/fax/fax_copy.php index cf809d9509..500b069fb5 100644 --- a/app/fax/fax_copy.php +++ b/app/fax/fax_copy.php @@ -1,146 +1,146 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -require_once "resources/paging.php"; -if (permission_exists('fax_extension_add')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//set the http get/post variable(s) to a php variable - if (isset($_REQUEST["id"])) { - $fax_uuid = check_str($_REQUEST["id"]); - } - -//get the data - $sql = "select * from v_fax "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and fax_uuid = '$fax_uuid' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) == 0) { - echo "access denied"; - exit; - } - foreach ($result as &$row) { - $fax_extension = $row["fax_extension"]; - $fax_name = $row["fax_name"]; - $fax_email = $row["fax_email"]; - $fax_email_connection_type = $row["fax_email_connection_type"]; - $fax_email_connection_host = $row["fax_email_connection_host"]; - $fax_email_connection_port = $row["fax_email_connection_port"]; - $fax_email_connection_security = $row["fax_email_connection_security"]; - $fax_email_connection_validate = $row["fax_email_connection_validate"]; - $fax_email_connection_username = $row["fax_email_connection_username"]; - $fax_email_connection_password = $row["fax_email_connection_password"]; - $fax_email_connection_mailbox = $row["fax_email_connection_mailbox"]; - $fax_email_inbound_subject_tag = $row["fax_email_inbound_subject_tag"]; - $fax_email_outbound_subject_tag = $row["fax_email_outbound_subject_tag"]; - $fax_email_outbound_authorized_senders = $row["fax_email_outbound_authorized_senders"]; - $fax_pin_number = $row["fax_pin_number"]; - $fax_caller_id_name = $row["fax_caller_id_name"]; - $fax_caller_id_number = $row["fax_caller_id_number"]; - $fax_forward_number = $row["fax_forward_number"]; - $fax_description = 'copy: '.$row["fax_description"]; - } - unset ($prep_statement); - -//copy the fax extension - $fax_uuid = uuid(); - $dialplan_uuid = uuid(); - $sql = "insert into v_fax "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "fax_uuid, "; - $sql .= "dialplan_uuid, "; - $sql .= "fax_extension, "; - $sql .= "fax_name, "; - $sql .= "fax_email, "; - $sql .= "fax_email_connection_type, "; - $sql .= "fax_email_connection_host, "; - $sql .= "fax_email_connection_port, "; - $sql .= "fax_email_connection_security, "; - $sql .= "fax_email_connection_validate, "; - $sql .= "fax_email_connection_username, "; - $sql .= "fax_email_connection_password, "; - $sql .= "fax_email_connection_mailbox, "; - $sql .= "fax_email_inbound_subject_tag, "; - $sql .= "fax_email_outbound_subject_tag, "; - $sql .= "fax_email_outbound_authorized_senders, "; - $sql .= "fax_pin_number, "; - $sql .= "fax_caller_id_name, "; - $sql .= "fax_caller_id_number, "; - if (strlen($fax_forward_number) > 0) { - $sql .= "fax_forward_number, "; - } - $sql .= "fax_description "; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'$fax_uuid', "; - $sql .= "'$dialplan_uuid', "; - $sql .= "'$fax_extension', "; - $sql .= "'$fax_name', "; - $sql .= "'$fax_email', "; - $sql .= "'$fax_email_connection_type', "; - $sql .= "'$fax_email_connection_host', "; - $sql .= "'$fax_email_connection_port', "; - $sql .= "'$fax_email_connection_security', "; - $sql .= "'$fax_email_connection_validate', "; - $sql .= "'$fax_email_connection_username', "; - $sql .= "'$fax_email_connection_password', "; - $sql .= "'$fax_email_connection_mailbox', "; - $sql .= "'$fax_email_inbound_subject_tag', "; - $sql .= "'$fax_email_outbound_subject_tag', "; - $sql .= "'$fax_email_outbound_authorized_senders', "; - $sql .= "'$fax_pin_number', "; - $sql .= "'$fax_caller_id_name', "; - $sql .= "'$fax_caller_id_number', "; - if (strlen($fax_forward_number) > 0) { - $sql .= "'$fax_forward_number', "; - } - $sql .= "'$fax_description' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - -//redirect the user - $_SESSION["message"] = $text['confirm-copy']; - header("Location: fax.php"); - return; - + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +require_once "resources/paging.php"; +if (permission_exists('fax_extension_add')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//set the http get/post variable(s) to a php variable + if (isset($_REQUEST["id"])) { + $fax_uuid = check_str($_REQUEST["id"]); + } + +//get the data + $sql = "select * from v_fax "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and fax_uuid = '$fax_uuid' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) == 0) { + echo "access denied"; + exit; + } + foreach ($result as &$row) { + $fax_extension = $row["fax_extension"]; + $fax_name = $row["fax_name"]; + $fax_email = $row["fax_email"]; + $fax_email_connection_type = $row["fax_email_connection_type"]; + $fax_email_connection_host = $row["fax_email_connection_host"]; + $fax_email_connection_port = $row["fax_email_connection_port"]; + $fax_email_connection_security = $row["fax_email_connection_security"]; + $fax_email_connection_validate = $row["fax_email_connection_validate"]; + $fax_email_connection_username = $row["fax_email_connection_username"]; + $fax_email_connection_password = $row["fax_email_connection_password"]; + $fax_email_connection_mailbox = $row["fax_email_connection_mailbox"]; + $fax_email_inbound_subject_tag = $row["fax_email_inbound_subject_tag"]; + $fax_email_outbound_subject_tag = $row["fax_email_outbound_subject_tag"]; + $fax_email_outbound_authorized_senders = $row["fax_email_outbound_authorized_senders"]; + $fax_pin_number = $row["fax_pin_number"]; + $fax_caller_id_name = $row["fax_caller_id_name"]; + $fax_caller_id_number = $row["fax_caller_id_number"]; + $fax_forward_number = $row["fax_forward_number"]; + $fax_description = 'copy: '.$row["fax_description"]; + } + unset ($prep_statement); + +//copy the fax extension + $fax_uuid = uuid(); + $dialplan_uuid = uuid(); + $sql = "insert into v_fax "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "fax_uuid, "; + $sql .= "dialplan_uuid, "; + $sql .= "fax_extension, "; + $sql .= "fax_name, "; + $sql .= "fax_email, "; + $sql .= "fax_email_connection_type, "; + $sql .= "fax_email_connection_host, "; + $sql .= "fax_email_connection_port, "; + $sql .= "fax_email_connection_security, "; + $sql .= "fax_email_connection_validate, "; + $sql .= "fax_email_connection_username, "; + $sql .= "fax_email_connection_password, "; + $sql .= "fax_email_connection_mailbox, "; + $sql .= "fax_email_inbound_subject_tag, "; + $sql .= "fax_email_outbound_subject_tag, "; + $sql .= "fax_email_outbound_authorized_senders, "; + $sql .= "fax_pin_number, "; + $sql .= "fax_caller_id_name, "; + $sql .= "fax_caller_id_number, "; + if (strlen($fax_forward_number) > 0) { + $sql .= "fax_forward_number, "; + } + $sql .= "fax_description "; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'$fax_uuid', "; + $sql .= "'$dialplan_uuid', "; + $sql .= "'$fax_extension', "; + $sql .= "'$fax_name', "; + $sql .= "'$fax_email', "; + $sql .= "'$fax_email_connection_type', "; + $sql .= "'$fax_email_connection_host', "; + $sql .= "'$fax_email_connection_port', "; + $sql .= "'$fax_email_connection_security', "; + $sql .= "'$fax_email_connection_validate', "; + $sql .= "'$fax_email_connection_username', "; + $sql .= "'$fax_email_connection_password', "; + $sql .= "'$fax_email_connection_mailbox', "; + $sql .= "'$fax_email_inbound_subject_tag', "; + $sql .= "'$fax_email_outbound_subject_tag', "; + $sql .= "'$fax_email_outbound_authorized_senders', "; + $sql .= "'$fax_pin_number', "; + $sql .= "'$fax_caller_id_name', "; + $sql .= "'$fax_caller_id_number', "; + if (strlen($fax_forward_number) > 0) { + $sql .= "'$fax_forward_number', "; + } + $sql .= "'$fax_description' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + +//redirect the user + $_SESSION["message"] = $text['confirm-copy']; + header("Location: fax.php"); + return; + ?> \ No newline at end of file diff --git a/app/fax/fax_edit.php b/app/fax/fax_edit.php index fb7004788c..13a8b5d992 100644 --- a/app/fax/fax_edit.php +++ b/app/fax/fax_edit.php @@ -1,1042 +1,1042 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - Luis Daniel Lucio Quiroz -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('fax_extension_add') || permission_exists('fax_extension_edit') || permission_exists('fax_extension_delete')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//detect billing app - $billing_app_exists = file_exists($_SERVER["PROJECT_ROOT"]."/app/billing/app_config.php"); - - if ($billing_app_exists) { - require_once "app/billing/resources/functions/currency.php"; - require_once "app/billing/resources/functions/rating.php"; - } - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get the fax_extension and save it as a variable - if (strlen($_REQUEST["fax_extension"]) > 0) { - $fax_extension = check_str($_REQUEST["fax_extension"]); - } - -//set the fax directory - $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']; - -//get the fax extension - if (strlen($fax_extension) > 0) { - //set the fax directories. example /usr/local/freeswitch/storage/fax/329/inbox - $dir_fax_inbox = $fax_dir.'/'.$fax_extension.'/inbox'; - $dir_fax_sent = $fax_dir.'/'.$fax_extension.'/sent'; - $dir_fax_temp = $fax_dir.'/'.$fax_extension.'/temp'; - - //make sure the directories exist - if (!is_dir($_SESSION['switch']['storage']['dir'])) { - mkdir($_SESSION['switch']['storage']['dir']); - chmod($dir_fax_sent,0774); - } - if (!is_dir($fax_dir.'/'.$fax_extension)) { - mkdir($fax_dir.'/'.$fax_extension,0774,true); - chmod($fax_dir.'/'.$fax_extension,0774); - } - if (!is_dir($dir_fax_inbox)) { - mkdir($dir_fax_inbox,0774,true); - chmod($dir_fax_inbox,0774); - } - if (!is_dir($dir_fax_sent)) { - mkdir($dir_fax_sent,0774,true); - chmod($dir_fax_sent,0774); - } - if (!is_dir($dir_fax_temp)) { - mkdir($dir_fax_temp,0774,true); - chmod($dir_fax_temp,0774); - } - } - -//set the action as an add or an update - if (isset($_REQUEST["id"])) { - $action = "update"; - $fax_uuid = check_str($_REQUEST["id"]); - $dialplan_uuid = check_str($_REQUEST["dialplan_uuid"]); - } - else { - $action = "add"; - } - -//get the http post values and set them as php variables - if (count($_POST) > 0) { - $fax_name = check_str($_POST["fax_name"]); - $fax_extension = check_str($_POST["fax_extension"]); - $fax_accountcode = check_str($_POST["accountcode"]); - $fax_destination_number = check_str($_POST["fax_destination_number"]); - $fax_prefix = check_str($_POST["fax_prefix"]); - $fax_email = check_str($_POST["fax_email"]); - $fax_email_connection_type = check_str($_POST["fax_email_connection_type"]); - $fax_email_connection_host = check_str($_POST["fax_email_connection_host"]); - $fax_email_connection_port = check_str($_POST["fax_email_connection_port"]); - $fax_email_connection_security = check_str($_POST["fax_email_connection_security"]); - $fax_email_connection_validate = check_str($_POST["fax_email_connection_validate"]); - $fax_email_connection_username = check_str($_POST["fax_email_connection_username"]); - $fax_email_connection_password = check_str($_POST["fax_email_connection_password"]); - $fax_email_connection_mailbox = check_str($_POST["fax_email_connection_mailbox"]); - $fax_email_inbound_subject_tag = check_str($_POST["fax_email_inbound_subject_tag"]); - $fax_email_outbound_subject_tag = check_str($_POST["fax_email_outbound_subject_tag"]); - $fax_email_outbound_authorized_senders = $_POST["fax_email_outbound_authorized_senders"]; - $fax_caller_id_name = check_str($_POST["fax_caller_id_name"]); - $fax_caller_id_number = check_str($_POST["fax_caller_id_number"]); - $fax_forward_number = check_str($_POST["fax_forward_number"]); - if (strlen($fax_destination_number) == 0) { - $fax_destination_number = $fax_extension; - } - if (strlen($fax_forward_number) > 3) { - //$fax_forward_number = preg_replace("~[^0-9]~", "",$fax_forward_number); - $fax_forward_number = str_replace(" ", "", $fax_forward_number); - $fax_forward_number = str_replace("-", "", $fax_forward_number); - } - if (strripos($fax_forward_number, '$1') === false) { - $forward_prefix = ''; //not found - } else { - $forward_prefix = $forward_prefix.$fax_forward_number.'#'; //found - } - $fax_local = check_str($_POST["fax_local"]); //! @todo check in database - $fax_description = check_str($_POST["fax_description"]); - $fax_send_greeting = check_str($_POST["fax_send_greeting"]); - $fax_send_channels = check_str($_POST["fax_send_channels"]); - } - -//delete the user from the fax users - if ($_GET["a"] == "delete" && permission_exists("fax_extension_delete")) { - //set the variables - $user_uuid = check_str($_REQUEST["user_uuid"]); - $fax_uuid = check_str($_REQUEST["id"]); - - //delete the group from the users - $sql = "delete from v_fax_users "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and fax_uuid = '".$fax_uuid."' "; - $sql .= "and user_uuid = '".$user_uuid."' "; - $db->exec(check_sql($sql)); - - //redirect the browser - $_SESSION["message"] = $text['message-delete']; - header("Location: fax_edit.php?id=".$fax_uuid); - return; - } - -//add the user to the fax users - if (strlen($_REQUEST["user_uuid"]) > 0 && strlen($_REQUEST["id"]) > 0 && $_GET["a"] != "delete") { - //set the variables - $user_uuid = check_str($_REQUEST["user_uuid"]); - $fax_uuid = check_str($_REQUEST["id"]); - //assign the user to the fax extension - $sql_insert = "insert into v_fax_users "; - $sql_insert .= "("; - $sql_insert .= "fax_user_uuid, "; - $sql_insert .= "domain_uuid, "; - $sql_insert .= "fax_uuid, "; - $sql_insert .= "user_uuid "; - $sql_insert .= ")"; - $sql_insert .= "values "; - $sql_insert .= "("; - $sql_insert .= "'".uuid()."', "; - $sql_insert .= "'".$_SESSION['domain_uuid']."', "; - $sql_insert .= "'".$fax_uuid."', "; - $sql_insert .= "'".$user_uuid."' "; - $sql_insert .= ")"; - $db->exec($sql_insert); - - //redirect the browser - $_SESSION["message"] = $text['confirm-add']; - header("Location: fax_edit.php?id=".$fax_uuid); - return; - } - -//clear file status cache - clearstatcache(); - -if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) { - - $msg = ''; - if ($action == "update" && permission_exists('fax_extension_edit')) { - $fax_uuid = check_str($_POST["fax_uuid"]); - } - - //check for all required data - if (strlen($fax_extension) == 0) { $msg .= "".$text['confirm-ext']."
\n"; } - if (strlen($fax_name) == 0) { $msg .= "".$text['confirm-fax']."
\n"; } - if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) { - require_once "resources/header.php"; - require_once "resources/persist_form_var.php"; - echo "
\n"; - echo "
\n"; - echo $msg."
"; - echo "
\n"; - persistformvar($_POST); - echo "
\n"; - require_once "resources/footer.php"; - return; - } - - //replace the spaces with a dash - $fax_name = str_replace(" ", "-", $fax_name); - - //escape the commas with a backslash and remove the spaces - $fax_email = str_replace(" ", "", $fax_email); - - //set the $php_bin - //if (file_exists(PHP_BINDIR."/php")) { $php_bin = 'php'; } - if (substr(strtoupper(PHP_OS), 0, 3) == "WIN") { - $php_bin = 'php.exe'; - } - else { - $php_bin = 'php'; - } - - //add or update the database - if ($_POST["persistformvar"] != "true") { - - //prep authorized senders - if (sizeof($fax_email_outbound_authorized_senders) > 0) { - foreach ($fax_email_outbound_authorized_senders as $sender_num => $sender) { - $sender = check_str($sender); - if ($sender == '' || !valid_email($sender)) { unset($fax_email_outbound_authorized_senders[$sender_num]); } - } - $fax_email_outbound_authorized_senders = implode(',', $fax_email_outbound_authorized_senders); - } - - if ($action == "add" && permission_exists('fax_extension_add')) { - //prepare the unique identifiers - $fax_uuid = uuid(); - $dialplan_uuid = uuid(); - - //add the fax extension to the database - $sql = "insert into v_fax "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "fax_uuid, "; - $sql .= "dialplan_uuid, "; - $sql .= "fax_extension, "; - $sql .= "accountcode, "; - $sql .= "fax_destination_number, "; - $sql .= "fax_prefix, "; - $sql .= "fax_name, "; - $sql .= "fax_email, "; - if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { - $sql .= "fax_email_connection_type, "; - $sql .= "fax_email_connection_host, "; - $sql .= "fax_email_connection_port, "; - $sql .= "fax_email_connection_security, "; - $sql .= "fax_email_connection_validate, "; - $sql .= "fax_email_connection_username, "; - $sql .= "fax_email_connection_password, "; - $sql .= "fax_email_connection_mailbox, "; - $sql .= "fax_email_inbound_subject_tag, "; - $sql .= "fax_email_outbound_subject_tag, "; - $sql .= "fax_email_outbound_authorized_senders, "; - } - $sql .= "fax_caller_id_name, "; - $sql .= "fax_caller_id_number, "; - if (strlen($fax_forward_number) > 0) { - $sql .= "fax_forward_number, "; - } - $sql .= "fax_send_greeting,"; - $sql .= "fax_send_channels,"; - $sql .= "fax_description "; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$_SESSION['domain_uuid']."', "; - $sql .= "'$fax_uuid', "; - $sql .= "'$dialplan_uuid', "; - $sql .= "'$fax_extension', "; - $sql .= "'$fax_accountcode', "; - $sql .= "'$fax_destination_number', "; - $sql .= "'$fax_prefix', "; - $sql .= "'$fax_name', "; - $sql .= "'$fax_email', "; - if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { - $sql .= "'$fax_email_connection_type', "; - $sql .= "'$fax_email_connection_host', "; - $sql .= "'$fax_email_connection_port', "; - $sql .= "'$fax_email_connection_security', "; - $sql .= "'$fax_email_connection_validate', "; - $sql .= "'$fax_email_connection_username', "; - $sql .= "'$fax_email_connection_password', "; - $sql .= "'$fax_email_connection_mailbox', "; - $sql .= "'$fax_email_inbound_subject_tag', "; - $sql .= "'$fax_email_outbound_subject_tag', "; - $sql .= "'$fax_email_outbound_authorized_senders', "; - } - $sql .= "'$fax_caller_id_name', "; - $sql .= "'$fax_caller_id_number', "; - if (strlen($fax_forward_number) > 0) { - $sql .= "'$fax_forward_number', "; - } - $sql .= (strlen($fax_send_greeting)==0?'NULL':"'$fax_send_greeting'") . ","; - $sql .= (strlen($fax_send_channels)==0?'NULL':"'$fax_send_channels'") . ","; - - $sql .= "'$fax_description' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - - //set the dialplan action - $dialplan_type = "add"; - } - - if ($action == "update" && permission_exists('fax_extension_edit')) { - //update the fax extension in the database - $dialplan_type = ""; - $sql = "update v_fax set "; - $sql .= "fax_extension = '$fax_extension', "; - $sql .= "accountcode = '$fax_accountcode', "; - $sql .= "fax_destination_number = '$fax_destination_number', "; - $sql .= "fax_prefix = '$fax_prefix', "; - $sql .= "fax_name = '$fax_name', "; - $sql .= "fax_email = '$fax_email', "; - if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { - $sql .= "fax_email_connection_type = '$fax_email_connection_type', "; - $sql .= "fax_email_connection_host = '$fax_email_connection_host', "; - $sql .= "fax_email_connection_port = '$fax_email_connection_port', "; - $sql .= "fax_email_connection_security = '$fax_email_connection_security', "; - $sql .= "fax_email_connection_validate = '$fax_email_connection_validate', "; - $sql .= "fax_email_connection_username = '$fax_email_connection_username', "; - $sql .= "fax_email_connection_password = '$fax_email_connection_password', "; - $sql .= "fax_email_connection_mailbox = '$fax_email_connection_mailbox', "; - $sql .= "fax_email_inbound_subject_tag = '$fax_email_inbound_subject_tag', "; - $sql .= "fax_email_outbound_subject_tag = '$fax_email_outbound_subject_tag', "; - $sql .= "fax_email_outbound_authorized_senders = '$fax_email_outbound_authorized_senders', "; - } - $sql .= "fax_caller_id_name = '$fax_caller_id_name', "; - $sql .= "fax_caller_id_number = '$fax_caller_id_number', "; - if (strlen($fax_forward_number) > 0) { - $sql .= "fax_forward_number = '$fax_forward_number', "; - } - else { - $sql .= "fax_forward_number = null, "; - } - $tmp = strlen($fax_send_greeting)==0?'NULL':"'$fax_send_greeting'"; - $sql .= "fax_send_greeting = $tmp,"; - $tmp = strlen($fax_send_channels)==0?'NULL':"'$fax_send_channels'"; - $sql .= "fax_send_channels = $tmp,"; - - $sql .= "fax_description = '$fax_description' "; - - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and fax_uuid = '$fax_uuid' "; - - $db->exec(check_sql($sql)); - unset($sql); - } - - //get the dialplan_uuid - $sql = "select * from v_fax "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and fax_uuid = '$fax_uuid' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $dialplan_uuid = $row["dialplan_uuid"]; - } - unset ($prep_statement); - - //dialplan add or update - $c = new fax; - $c->db = $db; - $c->domain_uuid = $_SESSION['domain_uuid']; - $c->dialplan_uuid = $dialplan_uuid; - $c->fax_name = $fax_name; - $c->fax_uuid = $fax_uuid; - $c->fax_extension = $fax_extension; - $c->fax_forward_number = $fax_forward_number; - $c->destination_number = $fax_destination_number; - $c->fax_description = $fax_description; - $a = $c->dialplan(); - - //redirect the browser - if ($action == "update" && permission_exists('fax_extension_edit')) { - $_SESSION["message"] = $text['confirm-update']; - } - if ($action == "add" && permission_exists('fax_extension_add')) { - $_SESSION["message"] = $text['confirm-add']; - } - header("Location: fax.php"); - return; - - } //if ($_POST["persistformvar"] != "true") -} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) - -//pre-populate the form - if (strlen($_GET['id']) > 0 && $_POST["persistformvar"] != "true") { - $fax_uuid = check_str($_GET["id"]); - $sql = "select * from v_fax "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and fax_uuid = '$fax_uuid' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) == 0) { - echo "access denied"; - exit; - } - foreach ($result as &$row) { - $dialplan_uuid = $row["dialplan_uuid"]; - $fax_extension = $row["fax_extension"]; - $fax_accountcode = $row["accountcode"]; - $fax_destination_number = $row["fax_destination_number"]; - $fax_prefix = $row["fax_prefix"]; - $fax_name = $row["fax_name"]; - $fax_email = $row["fax_email"]; - $fax_email_connection_type = $row["fax_email_connection_type"]; - $fax_email_connection_host = $row["fax_email_connection_host"]; - $fax_email_connection_port = $row["fax_email_connection_port"]; - $fax_email_connection_security = $row["fax_email_connection_security"]; - $fax_email_connection_validate = $row["fax_email_connection_validate"]; - $fax_email_connection_username = $row["fax_email_connection_username"]; - $fax_email_connection_password = $row["fax_email_connection_password"]; - $fax_email_connection_mailbox = $row["fax_email_connection_mailbox"]; - $fax_email_inbound_subject_tag = $row["fax_email_inbound_subject_tag"]; - $fax_email_outbound_subject_tag = $row["fax_email_outbound_subject_tag"]; - $fax_email_outbound_authorized_senders = $row["fax_email_outbound_authorized_senders"]; - $fax_caller_id_name = $row["fax_caller_id_name"]; - $fax_caller_id_number = $row["fax_caller_id_number"]; - $fax_forward_number = $row["fax_forward_number"]; - $fax_description = $row["fax_description"]; - $fax_send_greeting = $row["fax_send_greeting"]; - $fax_send_channels = $row["fax_send_channels"]; - } - unset ($prep_statement); - } - else{ - $fax_send_channels = 10; - } - -//replace the dash with a space - $fax_name = str_replace("-", " ", $fax_name); - -//set the dialplan_uuid - if (strlen($dialplan_uuid) == 0) { - $dialplan_uuid = uuid(); - } - -//show the header - require_once "resources/header.php"; - -//advanced button js - echo "\n"; - -//fax extension form - echo "
\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - if (!permission_exists('fax_extension_delete')) { - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - } - else { //admin, superadmin, etc - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if (if_group("superadmin") || (if_group("admin") && $billing_app_exists)) { - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - } - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if (if_group("admin") || if_group("superadmin")) { - if ($action == "update") { - echo " "; - echo " "; - echo " "; - echo " "; - } - } - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - } - - echo " \n"; - echo " \n"; - echo " "; - echo "
".$text['header-fax_server_settings']."

\n"; - echo " \n"; - if ((if_group("admin") || if_group("superadmin")) && $action == "update") { - echo " \n"; - } - echo " \n"; - echo "
\n"; - echo " ".$text['label-email']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-email']."\n"; - echo "
\n"; - echo " ".$text['label-name']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo "".$text['description-name']."\n"; - echo "
\n"; - echo " ".$text['label-extension']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo "".$text['description-extension']."\n"; - echo "
\n"; - echo " ".$text['label-accountcode']."\n"; - echo "\n"; - if ($billing_app_exists) { - $sql_accountcode = "SELECT type_value FROM v_billings WHERE domain_uuid = '".$domain_uuid."'"; - echo ""; - } - else { - if ($action == "add") { $fax_accountcode = $_SESSION['domain_name']; } - echo "\n"; - } - - echo "
\n"; - echo $text['description-accountcode']."\n"; - echo "
\n"; - echo " ".$text['label-destination-number']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-destination-number']."\n"; - echo "
\n"; - echo " ".$text['label-fax_prefix']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax_prefix']."\n"; - echo "
\n"; - echo " ".$text['label-email']."\n"; - echo "\n"; - echo " \n"; - if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { - echo "\n"; - } - echo "
\n"; - echo " ".$text['description-email']."\n"; - echo "
\n"; - echo " ".$text['label-caller-id-name']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo "".$text['description-caller-id-name']."\n"; - echo "
\n"; - echo " ".$text['label-caller-id-number']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo "".$text['description-caller-id-number']."\n"; - echo "
\n"; - echo " ".$text['label-forward']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo "".$text['description-forward-number']."\n"; - echo "
".$text['label-user-list'].""; - - $sql = "SELECT * FROM v_fax_users as e, v_users as u "; - $sql .= "where e.user_uuid = u.user_uuid "; - $sql .= "and e.domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and e.fax_uuid = '".$fax_uuid."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_ASSOC); - $result_count = count($result); - if ($result_count > 0) { - echo " \n"; - foreach($result as $field) { - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - $assigned_user_uuids[] = $field['user_uuid']; - } - echo "
".$field['username']."\n"; - echo " $v_link_label_delete\n"; - echo "
\n"; - echo "
\n"; - } - $sql = "SELECT * FROM v_users "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - foreach($assigned_user_uuids as $assigned_user_uuid) { - $sql .= "and user_uuid <> '".$assigned_user_uuid."' "; - } - unset($assigned_user_uuids); - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - echo " "; - echo " \n"; - unset($sql, $result); - echo "
\n"; - echo " ".$text['description-user-add']."\n"; - echo "
\n"; - echo "
\n"; - echo " ".$text['label-fax_send_greeting']."\n"; - echo "\n"; - if (permission_exists('fax_extension_add') || permission_exists('fax_extension_edit')) { - echo "\n"; - echo "\n"; - } - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax_send_greeting']."\n"; - echo "
\n"; - echo " ".$text['label-fax_send_channels']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax_send_channels']."\n"; - echo "
\n"; - echo " ".$text['label-description']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo "".$text['description-info']."\n"; - echo "
\n"; - echo "
"; - if ($action == "update") { - if (!permission_exists('fax_extension_delete')) { - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - } - echo " \n"; - echo " \n"; - } - echo " \n"; - echo "
"; - echo "
\n"; - - if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { - - echo "
\n"; - - echo "".$text['label-advanced_settings']."

"; - echo $text['description-advanced_settings']."

"; - - echo "\n"; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo "
"; - - echo "\n"; - - echo ""; - echo ""; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "
"; - echo " ".$text['label-email_account_connection']."

"; - echo "
\n"; - echo " ".$text['label-email_connection_type']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-email_connection_type']."\n"; - echo "
\n"; - echo " ".$text['label-email_connection_server']."\n"; - echo "\n"; - echo "  : "; - echo "\n"; - echo "
\n"; - echo " ".$text['description-email_connection_server']."\n"; - echo "
\n"; - echo " ".$text['label-email_connection_security']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-email_connection_security']."\n"; - echo "
\n"; - echo " ".$text['label-email_connection_validate']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-email_connection_validate']."\n"; - echo "
\n"; - echo " ".$text['label-email_connection_username']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-email_connection_username']."\n"; - echo "
\n"; - echo " ".$text['label-email_connection_password']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-email_connection_password']."\n"; - echo "
\n"; - echo " ".$text['label-email_connection_mailbox']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-email_connection_mailbox']."\n"; - echo "
\n"; - - echo "
    "; - - echo "\n"; - - echo ""; - echo ""; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if (file_exists("fax_emails.php")) { - - echo ""; - echo ""; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - } - - echo "
"; - echo " ".$text['label-email_remote_inbox']."

"; - echo "
\n"; - echo " ".$text['label-email_inbound_subject_tag']."\n"; - echo "\n"; - echo " [ ]\n"; - echo "
\n"; - echo " ".$text['description-email_inbound_subject_tag']."\n"; - echo "
"; - echo "

"; - echo " ".$text['label-email_email-to-fax']."

"; - echo "
\n"; - echo " ".$text['label-email_outbound_subject_tag']."\n"; - echo "\n"; - echo " [ ]\n"; - echo "
\n"; - echo " ".$text['description-email_outbound_subject_tag']."\n"; - echo "
\n"; - echo " ".$text['label-email_outbound_authorized_senders']."\n"; - echo "\n"; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo "
"; - if (substr_count($fax_email_outbound_authorized_senders, ',') > 0) { - $senders = explode(',', $fax_email_outbound_authorized_senders); - } - else { - $senders[] = $fax_email_outbound_authorized_senders; - } - $senders[] = ''; // empty one - foreach ($senders as $sender_num => $sender) { - echo " ".((sizeof($senders) > 0 && $sender_num < (sizeof($senders) - 1) ) ? "
" : null); - } - echo "
"; - echo " $v_link_label_add"; - echo "
"; - echo " ".$text['description-email_outbound_authorized_senders']."\n"; - echo "
\n"; - - echo "
"; - echo "
\n"; - echo "
"; - echo "
"; - echo "
\n"; - } - - echo "
"; - -//show the footer - require_once "resources/footer.php"; - + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Luis Daniel Lucio Quiroz +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('fax_extension_add') || permission_exists('fax_extension_edit') || permission_exists('fax_extension_delete')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//detect billing app + $billing_app_exists = file_exists($_SERVER["PROJECT_ROOT"]."/app/billing/app_config.php"); + + if ($billing_app_exists) { + require_once "app/billing/resources/functions/currency.php"; + require_once "app/billing/resources/functions/rating.php"; + } + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get the fax_extension and save it as a variable + if (strlen($_REQUEST["fax_extension"]) > 0) { + $fax_extension = check_str($_REQUEST["fax_extension"]); + } + +//set the fax directory + $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']; + +//get the fax extension + if (strlen($fax_extension) > 0) { + //set the fax directories. example /usr/local/freeswitch/storage/fax/329/inbox + $dir_fax_inbox = $fax_dir.'/'.$fax_extension.'/inbox'; + $dir_fax_sent = $fax_dir.'/'.$fax_extension.'/sent'; + $dir_fax_temp = $fax_dir.'/'.$fax_extension.'/temp'; + + //make sure the directories exist + if (!is_dir($_SESSION['switch']['storage']['dir'])) { + mkdir($_SESSION['switch']['storage']['dir']); + chmod($dir_fax_sent,0774); + } + if (!is_dir($fax_dir.'/'.$fax_extension)) { + mkdir($fax_dir.'/'.$fax_extension,0774,true); + chmod($fax_dir.'/'.$fax_extension,0774); + } + if (!is_dir($dir_fax_inbox)) { + mkdir($dir_fax_inbox,0774,true); + chmod($dir_fax_inbox,0774); + } + if (!is_dir($dir_fax_sent)) { + mkdir($dir_fax_sent,0774,true); + chmod($dir_fax_sent,0774); + } + if (!is_dir($dir_fax_temp)) { + mkdir($dir_fax_temp,0774,true); + chmod($dir_fax_temp,0774); + } + } + +//set the action as an add or an update + if (isset($_REQUEST["id"])) { + $action = "update"; + $fax_uuid = check_str($_REQUEST["id"]); + $dialplan_uuid = check_str($_REQUEST["dialplan_uuid"]); + } + else { + $action = "add"; + } + +//get the http post values and set them as php variables + if (count($_POST) > 0) { + $fax_name = check_str($_POST["fax_name"]); + $fax_extension = check_str($_POST["fax_extension"]); + $fax_accountcode = check_str($_POST["accountcode"]); + $fax_destination_number = check_str($_POST["fax_destination_number"]); + $fax_prefix = check_str($_POST["fax_prefix"]); + $fax_email = check_str($_POST["fax_email"]); + $fax_email_connection_type = check_str($_POST["fax_email_connection_type"]); + $fax_email_connection_host = check_str($_POST["fax_email_connection_host"]); + $fax_email_connection_port = check_str($_POST["fax_email_connection_port"]); + $fax_email_connection_security = check_str($_POST["fax_email_connection_security"]); + $fax_email_connection_validate = check_str($_POST["fax_email_connection_validate"]); + $fax_email_connection_username = check_str($_POST["fax_email_connection_username"]); + $fax_email_connection_password = check_str($_POST["fax_email_connection_password"]); + $fax_email_connection_mailbox = check_str($_POST["fax_email_connection_mailbox"]); + $fax_email_inbound_subject_tag = check_str($_POST["fax_email_inbound_subject_tag"]); + $fax_email_outbound_subject_tag = check_str($_POST["fax_email_outbound_subject_tag"]); + $fax_email_outbound_authorized_senders = $_POST["fax_email_outbound_authorized_senders"]; + $fax_caller_id_name = check_str($_POST["fax_caller_id_name"]); + $fax_caller_id_number = check_str($_POST["fax_caller_id_number"]); + $fax_forward_number = check_str($_POST["fax_forward_number"]); + if (strlen($fax_destination_number) == 0) { + $fax_destination_number = $fax_extension; + } + if (strlen($fax_forward_number) > 3) { + //$fax_forward_number = preg_replace("~[^0-9]~", "",$fax_forward_number); + $fax_forward_number = str_replace(" ", "", $fax_forward_number); + $fax_forward_number = str_replace("-", "", $fax_forward_number); + } + if (strripos($fax_forward_number, '$1') === false) { + $forward_prefix = ''; //not found + } else { + $forward_prefix = $forward_prefix.$fax_forward_number.'#'; //found + } + $fax_local = check_str($_POST["fax_local"]); //! @todo check in database + $fax_description = check_str($_POST["fax_description"]); + $fax_send_greeting = check_str($_POST["fax_send_greeting"]); + $fax_send_channels = check_str($_POST["fax_send_channels"]); + } + +//delete the user from the fax users + if ($_GET["a"] == "delete" && permission_exists("fax_extension_delete")) { + //set the variables + $user_uuid = check_str($_REQUEST["user_uuid"]); + $fax_uuid = check_str($_REQUEST["id"]); + + //delete the group from the users + $sql = "delete from v_fax_users "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and fax_uuid = '".$fax_uuid."' "; + $sql .= "and user_uuid = '".$user_uuid."' "; + $db->exec(check_sql($sql)); + + //redirect the browser + $_SESSION["message"] = $text['message-delete']; + header("Location: fax_edit.php?id=".$fax_uuid); + return; + } + +//add the user to the fax users + if (strlen($_REQUEST["user_uuid"]) > 0 && strlen($_REQUEST["id"]) > 0 && $_GET["a"] != "delete") { + //set the variables + $user_uuid = check_str($_REQUEST["user_uuid"]); + $fax_uuid = check_str($_REQUEST["id"]); + //assign the user to the fax extension + $sql_insert = "insert into v_fax_users "; + $sql_insert .= "("; + $sql_insert .= "fax_user_uuid, "; + $sql_insert .= "domain_uuid, "; + $sql_insert .= "fax_uuid, "; + $sql_insert .= "user_uuid "; + $sql_insert .= ")"; + $sql_insert .= "values "; + $sql_insert .= "("; + $sql_insert .= "'".uuid()."', "; + $sql_insert .= "'".$_SESSION['domain_uuid']."', "; + $sql_insert .= "'".$fax_uuid."', "; + $sql_insert .= "'".$user_uuid."' "; + $sql_insert .= ")"; + $db->exec($sql_insert); + + //redirect the browser + $_SESSION["message"] = $text['confirm-add']; + header("Location: fax_edit.php?id=".$fax_uuid); + return; + } + +//clear file status cache + clearstatcache(); + +if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) { + + $msg = ''; + if ($action == "update" && permission_exists('fax_extension_edit')) { + $fax_uuid = check_str($_POST["fax_uuid"]); + } + + //check for all required data + if (strlen($fax_extension) == 0) { $msg .= "".$text['confirm-ext']."
\n"; } + if (strlen($fax_name) == 0) { $msg .= "".$text['confirm-fax']."
\n"; } + if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) { + require_once "resources/header.php"; + require_once "resources/persist_form_var.php"; + echo "
\n"; + echo "
\n"; + echo $msg."
"; + echo "
\n"; + persistformvar($_POST); + echo "
\n"; + require_once "resources/footer.php"; + return; + } + + //replace the spaces with a dash + $fax_name = str_replace(" ", "-", $fax_name); + + //escape the commas with a backslash and remove the spaces + $fax_email = str_replace(" ", "", $fax_email); + + //set the $php_bin + //if (file_exists(PHP_BINDIR."/php")) { $php_bin = 'php'; } + if (substr(strtoupper(PHP_OS), 0, 3) == "WIN") { + $php_bin = 'php.exe'; + } + else { + $php_bin = 'php'; + } + + //add or update the database + if ($_POST["persistformvar"] != "true") { + + //prep authorized senders + if (sizeof($fax_email_outbound_authorized_senders) > 0) { + foreach ($fax_email_outbound_authorized_senders as $sender_num => $sender) { + $sender = check_str($sender); + if ($sender == '' || !valid_email($sender)) { unset($fax_email_outbound_authorized_senders[$sender_num]); } + } + $fax_email_outbound_authorized_senders = implode(',', $fax_email_outbound_authorized_senders); + } + + if ($action == "add" && permission_exists('fax_extension_add')) { + //prepare the unique identifiers + $fax_uuid = uuid(); + $dialplan_uuid = uuid(); + + //add the fax extension to the database + $sql = "insert into v_fax "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "fax_uuid, "; + $sql .= "dialplan_uuid, "; + $sql .= "fax_extension, "; + $sql .= "accountcode, "; + $sql .= "fax_destination_number, "; + $sql .= "fax_prefix, "; + $sql .= "fax_name, "; + $sql .= "fax_email, "; + if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { + $sql .= "fax_email_connection_type, "; + $sql .= "fax_email_connection_host, "; + $sql .= "fax_email_connection_port, "; + $sql .= "fax_email_connection_security, "; + $sql .= "fax_email_connection_validate, "; + $sql .= "fax_email_connection_username, "; + $sql .= "fax_email_connection_password, "; + $sql .= "fax_email_connection_mailbox, "; + $sql .= "fax_email_inbound_subject_tag, "; + $sql .= "fax_email_outbound_subject_tag, "; + $sql .= "fax_email_outbound_authorized_senders, "; + } + $sql .= "fax_caller_id_name, "; + $sql .= "fax_caller_id_number, "; + if (strlen($fax_forward_number) > 0) { + $sql .= "fax_forward_number, "; + } + $sql .= "fax_send_greeting,"; + $sql .= "fax_send_channels,"; + $sql .= "fax_description "; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$_SESSION['domain_uuid']."', "; + $sql .= "'$fax_uuid', "; + $sql .= "'$dialplan_uuid', "; + $sql .= "'$fax_extension', "; + $sql .= "'$fax_accountcode', "; + $sql .= "'$fax_destination_number', "; + $sql .= "'$fax_prefix', "; + $sql .= "'$fax_name', "; + $sql .= "'$fax_email', "; + if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { + $sql .= "'$fax_email_connection_type', "; + $sql .= "'$fax_email_connection_host', "; + $sql .= "'$fax_email_connection_port', "; + $sql .= "'$fax_email_connection_security', "; + $sql .= "'$fax_email_connection_validate', "; + $sql .= "'$fax_email_connection_username', "; + $sql .= "'$fax_email_connection_password', "; + $sql .= "'$fax_email_connection_mailbox', "; + $sql .= "'$fax_email_inbound_subject_tag', "; + $sql .= "'$fax_email_outbound_subject_tag', "; + $sql .= "'$fax_email_outbound_authorized_senders', "; + } + $sql .= "'$fax_caller_id_name', "; + $sql .= "'$fax_caller_id_number', "; + if (strlen($fax_forward_number) > 0) { + $sql .= "'$fax_forward_number', "; + } + $sql .= (strlen($fax_send_greeting)==0?'NULL':"'$fax_send_greeting'") . ","; + $sql .= (strlen($fax_send_channels)==0?'NULL':"'$fax_send_channels'") . ","; + + $sql .= "'$fax_description' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + + //set the dialplan action + $dialplan_type = "add"; + } + + if ($action == "update" && permission_exists('fax_extension_edit')) { + //update the fax extension in the database + $dialplan_type = ""; + $sql = "update v_fax set "; + $sql .= "fax_extension = '$fax_extension', "; + $sql .= "accountcode = '$fax_accountcode', "; + $sql .= "fax_destination_number = '$fax_destination_number', "; + $sql .= "fax_prefix = '$fax_prefix', "; + $sql .= "fax_name = '$fax_name', "; + $sql .= "fax_email = '$fax_email', "; + if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { + $sql .= "fax_email_connection_type = '$fax_email_connection_type', "; + $sql .= "fax_email_connection_host = '$fax_email_connection_host', "; + $sql .= "fax_email_connection_port = '$fax_email_connection_port', "; + $sql .= "fax_email_connection_security = '$fax_email_connection_security', "; + $sql .= "fax_email_connection_validate = '$fax_email_connection_validate', "; + $sql .= "fax_email_connection_username = '$fax_email_connection_username', "; + $sql .= "fax_email_connection_password = '$fax_email_connection_password', "; + $sql .= "fax_email_connection_mailbox = '$fax_email_connection_mailbox', "; + $sql .= "fax_email_inbound_subject_tag = '$fax_email_inbound_subject_tag', "; + $sql .= "fax_email_outbound_subject_tag = '$fax_email_outbound_subject_tag', "; + $sql .= "fax_email_outbound_authorized_senders = '$fax_email_outbound_authorized_senders', "; + } + $sql .= "fax_caller_id_name = '$fax_caller_id_name', "; + $sql .= "fax_caller_id_number = '$fax_caller_id_number', "; + if (strlen($fax_forward_number) > 0) { + $sql .= "fax_forward_number = '$fax_forward_number', "; + } + else { + $sql .= "fax_forward_number = null, "; + } + $tmp = strlen($fax_send_greeting)==0?'NULL':"'$fax_send_greeting'"; + $sql .= "fax_send_greeting = $tmp,"; + $tmp = strlen($fax_send_channels)==0?'NULL':"'$fax_send_channels'"; + $sql .= "fax_send_channels = $tmp,"; + + $sql .= "fax_description = '$fax_description' "; + + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and fax_uuid = '$fax_uuid' "; + + $db->exec(check_sql($sql)); + unset($sql); + } + + //get the dialplan_uuid + $sql = "select * from v_fax "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and fax_uuid = '$fax_uuid' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $dialplan_uuid = $row["dialplan_uuid"]; + } + unset ($prep_statement); + + //dialplan add or update + $c = new fax; + $c->db = $db; + $c->domain_uuid = $_SESSION['domain_uuid']; + $c->dialplan_uuid = $dialplan_uuid; + $c->fax_name = $fax_name; + $c->fax_uuid = $fax_uuid; + $c->fax_extension = $fax_extension; + $c->fax_forward_number = $fax_forward_number; + $c->destination_number = $fax_destination_number; + $c->fax_description = $fax_description; + $a = $c->dialplan(); + + //redirect the browser + if ($action == "update" && permission_exists('fax_extension_edit')) { + $_SESSION["message"] = $text['confirm-update']; + } + if ($action == "add" && permission_exists('fax_extension_add')) { + $_SESSION["message"] = $text['confirm-add']; + } + header("Location: fax.php"); + return; + + } //if ($_POST["persistformvar"] != "true") +} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) + +//pre-populate the form + if (strlen($_GET['id']) > 0 && $_POST["persistformvar"] != "true") { + $fax_uuid = check_str($_GET["id"]); + $sql = "select * from v_fax "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and fax_uuid = '$fax_uuid' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) == 0) { + echo "access denied"; + exit; + } + foreach ($result as &$row) { + $dialplan_uuid = $row["dialplan_uuid"]; + $fax_extension = $row["fax_extension"]; + $fax_accountcode = $row["accountcode"]; + $fax_destination_number = $row["fax_destination_number"]; + $fax_prefix = $row["fax_prefix"]; + $fax_name = $row["fax_name"]; + $fax_email = $row["fax_email"]; + $fax_email_connection_type = $row["fax_email_connection_type"]; + $fax_email_connection_host = $row["fax_email_connection_host"]; + $fax_email_connection_port = $row["fax_email_connection_port"]; + $fax_email_connection_security = $row["fax_email_connection_security"]; + $fax_email_connection_validate = $row["fax_email_connection_validate"]; + $fax_email_connection_username = $row["fax_email_connection_username"]; + $fax_email_connection_password = $row["fax_email_connection_password"]; + $fax_email_connection_mailbox = $row["fax_email_connection_mailbox"]; + $fax_email_inbound_subject_tag = $row["fax_email_inbound_subject_tag"]; + $fax_email_outbound_subject_tag = $row["fax_email_outbound_subject_tag"]; + $fax_email_outbound_authorized_senders = $row["fax_email_outbound_authorized_senders"]; + $fax_caller_id_name = $row["fax_caller_id_name"]; + $fax_caller_id_number = $row["fax_caller_id_number"]; + $fax_forward_number = $row["fax_forward_number"]; + $fax_description = $row["fax_description"]; + $fax_send_greeting = $row["fax_send_greeting"]; + $fax_send_channels = $row["fax_send_channels"]; + } + unset ($prep_statement); + } + else{ + $fax_send_channels = 10; + } + +//replace the dash with a space + $fax_name = str_replace("-", " ", $fax_name); + +//set the dialplan_uuid + if (strlen($dialplan_uuid) == 0) { + $dialplan_uuid = uuid(); + } + +//show the header + require_once "resources/header.php"; + +//advanced button js + echo "\n"; + +//fax extension form + echo "
\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + if (!permission_exists('fax_extension_delete')) { + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + } + else { //admin, superadmin, etc + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if (if_group("superadmin") || (if_group("admin") && $billing_app_exists)) { + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + } + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if (if_group("admin") || if_group("superadmin")) { + if ($action == "update") { + echo " "; + echo " "; + echo " "; + echo " "; + } + } + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + } + + echo " \n"; + echo " \n"; + echo " "; + echo "
".$text['header-fax_server_settings']."

\n"; + echo " \n"; + if ((if_group("admin") || if_group("superadmin")) && $action == "update") { + echo " \n"; + } + echo " \n"; + echo "
\n"; + echo " ".$text['label-email']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-email']."\n"; + echo "
\n"; + echo " ".$text['label-name']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo "".$text['description-name']."\n"; + echo "
\n"; + echo " ".$text['label-extension']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo "".$text['description-extension']."\n"; + echo "
\n"; + echo " ".$text['label-accountcode']."\n"; + echo "\n"; + if ($billing_app_exists) { + $sql_accountcode = "SELECT type_value FROM v_billings WHERE domain_uuid = '".$domain_uuid."'"; + echo ""; + } + else { + if ($action == "add") { $fax_accountcode = $_SESSION['domain_name']; } + echo "\n"; + } + + echo "
\n"; + echo $text['description-accountcode']."\n"; + echo "
\n"; + echo " ".$text['label-destination-number']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-destination-number']."\n"; + echo "
\n"; + echo " ".$text['label-fax_prefix']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax_prefix']."\n"; + echo "
\n"; + echo " ".$text['label-email']."\n"; + echo "\n"; + echo " \n"; + if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { + echo "\n"; + } + echo "
\n"; + echo " ".$text['description-email']."\n"; + echo "
\n"; + echo " ".$text['label-caller-id-name']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo "".$text['description-caller-id-name']."\n"; + echo "
\n"; + echo " ".$text['label-caller-id-number']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo "".$text['description-caller-id-number']."\n"; + echo "
\n"; + echo " ".$text['label-forward']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo "".$text['description-forward-number']."\n"; + echo "
".$text['label-user-list'].""; + + $sql = "SELECT * FROM v_fax_users as e, v_users as u "; + $sql .= "where e.user_uuid = u.user_uuid "; + $sql .= "and e.domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and e.fax_uuid = '".$fax_uuid."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_ASSOC); + $result_count = count($result); + if ($result_count > 0) { + echo " \n"; + foreach($result as $field) { + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + $assigned_user_uuids[] = $field['user_uuid']; + } + echo "
".$field['username']."\n"; + echo " $v_link_label_delete\n"; + echo "
\n"; + echo "
\n"; + } + $sql = "SELECT * FROM v_users "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + foreach($assigned_user_uuids as $assigned_user_uuid) { + $sql .= "and user_uuid <> '".$assigned_user_uuid."' "; + } + unset($assigned_user_uuids); + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + echo " "; + echo " \n"; + unset($sql, $result); + echo "
\n"; + echo " ".$text['description-user-add']."\n"; + echo "
\n"; + echo "
\n"; + echo " ".$text['label-fax_send_greeting']."\n"; + echo "\n"; + if (permission_exists('fax_extension_add') || permission_exists('fax_extension_edit')) { + echo "\n"; + echo "\n"; + } + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax_send_greeting']."\n"; + echo "
\n"; + echo " ".$text['label-fax_send_channels']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax_send_channels']."\n"; + echo "
\n"; + echo " ".$text['label-description']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo "".$text['description-info']."\n"; + echo "
\n"; + echo "
"; + if ($action == "update") { + if (!permission_exists('fax_extension_delete')) { + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + } + echo " \n"; + echo " \n"; + } + echo " \n"; + echo "
"; + echo "
\n"; + + if (permission_exists('fax_extension_advanced') && function_exists("imap_open") && file_exists("fax_files_remote.php")) { + + echo "
\n"; + + echo "".$text['label-advanced_settings']."

"; + echo $text['description-advanced_settings']."

"; + + echo "\n"; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo "
"; + + echo "\n"; + + echo ""; + echo ""; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "
"; + echo " ".$text['label-email_account_connection']."

"; + echo "
\n"; + echo " ".$text['label-email_connection_type']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-email_connection_type']."\n"; + echo "
\n"; + echo " ".$text['label-email_connection_server']."\n"; + echo "\n"; + echo "  : "; + echo "\n"; + echo "
\n"; + echo " ".$text['description-email_connection_server']."\n"; + echo "
\n"; + echo " ".$text['label-email_connection_security']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-email_connection_security']."\n"; + echo "
\n"; + echo " ".$text['label-email_connection_validate']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-email_connection_validate']."\n"; + echo "
\n"; + echo " ".$text['label-email_connection_username']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-email_connection_username']."\n"; + echo "
\n"; + echo " ".$text['label-email_connection_password']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-email_connection_password']."\n"; + echo "
\n"; + echo " ".$text['label-email_connection_mailbox']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-email_connection_mailbox']."\n"; + echo "
\n"; + + echo "
    "; + + echo "\n"; + + echo ""; + echo ""; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if (file_exists("fax_emails.php")) { + + echo ""; + echo ""; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + } + + echo "
"; + echo " ".$text['label-email_remote_inbox']."

"; + echo "
\n"; + echo " ".$text['label-email_inbound_subject_tag']."\n"; + echo "\n"; + echo " [ ]\n"; + echo "
\n"; + echo " ".$text['description-email_inbound_subject_tag']."\n"; + echo "
"; + echo "

"; + echo " ".$text['label-email_email-to-fax']."

"; + echo "
\n"; + echo " ".$text['label-email_outbound_subject_tag']."\n"; + echo "\n"; + echo " [ ]\n"; + echo "
\n"; + echo " ".$text['description-email_outbound_subject_tag']."\n"; + echo "
\n"; + echo " ".$text['label-email_outbound_authorized_senders']."\n"; + echo "\n"; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo "
"; + if (substr_count($fax_email_outbound_authorized_senders, ',') > 0) { + $senders = explode(',', $fax_email_outbound_authorized_senders); + } + else { + $senders[] = $fax_email_outbound_authorized_senders; + } + $senders[] = ''; // empty one + foreach ($senders as $sender_num => $sender) { + echo " ".((sizeof($senders) > 0 && $sender_num < (sizeof($senders) - 1) ) ? "
" : null); + } + echo "
"; + echo " $v_link_label_add"; + echo "
"; + echo " ".$text['description-email_outbound_authorized_senders']."\n"; + echo "
\n"; + + echo "
"; + echo "
\n"; + echo "
"; + echo "
"; + echo "
\n"; + } + + echo "
"; + +//show the footer + require_once "resources/footer.php"; + ?> \ No newline at end of file diff --git a/app/fax/fax_emails.php b/app/fax/fax_emails.php index 42715fc662..39db44a70a 100644 --- a/app/fax/fax_emails.php +++ b/app/fax/fax_emails.php @@ -1,387 +1,387 @@ - - Portions created by the Initial Developer are Copyright (C) 2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - James Rose -*/ - -include "root.php"; -require_once "resources/require.php"; -require_once "resources/functions/object_to_array.php"; -require_once "resources/functions/parse_message.php"; -require_once "resources/classes/text.php"; - -//get accounts to monitor -$sql = "select * from v_fax "; -$sql .= "where fax_email_connection_host <> '' "; -$sql .= "and fax_email_connection_host is not null "; -$prep_statement = $db->prepare(check_sql($sql)); -$prep_statement->execute(); -$result = $prep_statement->fetchAll(PDO::FETCH_NAMED); -unset($sql, $prep_statement); - -function arr_to_map(&$arr){ - if(is_array($arr)){ - $map = Array(); - foreach($arr as &$val){ - $map[$val] = true; - } - return $map; - } - return false; -} - -if (sizeof($result) != 0) { - - //load default settings - $default_settings = load_default_settings(); - - //get event socket connection parameters - $sql = "select event_socket_ip_address, event_socket_port, event_socket_password from v_settings"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $record = $prep_statement->fetch(PDO::FETCH_NAMED); - $event_socket['ip_address'] = $record['event_socket_ip_address']; - $event_socket['port'] = $record['event_socket_port']; - $event_socket['password'] = $record['event_socket_password']; - unset($sql, $prep_statement, $record); - - $fax_send_mode_default = $_SESSION['fax']['send_mode']['text']; - if(strlen($fax_send_mode_default) == 0){ - $fax_send_mode_default = 'direct'; - } - $fax_cover_font_default = $_SESSION['fax']['cover_font']['text']; - - $fax_allowed_extension_default = arr_to_map($_SESSION['fax']['allowed_extension']); - if($fax_allowed_extension_default == false){ - $tmp = Array('.pdf', '.tiff', '.tif'); - $fax_allowed_extension_default = arr_to_map($tmp); - } - - foreach ($result as $row) { - //get fax server and account connection details - $fax_uuid = $row["fax_uuid"]; - $domain_uuid = $row["domain_uuid"]; - $fax_extension = $row["fax_extension"]; - $fax_email = $row["fax_email"]; - $fax_pin_number = $row["fax_pin_number"]; - $fax_caller_id_name = $row["fax_caller_id_name"]; - $fax_caller_id_number = $row["fax_caller_id_number"]; - $fax_email_connection_type = $row["fax_email_connection_type"]; - $fax_email_connection_host = $row["fax_email_connection_host"]; - $fax_email_connection_port = $row["fax_email_connection_port"]; - $fax_email_connection_security = $row["fax_email_connection_security"]; - $fax_email_connection_validate = $row["fax_email_connection_validate"]; - $fax_email_connection_username = $row["fax_email_connection_username"]; - $fax_email_connection_password = $row["fax_email_connection_password"]; - $fax_email_connection_mailbox = $row["fax_email_connection_mailbox"]; - $fax_email_outbound_subject_tag = $row["fax_email_outbound_subject_tag"]; - $fax_email_outbound_authorized_senders = $row["fax_email_outbound_authorized_senders"]; - $fax_send_greeting = $row["fax_send_greeting"]; - - //load default settings, then domain settings over top - unset($_SESSION); - $_SESSION = $default_settings; - load_domain_settings($domain_uuid); - - $fax_send_mode = $_SESSION['fax']['send_mode']['text']; - if(strlen($fax_send_mode) == 0){ - $fax_send_mode = $fax_send_mode_default; - } - - $fax_cover_font = $_SESSION['fax']['cover_font']['text']; - if(strlen($fax_cover_font) == 0){ - $fax_cover_font = $fax_cover_font_default; - } - - $fax_allowed_extension = arr_to_map($_SESSION['fax']['allowed_extension']); - if($fax_allowed_extension == false){ - $fax_allowed_extension = $fax_allowed_extension_default; - } - - //load event socket connection parameters - $_SESSION['event_socket_ip_address'] = $event_socket['ip_address']; - $_SESSION['event_socket_port'] = $event_socket['port']; - $_SESSION['event_socket_password'] = $event_socket['password']; - - //get domain name, set local and session variables - $sql = "select domain_name from v_domains where domain_uuid = '".$domain_uuid."'"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $record = $prep_statement->fetch(PDO::FETCH_NAMED); - $domain_name = $record['domain_name']; - $_SESSION['domain_name'] = $record['domain_name']; - $_SESSION['domain_uuid'] = $domain_uuid; - unset($sql, $prep_statement, $record); - - //set needed variables - $fax_page_size = $_SESSION['fax']['page_size']['text']; - $fax_resolution = $_SESSION['fax']['resolution']['text']; - $fax_header = $_SESSION['fax']['cover_header']['text']; - $fax_footer = $_SESSION['fax']['cover_footer']['text']; - $fax_sender = $fax_caller_id_name; - - //open account connection - $fax_email_connection = "{".$fax_email_connection_host.":".$fax_email_connection_port."/".$fax_email_connection_type; - $fax_email_connection .= ($fax_email_connection_security != '') ? "/".$fax_email_connection_security : "/notls"; - $fax_email_connection .= "/".(($fax_email_connection_validate == 'false') ? "no" : null)."validate-cert"; - $fax_email_connection .= "}".$fax_email_connection_mailbox; - if (!$connection = imap_open($fax_email_connection, $fax_email_connection_username, $fax_email_connection_password)) { - print_r(imap_errors()); - continue; // try next account - } - - //get emails - if ($emails = imap_search($connection, "SUBJECT \"[".$fax_email_outbound_subject_tag."]\"", SE_UID)) { - - //get authorized sender(s) - if (substr_count($fax_email_outbound_authorized_senders, ',') > 0) { - $authorized_senders = explode(',', $fax_email_outbound_authorized_senders); - } - else { - $authorized_senders[] = $fax_email_outbound_authorized_senders; - } - - sort($emails); // oldest first - foreach ($emails as $email_id) { - $metadata = object_to_array(imap_fetch_overview($connection, $email_id, FT_UID)); - - //format from address - $tmp = object_to_array(imap_rfc822_parse_adrlist($metadata[0]['from'], null)); - $metadata[0]['from'] = $tmp[0]['mailbox']."@".$tmp[0]['host']; - - //check sender - $sender_authorized = false; - foreach ($authorized_senders as $authorized_sender) { - if (substr_count($metadata[0]['from'], $authorized_sender) > 0) { $sender_authorized = true; } - } - - if ($sender_authorized) { - - //add multi-lingual support - $language = new text; - $text = $language->get(); - - //sent sender address (used in api call) - $mailto_address_user = $metadata[0]['from']; - - //parse recipient fax number(s) - $fax_subject = $metadata[0]['subject']; - $tmp = explode(']', $fax_subject); //closing bracket of subject tag - $tmp = $tmp[1]; - $tmp = str_replace(':', ',', $tmp); - $tmp = str_replace(';', ',', $tmp); - $tmp = str_replace('|', ',', $tmp); - if (substr_count($tmp, ',') > 0) { - $fax_numbers = explode(',', $tmp); - } - else { - $fax_numbers[] = $tmp; - } - unset($fax_subject); //clear so not on cover page - - $message = parse_message($connection, $email_id, FT_UID); - - //get email body (if any) for cover page - $fax_message = ''; - - //Debug print - print('attachments:' . "\n"); - foreach($message['attachments'] as &$attachment){ - print(' - ' . $attachment['type'] . ' - ' . $attachment['name'] . ': ' . $attachment['size'] . ' disposition: ' . $attachment['disposition'] . "\n"); - } - print('messages:' . "\n"); - foreach($message['messages'] as &$msg){ - print(' - ' . $msg['type'] . ' - ' . $msg['size'] . "\n"); - // print($msg['data']); - // print("\n--------------------------------------------------------\n"); - } - - foreach($message['messages'] as &$msg){ - if(($msg['size'] > 0) && ($msg['type'] == 'text/plain')) { - $fax_message = $msg['data']; - break; - } - } - - if ($fax_message != '') { - $fax_message = strip_tags($fax_message); - $fax_message = str_replace("\r\n\r\n", "\r\n", $fax_message); - } - - // set fax directory (used for pdf creation - cover and/or attachments) - $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax'.(($domain_name != '') ? '/'.$domain_name : null); - - //handle attachments (if any) - $emailed_files = Array(); - $attachments = $message['attachments']; - if (sizeof($attachments) > 0) { - foreach ($attachments as &$attachment) { - $fax_file_extension = pathinfo($attachment['name'], PATHINFO_EXTENSION); - - //block unknown files - if ($fax_file_extension == '') {continue; } - //block unauthorized files - if (!$fax_allowed_extension['.' . $fax_file_extension]) { continue; } - //support only attachments - if($attachment['disposition'] != 'attachment'){ continue; } - - //store attachment in local fax temp folder - $local_filepath = $fax_dir.'/'.$fax_extension.'/temp/'.$attachment['name']; - file_put_contents($local_filepath, $attachment['data']); - - //load files array with attachments - $emailed_files['error'][] = 0; - $emailed_files['size'][] = $attachment['size']; - $emailed_files['tmp_name'][] = $attachment['name']; - $emailed_files['name'][] = $attachment['name']; - } - } - - //Debug print - print('***********************' . "\n"); - print('fax message:' . "\n"); - print(' - length: ' . strlen($fax_message) . "\n"); - print('fax files [' . sizeof($emailed_files['name']) . ']:' . "\n"); - for($i = 0; $i < sizeof($emailed_files['name']);++$i){ - print(' - ' . $emailed_files['name'][$i] . ' - ' . $emailed_files['size'][$i] . "\n"); - } - print('***********************' . "\n"); - - //send fax - $cwd = getcwd(); - $included = true; - require("fax_send.php"); - if($cwd){ - chdir($cwd); - } - - //reset variables - unset($fax_numbers); - } - - //delete email - if (imap_delete($connection, $email_id, FT_UID)) { - imap_expunge($connection); - } - } - unset($authorized_senders); - } - - //close account connection - imap_close($connection); - } -} - -//functions used above -function load_default_settings() { - global $db; - - $sql = "select * from v_default_settings "; - $sql .= "where default_setting_enabled = 'true' "; - try { - $prep_statement = $db->prepare($sql . " order by default_setting_order asc "); - $prep_statement->execute(); - } - catch(PDOException $e) { - $prep_statement = $db->prepare($sql); - $prep_statement->execute(); - } - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - //load the settings into an array - foreach ($result as $row) { - $name = $row['default_setting_name']; - $category = $row['default_setting_category']; - $subcategory = $row['default_setting_subcategory']; - if (strlen($subcategory) == 0) { - if ($name == "array") { - $settings[$category][] = $row['default_setting_value']; - } - else { - $settings[$category][$name] = $row['default_setting_value']; - } - } else { - if ($name == "array") { - $settings[$category][$subcategory][] = $row['default_setting_value']; - } - else { - $settings[$category][$subcategory][$name] = $row['default_setting_value']; - $settings[$category][$subcategory][$name] = $row['default_setting_value']; - } - } - } - return $settings; -} - -function load_domain_settings($domain_uuid) { - global $db; - - if ($domain_uuid) { - $sql = "select * from v_domain_settings "; - $sql .= "where domain_uuid = '" . $domain_uuid . "' "; - $sql .= "and domain_setting_enabled = 'true' "; - try { - $prep_statement = $db->prepare($sql . " order by domain_setting_order asc "); - $prep_statement->execute(); - } - catch(PDOException $e) { - $prep_statement = $db->prepare($sql); - $prep_statement->execute(); - } - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - //unset the arrays that domains are overriding - foreach ($result as $row) { - $name = $row['domain_setting_name']; - $category = $row['domain_setting_category']; - $subcategory = $row['domain_setting_subcategory']; - if ($name == "array") { - unset($_SESSION[$category][$subcategory]); - } - } - //set the settings as a session - foreach ($result as $row) { - $name = $row['domain_setting_name']; - $category = $row['domain_setting_category']; - $subcategory = $row['domain_setting_subcategory']; - if (strlen($subcategory) == 0) { - //$$category[$name] = $row['domain_setting_value']; - if ($name == "array") { - $_SESSION[$category][] = $row['domain_setting_value']; - } - else { - $_SESSION[$category][$name] = $row['domain_setting_value']; - } - } else { - //$$category[$subcategory][$name] = $row['domain_setting_value']; - if ($name == "array") { - $_SESSION[$category][$subcategory][] = $row['domain_setting_value']; - } - else { - $_SESSION[$category][$subcategory][$name] = $row['domain_setting_value']; - } - } - } - } -} - + + Portions created by the Initial Developer are Copyright (C) 2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + James Rose +*/ + +include "root.php"; +require_once "resources/require.php"; +require_once "resources/functions/object_to_array.php"; +require_once "resources/functions/parse_message.php"; +require_once "resources/classes/text.php"; + +//get accounts to monitor +$sql = "select * from v_fax "; +$sql .= "where fax_email_connection_host <> '' "; +$sql .= "and fax_email_connection_host is not null "; +$prep_statement = $db->prepare(check_sql($sql)); +$prep_statement->execute(); +$result = $prep_statement->fetchAll(PDO::FETCH_NAMED); +unset($sql, $prep_statement); + +function arr_to_map(&$arr){ + if(is_array($arr)){ + $map = Array(); + foreach($arr as &$val){ + $map[$val] = true; + } + return $map; + } + return false; +} + +if (sizeof($result) != 0) { + + //load default settings + $default_settings = load_default_settings(); + + //get event socket connection parameters + $sql = "select event_socket_ip_address, event_socket_port, event_socket_password from v_settings"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $record = $prep_statement->fetch(PDO::FETCH_NAMED); + $event_socket['ip_address'] = $record['event_socket_ip_address']; + $event_socket['port'] = $record['event_socket_port']; + $event_socket['password'] = $record['event_socket_password']; + unset($sql, $prep_statement, $record); + + $fax_send_mode_default = $_SESSION['fax']['send_mode']['text']; + if(strlen($fax_send_mode_default) == 0){ + $fax_send_mode_default = 'direct'; + } + $fax_cover_font_default = $_SESSION['fax']['cover_font']['text']; + + $fax_allowed_extension_default = arr_to_map($_SESSION['fax']['allowed_extension']); + if($fax_allowed_extension_default == false){ + $tmp = Array('.pdf', '.tiff', '.tif'); + $fax_allowed_extension_default = arr_to_map($tmp); + } + + foreach ($result as $row) { + //get fax server and account connection details + $fax_uuid = $row["fax_uuid"]; + $domain_uuid = $row["domain_uuid"]; + $fax_extension = $row["fax_extension"]; + $fax_email = $row["fax_email"]; + $fax_pin_number = $row["fax_pin_number"]; + $fax_caller_id_name = $row["fax_caller_id_name"]; + $fax_caller_id_number = $row["fax_caller_id_number"]; + $fax_email_connection_type = $row["fax_email_connection_type"]; + $fax_email_connection_host = $row["fax_email_connection_host"]; + $fax_email_connection_port = $row["fax_email_connection_port"]; + $fax_email_connection_security = $row["fax_email_connection_security"]; + $fax_email_connection_validate = $row["fax_email_connection_validate"]; + $fax_email_connection_username = $row["fax_email_connection_username"]; + $fax_email_connection_password = $row["fax_email_connection_password"]; + $fax_email_connection_mailbox = $row["fax_email_connection_mailbox"]; + $fax_email_outbound_subject_tag = $row["fax_email_outbound_subject_tag"]; + $fax_email_outbound_authorized_senders = $row["fax_email_outbound_authorized_senders"]; + $fax_send_greeting = $row["fax_send_greeting"]; + + //load default settings, then domain settings over top + unset($_SESSION); + $_SESSION = $default_settings; + load_domain_settings($domain_uuid); + + $fax_send_mode = $_SESSION['fax']['send_mode']['text']; + if(strlen($fax_send_mode) == 0){ + $fax_send_mode = $fax_send_mode_default; + } + + $fax_cover_font = $_SESSION['fax']['cover_font']['text']; + if(strlen($fax_cover_font) == 0){ + $fax_cover_font = $fax_cover_font_default; + } + + $fax_allowed_extension = arr_to_map($_SESSION['fax']['allowed_extension']); + if($fax_allowed_extension == false){ + $fax_allowed_extension = $fax_allowed_extension_default; + } + + //load event socket connection parameters + $_SESSION['event_socket_ip_address'] = $event_socket['ip_address']; + $_SESSION['event_socket_port'] = $event_socket['port']; + $_SESSION['event_socket_password'] = $event_socket['password']; + + //get domain name, set local and session variables + $sql = "select domain_name from v_domains where domain_uuid = '".$domain_uuid."'"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $record = $prep_statement->fetch(PDO::FETCH_NAMED); + $domain_name = $record['domain_name']; + $_SESSION['domain_name'] = $record['domain_name']; + $_SESSION['domain_uuid'] = $domain_uuid; + unset($sql, $prep_statement, $record); + + //set needed variables + $fax_page_size = $_SESSION['fax']['page_size']['text']; + $fax_resolution = $_SESSION['fax']['resolution']['text']; + $fax_header = $_SESSION['fax']['cover_header']['text']; + $fax_footer = $_SESSION['fax']['cover_footer']['text']; + $fax_sender = $fax_caller_id_name; + + //open account connection + $fax_email_connection = "{".$fax_email_connection_host.":".$fax_email_connection_port."/".$fax_email_connection_type; + $fax_email_connection .= ($fax_email_connection_security != '') ? "/".$fax_email_connection_security : "/notls"; + $fax_email_connection .= "/".(($fax_email_connection_validate == 'false') ? "no" : null)."validate-cert"; + $fax_email_connection .= "}".$fax_email_connection_mailbox; + if (!$connection = imap_open($fax_email_connection, $fax_email_connection_username, $fax_email_connection_password)) { + print_r(imap_errors()); + continue; // try next account + } + + //get emails + if ($emails = imap_search($connection, "SUBJECT \"[".$fax_email_outbound_subject_tag."]\"", SE_UID)) { + + //get authorized sender(s) + if (substr_count($fax_email_outbound_authorized_senders, ',') > 0) { + $authorized_senders = explode(',', $fax_email_outbound_authorized_senders); + } + else { + $authorized_senders[] = $fax_email_outbound_authorized_senders; + } + + sort($emails); // oldest first + foreach ($emails as $email_id) { + $metadata = object_to_array(imap_fetch_overview($connection, $email_id, FT_UID)); + + //format from address + $tmp = object_to_array(imap_rfc822_parse_adrlist($metadata[0]['from'], null)); + $metadata[0]['from'] = $tmp[0]['mailbox']."@".$tmp[0]['host']; + + //check sender + $sender_authorized = false; + foreach ($authorized_senders as $authorized_sender) { + if (substr_count($metadata[0]['from'], $authorized_sender) > 0) { $sender_authorized = true; } + } + + if ($sender_authorized) { + + //add multi-lingual support + $language = new text; + $text = $language->get(); + + //sent sender address (used in api call) + $mailto_address_user = $metadata[0]['from']; + + //parse recipient fax number(s) + $fax_subject = $metadata[0]['subject']; + $tmp = explode(']', $fax_subject); //closing bracket of subject tag + $tmp = $tmp[1]; + $tmp = str_replace(':', ',', $tmp); + $tmp = str_replace(';', ',', $tmp); + $tmp = str_replace('|', ',', $tmp); + if (substr_count($tmp, ',') > 0) { + $fax_numbers = explode(',', $tmp); + } + else { + $fax_numbers[] = $tmp; + } + unset($fax_subject); //clear so not on cover page + + $message = parse_message($connection, $email_id, FT_UID); + + //get email body (if any) for cover page + $fax_message = ''; + + //Debug print + print('attachments:' . "\n"); + foreach($message['attachments'] as &$attachment){ + print(' - ' . $attachment['type'] . ' - ' . $attachment['name'] . ': ' . $attachment['size'] . ' disposition: ' . $attachment['disposition'] . "\n"); + } + print('messages:' . "\n"); + foreach($message['messages'] as &$msg){ + print(' - ' . $msg['type'] . ' - ' . $msg['size'] . "\n"); + // print($msg['data']); + // print("\n--------------------------------------------------------\n"); + } + + foreach($message['messages'] as &$msg){ + if(($msg['size'] > 0) && ($msg['type'] == 'text/plain')) { + $fax_message = $msg['data']; + break; + } + } + + if ($fax_message != '') { + $fax_message = strip_tags($fax_message); + $fax_message = str_replace("\r\n\r\n", "\r\n", $fax_message); + } + + // set fax directory (used for pdf creation - cover and/or attachments) + $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax'.(($domain_name != '') ? '/'.$domain_name : null); + + //handle attachments (if any) + $emailed_files = Array(); + $attachments = $message['attachments']; + if (sizeof($attachments) > 0) { + foreach ($attachments as &$attachment) { + $fax_file_extension = pathinfo($attachment['name'], PATHINFO_EXTENSION); + + //block unknown files + if ($fax_file_extension == '') {continue; } + //block unauthorized files + if (!$fax_allowed_extension['.' . $fax_file_extension]) { continue; } + //support only attachments + if($attachment['disposition'] != 'attachment'){ continue; } + + //store attachment in local fax temp folder + $local_filepath = $fax_dir.'/'.$fax_extension.'/temp/'.$attachment['name']; + file_put_contents($local_filepath, $attachment['data']); + + //load files array with attachments + $emailed_files['error'][] = 0; + $emailed_files['size'][] = $attachment['size']; + $emailed_files['tmp_name'][] = $attachment['name']; + $emailed_files['name'][] = $attachment['name']; + } + } + + //Debug print + print('***********************' . "\n"); + print('fax message:' . "\n"); + print(' - length: ' . strlen($fax_message) . "\n"); + print('fax files [' . sizeof($emailed_files['name']) . ']:' . "\n"); + for($i = 0; $i < sizeof($emailed_files['name']);++$i){ + print(' - ' . $emailed_files['name'][$i] . ' - ' . $emailed_files['size'][$i] . "\n"); + } + print('***********************' . "\n"); + + //send fax + $cwd = getcwd(); + $included = true; + require("fax_send.php"); + if($cwd){ + chdir($cwd); + } + + //reset variables + unset($fax_numbers); + } + + //delete email + if (imap_delete($connection, $email_id, FT_UID)) { + imap_expunge($connection); + } + } + unset($authorized_senders); + } + + //close account connection + imap_close($connection); + } +} + +//functions used above +function load_default_settings() { + global $db; + + $sql = "select * from v_default_settings "; + $sql .= "where default_setting_enabled = 'true' "; + try { + $prep_statement = $db->prepare($sql . " order by default_setting_order asc "); + $prep_statement->execute(); + } + catch(PDOException $e) { + $prep_statement = $db->prepare($sql); + $prep_statement->execute(); + } + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + //load the settings into an array + foreach ($result as $row) { + $name = $row['default_setting_name']; + $category = $row['default_setting_category']; + $subcategory = $row['default_setting_subcategory']; + if (strlen($subcategory) == 0) { + if ($name == "array") { + $settings[$category][] = $row['default_setting_value']; + } + else { + $settings[$category][$name] = $row['default_setting_value']; + } + } else { + if ($name == "array") { + $settings[$category][$subcategory][] = $row['default_setting_value']; + } + else { + $settings[$category][$subcategory][$name] = $row['default_setting_value']; + $settings[$category][$subcategory][$name] = $row['default_setting_value']; + } + } + } + return $settings; +} + +function load_domain_settings($domain_uuid) { + global $db; + + if ($domain_uuid) { + $sql = "select * from v_domain_settings "; + $sql .= "where domain_uuid = '" . $domain_uuid . "' "; + $sql .= "and domain_setting_enabled = 'true' "; + try { + $prep_statement = $db->prepare($sql . " order by domain_setting_order asc "); + $prep_statement->execute(); + } + catch(PDOException $e) { + $prep_statement = $db->prepare($sql); + $prep_statement->execute(); + } + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + //unset the arrays that domains are overriding + foreach ($result as $row) { + $name = $row['domain_setting_name']; + $category = $row['domain_setting_category']; + $subcategory = $row['domain_setting_subcategory']; + if ($name == "array") { + unset($_SESSION[$category][$subcategory]); + } + } + //set the settings as a session + foreach ($result as $row) { + $name = $row['domain_setting_name']; + $category = $row['domain_setting_category']; + $subcategory = $row['domain_setting_subcategory']; + if (strlen($subcategory) == 0) { + //$$category[$name] = $row['domain_setting_value']; + if ($name == "array") { + $_SESSION[$category][] = $row['domain_setting_value']; + } + else { + $_SESSION[$category][$name] = $row['domain_setting_value']; + } + } else { + //$$category[$subcategory][$name] = $row['domain_setting_value']; + if ($name == "array") { + $_SESSION[$category][$subcategory][] = $row['domain_setting_value']; + } + else { + $_SESSION[$category][$subcategory][$name] = $row['domain_setting_value']; + } + } + } + } +} + ?> \ No newline at end of file diff --git a/app/fax/fax_file_delete.php b/app/fax/fax_file_delete.php index 6f70a3fc4d..f888891ed5 100644 --- a/app/fax/fax_file_delete.php +++ b/app/fax/fax_file_delete.php @@ -1,103 +1,103 @@ - - Portions created by the Initial Developer are Copyright (C) 2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('fax_file_delete')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - require_once "app_languages.php"; - foreach($text as $key => $value) { - $text[$key] = $value[$_SESSION['domain']['language']['code']]; - } - -//get the id - if (isset($_REQUEST["id"])) { - $fax_file_uuid = check_str($_REQUEST["id"]); - } - -//validate the id - if (strlen($fax_file_uuid) > 0) { - //get the fax file data - $sql = "select * from v_fax_files "; - $sql .= "where fax_file_uuid = '".$fax_file_uuid."' "; - $sql .= "and domain_uuid = '".$_SESSION['domain_uuid']."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $fax_uuid = $row["fax_uuid"]; - $fax_mode = $row["fax_mode"]; - $fax_file_path = $row["fax_file_path"]; - $fax_file_type = $row["fax_file_type"]; - } - unset($prep_statement); - - //set the type - if ($fax_mode == 'rx') { $type = 'inbox'; } - if ($fax_mode == 'tx') { $type = 'sent'; } - - //delete fax file(s) - if (substr_count($fax_file_path, '/temp/') > 0) { - $fax_file_path = str_replace('/temp/', '/'.$type.'/', $fax_file_path); - } - if (file_exists($fax_file_path)) { - @unlink($fax_file_path); - } - if ($fax_file_type == 'tif') { - $fax_file_path = str_replace('.tif', '.pdf', $fax_file_path); - if (file_exists($fax_file_path)) { - @unlink($fax_file_path); - } - } - else if ($fax_file_type == 'pdf') { - $fax_file_path = str_replace('.pdf', '.tif', $fax_file_path); - if (file_exists($fax_file_path)) { - @unlink($fax_file_path); - } - } - - //delete fax file record - $sql = "delete from v_fax_files "; - $sql .= "where fax_file_uuid = '".$fax_file_uuid."' "; - $sql .= "and domain_uuid = '".$_SESSION['domain_uuid']."' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - unset($prep_statement); - - $_SESSION['message'] = $text['message-delete']; - } - -//redirect the user - header('Location: fax_files.php?id='.$fax_uuid.'&box='.$type); - + + Portions created by the Initial Developer are Copyright (C) 2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('fax_file_delete')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + require_once "app_languages.php"; + foreach($text as $key => $value) { + $text[$key] = $value[$_SESSION['domain']['language']['code']]; + } + +//get the id + if (isset($_REQUEST["id"])) { + $fax_file_uuid = check_str($_REQUEST["id"]); + } + +//validate the id + if (strlen($fax_file_uuid) > 0) { + //get the fax file data + $sql = "select * from v_fax_files "; + $sql .= "where fax_file_uuid = '".$fax_file_uuid."' "; + $sql .= "and domain_uuid = '".$_SESSION['domain_uuid']."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $fax_uuid = $row["fax_uuid"]; + $fax_mode = $row["fax_mode"]; + $fax_file_path = $row["fax_file_path"]; + $fax_file_type = $row["fax_file_type"]; + } + unset($prep_statement); + + //set the type + if ($fax_mode == 'rx') { $type = 'inbox'; } + if ($fax_mode == 'tx') { $type = 'sent'; } + + //delete fax file(s) + if (substr_count($fax_file_path, '/temp/') > 0) { + $fax_file_path = str_replace('/temp/', '/'.$type.'/', $fax_file_path); + } + if (file_exists($fax_file_path)) { + @unlink($fax_file_path); + } + if ($fax_file_type == 'tif') { + $fax_file_path = str_replace('.tif', '.pdf', $fax_file_path); + if (file_exists($fax_file_path)) { + @unlink($fax_file_path); + } + } + else if ($fax_file_type == 'pdf') { + $fax_file_path = str_replace('.pdf', '.tif', $fax_file_path); + if (file_exists($fax_file_path)) { + @unlink($fax_file_path); + } + } + + //delete fax file record + $sql = "delete from v_fax_files "; + $sql .= "where fax_file_uuid = '".$fax_file_uuid."' "; + $sql .= "and domain_uuid = '".$_SESSION['domain_uuid']."' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + unset($prep_statement); + + $_SESSION['message'] = $text['message-delete']; + } + +//redirect the user + header('Location: fax_files.php?id='.$fax_uuid.'&box='.$type); + ?> \ No newline at end of file diff --git a/app/fax/fax_files.php b/app/fax/fax_files.php index 88fc0f81d8..bcd21b9c2a 100644 --- a/app/fax/fax_files.php +++ b/app/fax/fax_files.php @@ -1,394 +1,394 @@ - - Portions created by the Initial Developer are Copyright (C) 2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('fax_file_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get variables used to control the order - $order_by = check_str($_GET["order_by"]); - $order = check_str($_GET["order"]); - -//get fax extension - if (strlen($_GET['id']) > 0) { - if (is_uuid($_GET["id"])) { - $fax_uuid = $_GET["id"]; - } - if (if_group("superadmin") || if_group("admin")) { - //show all fax extensions - $sql = "select fax_name, fax_extension from v_fax "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and fax_uuid = '$fax_uuid' "; - } - else { - //show only assigned fax extensions - $sql = "select fax_name, fax_extension from v_fax as f, v_fax_users as u "; - $sql .= "where f.fax_uuid = u.fax_uuid "; - $sql .= "and f.domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and f.fax_uuid = '$fax_uuid' "; - $sql .= "and u.user_uuid = '".$_SESSION['user_uuid']."' "; - } - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) == 0) { - if (if_group("superadmin") || if_group("admin")) { - //allow access - } - else { - echo "access denied"; - exit; - } - } - foreach ($result as &$row) { - //set database fields as variables - $fax_name = $row["fax_name"]; - $fax_extension = $row["fax_extension"]; - //limit to one row - break; - } - unset ($prep_statement); - } - -//set the fax directory - $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']; - -//download the fax - if ($_GET['a'] == "download") { - session_cache_limiter('public'); - //test to see if it is in the inbox or sent directory. - if ($_GET['type'] == "fax_inbox") { - if (file_exists($fax_dir.'/'.check_str($_GET['ext']).'/inbox/'.check_str($_GET['filename']))) { - $tmp_faxdownload_file = $fax_dir.'/'.check_str($_GET['ext']).'/inbox/'.check_str($_GET['filename']); - } - } - else if ($_GET['type'] == "fax_sent") { - if (file_exists($fax_dir.'/'.check_str($_GET['ext']).'/sent/'.check_str($_GET['filename']))) { - $tmp_faxdownload_file = $fax_dir.'/'.check_str($_GET['ext']).'/sent/'.check_str($_GET['filename']); - } - } - //let's see if we found it. - if (strlen($tmp_faxdownload_file) > 0) { - $fd = fopen($tmp_faxdownload_file, "rb"); - if ($_GET['t'] == "bin") { - header("Content-Type: application/force-download"); - header("Content-Type: application/octet-stream"); - header("Content-Description: File Transfer"); - header('Content-Disposition: attachment; filename="'.check_str($_GET['filename']).'"'); - } - else { - $file_ext = substr(check_str($_GET['filename']), -3); - if ($file_ext == "tif") { - header("Content-Type: image/tiff"); - } - else if ($file_ext == "png") { - header("Content-Type: image/png"); - } - else if ($file_ext == "jpg") { - header('Content-Type: image/jpeg'); - } - else if ($file_ext == "pdf") { - header("Content-Type: application/pdf"); - } - } - header('Accept-Ranges: bytes'); - header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 - header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // date in the past - header("Content-Length: " . filesize($tmp_faxdownload_file)); - fpassthru($fd); - } - else { - echo "".$text['label-file'].""; - } - exit; - } - -//get the fax extension - if (strlen($fax_extension) > 0) { - //set the fax directories. example /usr/local/freeswitch/storage/fax/329/inbox - $dir_fax_inbox = $fax_dir.'/'.$fax_extension.'/inbox'; - $dir_fax_sent = $fax_dir.'/'.$fax_extension.'/sent'; - $dir_fax_temp = $fax_dir.'/'.$fax_extension.'/temp'; - - //make sure the directories exist - if (!is_dir($_SESSION['switch']['storage']['dir'])) { - mkdir($_SESSION['switch']['storage']['dir']); - chmod($dir_fax_sent,0774); - } - if (!is_dir($fax_dir.'/'.$fax_extension)) { - mkdir($fax_dir.'/'.$fax_extension,0774,true); - chmod($fax_dir.'/'.$fax_extension,0774); - } - if (!is_dir($dir_fax_inbox)) { - mkdir($dir_fax_inbox,0774,true); - chmod($dir_fax_inbox,0774); - } - if (!is_dir($dir_fax_sent)) { - mkdir($dir_fax_sent,0774,true); - chmod($dir_fax_sent,0774); - } - if (!is_dir($dir_fax_temp)) { - mkdir($dir_fax_temp,0774,true); - chmod($dir_fax_temp,0774); - } - } - -//additional includes - require_once "resources/header.php"; - require_once "resources/paging.php"; - -//prepare to page the results - $sql = "select count(*) as num_rows from v_fax_files "; - $sql .= "where fax_uuid = '$fax_uuid' "; - $sql .= "and domain_uuid = '$domain_uuid' "; - if ($_REQUEST['box'] == 'inbox') { - $sql .= "and fax_mode = 'rx' "; - } - if ($_REQUEST['box'] == 'sent') { - $sql .= "and fax_mode = 'tx' "; - } - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - if ($row['num_rows'] > 0) { - $num_rows = $row['num_rows']; - } - else { - $num_rows = '0'; - } - } - -//prepare to page the results - $rows_per_page = ($_SESSION['domain']['paging']['numeric'] != '') ? $_SESSION['domain']['paging']['numeric'] : 50; - $param = "&id=".$_GET['id']."&box=".$_GET['box']."&order_by=".$_GET['order_by']."&order=".$_GET['order']; - $page = $_GET['page']; - if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } - list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); - $offset = $rows_per_page * $page; - -//get the list - $sql = "select * from v_fax_files "; - $sql .= "where fax_uuid = '$fax_uuid' "; - $sql .= "and domain_uuid = '$domain_uuid' "; - if ($_REQUEST['box'] == 'inbox') { - $sql .= "and fax_mode = 'rx' "; - } - if ($_REQUEST['box'] == 'sent') { - $sql .= "and fax_mode = 'tx' "; - } - $sql .= "order by ".((strlen($order_by) > 0) ? $order_by.' '.$order : "fax_date desc")." "; - $sql .= "limit $rows_per_page offset $offset "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $fax_files = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - -//show the header - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { - echo " ".$text['header-inbox'].": ".$fax_name." (".$fax_extension.")\n"; - } - if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { - echo " ".$text['header-sent'].": ".$fax_name." (".$fax_extension.")\n"; - } - echo " \n"; - echo " \n"; - echo "
\n"; - echo "
\n"; - -//show the table and content - $c = 0; - $row_style["0"] = "row_style0"; - $row_style["1"] = "row_style1"; - - echo "\n"; - echo "\n"; - echo th_order_by('fax_caller_id_name', $text['label-fax_caller_id_name'], $order_by, $order, "&id=".$_GET['id']."&box=".$_GET['box']."&page=".$_GET['page']); - echo th_order_by('fax_caller_id_number', $text['label-fax_caller_id_number'], $order_by, $order, "&id=".$_GET['id']."&box=".$_GET['box']."&page=".$_GET['page']); - if ($_REQUEST['box'] == 'sent') { - echo th_order_by('fax_destination', $text['label-fax_destination'], $order_by, $order, "&id=".$_GET['id']."&box=".$_GET['box']."&page=".$_GET['page']); - } - echo "\n"; - echo "\n"; - echo th_order_by('fax_date', $text['label-fax_date'], $order_by, $order, "&id=".$_GET['id']."&box=".$_GET['box']."&page=".$_GET['page']); - echo "\n"; - echo "\n"; - if ($num_rows > 0) { - foreach($fax_files as $row) { - $file = basename($row['fax_file_path']); - if (strtolower(substr($file, -3)) == "tif" || strtolower(substr($file, -3)) == "pdf") { - $file_name = substr($file, 0, (strlen($file) -4)); - } - $file_ext = $row['fax_file_type']; - - //decode the base64 - if (strlen($row['fax_base64']) > 0) { - if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { - if (!file_exists($dir_fax_inbox.'/'.$file)) { - file_put_contents($dir_fax_inbox.'/'.$file, base64_decode($row['fax_base64'])); - } - } - if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { - if (!file_exists($dir_fax_sent.'/'.$file)) { - //decode the base64 - file_put_contents($dir_fax_sent.'/'.$file, base64_decode($row['fax_base64'])); - } - } - } - - //convert the tif to pdf - unset($dir_fax); - if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { - if (!file_exists($dir_fax_inbox.'/'.$file_name.".pdf")) { - $dir_fax = $dir_fax_inbox; - } - } - if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { - if (!file_exists($dir_fax_sent.'/'.$file_name.".pdf")) { - $dir_fax = $dir_fax_sent; - } - } - if ($dir_fax != '') { - chdir($dir_fax); - //get fax resolution (ppi, W & H) - $resp = exec("tiffinfo ".$file_name.".tif | grep 'Resolution:'"); - $resp_array = explode(' ', trim($resp)); - $ppi_w = (int) $resp_array[1]; - $ppi_h = (int) $resp_array[2]; - unset($resp_array); - $gs_r = $ppi_w.'x'.$ppi_h; //used by ghostscript - //get page dimensions/size (pixels/inches, W & H) - $resp = exec("tiffinfo ".$file_name.".tif | grep 'Image Width:'"); - $resp_array = explode(' ', trim($resp)); - $pix_w = $resp_array[2]; - $pix_h = $resp_array[5]; - unset($resp_array); - $gs_g = $pix_w.'x'.$pix_h; //used by ghostscript - $page_width = $pix_w / $ppi_w; - $page_height = $pix_h / $ppi_h; - if ($page_width > 8.4 && $page_height > 13) { - $page_width = 8.5; - $page_height = 14; - $page_size = 'legal'; - } - else if ($page_width > 8.4 && $page_height < 12) { - $page_width = 8.5; - $page_height = 11; - $page_size = 'letter'; - } - else if ($page_width < 8.4 && $page_height > 11) { - $page_width = 8.3; - $page_height = 11.7; - $page_size = 'a4'; - } - //generate pdf (a work around, as tiff2pdf improperly inverts the colors) - $cmd_tif2pdf = "tiff2pdf -i -u i -p ".$page_size." -w ".$page_width." -l ".$page_height." -f -o ".$dir_fax_temp.'/'.$file_name.".pdf ".$dir_fax.'/'.$file_name.".tif"; - //echo $cmd_tif2pdf."
"; - exec($cmd_tif2pdf); - chdir($dir_fax_temp); - $cmd_pdf2tif = "gs -q -sDEVICE=tiffg3 -r".$gs_r." -g".$gs_g." -dNOPAUSE -sOutputFile=".$file_name."_temp.tif -- ".$file_name.".pdf -c quit"; - //echo $cmd_pdf2tif."
"; - exec($cmd_pdf2tif); //convert pdf to tif - @unlink($dir_fax_temp.'/'.$file_name.".pdf"); - $cmd_tif2pdf = "tiff2pdf -i -u i -p ".$page_size." -w ".$page_width." -l ".$page_height." -f -o ".$dir_fax.'/'.$file_name.".pdf ".$dir_fax_temp.'/'.$file_name."_temp.tif"; - //echo $cmd_tif2pdf."
"; - exec($cmd_tif2pdf); - @unlink($dir_fax_temp.'/'.$file_name."_temp.tif"); - } - echo ""; - echo "\n"; - echo " \n"; - echo " \n"; - if ($_REQUEST['box'] == 'sent') { - echo " \n"; - } - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "\n"; - $c = ($c) ? 0 : 1; - } //end foreach - unset($sql, $fax_files); - } //end if results - -//show the paging controls - echo "
".$text['table-file']."".$text['table-view']." 
".$row['fax_caller_id_name']." ".format_phone($row['fax_caller_id_number'])." ".format_phone($row['fax_destination'])." \n"; - if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { - echo " \n"; - } - if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { - echo " \n"; - } - echo " $file_name"; - echo " "; - echo " \n"; - if ($_REQUEST['box'] == 'inbox') { - $dir_fax = $dir_fax_inbox; - } - if ($_REQUEST['box'] == 'sent') { - $dir_fax = $dir_fax_sent; - } - if (file_exists($dir_fax.'/'.$file_name.".pdf")) { - if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { - echo " PDF\n"; - } - if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { - echo " PDF\n"; - } - } - else { - echo " \n"; - } - echo " ".date("F d Y H:i:s", strtotime($row['fax_date']))." "; - if (permission_exists('fax_file_delete')) { - echo "$v_link_label_delete"; - } - echo "
"; - echo "

"; - - echo "
".$paging_controls."
\n"; - echo "

"; - -//include the footer - require_once "resources/footer.php"; + + Portions created by the Initial Developer are Copyright (C) 2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('fax_file_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get variables used to control the order + $order_by = check_str($_GET["order_by"]); + $order = check_str($_GET["order"]); + +//get fax extension + if (strlen($_GET['id']) > 0) { + if (is_uuid($_GET["id"])) { + $fax_uuid = $_GET["id"]; + } + if (if_group("superadmin") || if_group("admin")) { + //show all fax extensions + $sql = "select fax_name, fax_extension from v_fax "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and fax_uuid = '$fax_uuid' "; + } + else { + //show only assigned fax extensions + $sql = "select fax_name, fax_extension from v_fax as f, v_fax_users as u "; + $sql .= "where f.fax_uuid = u.fax_uuid "; + $sql .= "and f.domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and f.fax_uuid = '$fax_uuid' "; + $sql .= "and u.user_uuid = '".$_SESSION['user_uuid']."' "; + } + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) == 0) { + if (if_group("superadmin") || if_group("admin")) { + //allow access + } + else { + echo "access denied"; + exit; + } + } + foreach ($result as &$row) { + //set database fields as variables + $fax_name = $row["fax_name"]; + $fax_extension = $row["fax_extension"]; + //limit to one row + break; + } + unset ($prep_statement); + } + +//set the fax directory + $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']; + +//download the fax + if ($_GET['a'] == "download") { + session_cache_limiter('public'); + //test to see if it is in the inbox or sent directory. + if ($_GET['type'] == "fax_inbox") { + if (file_exists($fax_dir.'/'.check_str($_GET['ext']).'/inbox/'.check_str($_GET['filename']))) { + $tmp_faxdownload_file = $fax_dir.'/'.check_str($_GET['ext']).'/inbox/'.check_str($_GET['filename']); + } + } + else if ($_GET['type'] == "fax_sent") { + if (file_exists($fax_dir.'/'.check_str($_GET['ext']).'/sent/'.check_str($_GET['filename']))) { + $tmp_faxdownload_file = $fax_dir.'/'.check_str($_GET['ext']).'/sent/'.check_str($_GET['filename']); + } + } + //let's see if we found it. + if (strlen($tmp_faxdownload_file) > 0) { + $fd = fopen($tmp_faxdownload_file, "rb"); + if ($_GET['t'] == "bin") { + header("Content-Type: application/force-download"); + header("Content-Type: application/octet-stream"); + header("Content-Description: File Transfer"); + header('Content-Disposition: attachment; filename="'.check_str($_GET['filename']).'"'); + } + else { + $file_ext = substr(check_str($_GET['filename']), -3); + if ($file_ext == "tif") { + header("Content-Type: image/tiff"); + } + else if ($file_ext == "png") { + header("Content-Type: image/png"); + } + else if ($file_ext == "jpg") { + header('Content-Type: image/jpeg'); + } + else if ($file_ext == "pdf") { + header("Content-Type: application/pdf"); + } + } + header('Accept-Ranges: bytes'); + header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 + header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // date in the past + header("Content-Length: " . filesize($tmp_faxdownload_file)); + fpassthru($fd); + } + else { + echo "".$text['label-file'].""; + } + exit; + } + +//get the fax extension + if (strlen($fax_extension) > 0) { + //set the fax directories. example /usr/local/freeswitch/storage/fax/329/inbox + $dir_fax_inbox = $fax_dir.'/'.$fax_extension.'/inbox'; + $dir_fax_sent = $fax_dir.'/'.$fax_extension.'/sent'; + $dir_fax_temp = $fax_dir.'/'.$fax_extension.'/temp'; + + //make sure the directories exist + if (!is_dir($_SESSION['switch']['storage']['dir'])) { + mkdir($_SESSION['switch']['storage']['dir']); + chmod($dir_fax_sent,0774); + } + if (!is_dir($fax_dir.'/'.$fax_extension)) { + mkdir($fax_dir.'/'.$fax_extension,0774,true); + chmod($fax_dir.'/'.$fax_extension,0774); + } + if (!is_dir($dir_fax_inbox)) { + mkdir($dir_fax_inbox,0774,true); + chmod($dir_fax_inbox,0774); + } + if (!is_dir($dir_fax_sent)) { + mkdir($dir_fax_sent,0774,true); + chmod($dir_fax_sent,0774); + } + if (!is_dir($dir_fax_temp)) { + mkdir($dir_fax_temp,0774,true); + chmod($dir_fax_temp,0774); + } + } + +//additional includes + require_once "resources/header.php"; + require_once "resources/paging.php"; + +//prepare to page the results + $sql = "select count(*) as num_rows from v_fax_files "; + $sql .= "where fax_uuid = '$fax_uuid' "; + $sql .= "and domain_uuid = '$domain_uuid' "; + if ($_REQUEST['box'] == 'inbox') { + $sql .= "and fax_mode = 'rx' "; + } + if ($_REQUEST['box'] == 'sent') { + $sql .= "and fax_mode = 'tx' "; + } + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + if ($row['num_rows'] > 0) { + $num_rows = $row['num_rows']; + } + else { + $num_rows = '0'; + } + } + +//prepare to page the results + $rows_per_page = ($_SESSION['domain']['paging']['numeric'] != '') ? $_SESSION['domain']['paging']['numeric'] : 50; + $param = "&id=".$_GET['id']."&box=".$_GET['box']."&order_by=".$_GET['order_by']."&order=".$_GET['order']; + $page = $_GET['page']; + if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } + list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); + $offset = $rows_per_page * $page; + +//get the list + $sql = "select * from v_fax_files "; + $sql .= "where fax_uuid = '$fax_uuid' "; + $sql .= "and domain_uuid = '$domain_uuid' "; + if ($_REQUEST['box'] == 'inbox') { + $sql .= "and fax_mode = 'rx' "; + } + if ($_REQUEST['box'] == 'sent') { + $sql .= "and fax_mode = 'tx' "; + } + $sql .= "order by ".((strlen($order_by) > 0) ? $order_by.' '.$order : "fax_date desc")." "; + $sql .= "limit $rows_per_page offset $offset "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $fax_files = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + +//show the header + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { + echo " ".$text['header-inbox'].": ".$fax_name." (".$fax_extension.")\n"; + } + if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { + echo " ".$text['header-sent'].": ".$fax_name." (".$fax_extension.")\n"; + } + echo " \n"; + echo " \n"; + echo "
\n"; + echo "
\n"; + +//show the table and content + $c = 0; + $row_style["0"] = "row_style0"; + $row_style["1"] = "row_style1"; + + echo "\n"; + echo "\n"; + echo th_order_by('fax_caller_id_name', $text['label-fax_caller_id_name'], $order_by, $order, "&id=".$_GET['id']."&box=".$_GET['box']."&page=".$_GET['page']); + echo th_order_by('fax_caller_id_number', $text['label-fax_caller_id_number'], $order_by, $order, "&id=".$_GET['id']."&box=".$_GET['box']."&page=".$_GET['page']); + if ($_REQUEST['box'] == 'sent') { + echo th_order_by('fax_destination', $text['label-fax_destination'], $order_by, $order, "&id=".$_GET['id']."&box=".$_GET['box']."&page=".$_GET['page']); + } + echo "\n"; + echo "\n"; + echo th_order_by('fax_date', $text['label-fax_date'], $order_by, $order, "&id=".$_GET['id']."&box=".$_GET['box']."&page=".$_GET['page']); + echo "\n"; + echo "\n"; + if ($num_rows > 0) { + foreach($fax_files as $row) { + $file = basename($row['fax_file_path']); + if (strtolower(substr($file, -3)) == "tif" || strtolower(substr($file, -3)) == "pdf") { + $file_name = substr($file, 0, (strlen($file) -4)); + } + $file_ext = $row['fax_file_type']; + + //decode the base64 + if (strlen($row['fax_base64']) > 0) { + if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { + if (!file_exists($dir_fax_inbox.'/'.$file)) { + file_put_contents($dir_fax_inbox.'/'.$file, base64_decode($row['fax_base64'])); + } + } + if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { + if (!file_exists($dir_fax_sent.'/'.$file)) { + //decode the base64 + file_put_contents($dir_fax_sent.'/'.$file, base64_decode($row['fax_base64'])); + } + } + } + + //convert the tif to pdf + unset($dir_fax); + if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { + if (!file_exists($dir_fax_inbox.'/'.$file_name.".pdf")) { + $dir_fax = $dir_fax_inbox; + } + } + if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { + if (!file_exists($dir_fax_sent.'/'.$file_name.".pdf")) { + $dir_fax = $dir_fax_sent; + } + } + if ($dir_fax != '') { + chdir($dir_fax); + //get fax resolution (ppi, W & H) + $resp = exec("tiffinfo ".$file_name.".tif | grep 'Resolution:'"); + $resp_array = explode(' ', trim($resp)); + $ppi_w = (int) $resp_array[1]; + $ppi_h = (int) $resp_array[2]; + unset($resp_array); + $gs_r = $ppi_w.'x'.$ppi_h; //used by ghostscript + //get page dimensions/size (pixels/inches, W & H) + $resp = exec("tiffinfo ".$file_name.".tif | grep 'Image Width:'"); + $resp_array = explode(' ', trim($resp)); + $pix_w = $resp_array[2]; + $pix_h = $resp_array[5]; + unset($resp_array); + $gs_g = $pix_w.'x'.$pix_h; //used by ghostscript + $page_width = $pix_w / $ppi_w; + $page_height = $pix_h / $ppi_h; + if ($page_width > 8.4 && $page_height > 13) { + $page_width = 8.5; + $page_height = 14; + $page_size = 'legal'; + } + else if ($page_width > 8.4 && $page_height < 12) { + $page_width = 8.5; + $page_height = 11; + $page_size = 'letter'; + } + else if ($page_width < 8.4 && $page_height > 11) { + $page_width = 8.3; + $page_height = 11.7; + $page_size = 'a4'; + } + //generate pdf (a work around, as tiff2pdf improperly inverts the colors) + $cmd_tif2pdf = "tiff2pdf -i -u i -p ".$page_size." -w ".$page_width." -l ".$page_height." -f -o ".$dir_fax_temp.'/'.$file_name.".pdf ".$dir_fax.'/'.$file_name.".tif"; + //echo $cmd_tif2pdf."
"; + exec($cmd_tif2pdf); + chdir($dir_fax_temp); + $cmd_pdf2tif = "gs -q -sDEVICE=tiffg3 -r".$gs_r." -g".$gs_g." -dNOPAUSE -sOutputFile=".$file_name."_temp.tif -- ".$file_name.".pdf -c quit"; + //echo $cmd_pdf2tif."
"; + exec($cmd_pdf2tif); //convert pdf to tif + @unlink($dir_fax_temp.'/'.$file_name.".pdf"); + $cmd_tif2pdf = "tiff2pdf -i -u i -p ".$page_size." -w ".$page_width." -l ".$page_height." -f -o ".$dir_fax.'/'.$file_name.".pdf ".$dir_fax_temp.'/'.$file_name."_temp.tif"; + //echo $cmd_tif2pdf."
"; + exec($cmd_tif2pdf); + @unlink($dir_fax_temp.'/'.$file_name."_temp.tif"); + } + echo ""; + echo "\n"; + echo " \n"; + echo " \n"; + if ($_REQUEST['box'] == 'sent') { + echo " \n"; + } + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "\n"; + $c = ($c) ? 0 : 1; + } //end foreach + unset($sql, $fax_files); + } //end if results + +//show the paging controls + echo "
".$text['table-file']."".$text['table-view']." 
".$row['fax_caller_id_name']." ".format_phone($row['fax_caller_id_number'])." ".format_phone($row['fax_destination'])." \n"; + if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { + echo " \n"; + } + if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { + echo " \n"; + } + echo " $file_name"; + echo " "; + echo " \n"; + if ($_REQUEST['box'] == 'inbox') { + $dir_fax = $dir_fax_inbox; + } + if ($_REQUEST['box'] == 'sent') { + $dir_fax = $dir_fax_sent; + } + if (file_exists($dir_fax.'/'.$file_name.".pdf")) { + if ($_REQUEST['box'] == 'inbox' && permission_exists('fax_inbox_view')) { + echo " PDF\n"; + } + if ($_REQUEST['box'] == 'sent' && permission_exists('fax_sent_view')) { + echo " PDF\n"; + } + } + else { + echo " \n"; + } + echo " ".date("F d Y H:i:s", strtotime($row['fax_date']))." "; + if (permission_exists('fax_file_delete')) { + echo "$v_link_label_delete"; + } + echo "
"; + echo "

"; + + echo "
".$paging_controls."
\n"; + echo "

"; + +//include the footer + require_once "resources/footer.php"; ?> \ No newline at end of file diff --git a/app/fax/fax_files_remote.php b/app/fax/fax_files_remote.php index 23d4b1b731..98aba84223 100644 --- a/app/fax/fax_files_remote.php +++ b/app/fax/fax_files_remote.php @@ -1,243 +1,243 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - James Rose -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -require_once "resources/functions/object_to_array.php"; -require_once "resources/functions/parse_attachments.php"; -if (permission_exists('fax_inbox_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get fax server uuid, set connection parameters - if (strlen($_GET['id']) > 0) { - $fax_uuid = check_str($_GET["id"]); - - if (if_group("superadmin") || if_group("admin")) { - //show all fax extensions - $sql = "select * from v_fax "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and fax_uuid = '$fax_uuid' "; - } - else { - //show only assigned fax extensions - $sql = "select * from v_fax as f, v_fax_users as u "; - $sql .= "where f.fax_uuid = u.fax_uuid "; - $sql .= "and f.domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and f.fax_uuid = '$fax_uuid' "; - $sql .= "and u.user_uuid = '".$_SESSION['user_uuid']."' "; - } - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) == 0) { - if (!if_group("superadmin") && !if_group("admin")) { - echo "access denied"; - exit; - } - } - foreach ($result as &$row) { - $fax_name = $row["fax_name"]; - $fax_extension = $row["fax_extension"]; - $fax_email_connection_type = $row["fax_email_connection_type"]; - $fax_email_connection_host = $row["fax_email_connection_host"]; - $fax_email_connection_port = $row["fax_email_connection_port"]; - $fax_email_connection_security = $row["fax_email_connection_security"]; - $fax_email_connection_validate = $row["fax_email_connection_validate"]; - $fax_email_connection_username = $row["fax_email_connection_username"]; - $fax_email_connection_password = $row["fax_email_connection_password"]; - $fax_email_connection_mailbox = $row["fax_email_connection_mailbox"]; - $fax_email_inbound_subject_tag = $row["fax_email_inbound_subject_tag"]; - break; - } - unset ($prep_statement); - - // make connection - $fax_email_connection = "{".$fax_email_connection_host.":".$fax_email_connection_port."/".$fax_email_connection_type; - $fax_email_connection .= ($fax_email_connection_security != '') ? "/".$fax_email_connection_security : "/notls"; - $fax_email_connection .= "/".(($fax_email_connection_validate == 'false') ? "no" : null)."validate-cert"; - $fax_email_connection .= "}".$fax_email_connection_mailbox; - if (!$connection = imap_open($fax_email_connection, $fax_email_connection_username, $fax_email_connection_password)) { - $_SESSION["message_mood"] = 'negative'; - $_SESSION["message"] = $text['message-cannot_connect']."(".imap_last_error().")"; - header("Location: fax.php"); - exit; - } - - } - else { - header("Location: fax.php"); - exit; - } - -//message action - if ($_GET['email_id'] != '') { - $email_id = check_str($_GET['email_id']); - - //download attachment - if (isset($_GET['download'])) { - $attachment = parse_attachments($connection, $email_id, FT_UID); - $file_type = pathinfo($attachment[0]['filename'], PATHINFO_EXTENSION); - switch ($file_type) { - case "pdf" : header("Content-Type: application/pdf"); break; - case "tif" : header("Contet-Type: image/tiff"); break; - } - header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 - header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // date in the past - header("Content-Length: ".strlen($attachment[0]['attachment'])); - $browser = $_SERVER["HTTP_USER_AGENT"]; - if (preg_match("/MSIE 5.5/", $browser) || preg_match("/MSIE 6.0/", $browser)) { - header("Content-Disposition: filename=\"".$attachment[0]['filename']."\""); - } - else { - header("Content-Disposition: attachment; filename=\"".$attachment[0]['filename']."\""); - } - header("Content-Transfer-Encoding: binary"); - echo $attachment[0]['attachment']; - exit; - } - - //delete email - if (isset($_GET['delete']) && permission_exists('fax_inbox_delete')) { - $attachment = parse_attachments($connection, $email_id, FT_UID); - if (imap_delete($connection, $email_id, FT_UID)) { - if (imap_expunge($connection)) { - //clean up local inbox copy - $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']; - @unlink($fax_dir.'/'.$fax_extension.'/inbox/'.$attachment[0]['filename']); - //redirect user - $_SESSION["message"] = $text['message-delete']; - header("Location: ?id=".$fax_uuid); - exit; - } - } - else { - //redirect user - $_SESSION["message_mood"] = "negative"; - $_SESSION["message"] = $text['message-delete_failed']; - header("Location: ?id=".$fax_uuid); - exit; - } - } - else { - //redirect user - $_SESSION["message_mood"] = "negative"; - $_SESSION["message"] = $text['message-delete_failed']; - header("Location: ?id=".$fax_uuid); - exit; - } - - } - -//get emails - $emails = imap_search($connection, "SUBJECT \"".$fax_email_inbound_subject_tag."\"", SE_UID); - -//show the header - require_once "resources/header.php"; - - $row_style["0"] = "row_style0"; - $row_style["1"] = "row_style1"; - -//show the inbox - $c = 0; - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " ".$text['header-inbox'].": ".$fax_name." (".$fax_extension.")\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo "

\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - if (permission_exists('fax_inbox_delete')) { - echo " \n"; - } - echo " "; - - if ($emails) { - - rsort($emails); // most recent on top - - foreach ($emails as $email_id) { - $metadata = object_to_array(imap_fetch_overview($connection, $email_id, FT_UID)); - $attachment = parse_attachments($connection, $email_id, FT_UID); - $file_name = $attachment[0]['filename']; - $caller_id_name = substr($file_name, 0, strpos($file_name, '-')); - $caller_id_number = (is_numeric($caller_id_name)) ? format_phone((int) $caller_id_name) : null; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - if (permission_exists('fax_inbox_delete')) { - echo " \n"; - } - echo " \n"; -// $fax_message = imap_fetchbody($connection, $email_id, '1.1', FT_UID); -// if ($fax_message == '') { -// $fax_message = imap_fetchbody($connection, $email_id, '1', FT_UID); -// } - $c = ($c) ? 0 : 1; - } - - } - else { - echo "\n"; - echo " \n"; - echo "\n"; - } - - echo "
".$text['label-fax_caller_id_name']."".$text['label-fax_caller_id_number']."".$text['table-file']."".$text['label-email_size']."".$text['label-email_received']." 
".$caller_id_name."".$caller_id_number."".$file_name."".byte_convert(strlen($attachment[0]['attachment']))."".$metadata[0]['date']."".$v_link_label_delete."


".$text['message-no_faxes_found']."

"; - echo "

"; - -/* close the connection */ -imap_close($connection); - - -//show the footer - require_once "resources/footer.php"; -?> + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + James Rose +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +require_once "resources/functions/object_to_array.php"; +require_once "resources/functions/parse_attachments.php"; +if (permission_exists('fax_inbox_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get fax server uuid, set connection parameters + if (strlen($_GET['id']) > 0) { + $fax_uuid = check_str($_GET["id"]); + + if (if_group("superadmin") || if_group("admin")) { + //show all fax extensions + $sql = "select * from v_fax "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and fax_uuid = '$fax_uuid' "; + } + else { + //show only assigned fax extensions + $sql = "select * from v_fax as f, v_fax_users as u "; + $sql .= "where f.fax_uuid = u.fax_uuid "; + $sql .= "and f.domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and f.fax_uuid = '$fax_uuid' "; + $sql .= "and u.user_uuid = '".$_SESSION['user_uuid']."' "; + } + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) == 0) { + if (!if_group("superadmin") && !if_group("admin")) { + echo "access denied"; + exit; + } + } + foreach ($result as &$row) { + $fax_name = $row["fax_name"]; + $fax_extension = $row["fax_extension"]; + $fax_email_connection_type = $row["fax_email_connection_type"]; + $fax_email_connection_host = $row["fax_email_connection_host"]; + $fax_email_connection_port = $row["fax_email_connection_port"]; + $fax_email_connection_security = $row["fax_email_connection_security"]; + $fax_email_connection_validate = $row["fax_email_connection_validate"]; + $fax_email_connection_username = $row["fax_email_connection_username"]; + $fax_email_connection_password = $row["fax_email_connection_password"]; + $fax_email_connection_mailbox = $row["fax_email_connection_mailbox"]; + $fax_email_inbound_subject_tag = $row["fax_email_inbound_subject_tag"]; + break; + } + unset ($prep_statement); + + // make connection + $fax_email_connection = "{".$fax_email_connection_host.":".$fax_email_connection_port."/".$fax_email_connection_type; + $fax_email_connection .= ($fax_email_connection_security != '') ? "/".$fax_email_connection_security : "/notls"; + $fax_email_connection .= "/".(($fax_email_connection_validate == 'false') ? "no" : null)."validate-cert"; + $fax_email_connection .= "}".$fax_email_connection_mailbox; + if (!$connection = imap_open($fax_email_connection, $fax_email_connection_username, $fax_email_connection_password)) { + $_SESSION["message_mood"] = 'negative'; + $_SESSION["message"] = $text['message-cannot_connect']."(".imap_last_error().")"; + header("Location: fax.php"); + exit; + } + + } + else { + header("Location: fax.php"); + exit; + } + +//message action + if ($_GET['email_id'] != '') { + $email_id = check_str($_GET['email_id']); + + //download attachment + if (isset($_GET['download'])) { + $attachment = parse_attachments($connection, $email_id, FT_UID); + $file_type = pathinfo($attachment[0]['filename'], PATHINFO_EXTENSION); + switch ($file_type) { + case "pdf" : header("Content-Type: application/pdf"); break; + case "tif" : header("Contet-Type: image/tiff"); break; + } + header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 + header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // date in the past + header("Content-Length: ".strlen($attachment[0]['attachment'])); + $browser = $_SERVER["HTTP_USER_AGENT"]; + if (preg_match("/MSIE 5.5/", $browser) || preg_match("/MSIE 6.0/", $browser)) { + header("Content-Disposition: filename=\"".$attachment[0]['filename']."\""); + } + else { + header("Content-Disposition: attachment; filename=\"".$attachment[0]['filename']."\""); + } + header("Content-Transfer-Encoding: binary"); + echo $attachment[0]['attachment']; + exit; + } + + //delete email + if (isset($_GET['delete']) && permission_exists('fax_inbox_delete')) { + $attachment = parse_attachments($connection, $email_id, FT_UID); + if (imap_delete($connection, $email_id, FT_UID)) { + if (imap_expunge($connection)) { + //clean up local inbox copy + $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']; + @unlink($fax_dir.'/'.$fax_extension.'/inbox/'.$attachment[0]['filename']); + //redirect user + $_SESSION["message"] = $text['message-delete']; + header("Location: ?id=".$fax_uuid); + exit; + } + } + else { + //redirect user + $_SESSION["message_mood"] = "negative"; + $_SESSION["message"] = $text['message-delete_failed']; + header("Location: ?id=".$fax_uuid); + exit; + } + } + else { + //redirect user + $_SESSION["message_mood"] = "negative"; + $_SESSION["message"] = $text['message-delete_failed']; + header("Location: ?id=".$fax_uuid); + exit; + } + + } + +//get emails + $emails = imap_search($connection, "SUBJECT \"".$fax_email_inbound_subject_tag."\"", SE_UID); + +//show the header + require_once "resources/header.php"; + + $row_style["0"] = "row_style0"; + $row_style["1"] = "row_style1"; + +//show the inbox + $c = 0; + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " ".$text['header-inbox'].": ".$fax_name." (".$fax_extension.")\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo "

\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + if (permission_exists('fax_inbox_delete')) { + echo " \n"; + } + echo " "; + + if ($emails) { + + rsort($emails); // most recent on top + + foreach ($emails as $email_id) { + $metadata = object_to_array(imap_fetch_overview($connection, $email_id, FT_UID)); + $attachment = parse_attachments($connection, $email_id, FT_UID); + $file_name = $attachment[0]['filename']; + $caller_id_name = substr($file_name, 0, strpos($file_name, '-')); + $caller_id_number = (is_numeric($caller_id_name)) ? format_phone((int) $caller_id_name) : null; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + if (permission_exists('fax_inbox_delete')) { + echo " \n"; + } + echo " \n"; +// $fax_message = imap_fetchbody($connection, $email_id, '1.1', FT_UID); +// if ($fax_message == '') { +// $fax_message = imap_fetchbody($connection, $email_id, '1', FT_UID); +// } + $c = ($c) ? 0 : 1; + } + + } + else { + echo "\n"; + echo " \n"; + echo "\n"; + } + + echo "
".$text['label-fax_caller_id_name']."".$text['label-fax_caller_id_number']."".$text['table-file']."".$text['label-email_size']."".$text['label-email_received']." 
".$caller_id_name."".$caller_id_number."".$file_name."".byte_convert(strlen($attachment[0]['attachment']))."".$metadata[0]['date']."".$v_link_label_delete."


".$text['message-no_faxes_found']."

"; + echo "

"; + +/* close the connection */ +imap_close($connection); + + +//show the footer + require_once "resources/footer.php"; +?> diff --git a/app/fax/fax_send.php b/app/fax/fax_send.php index 0d02cbde82..5ec0e20229 100644 --- a/app/fax/fax_send.php +++ b/app/fax/fax_send.php @@ -1,1103 +1,1103 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - James Rose - Luis Daniel Lucio Quiroz - Errol Samuels -*/ - -if (!isset($included)) { $included = false; } - -if (stristr(PHP_OS, 'WIN')) { $IS_WINDOWS = true; } else { $IS_WINDOWS = false; } - -if (!$included) { - - include "root.php"; - require_once "resources/require.php"; - require_once "resources/check_auth.php"; - if (permission_exists('fax_send')) { - //access granted - } - else { - echo "access denied"; - exit; - } - - //add multi-lingual support - $language = new text; - $text = $language->get(); - - //get the fax_extension and save it as a variable - if (strlen($_REQUEST["fax_extension"]) > 0) { - $fax_extension = check_str($_REQUEST["fax_extension"]); - } - - //pre-populate the form - if (strlen($_REQUEST['id']) > 0 && $_POST["persistformvar"] != "true") { - $fax_uuid = check_str($_REQUEST["id"]); - if (if_group("superadmin") || if_group("admin")) { - //show all fax extensions - $sql = "select fax_uuid, fax_extension, fax_caller_id_name, fax_caller_id_number, "; - $sql .= "accountcode, fax_send_greeting "; - $sql .= "from v_fax "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and fax_uuid = '$fax_uuid' "; - } - else { - //show only assigned fax extensions - $sql = "select f.fax_uuid, f.fax_extension, f.fax_caller_id_name, f.fax_caller_id_number, "; - $sql .= "f.accountcode, f.fax_send_greeting "; - $sql .= "from v_fax as f, v_fax_users as u "; - $sql .= "where f.fax_uuid = u.fax_uuid "; - $sql .= "and f.domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and f.fax_uuid = '$fax_uuid' "; - $sql .= "and u.user_uuid = '".$_SESSION['user_uuid']."' "; - } - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) == 0) { - if (if_group("superadmin") || if_group("admin")) { - //allow access - } - else { - echo "access denied"; - exit; - } - } - foreach ($result as &$row) { - //set database fields as variables - $fax_uuid = $row["fax_uuid"]; - $fax_extension = $row["fax_extension"]; - $fax_caller_id_name = $row["fax_caller_id_name"]; - $fax_caller_id_number = $row["fax_caller_id_number"]; - $fax_accountcode = $row["accountcode"]; - $fax_send_greeting = $row["fax_send_greeting"]; - //limit to one row - break; - } - unset ($prep_statement); - $fax_send_mode = $_SESSION['fax']['send_mode']['text']; - if(strlen($fax_send_mode) == 0){ - $fax_send_mode = 'direct'; - } - } - - //set the fax directory - $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']; - - // set fax cover font to generate pdf - $fax_cover_font = $_SESSION['fax']['cover_font']['text']; -} -else{ - require_once "resources/classes/event_socket.php"; -} - -if(!function_exists('correct_path')) { - function correct_path($p) { - global $IS_WINDOWS; - if ($IS_WINDOWS) { - return str_replace('/', '\\', $p); - } - return $p; - } -} - -if(!function_exists('gs_cmd')) { - function gs_cmd($args) { - global $IS_WINDOWS; - if ($IS_WINDOWS) { - return 'gswin32c '.$args; - } - return 'gs '.$args; - } -} - -if(!function_exists('fax_enqueue')) { - function fax_enqueue($fax_uuid, $fax_file, $wav_file, $reply_address, $fax_uri, $fax_dtmf, $dial_string){ - global $db, $db_type; - - $fax_task_uuid = uuid(); - $dial_string .= "fax_task_uuid='" . $fax_task_uuid . "',"; - $description = ''; //! @todo add description - if ($db_type == "pgsql") { - $date_utc_now_sql = "NOW() at time zone 'utc'"; - } - if ($db_type == "mysql") { - $date_utc_now_sql = "UTC_TIMESTAMP()"; - } - if ($db_type == "sqlite") { - $date_utc_now_sql = "datetime('now')"; - } - $sql = <<prepare($sql); - $i = 0; - $stmt->bindValue(++$i, $fax_task_uuid); - $stmt->bindValue(++$i, $fax_uuid); - $stmt->bindValue(++$i, $fax_file); - $stmt->bindValue(++$i, $wav_file); - $stmt->bindValue(++$i, $fax_uri); - $stmt->bindValue(++$i, $dial_string); - $stmt->bindValue(++$i, $fax_dtmf); - $stmt->bindValue(++$i, $reply_address); - $stmt->bindValue(++$i, $description); - if ($stmt->execute()) { - $response = 'Enqueued'; - } - else{ - //! @todo log error - $response = 'Fail enqueue'; - var_dump($db->errorInfo()); - } - unset($stmt); - return $response; - } -} - -if(!function_exists('fax_split_dtmf')) { -function fax_split_dtmf(&$fax_number, &$fax_dtmf){ - $tmp = array(); - $fax_dtmf = ''; - if(preg_match('/^\s*(.*?)\s*\((.*)\)\s*$/', $fax_number, $tmp)){ - $fax_number = $tmp[1]; - $fax_dtmf = $tmp[2]; - } -} -} - -//get the fax extension - if (strlen($fax_extension) > 0) { - //set the fax directories. example /usr/local/freeswitch/storage/fax/329/inbox - $dir_fax_inbox = $fax_dir.'/'.$fax_extension.'/inbox'; - $dir_fax_sent = $fax_dir.'/'.$fax_extension.'/sent'; - $dir_fax_temp = $fax_dir.'/'.$fax_extension.'/temp'; - - //make sure the directories exist - if (!is_dir($_SESSION['switch']['storage']['dir'])) { - mkdir($_SESSION['switch']['storage']['dir']); - chmod($_SESSION['switch']['storage']['dir'],0774); - } - if (!is_dir($_SESSION['switch']['storage']['dir'].'/fax')) { - mkdir($_SESSION['switch']['storage']['dir'].'/fax'); - chmod($_SESSION['switch']['storage']['dir'].'/fax',0774); - } - if (!is_dir($_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name'])) { - mkdir($_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']); - chmod($_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name'],0774); - } - if (!is_dir($fax_dir.'/'.$fax_extension)) { - mkdir($fax_dir.'/'.$fax_extension,0774,true); - chmod($fax_dir.'/'.$fax_extension,0774); - } - if (!is_dir($dir_fax_inbox)) { - mkdir($dir_fax_inbox,0774,true); - chmod($dir_fax_inbox,0774); - } - if (!is_dir($dir_fax_sent)) { - mkdir($dir_fax_sent,0774,true); - chmod($dir_fax_sent,0774); - } - if (!is_dir($dir_fax_temp)) { - mkdir($dir_fax_temp,0774,true); - chmod($dir_fax_temp,0774); - } - } - -//clear file status cache - clearstatcache(); - -//send the fax - $continue = false; - - if (!$included) { - if (($_POST['action'] == "send")) { - - $fax_numbers = $_POST['fax_numbers']; - $fax_uuid = check_str($_POST["id"]); - $fax_caller_id_name = check_str($_POST['fax_caller_id_name']); - $fax_caller_id_number = check_str($_POST['fax_caller_id_number']); - $fax_header = check_str($_POST['fax_header']); - $fax_sender = check_str($_POST['fax_sender']); - $fax_recipient = check_str($_POST['fax_recipient']); - $fax_subject = check_str($_POST['fax_subject']); - $fax_message = check_str($_POST['fax_message']); - $fax_resolution = check_str($_POST['fax_resolution']); - $fax_page_size = check_str($_POST['fax_page_size']); - $fax_footer = check_str($_POST['fax_footer']); - - $continue = true; - } - } - else { - //all necessary local and session variables should - //be already set by now by file including this one - $continue = true; - } - -// cleanup numbers - if (isset($fax_numbers)) { - foreach ($fax_numbers as $index => $fax_number) { - fax_split_dtmf($fax_number, $fax_dtmf); - $fax_number = preg_replace("~[^0-9]~", "", $fax_number); - $fax_dtmf = preg_replace("~[^0-9Pp*#]~", "", $fax_dtmf); - if ($fax_number != ''){ - if ($fax_dtmf != '') {$fax_number .= " (" . $fax_dtmf . ")";} - $fax_numbers[$index] = $fax_number; - } - else{ - unset($fax_numbers[$index]); - } - } - sort($fax_numbers); - } - - if ($continue) { - //determine page size - switch ($fax_page_size) { - case 'a4' : - $page_width = 8.3; //in - $page_height = 11.7; //in - break; - case 'legal' : - $page_width = 8.5; //in - $page_height = 14; //in - break; - case 'letter' : - default : - $page_width = 8.5; //in - $page_height = 11; //in - } - - //set resolution - switch ($fax_resolution) { - case 'fine': - $gs_r = '204x196'; - $gs_g = ((int) ($page_width * 204)).'x'.((int) ($page_height * 196)); - break; - case 'superfine': - $gs_r = '408x391'; - $gs_g = ((int) ($page_width * 408)).'x'.((int) ($page_height * 391)); - break; - case 'normal': - default: - $gs_r = '204x98'; - $gs_g = ((int) ($page_width * 204)).'x'.((int) ($page_height * 98)); - break; - } - - // process uploaded or emailed files (if any) - $fax_page_count = 0; - $_files = (!$included) ? $_FILES['fax_files'] : $emailed_files; - foreach ($_files['tmp_name'] as $index => $fax_tmp_name) { - $uploaded_file = (!$included) ? is_uploaded_file($fax_tmp_name) : true; - if ( $uploaded_file && $_files['error'][$index] == 0 && $_files['size'][$index] > 0 ) { - //get the file extension - $fax_file_extension = strtolower(pathinfo($_files['name'][$index], PATHINFO_EXTENSION)); - if ($fax_file_extension == "tiff") { $fax_file_extension = "tif"; } - - //block unauthorized files - $disallowed_file_extensions = explode(',','sh,ssh,so,dll,exe,bat,vbs,zip,rar,z,tar,tbz,tgz,gz'); - if (in_array($fax_file_extension, $disallowed_file_extensions) || $fax_file_extension == '') { continue; } - - $fax_name = $_files['name'][$index]; - $fax_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $fax_name); - $fax_name = str_replace(" ", "_", $fax_name); - - //lua doesn't seem to like special chars with env:GetHeader - $fax_name = str_replace(";", "_", $fax_name); - $fax_name = str_replace(",", "_", $fax_name); - $fax_name = str_replace("'", "_", $fax_name); - $fax_name = str_replace("!", "_", $fax_name); - $fax_name = str_replace("@", "_", $fax_name); - $fax_name = str_replace("#", "_", $fax_name); - $fax_name = str_replace("$", "_", $fax_name); - $fax_name = str_replace("%", "_", $fax_name); - $fax_name = str_replace("^", "_", $fax_name); - $fax_name = str_replace("`", "_", $fax_name); - $fax_name = str_replace("~", "_", $fax_name); - $fax_name = str_replace("&", "_", $fax_name); - $fax_name = str_replace("(", "_", $fax_name); - $fax_name = str_replace(")", "_", $fax_name); - $fax_name = str_replace("+", "_", $fax_name); - $fax_name = str_replace("=", "_", $fax_name); - - if (!$included) { - //move uploaded file - move_uploaded_file($_files['tmp_name'][$index], $dir_fax_temp.'/'.$fax_name.'.'.$fax_file_extension); - } - - //convert uploaded file to pdf, if necessary - if ($fax_file_extension != "pdf" && $fax_file_extension != "tif") { - chdir($dir_fax_temp); - exec("libreoffice --headless --convert-to pdf --outdir ".$dir_fax_temp." ".$dir_fax_temp.'/'.$fax_name.'.'.$fax_file_extension); - @unlink($dir_fax_temp.'/'.$fax_name.'.'.$fax_file_extension); - } - - //convert uploaded pdf to tif - if (file_exists($dir_fax_temp.'/'.$fax_name.'.pdf')) { - chdir($dir_fax_temp); - - //convert pdf to tif - $cmd = gs_cmd("-q -sDEVICE=tiffg3 -r".$gs_r." -g".$gs_g." -dNOPAUSE -sOutputFile=".correct_path($fax_name).".tif -- ".correct_path($fax_name).".pdf -c quit"); - // echo($cmd . "
\n"); - exec($cmd); - @unlink($dir_fax_temp.'/'.$fax_name.'.pdf'); - } - - $cmd = "tiffinfo ".correct_path($dir_fax_temp.'/'.$fax_name).".tif | grep \"Page Number\" | grep -c \"P\""; - // echo($cmd . "
\n"); - $tif_page_count = exec($cmd); - if ($tif_page_count != '') { - $fax_page_count += $tif_page_count; - } - - //add file to array - $tif_files[] = $dir_fax_temp.'/'.$fax_name.'.tif'; - } //if - } //foreach - - // unique id for this fax - $fax_instance_uuid = uuid(); - - //generate cover page, merge with pdf - if ($fax_subject != '' || $fax_message != '') { - - //load pdf libraries - require_once("resources/tcpdf/tcpdf.php"); - require_once("resources/fpdi/fpdi.php"); - - // initialize pdf - $pdf = new FPDI('P', 'in'); - $pdf -> SetAutoPageBreak(false); - $pdf -> setPrintHeader(false); - $pdf -> setPrintFooter(false); - $pdf -> SetMargins(0, 0, 0, true); - - if(strlen($fax_cover_font) > 0){ - if(substr($fax_cover_font, -4) == '.ttf'){ - $pdf_font = TCPDF_FONTS::addTTFfont($fax_cover_font); - } - else{ - $pdf_font = $fax_cover_font; - } - } - - if(!$pdf_font){ - $pdf_font = 'times'; - } - - //add blank page - $pdf -> AddPage('P', array($page_width, $page_height)); - - // content offset, if necessary - $x = 0; - $y = 0; - - //logo - $display_logo = false; - if (!isset($_SESSION['fax']['cover_logo']['text'])) { - $logo = PROJECT_PATH."/app/fax/resources/images/logo.jpg"; - $display_logo = true; - } - else if (isset($_SESSION['fax']['cover_logo']['text']) && $_SESSION['fax']['cover_logo']['text'] != '') { - $logo = $_SESSION['fax']['cover_logo']['text']; - if (substr($logo, 0, 4) == 'http') { - $remote_filename = strtolower(pathinfo($logo, PATHINFO_BASENAME)); - $remote_fileext = pathinfo($remote_filename, PATHINFO_EXTENSION); - if ($remote_fileext == 'gif' || $remote_fileext == 'jpg' || $remote_fileext == 'jpeg' || $remote_fileext == 'png' || $remote_fileext == 'bmp') { - if (!file_exists($dir_fax_temp.'/'.$remote_filename)) { - $raw = file_get_contents($logo); - if (file_put_contents($dir_fax_temp.'/'.$remote_filename, $raw)) { - $logo = $dir_fax_temp.'/'.$remote_filename; - } - else { - unset($logo); - } - } - else { - $logo = $dir_fax_temp.'/'.$remote_filename; - } - } - else { - unset($logo); - } - } - $display_logo = true; - } - - if ($display_logo) { - $pdf -> Image($logo, 0.5, 0.4, 2.5, 0.9, null, null, 'N', true, 300, null, false, false, 0, true); - } - else { - //set position for header text, if enabled - $pdf -> SetXY($x + 0.5, $y + 0.4); - } - - //header - if ($fax_header != '') { - $pdf -> SetLeftMargin(0.5); - $pdf -> SetFont($pdf_font, "", 10); - $pdf -> Write(0.3, $fax_header); - } - - //fax, cover sheet - $pdf -> SetTextColor(0,0,0); - $pdf -> SetFont($pdf_font, "B", 55); - $pdf -> SetXY($x + 4.55, $y + 0.25); - $pdf -> Cell($x + 3.50, $y + 0.4, $text['label-fax-fax'], 0, 0, 'R', false, null, 0, false, 'T', 'T'); - $pdf -> SetFont($pdf_font, "", 12); - $pdf -> SetFontSpacing(0.0425); - $pdf -> SetXY($x + 4.55, $y + 1.0); - $pdf -> Cell($x + 3.50, $y + 0.4, $text['label-fax-cover-sheet'], 0, 0, 'R', false, null, 0, false, 'T', 'T'); - $pdf -> SetFontSpacing(0); - - //field labels - $pdf -> SetFont($pdf_font, "B", 12); - if ($fax_recipient != '' || sizeof($fax_numbers) > 0) { - $pdf -> Text($x + 0.5, $y + 2.0, strtoupper($text['label-fax-recipient']).":"); - } - if ($fax_sender != '' || $fax_caller_id_number != '') { - $pdf -> Text($x + 0.5, $y + 2.3, strtoupper($text['label-fax-sender']).":"); - } - if ($fax_page_count > 0) { - $pdf -> Text($x + 0.5, $y + 2.6, strtoupper($text['label-fax-attached']).":"); - } - if ($fax_subject != '') { - $pdf -> Text($x + 0.5, $y + 2.9, strtoupper($text['label-fax-subject']).":"); - } - - //field values - $pdf -> SetFont($pdf_font, "", 12); - $pdf -> SetXY($x + 2.0, $y + 1.95); - if ($fax_recipient != '') { - $pdf -> Write(0.3, $fax_recipient); - } - if (sizeof($fax_numbers) > 0) { - $fax_number_string = ($fax_recipient != '') ? ' (' : null; - $fax_number_string .= format_phone($fax_numbers[0]); - if (sizeof($fax_numbers) > 1) { - for ($n = 1; $n <= sizeof($fax_numbers); $n++) { - if ($n == 4) { break; } - $fax_number_string .= ', '.format_phone($fax_numbers[$n]); - } - } - $fax_number_string .= (sizeof($fax_numbers) > 4) ? ', +'.(sizeof($fax_numbers) - 4) : null; - $fax_number_string .= ($fax_recipient != '') ? ')' : null; - $pdf -> Write(0.3, $fax_number_string); - } - $pdf -> SetXY($x + 2.0, $y + 2.25); - if ($fax_sender != '') { - $pdf -> Write(0.3, $fax_sender); - if ($fax_caller_id_number != '') { - $pdf -> Write(0.3, ' ('.format_phone($fax_caller_id_number).')'); - } - } - else { - if ($fax_caller_id_number != '') { - $pdf -> Write(0.3, format_phone($fax_caller_id_number)); - } - } - if ($fax_page_count > 0) { - $pdf -> Text($x + 2.0, $y + 2.6, $fax_page_count.' '.$text['label-fax-page'.(($fax_page_count > 1) ? 's' : null)]); - } - if ($fax_subject != '') { - $pdf -> Text($x + 2.0, $y + 2.9, $fax_subject); - } - - //message - $pdf -> Rect($x + 0.5, $y + 3.4, 7.5, 6.25, 'D'); - if ($fax_message != '') { - $pdf -> SetFont($pdf_font, "", 12); - $pdf -> SetXY($x + 0.75, $y + 3.65); - $pdf -> MultiCell(7, 5.75, $fax_message, 0, 'L', false); - } - - //footer - if ($fax_footer != '') { - $pdf -> SetFont("helvetica", "", 8); - $pdf -> SetXY($x + 0.5, $y + 9.9); - $pdf -> MultiCell(7.5, 0.75, $fax_footer, 0, 'C', false); - } - - // save cover pdf - $pdf -> Output($dir_fax_temp.'/'.$fax_instance_uuid.'_cover.pdf', "F"); // Display [I]nline, Save to [F]ile, [D]ownload - - //convert pdf to tif, add to array of pages, delete pdf - if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.'_cover.pdf')) { - chdir($dir_fax_temp); - $cmd = gs_cmd("-q -sDEVICE=tiffg3 -r".$gs_r." -g".$gs_g." -dNOPAUSE -sOutputFile=".correct_path($fax_instance_uuid)."_cover.tif -- ".correct_path($fax_instance_uuid)."_cover.pdf -c quit"); - // echo($cmd . "
\n"); - exec($cmd); - if (is_array($tif_files) && sizeof($tif_files) > 0) { - array_unshift($tif_files, $dir_fax_temp.'/'.$fax_instance_uuid.'_cover.tif'); - } - else { - $tif_files[] = $dir_fax_temp.'/'.$fax_instance_uuid.'_cover.tif'; - } - @unlink($dir_fax_temp.'/'.$fax_instance_uuid.'_cover.pdf'); - } - } - - //combine tif files into single multi-page tif - if (is_array($tif_files) && sizeof($tif_files) > 0) { - $cmd = "tiffcp -c none "; - foreach ($tif_files as $tif_file) { - $cmd .= correct_path($tif_file) . ' '; - } - $cmd .= correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'.tif'); - //echo($cmd . "
\n"); - exec($cmd); - - foreach ($tif_files as $tif_file) { - @unlink($tif_file); - } - - //generate pdf (a work around, as tiff2pdf was improperly inverting the colors) - $cmd = 'tiff2pdf -u i -p '.$fax_page_size. - ' -w '.$page_width. - ' -l '.$page_height. - ' -f -o '. - correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'.pdf').' '. - correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'.tif'); - // echo($cmd . "
\n"); - exec($cmd); - - chdir($dir_fax_temp); - - //convert pdf to tif - $cmd = gs_cmd('-q -sDEVICE=tiffg3 -r'.$gs_r.' -g'.$gs_g.' -dNOPAUSE -sOutputFile='. - correct_path($fax_instance_uuid.'_temp.tif'). - ' -- '.$fax_instance_uuid.'.pdf -c quit'); - // echo($cmd . "
\n"); - exec($cmd); - - @unlink($dir_fax_temp.'/'.$fax_instance_uuid.".pdf"); - - $cmd = 'tiff2pdf -u i -p '.$fax_page_size. - ' -w '.$page_width. - ' -l '.$page_height. - ' -f -o '. - correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'.pdf').' '. - correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'_temp.tif'); - // echo($cmd . "
\n"); - exec($cmd); - - @unlink($dir_fax_temp.'/'.$fax_instance_uuid."_temp.tif"); - } - else { - if (!$included) { - //nothing to send, redirect the browser - $_SESSION['message_mood'] = 'negative'; - $_SESSION["message"] = $text['message-invalid-fax']; - header("Location: fax_send.php?id=".$fax_uuid); - exit; - } - } - - //preview, if requested - if (($_REQUEST['submit'] != '') && ($_REQUEST['submit'] == $text['button-preview'])) { - unset($file_type); - if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.'.pdf')) { - $file_type = 'pdf'; - $content_type = 'application/pdf'; - @unlink($dir_fax_temp.'/'.$fax_instance_uuid.".tif"); - } - else if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.'.tif')) { - $file_type = 'tif'; - $content_type = 'image/tiff'; - @unlink($dir_fax_temp.'/'.$fax_instance_uuid.".pdf"); - } - if ($file_type != '') { - //push download - $fd = fopen($dir_fax_temp.'/'.$fax_instance_uuid.'.'.$file_type, "rb"); - header("Content-Type: application/force-download"); - header("Content-Type: application/octet-stream"); - header("Content-Type: application/download"); - header("Content-Description: File Transfer"); - header('Content-Disposition: attachment; filename="'.$fax_instance_uuid.'.'.$file_type.'"'); - header("Content-Type: ".$content_type); - header('Accept-Ranges: bytes'); - header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 - header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // date in the past - header("Content-Length: ".filesize($dir_fax_temp.'/'.$fax_instance_uuid.'.'.$file_type)); - fpassthru($fd); - @unlink($dir_fax_temp.'/'.$fax_instance_uuid.".".$file_type); - } - exit; - } - - //get some more info to send the fax - $mailfrom_address = (isset($_SESSION['fax']['smtp_from']['var'])) ? $_SESSION['fax']['smtp_from']['var'] : $_SESSION['email']['smtp_from']['var']; - - $sql = "select * from v_fax where fax_uuid = '".$fax_uuid."'; "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_NAMED); - $mailto_address_fax = $result["fax_email"]; - $fax_prefix = $result["fax_prefix"]; - - if (!$included) { - $sql = "select contact_uuid from v_users where user_uuid = '".$_SESSION['user_uuid']."'; "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_NAMED); - - $sql = "select email_address from v_contact_emails where contact_uuid = '".$result["contact_uuid"]."' order by email_primary desc;"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_NAMED); - $mailto_address_user = $result["email_address"]; - } - else { - //use email-to-fax from address - } - - if ($mailto_address_fax != '' && $mailto_address_user != $mailto_address_fax) { - $mailto_address = $mailto_address_fax.",".$mailto_address_user; - } - else { - $mailto_address = $mailto_address_user; - } - - //send the fax - $fax_file = $dir_fax_temp."/".$fax_instance_uuid.".tif"; - $common_dial_string = "for_fax=1,"; - $common_dial_string .= "accountcode='" . $fax_accountcode . "',"; - $common_dial_string .= "sip_h_X-accountcode='" . $fax_accountcode . "',"; - $common_dial_string .= "domain_uuid=" . $_SESSION["domain_uuid"] . ","; - $common_dial_string .= "domain_name=" . $_SESSION["domain_name"] . ","; - $common_dial_string .= "origination_caller_id_name='" . $fax_caller_id_name . "',"; - $common_dial_string .= "origination_caller_id_number='" . $fax_caller_id_number . "',"; - $common_dial_string .= "fax_ident='" . $fax_caller_id_number . "',"; - $common_dial_string .= "fax_header='" . $fax_caller_id_name . "',"; - $common_dial_string .= "fax_file='" . $fax_file . "',"; - - foreach ($fax_numbers as $fax_number) { - $dial_string = $common_dial_string; - - fax_split_dtmf($fax_number, $fax_dtmf); - - //prepare the fax command - $route_array = outbound_route_to_bridge($_SESSION['domain_uuid'], $fax_prefix . $fax_number); - - if (count($route_array) == 0) { - //send the internal call to the registered extension - $fax_uri = "user/".$fax_number."@".$_SESSION['domain_name']; - $t38 = ""; - } - else { - //send the external call - $fax_uri = $route_array[0]; - $t38 = "fax_enable_t38=true,fax_enable_t38_request=true,"; - } - - if ($fax_send_mode != 'queue') { - $dial_string .= $t38; - $dial_string .= "mailto_address='" . $mailto_address . "',"; - $dial_string .= "mailfrom_address='" . $mailfrom_address . "',"; - $dial_string .= "fax_uri=" . $fax_uri . ","; - $dial_string .= "fax_retry_attempts=1" . ","; - $dial_string .= "fax_retry_limit=20" . ","; - $dial_string .= "fax_retry_sleep=180" . ","; - $dial_string .= "fax_verbose=true" . ","; - $dial_string .= "fax_use_ecm=off" . ","; - $dial_string .= "api_hangup_hook='lua fax_retry.lua'"; - $dial_string = "{" . $dial_string . "}" . $fax_uri." &txfax('".$fax_file."')"; - - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if ($fp) { - $cmd = "api originate " . $dial_string; - // echo($cmd . "
\n"); - //send the command to event socket - $response = event_socket_request($fp, $cmd); - $response = str_replace("\n", "", $response); - $uuid = str_replace("+OK ", "", $response); - } - fclose($fp); - } - else{ // enqueue - $wav_file = ''; //! @todo add custom message - $response = fax_enqueue($fax_uuid, $fax_file, $wav_file, $mailto_address, $fax_uri, $fax_dtmf, $dial_string); - } - } - - //wait for a few seconds - sleep(5); - - //move the generated tif (and pdf) files to the sent directory - if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.".tif")) { - copy($dir_fax_temp.'/'.$fax_instance_uuid.".tif", $dir_fax_sent.'/'.$fax_instance_uuid.".tif"); - } - - if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.".pdf")) { - copy($dir_fax_temp.'/'.$fax_instance_uuid.".pdf ", $dir_fax_sent.'/'.$fax_instance_uuid.".pdf"); - } - - if (!$included) { - //redirect the browser - $_SESSION["message"] = $response; - if (permission_exists('fax_active_view')) { - header("Location: fax_active.php?id=".$fax_uuid); - } - else { - header("Location: fax_files.php?id=".$fax_uuid."&box=sent"); - } - exit; - } - - } //end upload and send fax - - -if (!$included) { - - //show the header - require_once "resources/header.php"; - - //javascript to toggle input/select boxes, add fax numbers - echo "\n"; - echo ""; - - //fax extension form - echo "
\n"; - echo "\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - echo "
\n"; - echo " ".$text['header-send']."\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo "
\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo " \n"; - echo " \n"; - echo " "; - echo "
\n"; - echo " ".$text['description-2']." ".((if_group('superadmin')) ? $text['description-3'] : null)." \n"; - echo "

\n"; - echo "
\n"; - echo " ".$text['label-fax-header']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax-header']."\n"; - echo "
\n"; - echo " ".$text['label-fax-sender']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax-sender']."\n"; - echo "
\n"; - echo " ".$text['label-fax-recipient']."\n"; - echo "\n"; - //retrieve current user's assigned groups (uuids) - foreach ($_SESSION['groups'] as $group_data) { - $user_group_uuids[] = $group_data['group_uuid']; - } - //add user's uuid to group uuid list to include private (non-shared) contacts - $user_group_uuids[] = $_SESSION["user_uuid"]; - $sql = "select "; - $sql .= "c.contact_organization, "; - $sql .= "c.contact_name_given, "; - $sql .= "c.contact_name_family, "; - $sql .= "c.contact_nickname, "; - $sql .= "cp.phone_number "; - $sql .= "from "; - $sql .= "v_contacts as c, "; - $sql .= "v_contact_phones as cp "; - $sql .= "where "; - $sql .= "c.contact_uuid = cp.contact_uuid and "; - $sql .= "c.domain_uuid = '".$_SESSION['domain_uuid']."' and "; - $sql .= "cp.domain_uuid = '".$_SESSION['domain_uuid']."' and "; - $sql .= "cp.phone_type_fax = 1 and "; - $sql .= "cp.phone_number is not null and "; - $sql .= "cp.phone_number <> '' "; - if (sizeof($user_group_uuids) > 0) { - //only show contacts assigned to current user's group(s) and those not assigned to any group - $sql .= "and ( \n"; - $sql .= " c.contact_uuid in ( \n"; - $sql .= " select contact_uuid from v_contact_groups "; - $sql .= " where group_uuid in ('".implode("','", $user_group_uuids)."') "; - $sql .= " and domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= " ) \n"; - $sql .= " or \n"; - $sql .= " c.contact_uuid not in ( \n"; - $sql .= " select contact_uuid from v_contact_groups "; - $sql .= " where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= " ) \n"; - $sql .= ") \n"; - } - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement -> execute(); - $result = $prep_statement -> fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - if ($result_count > 0) { - foreach ($result as &$row) { - if ($row['contact_organization'] != '') { - $contact_option_label = $row['contact_organization']; - } - if ($row['contact_name_given'] != '' || $row['contact_name_family'] != '' || $row['contact_nickname'] != '') { - $contact_option_label .= ($row['contact_organization'] != '') ? "," : null; - $contact_option_label .= ($row['contact_name_given'] != '') ? (($row['contact_organization'] != '') ? " " : null).$row['contact_name_given'] : null; - $contact_option_label .= ($row['contact_name_family'] != '') ? (($row['contact_organization'] != '' || $row['contact_name_given'] != '') ? " " : null).$row['contact_name_family'] : null; - $contact_option_label .= ($row['contact_nickname'] != '') ? (($row['contact_organization'] != '' || $row['contact_name_given'] != '' || $row['contact_name_family'] != '') ? " (".$row['contact_nickname'].")" : $row['contact_nickname']) : null; - } - $contact_option_value_recipient = $contact_option_label; - $contact_option_value_faxnumber = $row['phone_number']; - $contact_option_label .= ":  ".format_phone($row['phone_number']); - $contact_labels[] = $contact_option_label; - $contact_values[] = $contact_option_value_faxnumber."|".$contact_option_value_recipient; - unset($contact_option_label); - } - asort($contact_labels, SORT_NATURAL); // sort by name(s) - echo " \n"; - } - unset ($prep_statement); - echo " \n"; - if ($result_count > 0) { - echo " \n"; - } - echo "
\n"; - echo " ".$text['description-fax-recipient']."\n"; - echo "
\n"; - echo " ".$text['label-fax-number']."\n"; - echo "\n"; - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - echo "
"; - echo " \n"; - echo " "; - echo " $v_link_label_add"; - echo "
"; - echo " ".$text['description-fax-number']."\n"; - echo "
\n"; - echo " ".$text['label-fax_files']."\n"; - echo "\n"; - for ($f = 1; $f <= 3; $f++) { - echo " 1) ? "style='display: none;'" : null).">"; - echo "
"; - echo " "; - echo "
\n"; - } - echo " ".$text['description-fax_files']."\n"; - echo "
\n"; - echo " ".$text['label-fax-resolution']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax-resolution']."\n"; - echo "
\n"; - echo " ".$text['label-fax-page-size']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax-page-size']."\n"; - echo "
\n"; - echo " ".$text['label-fax-subject']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax-subject']."\n"; - echo "
\n"; - echo " ".$text['label-fax-message']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax-message']."\n"; - echo "
\n"; - echo " ".$text['label-fax-footer']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " ".$text['description-fax-footer']."\n"; - echo "
\n"; - echo "
\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
"; - echo "
\n"; - echo "
\n"; - - //show the footer - require_once "resources/footer.php"; - -} - -// used for initial element alignment during pdf generation -/* -function showgrid($pdf) { - // generate a grid for placement - for ($x=0; $x<=8.5; $x+=0.1) { - for ($y=0; $y<=11; $y+=0.1) { - $pdf -> SetTextColor(0,0,0); - $pdf -> SetFont("courier", "", 3); - $pdf -> Text($x-0.01,$y-0.01,"."); - } - } - for ($x=0; $x<=9; $x+=1) { - for ($y=0; $y<=11; $y+=1) { - $pdf -> SetTextColor(255,0,0); - $pdf -> SetFont("times", "", 10); - $pdf -> Text($x-.02,$y-.01,"."); - $pdf -> SetFont("courier", "", 4); - $pdf -> Text($x+0.01,$y+0.035,$x.",".$y); - } - } -} -*/ -?> + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + James Rose + Luis Daniel Lucio Quiroz + Errol Samuels +*/ + +if (!isset($included)) { $included = false; } + +if (stristr(PHP_OS, 'WIN')) { $IS_WINDOWS = true; } else { $IS_WINDOWS = false; } + +if (!$included) { + + include "root.php"; + require_once "resources/require.php"; + require_once "resources/check_auth.php"; + if (permission_exists('fax_send')) { + //access granted + } + else { + echo "access denied"; + exit; + } + + //add multi-lingual support + $language = new text; + $text = $language->get(); + + //get the fax_extension and save it as a variable + if (strlen($_REQUEST["fax_extension"]) > 0) { + $fax_extension = check_str($_REQUEST["fax_extension"]); + } + + //pre-populate the form + if (strlen($_REQUEST['id']) > 0 && $_POST["persistformvar"] != "true") { + $fax_uuid = check_str($_REQUEST["id"]); + if (if_group("superadmin") || if_group("admin")) { + //show all fax extensions + $sql = "select fax_uuid, fax_extension, fax_caller_id_name, fax_caller_id_number, "; + $sql .= "accountcode, fax_send_greeting "; + $sql .= "from v_fax "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and fax_uuid = '$fax_uuid' "; + } + else { + //show only assigned fax extensions + $sql = "select f.fax_uuid, f.fax_extension, f.fax_caller_id_name, f.fax_caller_id_number, "; + $sql .= "f.accountcode, f.fax_send_greeting "; + $sql .= "from v_fax as f, v_fax_users as u "; + $sql .= "where f.fax_uuid = u.fax_uuid "; + $sql .= "and f.domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and f.fax_uuid = '$fax_uuid' "; + $sql .= "and u.user_uuid = '".$_SESSION['user_uuid']."' "; + } + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) == 0) { + if (if_group("superadmin") || if_group("admin")) { + //allow access + } + else { + echo "access denied"; + exit; + } + } + foreach ($result as &$row) { + //set database fields as variables + $fax_uuid = $row["fax_uuid"]; + $fax_extension = $row["fax_extension"]; + $fax_caller_id_name = $row["fax_caller_id_name"]; + $fax_caller_id_number = $row["fax_caller_id_number"]; + $fax_accountcode = $row["accountcode"]; + $fax_send_greeting = $row["fax_send_greeting"]; + //limit to one row + break; + } + unset ($prep_statement); + $fax_send_mode = $_SESSION['fax']['send_mode']['text']; + if(strlen($fax_send_mode) == 0){ + $fax_send_mode = 'direct'; + } + } + + //set the fax directory + $fax_dir = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']; + + // set fax cover font to generate pdf + $fax_cover_font = $_SESSION['fax']['cover_font']['text']; +} +else{ + require_once "resources/classes/event_socket.php"; +} + +if(!function_exists('correct_path')) { + function correct_path($p) { + global $IS_WINDOWS; + if ($IS_WINDOWS) { + return str_replace('/', '\\', $p); + } + return $p; + } +} + +if(!function_exists('gs_cmd')) { + function gs_cmd($args) { + global $IS_WINDOWS; + if ($IS_WINDOWS) { + return 'gswin32c '.$args; + } + return 'gs '.$args; + } +} + +if(!function_exists('fax_enqueue')) { + function fax_enqueue($fax_uuid, $fax_file, $wav_file, $reply_address, $fax_uri, $fax_dtmf, $dial_string){ + global $db, $db_type; + + $fax_task_uuid = uuid(); + $dial_string .= "fax_task_uuid='" . $fax_task_uuid . "',"; + $description = ''; //! @todo add description + if ($db_type == "pgsql") { + $date_utc_now_sql = "NOW() at time zone 'utc'"; + } + if ($db_type == "mysql") { + $date_utc_now_sql = "UTC_TIMESTAMP()"; + } + if ($db_type == "sqlite") { + $date_utc_now_sql = "datetime('now')"; + } + $sql = <<prepare($sql); + $i = 0; + $stmt->bindValue(++$i, $fax_task_uuid); + $stmt->bindValue(++$i, $fax_uuid); + $stmt->bindValue(++$i, $fax_file); + $stmt->bindValue(++$i, $wav_file); + $stmt->bindValue(++$i, $fax_uri); + $stmt->bindValue(++$i, $dial_string); + $stmt->bindValue(++$i, $fax_dtmf); + $stmt->bindValue(++$i, $reply_address); + $stmt->bindValue(++$i, $description); + if ($stmt->execute()) { + $response = 'Enqueued'; + } + else{ + //! @todo log error + $response = 'Fail enqueue'; + var_dump($db->errorInfo()); + } + unset($stmt); + return $response; + } +} + +if(!function_exists('fax_split_dtmf')) { +function fax_split_dtmf(&$fax_number, &$fax_dtmf){ + $tmp = array(); + $fax_dtmf = ''; + if(preg_match('/^\s*(.*?)\s*\((.*)\)\s*$/', $fax_number, $tmp)){ + $fax_number = $tmp[1]; + $fax_dtmf = $tmp[2]; + } +} +} + +//get the fax extension + if (strlen($fax_extension) > 0) { + //set the fax directories. example /usr/local/freeswitch/storage/fax/329/inbox + $dir_fax_inbox = $fax_dir.'/'.$fax_extension.'/inbox'; + $dir_fax_sent = $fax_dir.'/'.$fax_extension.'/sent'; + $dir_fax_temp = $fax_dir.'/'.$fax_extension.'/temp'; + + //make sure the directories exist + if (!is_dir($_SESSION['switch']['storage']['dir'])) { + mkdir($_SESSION['switch']['storage']['dir']); + chmod($_SESSION['switch']['storage']['dir'],0774); + } + if (!is_dir($_SESSION['switch']['storage']['dir'].'/fax')) { + mkdir($_SESSION['switch']['storage']['dir'].'/fax'); + chmod($_SESSION['switch']['storage']['dir'].'/fax',0774); + } + if (!is_dir($_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name'])) { + mkdir($_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name']); + chmod($_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name'],0774); + } + if (!is_dir($fax_dir.'/'.$fax_extension)) { + mkdir($fax_dir.'/'.$fax_extension,0774,true); + chmod($fax_dir.'/'.$fax_extension,0774); + } + if (!is_dir($dir_fax_inbox)) { + mkdir($dir_fax_inbox,0774,true); + chmod($dir_fax_inbox,0774); + } + if (!is_dir($dir_fax_sent)) { + mkdir($dir_fax_sent,0774,true); + chmod($dir_fax_sent,0774); + } + if (!is_dir($dir_fax_temp)) { + mkdir($dir_fax_temp,0774,true); + chmod($dir_fax_temp,0774); + } + } + +//clear file status cache + clearstatcache(); + +//send the fax + $continue = false; + + if (!$included) { + if (($_POST['action'] == "send")) { + + $fax_numbers = $_POST['fax_numbers']; + $fax_uuid = check_str($_POST["id"]); + $fax_caller_id_name = check_str($_POST['fax_caller_id_name']); + $fax_caller_id_number = check_str($_POST['fax_caller_id_number']); + $fax_header = check_str($_POST['fax_header']); + $fax_sender = check_str($_POST['fax_sender']); + $fax_recipient = check_str($_POST['fax_recipient']); + $fax_subject = check_str($_POST['fax_subject']); + $fax_message = check_str($_POST['fax_message']); + $fax_resolution = check_str($_POST['fax_resolution']); + $fax_page_size = check_str($_POST['fax_page_size']); + $fax_footer = check_str($_POST['fax_footer']); + + $continue = true; + } + } + else { + //all necessary local and session variables should + //be already set by now by file including this one + $continue = true; + } + +// cleanup numbers + if (isset($fax_numbers)) { + foreach ($fax_numbers as $index => $fax_number) { + fax_split_dtmf($fax_number, $fax_dtmf); + $fax_number = preg_replace("~[^0-9]~", "", $fax_number); + $fax_dtmf = preg_replace("~[^0-9Pp*#]~", "", $fax_dtmf); + if ($fax_number != ''){ + if ($fax_dtmf != '') {$fax_number .= " (" . $fax_dtmf . ")";} + $fax_numbers[$index] = $fax_number; + } + else{ + unset($fax_numbers[$index]); + } + } + sort($fax_numbers); + } + + if ($continue) { + //determine page size + switch ($fax_page_size) { + case 'a4' : + $page_width = 8.3; //in + $page_height = 11.7; //in + break; + case 'legal' : + $page_width = 8.5; //in + $page_height = 14; //in + break; + case 'letter' : + default : + $page_width = 8.5; //in + $page_height = 11; //in + } + + //set resolution + switch ($fax_resolution) { + case 'fine': + $gs_r = '204x196'; + $gs_g = ((int) ($page_width * 204)).'x'.((int) ($page_height * 196)); + break; + case 'superfine': + $gs_r = '408x391'; + $gs_g = ((int) ($page_width * 408)).'x'.((int) ($page_height * 391)); + break; + case 'normal': + default: + $gs_r = '204x98'; + $gs_g = ((int) ($page_width * 204)).'x'.((int) ($page_height * 98)); + break; + } + + // process uploaded or emailed files (if any) + $fax_page_count = 0; + $_files = (!$included) ? $_FILES['fax_files'] : $emailed_files; + foreach ($_files['tmp_name'] as $index => $fax_tmp_name) { + $uploaded_file = (!$included) ? is_uploaded_file($fax_tmp_name) : true; + if ( $uploaded_file && $_files['error'][$index] == 0 && $_files['size'][$index] > 0 ) { + //get the file extension + $fax_file_extension = strtolower(pathinfo($_files['name'][$index], PATHINFO_EXTENSION)); + if ($fax_file_extension == "tiff") { $fax_file_extension = "tif"; } + + //block unauthorized files + $disallowed_file_extensions = explode(',','sh,ssh,so,dll,exe,bat,vbs,zip,rar,z,tar,tbz,tgz,gz'); + if (in_array($fax_file_extension, $disallowed_file_extensions) || $fax_file_extension == '') { continue; } + + $fax_name = $_files['name'][$index]; + $fax_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $fax_name); + $fax_name = str_replace(" ", "_", $fax_name); + + //lua doesn't seem to like special chars with env:GetHeader + $fax_name = str_replace(";", "_", $fax_name); + $fax_name = str_replace(",", "_", $fax_name); + $fax_name = str_replace("'", "_", $fax_name); + $fax_name = str_replace("!", "_", $fax_name); + $fax_name = str_replace("@", "_", $fax_name); + $fax_name = str_replace("#", "_", $fax_name); + $fax_name = str_replace("$", "_", $fax_name); + $fax_name = str_replace("%", "_", $fax_name); + $fax_name = str_replace("^", "_", $fax_name); + $fax_name = str_replace("`", "_", $fax_name); + $fax_name = str_replace("~", "_", $fax_name); + $fax_name = str_replace("&", "_", $fax_name); + $fax_name = str_replace("(", "_", $fax_name); + $fax_name = str_replace(")", "_", $fax_name); + $fax_name = str_replace("+", "_", $fax_name); + $fax_name = str_replace("=", "_", $fax_name); + + if (!$included) { + //move uploaded file + move_uploaded_file($_files['tmp_name'][$index], $dir_fax_temp.'/'.$fax_name.'.'.$fax_file_extension); + } + + //convert uploaded file to pdf, if necessary + if ($fax_file_extension != "pdf" && $fax_file_extension != "tif") { + chdir($dir_fax_temp); + exec("libreoffice --headless --convert-to pdf --outdir ".$dir_fax_temp." ".$dir_fax_temp.'/'.$fax_name.'.'.$fax_file_extension); + @unlink($dir_fax_temp.'/'.$fax_name.'.'.$fax_file_extension); + } + + //convert uploaded pdf to tif + if (file_exists($dir_fax_temp.'/'.$fax_name.'.pdf')) { + chdir($dir_fax_temp); + + //convert pdf to tif + $cmd = gs_cmd("-q -sDEVICE=tiffg3 -r".$gs_r." -g".$gs_g." -dNOPAUSE -sOutputFile=".correct_path($fax_name).".tif -- ".correct_path($fax_name).".pdf -c quit"); + // echo($cmd . "
\n"); + exec($cmd); + @unlink($dir_fax_temp.'/'.$fax_name.'.pdf'); + } + + $cmd = "tiffinfo ".correct_path($dir_fax_temp.'/'.$fax_name).".tif | grep \"Page Number\" | grep -c \"P\""; + // echo($cmd . "
\n"); + $tif_page_count = exec($cmd); + if ($tif_page_count != '') { + $fax_page_count += $tif_page_count; + } + + //add file to array + $tif_files[] = $dir_fax_temp.'/'.$fax_name.'.tif'; + } //if + } //foreach + + // unique id for this fax + $fax_instance_uuid = uuid(); + + //generate cover page, merge with pdf + if ($fax_subject != '' || $fax_message != '') { + + //load pdf libraries + require_once("resources/tcpdf/tcpdf.php"); + require_once("resources/fpdi/fpdi.php"); + + // initialize pdf + $pdf = new FPDI('P', 'in'); + $pdf -> SetAutoPageBreak(false); + $pdf -> setPrintHeader(false); + $pdf -> setPrintFooter(false); + $pdf -> SetMargins(0, 0, 0, true); + + if(strlen($fax_cover_font) > 0){ + if(substr($fax_cover_font, -4) == '.ttf'){ + $pdf_font = TCPDF_FONTS::addTTFfont($fax_cover_font); + } + else{ + $pdf_font = $fax_cover_font; + } + } + + if(!$pdf_font){ + $pdf_font = 'times'; + } + + //add blank page + $pdf -> AddPage('P', array($page_width, $page_height)); + + // content offset, if necessary + $x = 0; + $y = 0; + + //logo + $display_logo = false; + if (!isset($_SESSION['fax']['cover_logo']['text'])) { + $logo = PROJECT_PATH."/app/fax/resources/images/logo.jpg"; + $display_logo = true; + } + else if (isset($_SESSION['fax']['cover_logo']['text']) && $_SESSION['fax']['cover_logo']['text'] != '') { + $logo = $_SESSION['fax']['cover_logo']['text']; + if (substr($logo, 0, 4) == 'http') { + $remote_filename = strtolower(pathinfo($logo, PATHINFO_BASENAME)); + $remote_fileext = pathinfo($remote_filename, PATHINFO_EXTENSION); + if ($remote_fileext == 'gif' || $remote_fileext == 'jpg' || $remote_fileext == 'jpeg' || $remote_fileext == 'png' || $remote_fileext == 'bmp') { + if (!file_exists($dir_fax_temp.'/'.$remote_filename)) { + $raw = file_get_contents($logo); + if (file_put_contents($dir_fax_temp.'/'.$remote_filename, $raw)) { + $logo = $dir_fax_temp.'/'.$remote_filename; + } + else { + unset($logo); + } + } + else { + $logo = $dir_fax_temp.'/'.$remote_filename; + } + } + else { + unset($logo); + } + } + $display_logo = true; + } + + if ($display_logo) { + $pdf -> Image($logo, 0.5, 0.4, 2.5, 0.9, null, null, 'N', true, 300, null, false, false, 0, true); + } + else { + //set position for header text, if enabled + $pdf -> SetXY($x + 0.5, $y + 0.4); + } + + //header + if ($fax_header != '') { + $pdf -> SetLeftMargin(0.5); + $pdf -> SetFont($pdf_font, "", 10); + $pdf -> Write(0.3, $fax_header); + } + + //fax, cover sheet + $pdf -> SetTextColor(0,0,0); + $pdf -> SetFont($pdf_font, "B", 55); + $pdf -> SetXY($x + 4.55, $y + 0.25); + $pdf -> Cell($x + 3.50, $y + 0.4, $text['label-fax-fax'], 0, 0, 'R', false, null, 0, false, 'T', 'T'); + $pdf -> SetFont($pdf_font, "", 12); + $pdf -> SetFontSpacing(0.0425); + $pdf -> SetXY($x + 4.55, $y + 1.0); + $pdf -> Cell($x + 3.50, $y + 0.4, $text['label-fax-cover-sheet'], 0, 0, 'R', false, null, 0, false, 'T', 'T'); + $pdf -> SetFontSpacing(0); + + //field labels + $pdf -> SetFont($pdf_font, "B", 12); + if ($fax_recipient != '' || sizeof($fax_numbers) > 0) { + $pdf -> Text($x + 0.5, $y + 2.0, strtoupper($text['label-fax-recipient']).":"); + } + if ($fax_sender != '' || $fax_caller_id_number != '') { + $pdf -> Text($x + 0.5, $y + 2.3, strtoupper($text['label-fax-sender']).":"); + } + if ($fax_page_count > 0) { + $pdf -> Text($x + 0.5, $y + 2.6, strtoupper($text['label-fax-attached']).":"); + } + if ($fax_subject != '') { + $pdf -> Text($x + 0.5, $y + 2.9, strtoupper($text['label-fax-subject']).":"); + } + + //field values + $pdf -> SetFont($pdf_font, "", 12); + $pdf -> SetXY($x + 2.0, $y + 1.95); + if ($fax_recipient != '') { + $pdf -> Write(0.3, $fax_recipient); + } + if (sizeof($fax_numbers) > 0) { + $fax_number_string = ($fax_recipient != '') ? ' (' : null; + $fax_number_string .= format_phone($fax_numbers[0]); + if (sizeof($fax_numbers) > 1) { + for ($n = 1; $n <= sizeof($fax_numbers); $n++) { + if ($n == 4) { break; } + $fax_number_string .= ', '.format_phone($fax_numbers[$n]); + } + } + $fax_number_string .= (sizeof($fax_numbers) > 4) ? ', +'.(sizeof($fax_numbers) - 4) : null; + $fax_number_string .= ($fax_recipient != '') ? ')' : null; + $pdf -> Write(0.3, $fax_number_string); + } + $pdf -> SetXY($x + 2.0, $y + 2.25); + if ($fax_sender != '') { + $pdf -> Write(0.3, $fax_sender); + if ($fax_caller_id_number != '') { + $pdf -> Write(0.3, ' ('.format_phone($fax_caller_id_number).')'); + } + } + else { + if ($fax_caller_id_number != '') { + $pdf -> Write(0.3, format_phone($fax_caller_id_number)); + } + } + if ($fax_page_count > 0) { + $pdf -> Text($x + 2.0, $y + 2.6, $fax_page_count.' '.$text['label-fax-page'.(($fax_page_count > 1) ? 's' : null)]); + } + if ($fax_subject != '') { + $pdf -> Text($x + 2.0, $y + 2.9, $fax_subject); + } + + //message + $pdf -> Rect($x + 0.5, $y + 3.4, 7.5, 6.25, 'D'); + if ($fax_message != '') { + $pdf -> SetFont($pdf_font, "", 12); + $pdf -> SetXY($x + 0.75, $y + 3.65); + $pdf -> MultiCell(7, 5.75, $fax_message, 0, 'L', false); + } + + //footer + if ($fax_footer != '') { + $pdf -> SetFont("helvetica", "", 8); + $pdf -> SetXY($x + 0.5, $y + 9.9); + $pdf -> MultiCell(7.5, 0.75, $fax_footer, 0, 'C', false); + } + + // save cover pdf + $pdf -> Output($dir_fax_temp.'/'.$fax_instance_uuid.'_cover.pdf', "F"); // Display [I]nline, Save to [F]ile, [D]ownload + + //convert pdf to tif, add to array of pages, delete pdf + if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.'_cover.pdf')) { + chdir($dir_fax_temp); + $cmd = gs_cmd("-q -sDEVICE=tiffg3 -r".$gs_r." -g".$gs_g." -dNOPAUSE -sOutputFile=".correct_path($fax_instance_uuid)."_cover.tif -- ".correct_path($fax_instance_uuid)."_cover.pdf -c quit"); + // echo($cmd . "
\n"); + exec($cmd); + if (is_array($tif_files) && sizeof($tif_files) > 0) { + array_unshift($tif_files, $dir_fax_temp.'/'.$fax_instance_uuid.'_cover.tif'); + } + else { + $tif_files[] = $dir_fax_temp.'/'.$fax_instance_uuid.'_cover.tif'; + } + @unlink($dir_fax_temp.'/'.$fax_instance_uuid.'_cover.pdf'); + } + } + + //combine tif files into single multi-page tif + if (is_array($tif_files) && sizeof($tif_files) > 0) { + $cmd = "tiffcp -c none "; + foreach ($tif_files as $tif_file) { + $cmd .= correct_path($tif_file) . ' '; + } + $cmd .= correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'.tif'); + //echo($cmd . "
\n"); + exec($cmd); + + foreach ($tif_files as $tif_file) { + @unlink($tif_file); + } + + //generate pdf (a work around, as tiff2pdf was improperly inverting the colors) + $cmd = 'tiff2pdf -u i -p '.$fax_page_size. + ' -w '.$page_width. + ' -l '.$page_height. + ' -f -o '. + correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'.pdf').' '. + correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'.tif'); + // echo($cmd . "
\n"); + exec($cmd); + + chdir($dir_fax_temp); + + //convert pdf to tif + $cmd = gs_cmd('-q -sDEVICE=tiffg3 -r'.$gs_r.' -g'.$gs_g.' -dNOPAUSE -sOutputFile='. + correct_path($fax_instance_uuid.'_temp.tif'). + ' -- '.$fax_instance_uuid.'.pdf -c quit'); + // echo($cmd . "
\n"); + exec($cmd); + + @unlink($dir_fax_temp.'/'.$fax_instance_uuid.".pdf"); + + $cmd = 'tiff2pdf -u i -p '.$fax_page_size. + ' -w '.$page_width. + ' -l '.$page_height. + ' -f -o '. + correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'.pdf').' '. + correct_path($dir_fax_temp.'/'.$fax_instance_uuid.'_temp.tif'); + // echo($cmd . "
\n"); + exec($cmd); + + @unlink($dir_fax_temp.'/'.$fax_instance_uuid."_temp.tif"); + } + else { + if (!$included) { + //nothing to send, redirect the browser + $_SESSION['message_mood'] = 'negative'; + $_SESSION["message"] = $text['message-invalid-fax']; + header("Location: fax_send.php?id=".$fax_uuid); + exit; + } + } + + //preview, if requested + if (($_REQUEST['submit'] != '') && ($_REQUEST['submit'] == $text['button-preview'])) { + unset($file_type); + if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.'.pdf')) { + $file_type = 'pdf'; + $content_type = 'application/pdf'; + @unlink($dir_fax_temp.'/'.$fax_instance_uuid.".tif"); + } + else if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.'.tif')) { + $file_type = 'tif'; + $content_type = 'image/tiff'; + @unlink($dir_fax_temp.'/'.$fax_instance_uuid.".pdf"); + } + if ($file_type != '') { + //push download + $fd = fopen($dir_fax_temp.'/'.$fax_instance_uuid.'.'.$file_type, "rb"); + header("Content-Type: application/force-download"); + header("Content-Type: application/octet-stream"); + header("Content-Type: application/download"); + header("Content-Description: File Transfer"); + header('Content-Disposition: attachment; filename="'.$fax_instance_uuid.'.'.$file_type.'"'); + header("Content-Type: ".$content_type); + header('Accept-Ranges: bytes'); + header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 + header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // date in the past + header("Content-Length: ".filesize($dir_fax_temp.'/'.$fax_instance_uuid.'.'.$file_type)); + fpassthru($fd); + @unlink($dir_fax_temp.'/'.$fax_instance_uuid.".".$file_type); + } + exit; + } + + //get some more info to send the fax + $mailfrom_address = (isset($_SESSION['fax']['smtp_from']['var'])) ? $_SESSION['fax']['smtp_from']['var'] : $_SESSION['email']['smtp_from']['var']; + + $sql = "select * from v_fax where fax_uuid = '".$fax_uuid."'; "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_NAMED); + $mailto_address_fax = $result["fax_email"]; + $fax_prefix = $result["fax_prefix"]; + + if (!$included) { + $sql = "select contact_uuid from v_users where user_uuid = '".$_SESSION['user_uuid']."'; "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_NAMED); + + $sql = "select email_address from v_contact_emails where contact_uuid = '".$result["contact_uuid"]."' order by email_primary desc;"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_NAMED); + $mailto_address_user = $result["email_address"]; + } + else { + //use email-to-fax from address + } + + if ($mailto_address_fax != '' && $mailto_address_user != $mailto_address_fax) { + $mailto_address = $mailto_address_fax.",".$mailto_address_user; + } + else { + $mailto_address = $mailto_address_user; + } + + //send the fax + $fax_file = $dir_fax_temp."/".$fax_instance_uuid.".tif"; + $common_dial_string = "for_fax=1,"; + $common_dial_string .= "accountcode='" . $fax_accountcode . "',"; + $common_dial_string .= "sip_h_X-accountcode='" . $fax_accountcode . "',"; + $common_dial_string .= "domain_uuid=" . $_SESSION["domain_uuid"] . ","; + $common_dial_string .= "domain_name=" . $_SESSION["domain_name"] . ","; + $common_dial_string .= "origination_caller_id_name='" . $fax_caller_id_name . "',"; + $common_dial_string .= "origination_caller_id_number='" . $fax_caller_id_number . "',"; + $common_dial_string .= "fax_ident='" . $fax_caller_id_number . "',"; + $common_dial_string .= "fax_header='" . $fax_caller_id_name . "',"; + $common_dial_string .= "fax_file='" . $fax_file . "',"; + + foreach ($fax_numbers as $fax_number) { + $dial_string = $common_dial_string; + + fax_split_dtmf($fax_number, $fax_dtmf); + + //prepare the fax command + $route_array = outbound_route_to_bridge($_SESSION['domain_uuid'], $fax_prefix . $fax_number); + + if (count($route_array) == 0) { + //send the internal call to the registered extension + $fax_uri = "user/".$fax_number."@".$_SESSION['domain_name']; + $t38 = ""; + } + else { + //send the external call + $fax_uri = $route_array[0]; + $t38 = "fax_enable_t38=true,fax_enable_t38_request=true,"; + } + + if ($fax_send_mode != 'queue') { + $dial_string .= $t38; + $dial_string .= "mailto_address='" . $mailto_address . "',"; + $dial_string .= "mailfrom_address='" . $mailfrom_address . "',"; + $dial_string .= "fax_uri=" . $fax_uri . ","; + $dial_string .= "fax_retry_attempts=1" . ","; + $dial_string .= "fax_retry_limit=20" . ","; + $dial_string .= "fax_retry_sleep=180" . ","; + $dial_string .= "fax_verbose=true" . ","; + $dial_string .= "fax_use_ecm=off" . ","; + $dial_string .= "api_hangup_hook='lua fax_retry.lua'"; + $dial_string = "{" . $dial_string . "}" . $fax_uri." &txfax('".$fax_file."')"; + + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if ($fp) { + $cmd = "api originate " . $dial_string; + // echo($cmd . "
\n"); + //send the command to event socket + $response = event_socket_request($fp, $cmd); + $response = str_replace("\n", "", $response); + $uuid = str_replace("+OK ", "", $response); + } + fclose($fp); + } + else{ // enqueue + $wav_file = ''; //! @todo add custom message + $response = fax_enqueue($fax_uuid, $fax_file, $wav_file, $mailto_address, $fax_uri, $fax_dtmf, $dial_string); + } + } + + //wait for a few seconds + sleep(5); + + //move the generated tif (and pdf) files to the sent directory + if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.".tif")) { + copy($dir_fax_temp.'/'.$fax_instance_uuid.".tif", $dir_fax_sent.'/'.$fax_instance_uuid.".tif"); + } + + if (file_exists($dir_fax_temp.'/'.$fax_instance_uuid.".pdf")) { + copy($dir_fax_temp.'/'.$fax_instance_uuid.".pdf ", $dir_fax_sent.'/'.$fax_instance_uuid.".pdf"); + } + + if (!$included) { + //redirect the browser + $_SESSION["message"] = $response; + if (permission_exists('fax_active_view')) { + header("Location: fax_active.php?id=".$fax_uuid); + } + else { + header("Location: fax_files.php?id=".$fax_uuid."&box=sent"); + } + exit; + } + + } //end upload and send fax + + +if (!$included) { + + //show the header + require_once "resources/header.php"; + + //javascript to toggle input/select boxes, add fax numbers + echo "\n"; + echo ""; + + //fax extension form + echo "
\n"; + echo "\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + echo "
\n"; + echo " ".$text['header-send']."\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo "
\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo " \n"; + echo " \n"; + echo " "; + echo "
\n"; + echo " ".$text['description-2']." ".((if_group('superadmin')) ? $text['description-3'] : null)." \n"; + echo "

\n"; + echo "
\n"; + echo " ".$text['label-fax-header']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax-header']."\n"; + echo "
\n"; + echo " ".$text['label-fax-sender']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax-sender']."\n"; + echo "
\n"; + echo " ".$text['label-fax-recipient']."\n"; + echo "\n"; + //retrieve current user's assigned groups (uuids) + foreach ($_SESSION['groups'] as $group_data) { + $user_group_uuids[] = $group_data['group_uuid']; + } + //add user's uuid to group uuid list to include private (non-shared) contacts + $user_group_uuids[] = $_SESSION["user_uuid"]; + $sql = "select "; + $sql .= "c.contact_organization, "; + $sql .= "c.contact_name_given, "; + $sql .= "c.contact_name_family, "; + $sql .= "c.contact_nickname, "; + $sql .= "cp.phone_number "; + $sql .= "from "; + $sql .= "v_contacts as c, "; + $sql .= "v_contact_phones as cp "; + $sql .= "where "; + $sql .= "c.contact_uuid = cp.contact_uuid and "; + $sql .= "c.domain_uuid = '".$_SESSION['domain_uuid']."' and "; + $sql .= "cp.domain_uuid = '".$_SESSION['domain_uuid']."' and "; + $sql .= "cp.phone_type_fax = 1 and "; + $sql .= "cp.phone_number is not null and "; + $sql .= "cp.phone_number <> '' "; + if (sizeof($user_group_uuids) > 0) { + //only show contacts assigned to current user's group(s) and those not assigned to any group + $sql .= "and ( \n"; + $sql .= " c.contact_uuid in ( \n"; + $sql .= " select contact_uuid from v_contact_groups "; + $sql .= " where group_uuid in ('".implode("','", $user_group_uuids)."') "; + $sql .= " and domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= " ) \n"; + $sql .= " or \n"; + $sql .= " c.contact_uuid not in ( \n"; + $sql .= " select contact_uuid from v_contact_groups "; + $sql .= " where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= " ) \n"; + $sql .= ") \n"; + } + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement -> execute(); + $result = $prep_statement -> fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + if ($result_count > 0) { + foreach ($result as &$row) { + if ($row['contact_organization'] != '') { + $contact_option_label = $row['contact_organization']; + } + if ($row['contact_name_given'] != '' || $row['contact_name_family'] != '' || $row['contact_nickname'] != '') { + $contact_option_label .= ($row['contact_organization'] != '') ? "," : null; + $contact_option_label .= ($row['contact_name_given'] != '') ? (($row['contact_organization'] != '') ? " " : null).$row['contact_name_given'] : null; + $contact_option_label .= ($row['contact_name_family'] != '') ? (($row['contact_organization'] != '' || $row['contact_name_given'] != '') ? " " : null).$row['contact_name_family'] : null; + $contact_option_label .= ($row['contact_nickname'] != '') ? (($row['contact_organization'] != '' || $row['contact_name_given'] != '' || $row['contact_name_family'] != '') ? " (".$row['contact_nickname'].")" : $row['contact_nickname']) : null; + } + $contact_option_value_recipient = $contact_option_label; + $contact_option_value_faxnumber = $row['phone_number']; + $contact_option_label .= ":  ".format_phone($row['phone_number']); + $contact_labels[] = $contact_option_label; + $contact_values[] = $contact_option_value_faxnumber."|".$contact_option_value_recipient; + unset($contact_option_label); + } + asort($contact_labels, SORT_NATURAL); // sort by name(s) + echo " \n"; + } + unset ($prep_statement); + echo " \n"; + if ($result_count > 0) { + echo " \n"; + } + echo "
\n"; + echo " ".$text['description-fax-recipient']."\n"; + echo "
\n"; + echo " ".$text['label-fax-number']."\n"; + echo "\n"; + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + echo "
"; + echo " \n"; + echo " "; + echo " $v_link_label_add"; + echo "
"; + echo " ".$text['description-fax-number']."\n"; + echo "
\n"; + echo " ".$text['label-fax_files']."\n"; + echo "\n"; + for ($f = 1; $f <= 3; $f++) { + echo " 1) ? "style='display: none;'" : null).">"; + echo "
"; + echo " "; + echo "
\n"; + } + echo " ".$text['description-fax_files']."\n"; + echo "
\n"; + echo " ".$text['label-fax-resolution']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax-resolution']."\n"; + echo "
\n"; + echo " ".$text['label-fax-page-size']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax-page-size']."\n"; + echo "
\n"; + echo " ".$text['label-fax-subject']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax-subject']."\n"; + echo "
\n"; + echo " ".$text['label-fax-message']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax-message']."\n"; + echo "
\n"; + echo " ".$text['label-fax-footer']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " ".$text['description-fax-footer']."\n"; + echo "
\n"; + echo "
\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
"; + echo "
\n"; + echo "
\n"; + + //show the footer + require_once "resources/footer.php"; + +} + +// used for initial element alignment during pdf generation +/* +function showgrid($pdf) { + // generate a grid for placement + for ($x=0; $x<=8.5; $x+=0.1) { + for ($y=0; $y<=11; $y+=0.1) { + $pdf -> SetTextColor(0,0,0); + $pdf -> SetFont("courier", "", 3); + $pdf -> Text($x-0.01,$y-0.01,"."); + } + } + for ($x=0; $x<=9; $x+=1) { + for ($y=0; $y<=11; $y+=1) { + $pdf -> SetTextColor(255,0,0); + $pdf -> SetFont("times", "", 10); + $pdf -> Text($x-.02,$y-.01,"."); + $pdf -> SetFont("courier", "", 4); + $pdf -> Text($x+0.01,$y+0.035,$x.",".$y); + } + } +} +*/ +?> diff --git a/app/fax/resources/classes/fax.php b/app/fax/resources/classes/fax.php index d20d842dca..8792767cbd 100644 --- a/app/fax/resources/classes/fax.php +++ b/app/fax/resources/classes/fax.php @@ -1,248 +1,248 @@ - - Copyright (C) 2015 - All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -/** - * cache class provides an abstracted cache - * - * @method string dialplan - builds the dialplan for the fax servers - */ -//define the fax class - if (!class_exists('fax')) { - class fax { - /** - * define the variables - */ - public $domain_uuid; - public $fax_uuid; - public $dialplan_uuid; - public $fax_name; - public $fax_description; - public $fax_extension; - public $fax_forward_number; - public $destination_number; - private $forward_prefix; - - /** - * Called when the object is created - */ - public function __construct() { - //place holder - } - - /** - * Called when there are no references to a particular object - * unset the variables used in the class - */ - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - /** - * Add a dialplan for call center - * @var string $domain_uuid the multi-tenant id - * @var string $value string to be cached - */ - public function dialplan() { - - //normalize the fax forward number - if (strlen($this->fax_forward_number) > 3) { - //$fax_forward_number = preg_replace("~[^0-9]~", "",$fax_forward_number); - $this->fax_forward_number = str_replace(" ", "", $this->fax_forward_number); - $this->fax_forward_number = str_replace("-", "", $this->fax_forward_number); - } - - //set the forward prefix - if (strripos($this->fax_forward_number, '$1') === false) { - $this->forward_prefix = ''; //not found - } else { - $this->forward_prefix = $this->forward_prefix.$this->fax_forward_number.'#'; //found - } - - //delete previous dialplan - if (strlen($this->dialplan_uuid) > 0) { - //delete the previous dialplan - $sql = "delete from v_dialplans "; - $sql .= "where dialplan_uuid = '".$this->dialplan_uuid."' "; - $sql .= "and domain_uuid = '".$this->domain_uuid."' "; - $this->db->exec($sql); - - $sql = "delete from v_dialplan_details "; - $sql .= "where dialplan_uuid = '".$this->dialplan_uuid."' "; - $sql .= "and domain_uuid = '".$this->domain_uuid."' "; - $this->db->exec($sql); - unset($sql); - } - unset($prep_statement); - - //build the dialplan array - $dialplan["app_uuid"] = "24108154-4ac3-1db6-1551-4731703a4440"; - $dialplan["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_name"] = ($this->fax_name != '') ? $this->fax_name : format_phone($this->destination_number); - $dialplan["dialplan_number"] = $this->fax_extension; - $dialplan["dialplan_context"] = $_SESSION['context']; - $dialplan["dialplan_continue"] = "false"; - $dialplan["dialplan_order"] = "310"; - $dialplan["dialplan_enabled"] = "true"; - $dialplan["dialplan_description"] = $this->fax_description; - $dialplan_detail_order = 10; - - //add the public condition - $y = 1; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "condition"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "destination_number"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "^".$this->destination_number."\$"; - $dialplan["dialplan_details"][$y]["dialplan_detail_break"] = ""; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "answer"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = ""; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "fax_uuid=".$this->fax_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "api_hangup_hook=lua app/fax/resources/scripts/hangup_rx.lua"; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - foreach($_SESSION['fax']['variable'] as $data) { - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; - if (substr($data,0,8) == "inbound:") { - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = substr($data,8,strlen($data)); - } - elseif (substr($data,0,9) == "outbound:") {} - else { - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = $data; - } - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - } - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; - if (strlen($_SESSION['fax']['last_fax']['text']) > 0) { - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "last_fax=".$_SESSION['fax']['last_fax']['text']; - } - else { - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "last_fax=\${caller_id_number}-\${strftime(%Y-%m-%d-%H-%M-%S)}"; - } - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "playback"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "silence_stream://2000"; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "rxfax"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name'].'/'.$this->fax_extension.'/inbox/'.$this->forward_prefix.'${last_fax}.tif'; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; - $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; - $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "hangup"; - $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = ""; - $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; - $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; - $y++; - - //add the dialplan permission - $p = new permissions; - $p->add("dialplan_add", 'temp'); - $p->add("dialplan_detail_add", 'temp'); - $p->add("dialplan_edit", 'temp'); - $p->add("dialplan_detail_edit", 'temp'); - - //save the dialplan - $orm = new orm; - $orm->name('dialplans'); - $orm->save($dialplan); - $dialplan_response = $orm->message; - $this->dialplan_uuid = $dialplan_response['uuid']; - - //if new dialplan uuid then update the call center queue - $sql = "update v_fax "; - $sql .= "set dialplan_uuid = '".$this->dialplan_uuid."' "; - $sql .= "where fax_uuid = '".$this->fax_uuid."' "; - $sql .= "and domain_uuid = '".$this->domain_uuid."' "; - $this->db->exec($sql); - unset($sql); - - //remove the temporary permission - $p->delete("dialplan_add", 'temp'); - $p->delete("dialplan_detail_add", 'temp'); - $p->delete("dialplan_edit", 'temp'); - $p->delete("dialplan_detail_edit", 'temp'); - - //synchronize the xml config - save_dialplan_xml(); - - //clear the cache - $cache = new cache; - $cache->delete("dialplan:".$_SESSION['context']); - - //return the dialplan_uuid - return $dialplan_response; - - } - } - } - -/* -$o = new fax; -$c->domain_uuid = ""; -$c->dialplan_uuid = ""; -$c->fax_name = ""; -$c->fax_extension = $fax_extension; -$c->fax_forward_number = $fax_forward_number; -$c->destination_number = $fax_destination_number; -$c->fax_description = $fax_description; -$c->dialplan(); -*/ - + + Copyright (C) 2015 + All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +/** + * cache class provides an abstracted cache + * + * @method string dialplan - builds the dialplan for the fax servers + */ +//define the fax class + if (!class_exists('fax')) { + class fax { + /** + * define the variables + */ + public $domain_uuid; + public $fax_uuid; + public $dialplan_uuid; + public $fax_name; + public $fax_description; + public $fax_extension; + public $fax_forward_number; + public $destination_number; + private $forward_prefix; + + /** + * Called when the object is created + */ + public function __construct() { + //place holder + } + + /** + * Called when there are no references to a particular object + * unset the variables used in the class + */ + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + /** + * Add a dialplan for call center + * @var string $domain_uuid the multi-tenant id + * @var string $value string to be cached + */ + public function dialplan() { + + //normalize the fax forward number + if (strlen($this->fax_forward_number) > 3) { + //$fax_forward_number = preg_replace("~[^0-9]~", "",$fax_forward_number); + $this->fax_forward_number = str_replace(" ", "", $this->fax_forward_number); + $this->fax_forward_number = str_replace("-", "", $this->fax_forward_number); + } + + //set the forward prefix + if (strripos($this->fax_forward_number, '$1') === false) { + $this->forward_prefix = ''; //not found + } else { + $this->forward_prefix = $this->forward_prefix.$this->fax_forward_number.'#'; //found + } + + //delete previous dialplan + if (strlen($this->dialplan_uuid) > 0) { + //delete the previous dialplan + $sql = "delete from v_dialplans "; + $sql .= "where dialplan_uuid = '".$this->dialplan_uuid."' "; + $sql .= "and domain_uuid = '".$this->domain_uuid."' "; + $this->db->exec($sql); + + $sql = "delete from v_dialplan_details "; + $sql .= "where dialplan_uuid = '".$this->dialplan_uuid."' "; + $sql .= "and domain_uuid = '".$this->domain_uuid."' "; + $this->db->exec($sql); + unset($sql); + } + unset($prep_statement); + + //build the dialplan array + $dialplan["app_uuid"] = "24108154-4ac3-1db6-1551-4731703a4440"; + $dialplan["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_name"] = ($this->fax_name != '') ? $this->fax_name : format_phone($this->destination_number); + $dialplan["dialplan_number"] = $this->fax_extension; + $dialplan["dialplan_context"] = $_SESSION['context']; + $dialplan["dialplan_continue"] = "false"; + $dialplan["dialplan_order"] = "310"; + $dialplan["dialplan_enabled"] = "true"; + $dialplan["dialplan_description"] = $this->fax_description; + $dialplan_detail_order = 10; + + //add the public condition + $y = 1; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "condition"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "destination_number"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "^".$this->destination_number."\$"; + $dialplan["dialplan_details"][$y]["dialplan_detail_break"] = ""; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "answer"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = ""; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "fax_uuid=".$this->fax_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "api_hangup_hook=lua app/fax/resources/scripts/hangup_rx.lua"; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + foreach($_SESSION['fax']['variable'] as $data) { + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; + if (substr($data,0,8) == "inbound:") { + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = substr($data,8,strlen($data)); + } + elseif (substr($data,0,9) == "outbound:") {} + else { + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = $data; + } + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + } + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "set"; + if (strlen($_SESSION['fax']['last_fax']['text']) > 0) { + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "last_fax=".$_SESSION['fax']['last_fax']['text']; + } + else { + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "last_fax=\${caller_id_number}-\${strftime(%Y-%m-%d-%H-%M-%S)}"; + } + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "playback"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = "silence_stream://2000"; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "rxfax"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = $_SESSION['switch']['storage']['dir'].'/fax/'.$_SESSION['domain_name'].'/'.$this->fax_extension.'/inbox/'.$this->forward_prefix.'${last_fax}.tif'; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + $dialplan["dialplan_details"][$y]["domain_uuid"] = $this->domain_uuid; + $dialplan["dialplan_details"][$y]["dialplan_detail_tag"] = "action"; + $dialplan["dialplan_details"][$y]["dialplan_detail_type"] = "hangup"; + $dialplan["dialplan_details"][$y]["dialplan_detail_data"] = ""; + $dialplan["dialplan_details"][$y]["dialplan_detail_group"] = "1"; + $dialplan["dialplan_details"][$y]["dialplan_detail_order"] = $y * 10; + $y++; + + //add the dialplan permission + $p = new permissions; + $p->add("dialplan_add", 'temp'); + $p->add("dialplan_detail_add", 'temp'); + $p->add("dialplan_edit", 'temp'); + $p->add("dialplan_detail_edit", 'temp'); + + //save the dialplan + $orm = new orm; + $orm->name('dialplans'); + $orm->save($dialplan); + $dialplan_response = $orm->message; + $this->dialplan_uuid = $dialplan_response['uuid']; + + //if new dialplan uuid then update the call center queue + $sql = "update v_fax "; + $sql .= "set dialplan_uuid = '".$this->dialplan_uuid."' "; + $sql .= "where fax_uuid = '".$this->fax_uuid."' "; + $sql .= "and domain_uuid = '".$this->domain_uuid."' "; + $this->db->exec($sql); + unset($sql); + + //remove the temporary permission + $p->delete("dialplan_add", 'temp'); + $p->delete("dialplan_detail_add", 'temp'); + $p->delete("dialplan_edit", 'temp'); + $p->delete("dialplan_detail_edit", 'temp'); + + //synchronize the xml config + save_dialplan_xml(); + + //clear the cache + $cache = new cache; + $cache->delete("dialplan:".$_SESSION['context']); + + //return the dialplan_uuid + return $dialplan_response; + + } + } + } + +/* +$o = new fax; +$c->domain_uuid = ""; +$c->dialplan_uuid = ""; +$c->fax_name = ""; +$c->fax_extension = $fax_extension; +$c->fax_forward_number = $fax_forward_number; +$c->destination_number = $fax_destination_number; +$c->fax_description = $fax_description; +$c->dialplan(); +*/ + ?> \ No newline at end of file diff --git a/app/fax/resources/functions/object_to_array.php b/app/fax/resources/functions/object_to_array.php index 45e8c2a1b7..fe84302e15 100644 --- a/app/fax/resources/functions/object_to_array.php +++ b/app/fax/resources/functions/object_to_array.php @@ -1,9 +1,9 @@ - \ No newline at end of file diff --git a/app/fax/resources/functions/parse_message.php b/app/fax/resources/functions/parse_message.php index e220cbe262..305f9db33e 100644 --- a/app/fax/resources/functions/parse_message.php +++ b/app/fax/resources/functions/parse_message.php @@ -1,145 +1,145 @@ -Array(),'attachments'=>Array()); - $structure = imap_fetchstructure($connection, $message_number, $option); - - if (isset($structure->parts)) { - $flatten = parse_message_flatten($structure->parts); - } - else { - $flatten = Array(1 => $structure); - } - - foreach($flatten as $id => &$part){ - switch($part->type) { - case TYPETEXT: - $message = parse_message_decode_text($connection, $part, $message_number, $id, $option, $to_charset); - $result['messages'][] = $message; - break; - - case TYPEAPPLICATION: case TYPEAUDIO: case TYPEIMAGE: case TYPEVIDEO: case TYPEOTHER: - $attachment = parse_message_decode_attach($connection, $part, $message_number, $id, $option); - if($attachment){ - $result['attachments'][] = $attachment; - } - break; - - case TYPEMULTIPART: case TYPEMESSAGE: - break; - } - } - - return $result; -} - -function parse_message_decode_text($connection, &$part, $message_number, $id, $option, $to_charset){ - $msg = parse_message_fetch_body($connection, $part, $message_number, $id, $option); - - if($msg && $to_charset){ - $charset = ''; - if(isset($part->parameters) && count($part->parameters)) { - foreach($part->parameters as &$parameter){ - if($parameter->attribute == 'CHARSET') { - $charset = $parameter->value; - break; - } - } - } - if($charset){ - $msg = mb_convert_encoding($msg, $to_charset, $charset); - } - $msg = trim($msg); - } - - return Array( - 'data' => $msg, - 'type' => parse_message_get_type($part), - 'size' => strlen($msg), - ); -} - -function parse_message_decode_attach($connection, &$part, $message_number, $id, $option){ - $filename = false; - - if($part->ifdparameters) { - foreach($part->dparameters as $object) { - if(strtolower($object->attribute) == 'filename') { - $filename = $object->value; - break; - } - } - } - - if($part->ifparameters) { - foreach($part->parameters as $object) { - if(strtolower($object->attribute) == 'name') { - $filename = $object->value; - break; - } - } - } - - if(!$filename) { - return false; - } - - $body = parse_message_fetch_body($connection, $part, $message_number, $id, $option); - - return Array( - 'data' => $body, - 'type' => parse_message_get_type($part), - 'name' => $filename, - 'size' => strlen($body), - 'disposition' => $part->disposition, - ); -} - -function parse_message_fetch_body($connection, &$part, $message_number, $id, $option){ - $body = imap_fetchbody($connection, $message_number, $id, $option); - if($part->encoding == ENCBASE64){ - $body = base64_decode($body); - } - else if($part->encoding == ENCQUOTEDPRINTABLE){ - $body = quoted_printable_decode($body); - } - return $body; -} - -function parse_message_get_type(&$part){ - $types = Array( - TYPEMESSAGE => 'message', - TYPEMULTIPART => 'multipart', - TYPEAPPLICATION => 'application', - TYPEAUDIO => 'audio', - TYPEIMAGE => 'image', - TYPETEXT => 'text', - TYPEVIDEO => 'video', - TYPEMODEL => 'model', - TYPEOTHER => 'other', - ); - - return $types[$part->type] . '/' . strtolower($part->subtype); -} - -function parse_message_flatten(&$structure, &$result = array(), $prefix = '', $index = 1, $fullPrefix = true) { - foreach($structure as &$part) { - if(isset($part->parts)) { - if($part->type == TYPEMESSAGE) { - parse_message_flatten($part->parts, $result, $prefix.$index.'.', 0, false); - } - elseif($fullPrefix) { - parse_message_flatten($part->parts, $result, $prefix.$index.'.'); - } - else { - parse_message_flatten($part->parts, $result, $prefix); - } - } - else { - $result[$prefix.$index] = $part; - } - $index++; - } - return $result; -} - +Array(),'attachments'=>Array()); + $structure = imap_fetchstructure($connection, $message_number, $option); + + if (isset($structure->parts)) { + $flatten = parse_message_flatten($structure->parts); + } + else { + $flatten = Array(1 => $structure); + } + + foreach($flatten as $id => &$part){ + switch($part->type) { + case TYPETEXT: + $message = parse_message_decode_text($connection, $part, $message_number, $id, $option, $to_charset); + $result['messages'][] = $message; + break; + + case TYPEAPPLICATION: case TYPEAUDIO: case TYPEIMAGE: case TYPEVIDEO: case TYPEOTHER: + $attachment = parse_message_decode_attach($connection, $part, $message_number, $id, $option); + if($attachment){ + $result['attachments'][] = $attachment; + } + break; + + case TYPEMULTIPART: case TYPEMESSAGE: + break; + } + } + + return $result; +} + +function parse_message_decode_text($connection, &$part, $message_number, $id, $option, $to_charset){ + $msg = parse_message_fetch_body($connection, $part, $message_number, $id, $option); + + if($msg && $to_charset){ + $charset = ''; + if(isset($part->parameters) && count($part->parameters)) { + foreach($part->parameters as &$parameter){ + if($parameter->attribute == 'CHARSET') { + $charset = $parameter->value; + break; + } + } + } + if($charset){ + $msg = mb_convert_encoding($msg, $to_charset, $charset); + } + $msg = trim($msg); + } + + return Array( + 'data' => $msg, + 'type' => parse_message_get_type($part), + 'size' => strlen($msg), + ); +} + +function parse_message_decode_attach($connection, &$part, $message_number, $id, $option){ + $filename = false; + + if($part->ifdparameters) { + foreach($part->dparameters as $object) { + if(strtolower($object->attribute) == 'filename') { + $filename = $object->value; + break; + } + } + } + + if($part->ifparameters) { + foreach($part->parameters as $object) { + if(strtolower($object->attribute) == 'name') { + $filename = $object->value; + break; + } + } + } + + if(!$filename) { + return false; + } + + $body = parse_message_fetch_body($connection, $part, $message_number, $id, $option); + + return Array( + 'data' => $body, + 'type' => parse_message_get_type($part), + 'name' => $filename, + 'size' => strlen($body), + 'disposition' => $part->disposition, + ); +} + +function parse_message_fetch_body($connection, &$part, $message_number, $id, $option){ + $body = imap_fetchbody($connection, $message_number, $id, $option); + if($part->encoding == ENCBASE64){ + $body = base64_decode($body); + } + else if($part->encoding == ENCQUOTEDPRINTABLE){ + $body = quoted_printable_decode($body); + } + return $body; +} + +function parse_message_get_type(&$part){ + $types = Array( + TYPEMESSAGE => 'message', + TYPEMULTIPART => 'multipart', + TYPEAPPLICATION => 'application', + TYPEAUDIO => 'audio', + TYPEIMAGE => 'image', + TYPETEXT => 'text', + TYPEVIDEO => 'video', + TYPEMODEL => 'model', + TYPEOTHER => 'other', + ); + + return $types[$part->type] . '/' . strtolower($part->subtype); +} + +function parse_message_flatten(&$structure, &$result = array(), $prefix = '', $index = 1, $fullPrefix = true) { + foreach($structure as &$part) { + if(isset($part->parts)) { + if($part->type == TYPEMESSAGE) { + parse_message_flatten($part->parts, $result, $prefix.$index.'.', 0, false); + } + elseif($fullPrefix) { + parse_message_flatten($part->parts, $result, $prefix.$index.'.'); + } + else { + parse_message_flatten($part->parts, $result, $prefix); + } + } + else { + $result[$prefix.$index] = $part; + } + $index++; + } + return $result; +} + diff --git a/app/follow_me/app_menu.php b/app/follow_me/app_menu.php index 6054e217f0..d918f325b4 100644 --- a/app/follow_me/app_menu.php +++ b/app/follow_me/app_menu.php @@ -1,21 +1,21 @@ - + diff --git a/app/gateways/app_defaults.php b/app/gateways/app_defaults.php index a5eea236ba..4734e960a5 100644 --- a/app/gateways/app_defaults.php +++ b/app/gateways/app_defaults.php @@ -1,44 +1,44 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2010 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -//process this only one time -if ($domains_processed == 1) { - //set the sip_profiles directory for older installs - if (isset($_SESSION['switch']['gateways']['dir'])) { - $orm = new orm; - $orm->name('default_settings'); - $orm->uuid($_SESSION['switch']['gateways']['uuid']); - $array['default_setting_category'] = 'switch'; - $array['default_setting_subcategory'] = 'sip_profiles'; - $array['default_setting_name'] = 'dir'; - //$array['default_setting_value'] = ''; - //$array['default_setting_enabled'] = 'true'; - $orm->save($array); - unset($array); - } -} - + + Portions created by the Initial Developer are Copyright (C) 2008-2010 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +//process this only one time +if ($domains_processed == 1) { + //set the sip_profiles directory for older installs + if (isset($_SESSION['switch']['gateways']['dir'])) { + $orm = new orm; + $orm->name('default_settings'); + $orm->uuid($_SESSION['switch']['gateways']['uuid']); + $array['default_setting_category'] = 'switch'; + $array['default_setting_subcategory'] = 'sip_profiles'; + $array['default_setting_name'] = 'dir'; + //$array['default_setting_value'] = ''; + //$array['default_setting_enabled'] = 'true'; + $orm->save($array); + unset($array); + } +} + ?> \ No newline at end of file diff --git a/app/meetings/app_menu.php b/app/meetings/app_menu.php index 38d2493902..d4dd766814 100644 --- a/app/meetings/app_menu.php +++ b/app/meetings/app_menu.php @@ -1,12 +1,12 @@ - \ No newline at end of file diff --git a/app/operator_panel/index.php b/app/operator_panel/index.php index 31827423b0..b00afd3b13 100644 --- a/app/operator_panel/index.php +++ b/app/operator_panel/index.php @@ -1,443 +1,443 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - Luis Daniel Lucio Quiroz -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; - -if (permission_exists('operator_panel_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//set user status - if (isset($_REQUEST['status']) && $_REQUEST['status'] != '') { - $user_status = check_str($_REQUEST['status']); - //sql update - $sql = "update v_users set "; - $sql .= "user_status = '".$user_status."' "; - $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; - $sql .= "and user_uuid = '".$_SESSION['user']['user_uuid']."' "; - if (permission_exists("user_account_setting_edit")) { - $count = $db->exec(check_sql($sql)); - } - - //if call center app is installed then update the user_status - if (is_dir($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/app/call_center')) { - //update the user_status - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - $switch_cmd .= "callcenter_config agent set status ".$_SESSION['user']['username']."@".$_SESSION['domain_name']." '".$user_status."'"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); - - //update the user state - $cmd = "api callcenter_config agent set state ".$_SESSION['user']['username']."@".$_SESSION['domain_name']." Waiting"; - $response = event_socket_request($fp, $cmd); - } - - exit; - } - -$document['title'] = $text['title-operator_panel']; -require_once "resources/header.php"; -?> - - - - - - - - - - - - - - - -
- -

- - + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Luis Daniel Lucio Quiroz +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; + +if (permission_exists('operator_panel_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//set user status + if (isset($_REQUEST['status']) && $_REQUEST['status'] != '') { + $user_status = check_str($_REQUEST['status']); + //sql update + $sql = "update v_users set "; + $sql .= "user_status = '".$user_status."' "; + $sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' "; + $sql .= "and user_uuid = '".$_SESSION['user']['user_uuid']."' "; + if (permission_exists("user_account_setting_edit")) { + $count = $db->exec(check_sql($sql)); + } + + //if call center app is installed then update the user_status + if (is_dir($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/app/call_center')) { + //update the user_status + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + $switch_cmd .= "callcenter_config agent set status ".$_SESSION['user']['username']."@".$_SESSION['domain_name']." '".$user_status."'"; + $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + + //update the user state + $cmd = "api callcenter_config agent set state ".$_SESSION['user']['username']."@".$_SESSION['domain_name']." Waiting"; + $response = event_socket_request($fp, $cmd); + } + + exit; + } + +$document['title'] = $text['title-operator_panel']; +require_once "resources/header.php"; +?> + + + + + + + + + + + + + + + +
+ +

+ + \ No newline at end of file diff --git a/app/operator_panel/index_inc.php b/app/operator_panel/index_inc.php index 2c58342155..b2af6399ee 100644 --- a/app/operator_panel/index_inc.php +++ b/app/operator_panel/index_inc.php @@ -1,450 +1,450 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -require_once "./resources/functions/get_call_activity.php"; -if (permission_exists('operator_panel_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -$activity = get_call_activity(); - -foreach ($activity as $extension => $fields) { - if (substr_count($fields['call_group'], ',')) { - $tmp = explode(',', $fields['call_group']); - foreach ($tmp as $tmp_index => $tmp_value) { - if (trim($tmp_value) == '') { unset($tmp[$tmp_index]); } - else { $groups[] = $tmp_value; } - } - } - else if ($fields['call_group'] != '') { - $groups[] = $fields['call_group']; - } -} -$groups = array_unique($groups); -sort($groups); - -$onhover_pause_refresh = " onmouseover='refresh_stop();' onmouseout='refresh_start();'"; - -echo ""; -echo " "; -echo " "; -echo " "; -echo " "; -echo " "; -echo "
"; -echo " ".$text['title-operator_panel'].""; -echo " "; - -if (sizeof($_SESSION['user']['extensions']) > 0) { - $status_options[1]['status'] = "Available"; - $status_options[1]['label'] = $text['label-status_available']; - $status_options[1]['style'] = "op_btn_status_available"; - if (permission_exists('operator_panel_on_demand')) { - $status_options[2]['status'] = "Available (On Demand)"; - $status_options[2]['label'] = $text['label-status_on_demand']; - $status_options[2]['style'] = "op_btn_status_available_on_demand"; - } - $status_options[3]['status'] = "On Break"; - $status_options[3]['label'] = $text['label-status_on_break']; - $status_options[3]['style'] = "op_btn_status_on_break"; - $status_options[4]['status'] = "Do Not Disturb"; - $status_options[4]['label'] = $text['label-status_do_not_disturb']; - $status_options[4]['style'] = "op_btn_status_do_not_disturb"; - $status_options[5]['status'] = "Logged Out"; - $status_options[5]['label'] = $text['label-status_logged_out']; - $status_options[5]['style'] = "op_btn_status_logged_out"; - - foreach ($status_options as $status_option) { - echo " \n"; - } -} - -echo " "; -echo " "; -echo " "; -echo " "; - -if (permission_exists('operator_panel_eavesdrop')) { - echo " "; -} - -if (sizeof($groups) > 0) { - echo " "; -} - -echo " "; -echo "
"; -echo " \"".$text['label-refresh_pause']."\""; -echo " "; - if (sizeof($_SESSION['user']['extensions']) > 1) { - echo " "; - echo " "; - echo " \n"; - } - else if (sizeof($_SESSION['user']['extensions']) == 1) { - echo " "; - } - echo " "; - echo " "; - if (sizeof($groups) > 5) { - //show select box - echo " \n"; - } - else { - //show buttons - echo " "; - foreach ($groups as $group) { - echo " "; - } - } - echo "
"; - -echo "
"; -echo "
"; - -foreach ($activity as $extension => $ext) { - unset($block); - - //filter by group, if defined - if ($_REQUEST['group'] != '' && substr_count($ext['call_group'], $_REQUEST['group']) == 0 && !in_array($extension, $_SESSION['user']['extensions'])) { continue; } - - //check if feature code being called - $format_number = (substr($ext['dest'], 0, 1) == '*') ? false : true; - - //determine extension state, direction icon, and displayed name/number for caller/callee - if ($ext['state'] == 'CS_EXECUTE') { - if (($ext['callstate'] == 'RINGING' || $ext['callstate'] == 'EARLY' || $ext['callstate'] == 'RING_WAIT') && $ext['direction'] == 'inbound') { - $ext_state = 'ringing'; - } - else if ($ext['callstate'] == 'ACTIVE' && $ext['direction'] == 'outbound') { - $ext_state = 'active'; - } - else if ($ext['callstate'] == 'RING_WAIT' && $ext['direction'] == 'outbound') { - $ext_state = 'ringing'; - } - else if ($ext['callstate'] == 'ACTIVE' && $ext['direction'] == 'inbound') { - $ext_state = 'active'; - } - if (!$format_number) { - $call_name = 'System'; - $call_number = $ext['dest']; - } - else { - $call_name = $activity[$ext['dest']]['effective_caller_id_name']; - $call_number = format_phone($ext['dest']); - } - $dir_icon = 'outbound'; - } - else if ($ext['state'] == 'CS_HIBERNATE') { - if ($ext['callstate'] == 'ACTIVE') { - $ext_state = 'active'; - if ($ext['direction'] == 'inbound') { - $call_name = $activity[$ext['dest']]['effective_caller_id_name']; - $call_number = format_phone($ext['dest']); - $dir_icon = 'outbound'; - } - else if ($ext['direction'] == 'outbound') { - $call_name = $activity[$ext['cid_num']]['effective_caller_id_name']; - $call_number = format_phone($ext['cid_num']); - $dir_icon = 'inbound'; - } - } - } - else if ($ext['state'] == 'CS_CONSUME_MEDIA' || $ext['state'] == 'CS_EXCHANGE_MEDIA') { - if ($ext['state'] == 'CS_CONSUME_MEDIA' && $ext['callstate'] == 'RINGING' && $ext['direction'] == 'outbound') { - $ext_state = 'ringing'; - } - else if ($ext['state'] == 'CS_EXCHANGE_MEDIA' && $ext['callstate'] == 'ACTIVE' && $ext['direction'] == 'outbound') { - $ext_state = 'active'; - } - $dir_icon = 'inbound'; - $call_name = $activity[$ext['cid_num']]['effective_caller_id_name']; - $call_number = format_phone($ext['cid_num']); - } - else { - unset($ext_state, $dir_icon, $call_name, $call_number); - } - - //determine block style by state (if any) - $style = ($ext_state != '') ? "op_state_".$ext_state : null; - - //determine the call identifier passed on drop - if ($ext['uuid'] == $ext['call_uuid'] && $ext['variable_bridge_uuid'] == '') { // transfer an outbound internal call - $call_identifier = $activity[$call_number]['uuid']; - } - else if (($ext['variable_call_direction'] == 'outbound' || $ext['variable_call_direction'] == 'local') && $ext['variable_bridge_uuid'] != '') { // transfer an outbound external call - $call_identifier = $ext['variable_bridge_uuid']; - } - else { - if( $ext['call_uuid'] ) { - $call_identifier = $ext['call_uuid']; // transfer all other call types - } - else { - $call_identifier = $ext['uuid']; // e.g. voice menus - } - } - - //determine extension draggable state - if (permission_exists('operator_panel_manage')) { - if (!in_array($extension, $_SESSION['user']['extensions'])) { - //other extension - if ($ext_state == "ringing") { - if ($_GET['vd_ext_from'] == '' && $dir_icon == 'inbound') { - $draggable = true; // selectable - is ringing and not outbound so can transfer away the call (can set as vd_ext_from) - } - else { - $draggable = false; // unselectable - is ringing so can't send a call to the ext (can't set as vd_ext_to) - } - } - else if ($ext_state == 'active') { - $draggable = false; // unselectable - on a call already so can't transfer or send a call to the ext (can't set as vd_ext_from or vd_ext_to) - } - else { // idle - if ($_GET['vd_ext_from'] == '') { - $draggable = false; // unselectable - is idle, but can't initiate a call from the ext as is not assigned to user (can't set as vd_ext_from) - } - else { - $draggable = true; // selectable - is idle, so can transfer a call in to ext (can set as vd_ext_to). - } - } - } - else { - //user extension - if ($ext['uuid'] != '' && $ext['uuid'] == $ext['call_uuid'] && $ext['variable_bridge_uuid'] == '') { - $draggable = false; - } - else if ($ext_state == 'ringing' && $ext['variable_call_direction'] == 'local') { - $draggable = false; - } - else if ($ext_state != '' && !$format_number) { - $draggable = false; - } - else { - $draggable = true; - } - } - } - else { - $draggable = false; - } - - //determine extension (user) status - $ext_status = (in_array($extension, $_SESSION['user']['extensions'])) ? $ext_user_status[$_SESSION['user_uuid']] : $ext_user_status[$ext['user_uuid']]; - switch ($ext_status) { - case "Available" : - $status_icon = "available"; - $status_hover = $text['label-status_available']; - break; - case "Available (On Demand)" : - $status_icon = "available_on_demand"; - $status_hover = $text['label-status_available_on_demand']; - break; - case "On Break" : - $status_icon = "on_break"; - $status_hover = $text['label-status_on_break']; - break; - case "Do Not Disturb" : - $status_icon = "do_not_disturb"; - $status_hover = $text['label-status_do_not_disturb']; - break; - default : - $status_icon = "logged_out"; - $status_hover = $text['label-status_logged_out_or_unknown']; - } - - $block .= "
"; // DRAG TO - $block .= ""; - $block .= " "; - $block .= " "; - $block .= " "; - $block .= " "; - $block .= "
"; - $block .= " "; // DRAG FROM - $block .= ""; - $block .= ""; - $block .= " "; - if ($dir_icon != '') { - $block .= " \"".$text['label-call_direction']."\""; - } - $block .= "
"; - if ($ext_state != '') { - $block .= " "; - $block .= "
"; - $block .= " ".$ext['call_length']."
"; - $block .= " "; - //record - if (permission_exists('operator_panel_record') && $ext_state == 'active') { - $call_identifier_record = $ext['call_uuid']; - $rec_file = $_SESSION['switch']['recordings']['dir']."/archive/".date("Y")."/".date("M")."/".date("d")."/".$call_identifier_record.".wav"; - if (file_exists($rec_file)) { - $block .= ""; - } - else { - $block .= ""; - } - } - //eavesdrop - if (permission_exists('operator_panel_eavesdrop') && $ext_state == 'active' && sizeof($_SESSION['user']['extensions']) > 0 && !in_array($extension, $_SESSION['user']['extensions'])) { - $block .= ""; - } - //kill - if (permission_exists('operator_panel_kill') || in_array($extension, $_SESSION['user']['extensions'])) { - if ($ext['variable_bridge_uuid'] == '' && $ext_state == 'ringing') { - $call_identifier_kill = $ext['uuid']; - } - else if ($dir_icon == 'outbound') { - $call_identifier_kill = $ext['uuid']; - } - else { - $call_identifier_kill = $call_identifier; - } - $block .= ""; - } - $block .= ""; - //transfer - if (in_array($extension, $_SESSION['user']['extensions']) && $ext_state == 'active') { - $block .= ""; - } - $block .= "
"; - $block .= " ".$call_name."
".$call_number."
"; - $block .= "
"; - //transfer - if (in_array($extension, $_SESSION['user']['extensions']) && $ext_state == 'active') { - $call_identifier_transfer = $ext['variable_bridge_uuid']; - $block .= "
"; - $block .= " "; - $block .= "
\n"; - } - } - else { - //call - if (in_array($extension, $_SESSION['user']['extensions'])) { - $block .= " "; - $block .= "
"; - $block .= " "; - $block .= "
\n"; - } - } - $block .= "
"; - - if (if_group("superadmin") && isset($_GET['debug'])) { - $block .= ""; - $block .= "From ID
    ".$extension."
"; - $block .= "uuid
    ".$ext['uuid']."
"; - $block .= "call_uuid
    ".$ext['call_uuid']."
"; - $block .= "variable_bridge_uuid
    ".$ext['variable_bridge_uuid']."
"; - $block .= "direction
    ".$ext['direction']."
"; - $block .= "variable_call_direction
    ".$ext['variable_call_direction']."
"; - $block .= "state
    ".$ext['state']."
"; - $block .= "cid_num
    ".$ext['cid_num']."
"; - $block .= "dest
    ".$ext['dest']."
"; - $block .= "context
    ".$ext['context']."
"; - $block .= "presence_id
    ".$ext['presence_id']."
"; - $block .= "callstate
    ".$ext['callstate']."
"; - $block .= "
"; - } - $block .= "
"; - - if (in_array($extension, $_SESSION['user']['extensions'])) { - $user_extensions[] = $block; - } - else { - $other_extensions[] = $block; - } -} - - -if (sizeof($user_extensions) > 0) { - echo "
"; - foreach ($user_extensions as $ext_block) { - echo $ext_block; - } - echo "
"; -} - -if ($_REQUEST['group'] != '') { - if (sizeof($user_extensions) > 0) { echo "
"; } - echo "".ucwords($_REQUEST['group']).""; - echo "

"; -} -else if (sizeof($user_extensions) > 0) { - echo "
"; - echo "".$text['label-other_extensions'].""; - echo "

"; -} - -if (sizeof($other_extensions) > 0) { - echo "
"; - foreach ($other_extensions as $ext_block) { - echo $ext_block; - } - echo "
"; -} -else { - echo $text['label-no_extensions_found']; -} -echo "

"; - -if (if_group("superadmin") && isset($_GET['debug'])) { - echo '$activity
'; - echo ""; - echo "

"; - - echo '$_SESSION
'; - echo ""; -} -?> + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +require_once "./resources/functions/get_call_activity.php"; +if (permission_exists('operator_panel_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +$activity = get_call_activity(); + +foreach ($activity as $extension => $fields) { + if (substr_count($fields['call_group'], ',')) { + $tmp = explode(',', $fields['call_group']); + foreach ($tmp as $tmp_index => $tmp_value) { + if (trim($tmp_value) == '') { unset($tmp[$tmp_index]); } + else { $groups[] = $tmp_value; } + } + } + else if ($fields['call_group'] != '') { + $groups[] = $fields['call_group']; + } +} +$groups = array_unique($groups); +sort($groups); + +$onhover_pause_refresh = " onmouseover='refresh_stop();' onmouseout='refresh_start();'"; + +echo ""; +echo " "; +echo " "; +echo " "; +echo " "; +echo " "; +echo "
"; +echo " ".$text['title-operator_panel'].""; +echo " "; + +if (sizeof($_SESSION['user']['extensions']) > 0) { + $status_options[1]['status'] = "Available"; + $status_options[1]['label'] = $text['label-status_available']; + $status_options[1]['style'] = "op_btn_status_available"; + if (permission_exists('operator_panel_on_demand')) { + $status_options[2]['status'] = "Available (On Demand)"; + $status_options[2]['label'] = $text['label-status_on_demand']; + $status_options[2]['style'] = "op_btn_status_available_on_demand"; + } + $status_options[3]['status'] = "On Break"; + $status_options[3]['label'] = $text['label-status_on_break']; + $status_options[3]['style'] = "op_btn_status_on_break"; + $status_options[4]['status'] = "Do Not Disturb"; + $status_options[4]['label'] = $text['label-status_do_not_disturb']; + $status_options[4]['style'] = "op_btn_status_do_not_disturb"; + $status_options[5]['status'] = "Logged Out"; + $status_options[5]['label'] = $text['label-status_logged_out']; + $status_options[5]['style'] = "op_btn_status_logged_out"; + + foreach ($status_options as $status_option) { + echo " \n"; + } +} + +echo " "; +echo " "; +echo " "; +echo " "; + +if (permission_exists('operator_panel_eavesdrop')) { + echo " "; +} + +if (sizeof($groups) > 0) { + echo " "; +} + +echo " "; +echo "
"; +echo " \"".$text['label-refresh_pause']."\""; +echo " "; + if (sizeof($_SESSION['user']['extensions']) > 1) { + echo " "; + echo " "; + echo " \n"; + } + else if (sizeof($_SESSION['user']['extensions']) == 1) { + echo " "; + } + echo " "; + echo " "; + if (sizeof($groups) > 5) { + //show select box + echo " \n"; + } + else { + //show buttons + echo " "; + foreach ($groups as $group) { + echo " "; + } + } + echo "
"; + +echo "
"; +echo "
"; + +foreach ($activity as $extension => $ext) { + unset($block); + + //filter by group, if defined + if ($_REQUEST['group'] != '' && substr_count($ext['call_group'], $_REQUEST['group']) == 0 && !in_array($extension, $_SESSION['user']['extensions'])) { continue; } + + //check if feature code being called + $format_number = (substr($ext['dest'], 0, 1) == '*') ? false : true; + + //determine extension state, direction icon, and displayed name/number for caller/callee + if ($ext['state'] == 'CS_EXECUTE') { + if (($ext['callstate'] == 'RINGING' || $ext['callstate'] == 'EARLY' || $ext['callstate'] == 'RING_WAIT') && $ext['direction'] == 'inbound') { + $ext_state = 'ringing'; + } + else if ($ext['callstate'] == 'ACTIVE' && $ext['direction'] == 'outbound') { + $ext_state = 'active'; + } + else if ($ext['callstate'] == 'RING_WAIT' && $ext['direction'] == 'outbound') { + $ext_state = 'ringing'; + } + else if ($ext['callstate'] == 'ACTIVE' && $ext['direction'] == 'inbound') { + $ext_state = 'active'; + } + if (!$format_number) { + $call_name = 'System'; + $call_number = $ext['dest']; + } + else { + $call_name = $activity[$ext['dest']]['effective_caller_id_name']; + $call_number = format_phone($ext['dest']); + } + $dir_icon = 'outbound'; + } + else if ($ext['state'] == 'CS_HIBERNATE') { + if ($ext['callstate'] == 'ACTIVE') { + $ext_state = 'active'; + if ($ext['direction'] == 'inbound') { + $call_name = $activity[$ext['dest']]['effective_caller_id_name']; + $call_number = format_phone($ext['dest']); + $dir_icon = 'outbound'; + } + else if ($ext['direction'] == 'outbound') { + $call_name = $activity[$ext['cid_num']]['effective_caller_id_name']; + $call_number = format_phone($ext['cid_num']); + $dir_icon = 'inbound'; + } + } + } + else if ($ext['state'] == 'CS_CONSUME_MEDIA' || $ext['state'] == 'CS_EXCHANGE_MEDIA') { + if ($ext['state'] == 'CS_CONSUME_MEDIA' && $ext['callstate'] == 'RINGING' && $ext['direction'] == 'outbound') { + $ext_state = 'ringing'; + } + else if ($ext['state'] == 'CS_EXCHANGE_MEDIA' && $ext['callstate'] == 'ACTIVE' && $ext['direction'] == 'outbound') { + $ext_state = 'active'; + } + $dir_icon = 'inbound'; + $call_name = $activity[$ext['cid_num']]['effective_caller_id_name']; + $call_number = format_phone($ext['cid_num']); + } + else { + unset($ext_state, $dir_icon, $call_name, $call_number); + } + + //determine block style by state (if any) + $style = ($ext_state != '') ? "op_state_".$ext_state : null; + + //determine the call identifier passed on drop + if ($ext['uuid'] == $ext['call_uuid'] && $ext['variable_bridge_uuid'] == '') { // transfer an outbound internal call + $call_identifier = $activity[$call_number]['uuid']; + } + else if (($ext['variable_call_direction'] == 'outbound' || $ext['variable_call_direction'] == 'local') && $ext['variable_bridge_uuid'] != '') { // transfer an outbound external call + $call_identifier = $ext['variable_bridge_uuid']; + } + else { + if( $ext['call_uuid'] ) { + $call_identifier = $ext['call_uuid']; // transfer all other call types + } + else { + $call_identifier = $ext['uuid']; // e.g. voice menus + } + } + + //determine extension draggable state + if (permission_exists('operator_panel_manage')) { + if (!in_array($extension, $_SESSION['user']['extensions'])) { + //other extension + if ($ext_state == "ringing") { + if ($_GET['vd_ext_from'] == '' && $dir_icon == 'inbound') { + $draggable = true; // selectable - is ringing and not outbound so can transfer away the call (can set as vd_ext_from) + } + else { + $draggable = false; // unselectable - is ringing so can't send a call to the ext (can't set as vd_ext_to) + } + } + else if ($ext_state == 'active') { + $draggable = false; // unselectable - on a call already so can't transfer or send a call to the ext (can't set as vd_ext_from or vd_ext_to) + } + else { // idle + if ($_GET['vd_ext_from'] == '') { + $draggable = false; // unselectable - is idle, but can't initiate a call from the ext as is not assigned to user (can't set as vd_ext_from) + } + else { + $draggable = true; // selectable - is idle, so can transfer a call in to ext (can set as vd_ext_to). + } + } + } + else { + //user extension + if ($ext['uuid'] != '' && $ext['uuid'] == $ext['call_uuid'] && $ext['variable_bridge_uuid'] == '') { + $draggable = false; + } + else if ($ext_state == 'ringing' && $ext['variable_call_direction'] == 'local') { + $draggable = false; + } + else if ($ext_state != '' && !$format_number) { + $draggable = false; + } + else { + $draggable = true; + } + } + } + else { + $draggable = false; + } + + //determine extension (user) status + $ext_status = (in_array($extension, $_SESSION['user']['extensions'])) ? $ext_user_status[$_SESSION['user_uuid']] : $ext_user_status[$ext['user_uuid']]; + switch ($ext_status) { + case "Available" : + $status_icon = "available"; + $status_hover = $text['label-status_available']; + break; + case "Available (On Demand)" : + $status_icon = "available_on_demand"; + $status_hover = $text['label-status_available_on_demand']; + break; + case "On Break" : + $status_icon = "on_break"; + $status_hover = $text['label-status_on_break']; + break; + case "Do Not Disturb" : + $status_icon = "do_not_disturb"; + $status_hover = $text['label-status_do_not_disturb']; + break; + default : + $status_icon = "logged_out"; + $status_hover = $text['label-status_logged_out_or_unknown']; + } + + $block .= "
"; // DRAG TO + $block .= ""; + $block .= " "; + $block .= " "; + $block .= " "; + $block .= " "; + $block .= "
"; + $block .= " "; // DRAG FROM + $block .= ""; + $block .= ""; + $block .= " "; + if ($dir_icon != '') { + $block .= " \"".$text['label-call_direction']."\""; + } + $block .= "
"; + if ($ext_state != '') { + $block .= " "; + $block .= "
"; + $block .= " ".$ext['call_length']."
"; + $block .= " "; + //record + if (permission_exists('operator_panel_record') && $ext_state == 'active') { + $call_identifier_record = $ext['call_uuid']; + $rec_file = $_SESSION['switch']['recordings']['dir']."/archive/".date("Y")."/".date("M")."/".date("d")."/".$call_identifier_record.".wav"; + if (file_exists($rec_file)) { + $block .= ""; + } + else { + $block .= ""; + } + } + //eavesdrop + if (permission_exists('operator_panel_eavesdrop') && $ext_state == 'active' && sizeof($_SESSION['user']['extensions']) > 0 && !in_array($extension, $_SESSION['user']['extensions'])) { + $block .= ""; + } + //kill + if (permission_exists('operator_panel_kill') || in_array($extension, $_SESSION['user']['extensions'])) { + if ($ext['variable_bridge_uuid'] == '' && $ext_state == 'ringing') { + $call_identifier_kill = $ext['uuid']; + } + else if ($dir_icon == 'outbound') { + $call_identifier_kill = $ext['uuid']; + } + else { + $call_identifier_kill = $call_identifier; + } + $block .= ""; + } + $block .= ""; + //transfer + if (in_array($extension, $_SESSION['user']['extensions']) && $ext_state == 'active') { + $block .= ""; + } + $block .= "
"; + $block .= " ".$call_name."
".$call_number."
"; + $block .= "
"; + //transfer + if (in_array($extension, $_SESSION['user']['extensions']) && $ext_state == 'active') { + $call_identifier_transfer = $ext['variable_bridge_uuid']; + $block .= "
"; + $block .= " "; + $block .= "
\n"; + } + } + else { + //call + if (in_array($extension, $_SESSION['user']['extensions'])) { + $block .= " "; + $block .= "
"; + $block .= " "; + $block .= "
\n"; + } + } + $block .= "
"; + + if (if_group("superadmin") && isset($_GET['debug'])) { + $block .= ""; + $block .= "From ID
    ".$extension."
"; + $block .= "uuid
    ".$ext['uuid']."
"; + $block .= "call_uuid
    ".$ext['call_uuid']."
"; + $block .= "variable_bridge_uuid
    ".$ext['variable_bridge_uuid']."
"; + $block .= "direction
    ".$ext['direction']."
"; + $block .= "variable_call_direction
    ".$ext['variable_call_direction']."
"; + $block .= "state
    ".$ext['state']."
"; + $block .= "cid_num
    ".$ext['cid_num']."
"; + $block .= "dest
    ".$ext['dest']."
"; + $block .= "context
    ".$ext['context']."
"; + $block .= "presence_id
    ".$ext['presence_id']."
"; + $block .= "callstate
    ".$ext['callstate']."
"; + $block .= "
"; + } + $block .= "
"; + + if (in_array($extension, $_SESSION['user']['extensions'])) { + $user_extensions[] = $block; + } + else { + $other_extensions[] = $block; + } +} + + +if (sizeof($user_extensions) > 0) { + echo "
"; + foreach ($user_extensions as $ext_block) { + echo $ext_block; + } + echo "
"; +} + +if ($_REQUEST['group'] != '') { + if (sizeof($user_extensions) > 0) { echo "
"; } + echo "".ucwords($_REQUEST['group']).""; + echo "

"; +} +else if (sizeof($user_extensions) > 0) { + echo "
"; + echo "".$text['label-other_extensions'].""; + echo "

"; +} + +if (sizeof($other_extensions) > 0) { + echo "
"; + foreach ($other_extensions as $ext_block) { + echo $ext_block; + } + echo "
"; +} +else { + echo $text['label-no_extensions_found']; +} +echo "

"; + +if (if_group("superadmin") && isset($_GET['debug'])) { + echo '$activity
'; + echo ""; + echo "

"; + + echo '$_SESSION
'; + echo ""; +} +?> diff --git a/app/operator_panel/resources/functions/get_call_activity.php b/app/operator_panel/resources/functions/get_call_activity.php index bc1da3b574..c78f42d5ba 100644 --- a/app/operator_panel/resources/functions/get_call_activity.php +++ b/app/operator_panel/resources/functions/get_call_activity.php @@ -1,182 +1,182 @@ -prepare($sql); - $prep_statement->execute(); - $extensions = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - - //store extension status by user uuid - foreach($extensions as &$row) { - if ($row['user_uuid'] != '') { - $ext_user_status[$row['user_uuid']] = $row['user_status']; - unset($row['user_status']); - } - } - - //send the command - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if ($fp) { - $switch_cmd = 'show channels as json'; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); - $json_array = json_decode($switch_result, true); - } - - //build the response - $x = 0; - foreach($extensions as &$row) { - $user = $row['extension']; - if (strlen($row['number_alias']) >0 ) { - $user = $row['number_alias']; - } - - //add the extension details - $array[$x] = $row; - - //set the call detail defaults - $array[$x]["uuid"] = null; - $array[$x]["direction"] = null; - $array[$x]["created"] = null; - $array[$x]["created_epoch"] = null; - $array[$x]["name"] = null; - $array[$x]["state"] = null; - $array[$x]["cid_name"] = null; - $array[$x]["cid_num"] = null; - $array[$x]["ip_addr"] = null; - $array[$x]["dest"] = null; - $array[$x]["application"] = null; - $array[$x]["application_data"] = null; - $array[$x]["dialplan"] = null; - $array[$x]["context"] = null; - $array[$x]["read_codec"] = null; - $array[$x]["read_rate"] = null; - $array[$x]["read_bit_rate"] = null; - $array[$x]["write_codec"] = null; - $array[$x]["write_rate"] = null; - $array[$x]["write_bit_rate"] = null; - $array[$x]["secure"] = null; - $array[$x]["hostname"] = null; - $array[$x]["presence_id"] = null; - $array[$x]["presence_data"] = null; - $array[$x]["callstate"] = null; - $array[$x]["callee_name"] = null; - $array[$x]["callee_num"] = null; - $array[$x]["callee_direction"] = null; - $array[$x]["call_uuid"] = null; - $array[$x]["sent_callee_name"] = null; - $array[$x]["sent_callee_num"] = null; - $array[$x]["destination"] = null; - - //add the active call details - $found = false; - foreach($json_array['rows'] as &$field) { - $presence_id = $field['presence_id']; - $presence = explode("@", $presence_id); - $presence_id = $presence[0]; - $presence_domain = $presence[1]; - if ($user == $presence_id) { - if ($presence_domain == $_SESSION['domain_name']) { - $found = true; - break; - } - } - } - - //normalize the array - if ($found) { - $array[$x]["uuid"] = $field['uuid']; - $array[$x]["direction"] = $field['direction']; - $array[$x]["created"] = $field['created']; - $array[$x]["created_epoch"] = $field['created_epoch']; - $array[$x]["name"] = $field['name']; - $array[$x]["state"] = $field['state']; - $array[$x]["cid_name"] = $field['cid_name']; - $array[$x]["cid_num"] = $field['cid_num']; - $array[$x]["ip_addr"] = $field['ip_addr']; - $array[$x]["dest"] = $field['dest']; - $array[$x]["application"] = $field['application']; - $array[$x]["application_data"] = $field['application_data']; - $array[$x]["dialplan"] = $field['dialplan']; - $array[$x]["context"] = $field['context']; - $array[$x]["read_codec"] = $field['read_codec']; - $array[$x]["read_rate"] = $field['read_rate']; - $array[$x]["read_bit_rate"] = $field['read_bit_rate']; - $array[$x]["write_codec"] = $field['write_codec']; - $array[$x]["write_rate"] = $field['write_rate']; - $array[$x]["write_bit_rate"] = $field['write_bit_rate']; - $array[$x]["secure"] = $field['secure']; - $array[$x]["hostname"] = $field['hostname']; - $array[$x]["presence_id"] = $field['presence_id']; - $array[$x]["presence_data"] = $field['presence_data']; - $array[$x]["callstate"] = $field['callstate']; - $array[$x]["callee_name"] = $field['callee_name']; - $array[$x]["callee_num"] = $field['callee_num']; - $array[$x]["callee_direction"] = $field['callee_direction']; - $array[$x]["call_uuid"] = $field['call_uuid']; - $array[$x]["sent_callee_name"] = $field['sent_callee_name']; - $array[$x]["sent_callee_num"] = $field['sent_callee_num']; - $array[$x]["destination"] = $user; - - //calculate and set the call length - $call_length_seconds = time() - $array[$x]["created_epoch"]; - $call_length_hour = floor($call_length_seconds/3600); - $call_length_min = floor($call_length_seconds/60 - ($call_length_hour * 60)); - $call_length_sec = $call_length_seconds - (($call_length_hour * 3600) + ($call_length_min * 60)); - $call_length_min = sprintf("%02d", $call_length_min); - $call_length_sec = sprintf("%02d", $call_length_sec); - $call_length = $call_length_hour.':'.$call_length_min.':'.$call_length_sec; - $array[$x]['call_length'] = $call_length; - - //send the command - if ($field['state'] != '') { - if ($fp) { - $switch_cmd = 'uuid_dump '.$field['uuid'].' json'; - $dump_result = event_socket_request($fp, 'api '.$switch_cmd); - $dump_array = json_decode($dump_result, true); - foreach ($dump_array as $dump_var_name => $dump_var_value) { - $array[$x][$dump_var_name] = trim($dump_var_value); - } - } - } - - } - - //increment the row - $x++; - } - - //reindex array using extension instead of auto-incremented value - $result = array(); - foreach ($array as $index => $subarray) { - $extension = $subarray['extension']; - foreach ($subarray as $field => $value) { - $result[$extension][$field] = $array[$index][$field]; - unset($array[$index][$field]); - } - unset($array[$subarray['extension']]['extension']); - unset($array[$index]); - } - - //return array - return $result; -} +prepare($sql); + $prep_statement->execute(); + $extensions = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + + //store extension status by user uuid + foreach($extensions as &$row) { + if ($row['user_uuid'] != '') { + $ext_user_status[$row['user_uuid']] = $row['user_status']; + unset($row['user_status']); + } + } + + //send the command + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if ($fp) { + $switch_cmd = 'show channels as json'; + $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + $json_array = json_decode($switch_result, true); + } + + //build the response + $x = 0; + foreach($extensions as &$row) { + $user = $row['extension']; + if (strlen($row['number_alias']) >0 ) { + $user = $row['number_alias']; + } + + //add the extension details + $array[$x] = $row; + + //set the call detail defaults + $array[$x]["uuid"] = null; + $array[$x]["direction"] = null; + $array[$x]["created"] = null; + $array[$x]["created_epoch"] = null; + $array[$x]["name"] = null; + $array[$x]["state"] = null; + $array[$x]["cid_name"] = null; + $array[$x]["cid_num"] = null; + $array[$x]["ip_addr"] = null; + $array[$x]["dest"] = null; + $array[$x]["application"] = null; + $array[$x]["application_data"] = null; + $array[$x]["dialplan"] = null; + $array[$x]["context"] = null; + $array[$x]["read_codec"] = null; + $array[$x]["read_rate"] = null; + $array[$x]["read_bit_rate"] = null; + $array[$x]["write_codec"] = null; + $array[$x]["write_rate"] = null; + $array[$x]["write_bit_rate"] = null; + $array[$x]["secure"] = null; + $array[$x]["hostname"] = null; + $array[$x]["presence_id"] = null; + $array[$x]["presence_data"] = null; + $array[$x]["callstate"] = null; + $array[$x]["callee_name"] = null; + $array[$x]["callee_num"] = null; + $array[$x]["callee_direction"] = null; + $array[$x]["call_uuid"] = null; + $array[$x]["sent_callee_name"] = null; + $array[$x]["sent_callee_num"] = null; + $array[$x]["destination"] = null; + + //add the active call details + $found = false; + foreach($json_array['rows'] as &$field) { + $presence_id = $field['presence_id']; + $presence = explode("@", $presence_id); + $presence_id = $presence[0]; + $presence_domain = $presence[1]; + if ($user == $presence_id) { + if ($presence_domain == $_SESSION['domain_name']) { + $found = true; + break; + } + } + } + + //normalize the array + if ($found) { + $array[$x]["uuid"] = $field['uuid']; + $array[$x]["direction"] = $field['direction']; + $array[$x]["created"] = $field['created']; + $array[$x]["created_epoch"] = $field['created_epoch']; + $array[$x]["name"] = $field['name']; + $array[$x]["state"] = $field['state']; + $array[$x]["cid_name"] = $field['cid_name']; + $array[$x]["cid_num"] = $field['cid_num']; + $array[$x]["ip_addr"] = $field['ip_addr']; + $array[$x]["dest"] = $field['dest']; + $array[$x]["application"] = $field['application']; + $array[$x]["application_data"] = $field['application_data']; + $array[$x]["dialplan"] = $field['dialplan']; + $array[$x]["context"] = $field['context']; + $array[$x]["read_codec"] = $field['read_codec']; + $array[$x]["read_rate"] = $field['read_rate']; + $array[$x]["read_bit_rate"] = $field['read_bit_rate']; + $array[$x]["write_codec"] = $field['write_codec']; + $array[$x]["write_rate"] = $field['write_rate']; + $array[$x]["write_bit_rate"] = $field['write_bit_rate']; + $array[$x]["secure"] = $field['secure']; + $array[$x]["hostname"] = $field['hostname']; + $array[$x]["presence_id"] = $field['presence_id']; + $array[$x]["presence_data"] = $field['presence_data']; + $array[$x]["callstate"] = $field['callstate']; + $array[$x]["callee_name"] = $field['callee_name']; + $array[$x]["callee_num"] = $field['callee_num']; + $array[$x]["callee_direction"] = $field['callee_direction']; + $array[$x]["call_uuid"] = $field['call_uuid']; + $array[$x]["sent_callee_name"] = $field['sent_callee_name']; + $array[$x]["sent_callee_num"] = $field['sent_callee_num']; + $array[$x]["destination"] = $user; + + //calculate and set the call length + $call_length_seconds = time() - $array[$x]["created_epoch"]; + $call_length_hour = floor($call_length_seconds/3600); + $call_length_min = floor($call_length_seconds/60 - ($call_length_hour * 60)); + $call_length_sec = $call_length_seconds - (($call_length_hour * 3600) + ($call_length_min * 60)); + $call_length_min = sprintf("%02d", $call_length_min); + $call_length_sec = sprintf("%02d", $call_length_sec); + $call_length = $call_length_hour.':'.$call_length_min.':'.$call_length_sec; + $array[$x]['call_length'] = $call_length; + + //send the command + if ($field['state'] != '') { + if ($fp) { + $switch_cmd = 'uuid_dump '.$field['uuid'].' json'; + $dump_result = event_socket_request($fp, 'api '.$switch_cmd); + $dump_array = json_decode($dump_result, true); + foreach ($dump_array as $dump_var_name => $dump_var_value) { + $array[$x][$dump_var_name] = trim($dump_var_value); + } + } + } + + } + + //increment the row + $x++; + } + + //reindex array using extension instead of auto-incremented value + $result = array(); + foreach ($array as $index => $subarray) { + $extension = $subarray['extension']; + foreach ($subarray as $field => $value) { + $result[$extension][$field] = $array[$index][$field]; + unset($array[$index][$field]); + } + unset($array[$subarray['extension']]['extension']); + unset($array[$index]); + } + + //return array + return $result; +} diff --git a/app/provision/app_menu.php b/app/provision/app_menu.php index 1a00887852..356347583a 100644 --- a/app/provision/app_menu.php +++ b/app/provision/app_menu.php @@ -1,12 +1,12 @@ - \ No newline at end of file diff --git a/app/provision/resources/classes/provision.php b/app/provision/resources/classes/provision.php index 798f3fac8d..1dcb2d4234 100644 --- a/app/provision/resources/classes/provision.php +++ b/app/provision/resources/classes/provision.php @@ -1,1048 +1,1048 @@ - - Copyright (C) 2014-2016 - All Rights Reserved. - - Contributor(s): - Mark J Crane - Luis Daniel Lucio Quiroz -*/ -include "root.php"; - -//define the provision class - class provision { - public $db; - public $domain_uuid; - public $domain_name; - public $template_dir; - public $mac; - - public function __construct() { - //get the database object - global $db; - $this->db = $db; - //set the default template directory - if (PHP_OS == "Linux") { - //set the default template dir - if (strlen($this->template_dir) == 0) { - if (file_exists('/etc/fusionpbx/resources/templates/provision')) { - $this->template_dir = '/etc/fusionpbx/resources/templates/provision'; - } - else { - $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; - } - } - } elseif (PHP_OS == "FreeBSD") { - //if the FreeBSD port is installed use the following paths by default. - if (file_exists('/usr/local/etc/fusionpbx/resources/templates/provision')) { - if (strlen($this->template_dir) == 0) { - $this->template_dir = '/usr/local/etc/fusionpbx/resources/templates/provision'; - } - else { - $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; - } - } - else { - if (strlen($this->template_dir) == 0) { - $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; - } - else { - $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; - } - } - } elseif (PHP_OS == "NetBSD") { - //set the default template_dir - if (strlen($this->template_dir) == 0) { - $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; - } - } elseif (PHP_OS == "OpenBSD") { - //set the default template_dir - if (strlen($this->template_dir) == 0) { - $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; - } - } else { - //set the default template_dir - if (strlen($this->template_dir) == 0) { - $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; - } - } - - //normalize the mac address - if (isset($this->mac)) { - $this->mac = strtolower(preg_replace('#[^a-fA-F0-9./]#', '', $this->mac)); - } - } - - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - public function get_domain_uuid() { - return $this->domain_uuid; - } - - //define the function which checks to see if the mac address exists in devices - private function mac_exists($mac) { - //normalize the mac address - $mac = strtolower(preg_replace('#[^a-fA-F0-9./]#', '', $mac)); - //check in the devices table for a specific mac address - $sql = "SELECT count(*) as count FROM v_devices "; - $sql .= "WHERE device_mac_address=:mac "; - $prep_statement = $this->db->prepare(check_sql($sql)); - if ($prep_statement) { - //$prep_statement->bindParam(':domain_uuid', $domain_uuid); - $prep_statement->bindParam(':mac', $mac); - $prep_statement->execute(); - $row = $prep_statement->fetch(); - $count = $row['count']; - if ($row['count'] > 0) { - return true; - } - else { - return false; - } - } - else { - return false; - } - } - - //set the mac address in the correct format for the specific vendor - public function format_mac($mac, $vendor) { - switch (strtolower($vendor)) { - case "aastra": - $mac = strtoupper($mac); - break; - case "cisco": - $mac = strtoupper($mac); - break; - case "linksys": - $mac = strtolower($mac); - break; - case "mitel": - $mac = strtoupper($mac); - break; - case "polycom": - $mac = strtolower($mac); - break; - case "snom": - $mac = strtolower($mac); - break; - default: - $mac = strtolower($mac); - $mac = substr($mac, 0,2).'-'.substr($mac, 2,2).'-'.substr($mac, 4,2).'-'.substr($mac, 6,2).'-'.substr($mac, 8,2).'-'.substr($mac, 10,2); - } - return $mac; - } - - //define a function to check if a contact exists in the contacts array - private function contact_exists($contacts, $uuid) { - if (is_array($contacts[$uuid])) { - return true; - } - else { - return false; - } - } - - public function render() { - - //debug - $debug = $_REQUEST['debug']; // array - - //get the variables - $domain_uuid = $this->domain_uuid; - $device_template = $this->device_template; - $template_dir = $this->template_dir; - $mac = $this->mac; - $file = $this->file; - - //set the mac address to lower case to be consistent with the database - $mac = strtolower($mac); - - //get the device template - if (strlen($_REQUEST['template']) > 0) { - $device_template = $_REQUEST['template']; - $search = array('..', '/./'); - $device_template = str_replace($search, "", $device_template); - $device_template = str_replace('//', '/', $device_template); - } - - //remove ../ and slashes in the file name - $search = array('..', '/', '\\', '/./', '//'); - $file = str_replace($search, "", $file); - - //get the domain_name - if (strlen($domain_name) == 0) { - $sql = "SELECT domain_name FROM v_domains "; - $sql .= "WHERE domain_uuid=:domain_uuid "; - $prep_statement = $this->db->prepare(check_sql($sql)); - if ($prep_statement) { - //use the prepared statement - $prep_statement->bindParam(':domain_uuid', $domain_uuid); - $prep_statement->execute(); - $row = $prep_statement->fetch(); - unset($prep_statement); - //set the variables from values in the database - $domain_name = $row["domain_name"]; - } - } - - //build the provision array - foreach($_SESSION['provision'] as $key=>$val) { - if (strlen($val['var']) > 0) { $value = $val['var']; } - if (strlen($val['text']) > 0) { $value = $val['text']; } - $provision[$key] = $value; - } - - //check to see if the mac_address exists in devices - if (strlen($_REQUEST['user_id']) == 0 || strlen($_REQUEST['userid']) == 0) { - if ($this->mac_exists($mac)) { - //get the device_template - if (strlen($device_template) == 0) { - $sql = "SELECT * FROM v_devices "; - $sql .= "WHERE device_mac_address=:mac "; - if($provision['http_domain_filter'] == "true") { - $sql .= "AND domain_uuid=:domain_uuid "; - } - //$sql .= "WHERE device_mac_address= '$mac' "; - $prep_statement_2 = $this->db->prepare(check_sql($sql)); - if ($prep_statement_2) { - //use the prepared statement - $prep_statement_2->bindParam(':mac', $mac); - if($provision['http_domain_filter'] == "true") { - $prep_statement_2->bindParam(':domain_uuid', $domain_uuid); - } - $prep_statement_2->execute(); - $row = $prep_statement_2->fetch(); - //set the variables from values in the database - $device_uuid = $row["device_uuid"]; - $device_label = $row["device_label"]; - if (strlen($row["device_vendor"]) > 0) { - $device_vendor = strtolower($row["device_vendor"]); - } - $device_model = $row["device_model"]; - $device_firmware_version = $row["device_firmware_version"]; - $device_enabled = $row["device_enabled"]; - $device_template = $row["device_template"]; - $device_profile_uuid = $row["device_profile_uuid"]; - $device_description = $row["device_description"]; - } - } - - //find a template that was defined on another phone and use that as the default. - if (strlen($device_template) == 0) { - $sql = "SELECT * FROM v_devices "; - $sql .= "WHERE domain_uuid=:domain_uuid "; - $sql .= "limit 1 "; - $prep_statement_3 = $this->db->prepare(check_sql($sql)); - if ($prep_statement_3) { - $prep_statement_3->bindParam(':domain_uuid', $domain_uuid); - $prep_statement_3->execute(); - $row = $prep_statement_3->fetch(); - $device_label = $row["device_label"]; - $device_vendor = strtolower($row["device_vendor"]); - $device_model = $row["device_model"]; - $device_firmware_version = $row["device_firmware_version"]; - $device_enabled = $row["device_enabled"]; - $device_template = $row["device_template"]; - $device_profile_uuid = $row["device_profile_uuid"]; - $device_description = $row["device_description"]; - } - } - } - else { - //use the user_agent to pre-assign a template for 1-hit provisioning. Enter the a unique string to match in the user agent, and the template it should match. - $template_list=array( - "Linksys/SPA-2102"=>"linksys/spa2102", - "Linksys/SPA-3102"=>"linksys/spa3102", - "Linksys/SPA-9212"=>"linksys/spa921", - "Cisco/SPA301"=>"cisco/spa301", - "Cisco/SPA301D"=>"cisco/spa302d", - "Cisco/SPA303"=>"cisco/spa303", - "Cisco/SPA501G"=>"cisco/spa501g", - "Cisco/SPA502G"=>"cisco/spa502g", - "Cisco/SPA504G"=>"cisco/spa504g", - "Cisco/SPA508G"=>"cisco/spa508g", - "Cisco/SPA509G"=>"cisco/spa509g", - "Cisco/SPA512G"=>"cisco/spa512g", - "Cisco/SPA514G"=>"cisco/spa514g", - "Cisco/SPA525G2"=>"cisco/spa525g2", - "snom300-SIP"=>"snom/300", - "snom320-SIP"=>"snom/320", - "snom360-SIP"=>"snom/360", - "snom370-SIP"=>"snom/370", - "snom820-SIP"=>"snom/820", - "snom-m3-SIP"=>"snom/m3", - "yealink SIP-T20"=>"yealink/t20", - "yealink SIP-T22"=>"yealink/t22", - "yealink SIP-T26"=>"yealink/t26", - "Yealink SIP-T32"=>"yealink/t32", - "HW GXP1450"=>"grandstream/gxp1450", - "HW GXP2124"=>"grandstream/gxp2124", - "HW GXV3140"=>"grandstream/gxv3140", - "HW GXV3175"=>"grandstream/gxv3175", - "Wget/1.11.3"=>"konftel/kt300ip" - ); - - foreach ($template_list as $key=>$val){ - if(stripos($_SERVER['HTTP_USER_AGENT'],$key)!== false) { - $device_template = $val; - break; - } - } - unset($template_list); - - //mac address does not exist in the table so add it - if ($_SESSION['provision']['auto_insert_enabled']['boolean'] == "true" and strlen($domain_uuid) > 0) { - $device_uuid = uuid(); - $sql = "INSERT INTO v_devices "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "device_uuid, "; - $sql .= "device_mac_address, "; - $sql .= "device_vendor, "; - $sql .= "device_model, "; - $sql .= "device_enabled, "; - $sql .= "device_template, "; - $sql .= "device_description "; - $sql .= ") "; - $sql .= "VALUES "; - $sql .= "("; - $sql .= "'".$domain_uuid."', "; - $sql .= "'$device_uuid', "; - $sql .= "'$mac', "; - $sql .= "'$device_vendor', "; - $sql .= "'', "; - $sql .= "'true', "; - $sql .= "'$device_template', "; - $sql .= "'auto {$_SERVER['HTTP_USER_AGENT']}' "; - $sql .= ")"; - $this->db->exec(check_sql($sql)); - unset($sql); - } - } - } - - //alternate device_uuid - if (strlen($device_uuid) > 0) { - $sql = "SELECT * FROM v_devices "; - $sql .= "WHERE device_uuid = '".$device_uuid."' "; - if($provision['http_domain_filter'] == "true") { - $sql .= "AND domain_uuid=:domain_uuid "; - } - $prep_statement_3 = $this->db->prepare(check_sql($sql)); - if ($prep_statement_3) { - if($provision['http_domain_filter'] == "true") { - $prep_statement_3->bindParam(':domain_uuid', $domain_uuid); - } - $prep_statement_3->execute(); - $row = $prep_statement_3->fetch(); - $device_uuid_alternate = $row["device_uuid_alternate"]; - if (is_uuid($device_uuid_alternate)) { - //override the original device_uuid - $device_uuid = $device_uuid_alternate; - //get the new devices information - $sql = "SELECT * FROM v_devices "; - $sql .= "WHERE device_uuid = '".$device_uuid."' "; - if($provision['http_domain_filter'] == "true") { - $sql .= "AND domain_uuid=:domain_uuid "; - } - $prep_statement_4 = $this->db->prepare(check_sql($sql)); - if ($prep_statement_4) { - if($provision['http_domain_filter'] == "true") { - $prep_statement_4->bindParam(':domain_uuid', $domain_uuid); - } - $prep_statement_4->execute(); - $row = $prep_statement_4->fetch(); - $device_label = $row["device_label"]; - $device_firmware_version = $row["device_firmware_version"]; - $device_enabled = $row["device_enabled"]; - //keep the original template - $device_profile_uuid = $row["device_profile_uuid"]; - $device_description = $row["device_description"]; - } - unset($prep_statement_4); - } - } - unset($prep_statement_3); - } - - //get the device settings table in the provision category and update the provision array - if (strlen($device_uuid) > 0) { - $sql = "SELECT * FROM v_device_settings "; - $sql .= "WHERE device_uuid = '".$device_uuid."' "; - $sql .= "AND device_setting_enabled = 'true' "; - $prep_statement = $this->db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - foreach($result as $row) { - $key = $row['device_setting_subcategory']; - $value = $row['device_setting_value']; - $provision[$key] = $value; - } - unset ($prep_statement); - } - - //initialize a template object - $view = new template(); - if (strlen($_SESSION['provision']['template_engine']['text']) > 0) { - $view->engine = $_SESSION['provision']['template_engine']['text']; //raintpl, smarty, twig - } - else { - $view->engine = "smarty"; - } - $view->template_dir = $template_dir ."/".$device_template."/"; - $view->cache_dir = $_SESSION['server']['temp']['dir']; - $view->init(); - - //replace the variables in the template in the future loop through all the line numbers to do a replace for each possible line number - - //get the time zone - $time_zone_name = $_SESSION['domain']['time_zone']['name']; - if (strlen($time_zone_name) > 0) { - $time_zone_offset_raw = get_time_zone_offset($time_zone_name)/3600; - $time_zone_offset_hours = floor($time_zone_offset_raw); - $time_zone_offset_minutes = ($time_zone_offset_raw - $time_zone_offset_hours) * 60; - $time_zone_offset_minutes = number_pad($time_zone_offset_minutes, 2); - if ($time_zone_offset_raw > 0) { - $time_zone_offset_hours = number_pad($time_zone_offset_hours, 2); - $time_zone_offset_hours = "+".$time_zone_offset_hours; - } - else { - $time_zone_offset_hours = str_replace("-", "", $time_zone_offset_hours); - $time_zone_offset_hours = "-".number_pad($time_zone_offset_hours, 2); - } - $time_zone_offset = $time_zone_offset_hours.":".$time_zone_offset_minutes; - $view->assign("time_zone_offset" , $time_zone_offset); - } - - //create a mac address with back slashes for backwards compatability - $mac_dash = substr($mac, 0,2).'-'.substr($mac, 2,2).'-'.substr($mac, 4,2).'-'.substr($mac, 6,2).'-'.substr($mac, 8,2).'-'.substr($mac, 10,2); - - //get the provisioning information from device lines table - if (strlen($device_uuid) > 0) { - //get the device lines array - $sql = "select * from v_device_lines "; - $sql .= "where device_uuid = '".$device_uuid."' "; - $sql .= "and (enabled = 'true' or enabled is null or enabled = '') "; - $prep_statement = $this->db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_lines = $prep_statement->fetchAll(PDO::FETCH_NAMED); - //assign the keys array - $view->assign("lines", $device_lines); - //set the variables - foreach($device_lines as $row) { - //set the variables - $line_number = $row['line_number']; - $register_expires = $row['register_expires']; - $sip_transport = strtolower($row['sip_transport']); - $sip_port = $row['sip_port']; - - //set defaults - if (strlen($register_expires) == 0) { $register_expires = "120"; } - if (strlen($sip_transport) == 0) { $sip_transport = "tcp"; } - if (strlen($sip_port) == 0) { - if ($line_number == "" || $line_number == "1") { - $sip_port = "5060"; - } - else { - $sip_port = "506".($line_number + 1); - } - } - - //set a lines array index is the line number - $lines[$line_number]['register_expires'] = $register_expires; - $lines[$line_number]['sip_transport'] = strtolower($sip_transport); - $lines[$line_number]['sip_port'] = $sip_port; - $lines[$line_number]['server_address'] = $row["server_address"]; - $lines[$line_number]['outbound_proxy'] = $row["outbound_proxy"]; - $lines[$line_number]['display_name'] = $row["display_name"]; - $lines[$line_number]['auth_id'] = $row["auth_id"]; - $lines[$line_number]['user_id'] = $row["user_id"]; - $lines[$line_number]['password'] = $row["password"]; - - //assign the variables - $view->assign("server_address_".$line_number, $row["server_address"]); - $view->assign("outbound_proxy_".$line_number, $row["outbound_proxy"]); - $view->assign("display_name_".$line_number, $row["display_name"]); - $view->assign("auth_id_".$line_number, $row["auth_id"]); - $view->assign("user_id_".$line_number, $row["user_id"]); - $view->assign("user_password_".$line_number, $row["password"]); - $view->assign("sip_transport_".$line_number, $sip_transport); - $view->assign("sip_port_".$line_number, $sip_port); - $view->assign("register_expires_".$line_number, $register_expires); - } - unset ($prep_statement); - } - - //get the list of contact directly assigned to the user - //get the user_uuid to find the contacts assigned to the user and the groups the user is a member of. - if (strlen($device_uuid) > 0 and strlen($domain_uuid) > 0) { - foreach ($device_lines as &$line) { - //get the user_uuid assigned to the extension_uuid - if ($_SESSION['provision']['contact_users']['boolean'] == "true" || $_SESSION['provision']['contact_groups']['boolean'] == "true") { - $sql = "select user_uuid from v_extension_users "; - $sql .= "where extension_uuid in ( "; - $sql .= " select extension_uuid from v_extensions "; - $sql .= " where (extension = '".$line["user_id"]."' or number_alias = '".$line["user_id"]."') "; - $sql .= " and domain_uuid = '$domain_uuid' "; - $sql .= ") "; - $sql .= "and domain_uuid = '$domain_uuid' "; - $prep_statement = $this->db->prepare(check_sql($sql)); - $prep_statement->execute(); - $extension_users = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset($prep_statement); - foreach ($extension_users as &$row) { - $user_uuid = $row["user_uuid"]; - } - } - - //get the contacts assigned to the groups and add to the contacts array - if ($_SESSION['provision']['contact_groups']['boolean'] == "true") { - $sql = "select c.contact_uuid, c.contact_organization, c.contact_name_given, c.contact_name_family, "; - $sql .= "c.contact_type, c.contact_category, p.phone_label,"; - $sql .= "p.phone_number, p.phone_extension "; - $sql .= "from v_contacts as c, v_contact_phones as p "; - $sql .= "where c.contact_uuid in ( "; - $sql .= " select contact_uuid from v_contact_groups "; - $sql .= " where group_uuid in (' "; - $sql .= " select group_uuid from v_group_users "; - $sql .= " where user_uuid = '".$user_uuid."' "; - $sql .= " and domain_uuid = '$domain_uuid' "; - $sql .= " ) "; - $sql .= "and domain_uuid = '$domain_uuid' "; - $sql .= ") "; - //echo $sql."\n"; - $prep_statement = $this->db->prepare(check_sql($sql)); - $prep_statement->execute(); - $contact_groups = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset($prep_statement); - foreach ($contact_groups as $row) { - //get the contact_uuid - $uuid = $row['contact_uuid']; - //add the contacts to the contact array - if (!$this->contact_exists($contacts, $uuid)) { - $contacts[$uuid]['category'] = 'groups'; - $contacts[$uuid]['contact_uuid'] = $row['contact_uuid']; - $contacts[$uuid]['contact_type'] = $row['contact_type']; - $contacts[$uuid]['contact_category'] = $row['contact_category']; - $contacts[$uuid]['contact_organization'] = $row['contact_organization']; - $contacts[$uuid]['contact_name_given'] = $row['contact_name_given']; - $contacts[$uuid]['contact_name_family'] = $row['contact_name_family']; - $contacts[$uuid]['phone_label'] = $row['phone_label']; - $contacts[$uuid]['phone_number'] = $row['phone_number']; - $contacts[$uuid]['phone_extension'] = $row['phone_extension']; - } - } - } - - //get the contacts assigned to the user and add to the contacts array - if ($_SESSION['provision']['contact_users']['boolean'] == "true") { - $sql = "select c.contact_uuid, c.contact_organization, c.contact_name_given, c.contact_name_family, "; - $sql .= "c.contact_type, c.contact_category, p.phone_label,"; - $sql .= "p.phone_number, p.phone_extension "; - $sql .= "from v_contacts as c, v_contact_phones as p "; - $sql .= "where c.contact_uuid in ( "; - $sql .= " select contact_uuid from v_contact_users "; - $sql .= " where user_uuid = '".$user_uuid."' "; - $sql .= " and domain_uuid = '$domain_uuid' "; - $sql .= ") "; - $sql .= "and c.contact_uuid = p.contact_uuid "; - $sql .= "and p.phone_type_voice = '1' "; - $sql .= "and c.domain_uuid = '$domain_uuid' "; - //echo $sql."\n"; - $prep_statement = $this->db->prepare(check_sql($sql)); - $prep_statement->execute(); - $user_contacts = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset($prep_statement); - foreach ($user_contacts as $row) { - //get the contact_uuid - $uuid = $row['contact_uuid']; - //add the contacts to the contact array - if (!$this->contact_exists($contacts, $uuid)) { - $contacts[$uuid]['category'] = 'users'; - $contacts[$uuid]['contact_uuid'] = $row['contact_uuid']; - $contacts[$uuid]['contact_type'] = $row['contact_type']; - $contacts[$uuid]['contact_category'] = $row['contact_category']; - $contacts[$uuid]['contact_organization'] = $row['contact_organization']; - $contacts[$uuid]['contact_name_given'] = $row['contact_name_given']; - $contacts[$uuid]['contact_name_family'] = $row['contact_name_family']; - $contacts[$uuid]['phone_label'] = $row['phone_label']; - $contacts[$uuid]['phone_number'] = $row['phone_number']; - $contacts[$uuid]['phone_extension'] = $row['phone_extension']; - } - } - } - } - } - - //get the extensions and add them to the contacts array - if (strlen($device_uuid) > 0 and strlen($domain_uuid) > 0 and $_SESSION['provision']['contact_extensions']['boolean'] == "true") { - //get contacts from the database - $sql = "select extension_uuid as contact_uuid, directory_full_name, "; - $sql .= "effective_caller_id_name, effective_caller_id_number, "; - $sql .= "number_alias, extension "; - $sql .= "from v_extensions "; - $sql .= "where domain_uuid = '".$domain_uuid."' "; - $sql .= "and enabled = 'true' "; - $sql .= "order by number_alias, extension asc "; - $prep_statement = $this->db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $extensions = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($extensions as $row) { - //get the contact_uuid - $uuid = $row['contact_uuid']; - //get the names - if (strlen($row['directory_full_name']) > 0) { - $name_array = explode(" ", $row['directory_full_name']); - } else { - $name_array = explode(" ", $row['effective_caller_id_name']); - } - $contact_name_given = array_shift($name_array); - $contact_name_family = trim(implode(' ', $name_array)); - //get the phone_extension - if (is_numeric($row['extension'])) { - $phone_extension = $row['extension']; - } - else { - $phone_extension = $row['number_alias']; - } - //save the contact array values - $contacts[$uuid]['category'] = 'extensions'; - $contacts[$uuid]['contact_uuid'] = $row['contact_uuid']; - $contacts[$uuid]['contact_category'] = 'extensions'; - $contacts[$uuid]['contact_name_given'] = $contact_name_given; - $contacts[$uuid]['contact_name_family'] = $contact_name_family; - $contacts[$uuid]['phone_extension'] = $phone_extension; - //unset the variables - unset($name_array, $contact_name_given, $contact_name_family, $phone_extension); - } - } - } - - //assign the contacts array to the template - if (is_array($contacts)) { - $view->assign("contacts", $contacts); - unset($contacts); - } - - //get the provisioning information from device keys - if (strlen($device_uuid) > 0) { - //get the device keys array - $sql = "SELECT * FROM v_device_keys "; - $sql .= "WHERE ("; - $sql .= "device_uuid = '".$device_uuid."' "; - if (strlen($device_profile_uuid) > 0) { - $sql .= "or device_profile_uuid = '".$device_profile_uuid."' "; - } - $sql .= ") "; - $sql .= "AND (lower(device_key_vendor) = '".$device_vendor."' or device_key_vendor is null) "; - $sql .= "ORDER BY device_key_category asc, device_key_id asc, device_uuid desc"; - $prep_statement = $this->db->prepare(check_sql($sql)); - $prep_statement->execute(); - $device_keys = $prep_statement->fetchAll(PDO::FETCH_NAMED); - - //rebuild the array to allow profile keys to be overridden by keys assigned to this device - $x = 0; - $previous_category = ''; - $previous_id = ''; - foreach($device_keys as $row) { - //set the variables - if ($row['device_key_category'] == $previous_category && $row['device_key_id'] == $previous_id) { - $device_keys[$x]['device_key_override'] = "true"; - $device_keys[$x]['device_key_message'] = "value=".$device_keys[$x-1]['device_key_value']."&label=".$device_keys[$x-1]['device_key_label']; - unset($device_keys[$x-1]); - } - $device_keys[$x]['device_key_category'] = $row['device_key_category']; - $device_keys[$x]['device_key_id'] = $row['device_key_id']; //1 - $device_keys[$x]['device_key_type'] = $row['device_key_type']; //line, memory, expansion - $device_keys[$x]['device_key_line'] = $row['device_key_line']; - $device_keys[$x]['device_key_value'] = $row['device_key_value']; //1 - $device_keys[$x]['device_key_extension'] = $row['device_key_extension']; - $device_keys[$x]['device_key_label'] = $row['device_key_label']; //label - if (is_uuid($row['device_profile_uuid'])) { - $device_keys[$x]['device_key_owner'] = "profile"; - } - else { - $device_keys[$x]['device_key_owner'] = "device"; - } - //set previous values - $previous_category = $row['device_key_category']; - $previous_id = $row['device_key_id']; - //increment the key - $x++; - } - } - - //debug information - if ($debug == "array") { - echo "
\n";
-						print_r($device_keys);
-						echo "
\n";
-						exit;
-					}
-
-				//assign the keys array
-					$view->assign("keys", $device_keys);
-
-				//set the variables
-					foreach($device_keys as $row) {
-						//set the variables
-							$device_key_category = $row['device_key_category'];
-							$device_key_id = $row['device_key_id']; //1
-							$device_key_type = $row['device_key_type']; //line
-							$device_key_line = $row['device_key_line'];
-							$device_key_value = $row['device_key_value']; //1
-							$device_key_extension = $row['device_key_extension'];
-							$device_key_label = $row['device_key_label']; //label
-
-						//set the line key
-							$x = $device_key_line;
-
-						//add a simple variable with the index
-							if ($x === 0 || $x === 1) {
-								$device_key_value = str_replace("\${user_id}", $lines[$x]['user_id'], $device_key_value);
-								$device_key_value = str_replace("\${auth_id}", $lines[$x]['auth_id'], $device_key_value);
-								$device_key_value = str_replace("\${extension}", $lines[$x]['user_id'], $device_key_value);
-								$device_key_value = str_replace("\${password}", $lines[$x]['password'], $device_key_value);
-								$device_key_value = str_replace("\${register_expires}", $lines[$x]['register_expires'], $device_key_value);
-								$device_key_value = str_replace("\${sip_transport}", $lines[$x]['sip_transport'], $device_key_value);
-								$device_key_value = str_replace("\${sip_port}", $lines[$x]['sip_port'], $device_key_value);
-								$device_key_value = str_replace("\${server_address}", $lines[$x]['server_address'], $device_key_value);
-								$device_key_value = str_replace("\${outbound_proxy}", $lines[$x]['outbound_proxy'], $device_key_value);
-								$device_key_value = str_replace("\${display_name}", $lines[$x]['display_name'], $device_key_value);
-
-								$device_key_extension = str_replace("\${user_id}", $lines[$x]['user_id'], $device_key_extension);
-								$device_key_extension = str_replace("\${auth_id}", $lines[$x]['auth_id'], $device_key_extension);
-								$device_key_extension = str_replace("\${extension}", $lines[$x]['user_id'], $device_key_extension);
-								$device_key_extension = str_replace("\${password}", $lines[$x]['password'], $device_key_extension);
-								$device_key_extension = str_replace("\${register_expires}", $lines[$x]['register_expires'], $device_key_extension);
-								$device_key_extension = str_replace("\${sip_transport}", $lines[$x]['sip_transport'], $device_key_extension);
-								$device_key_extension = str_replace("\${sip_port}", $lines[$x]['sip_port'], $device_key_extension);
-								$device_key_extension = str_replace("\${server_address}", $lines[$x]['server_address'], $device_key_extension);
-								$device_key_extension = str_replace("\${outbound_proxy}", $lines[$x]['outbound_proxy'], $device_key_extension);
-								$device_key_extension = str_replace("\${display_name}", $lines[$x]['display_name'], $device_key_extension);
-
-								$device_key_label = str_replace("\${user_id}", $lines[$x]['user_id'], $device_key_label);
-								$device_key_label = str_replace("\${auth_id}", $lines[$x]['auth_id'], $device_key_label);
-								$device_key_label = str_replace("\${extension}", $lines[$x]['user_id'], $device_key_label);
-								$device_key_label = str_replace("\${password}", $lines[$x]['password'], $device_key_label);
-								$device_key_label = str_replace("\${register_expires}", $lines[$x]['register_expires'], $device_key_label);
-								$device_key_label = str_replace("\${sip_transport}", $lines[$x]['sip_transport'], $device_key_label);
-								$device_key_label = str_replace("\${sip_port}", $lines[$x]['sip_port'], $device_key_label);
-								$device_key_label = str_replace("\${server_address}", $lines[$x]['server_address'], $device_key_label);
-								$device_key_label = str_replace("\${outbound_proxy}", $lines[$x]['outbound_proxy'], $device_key_label);
-								$device_key_label = str_replace("\${display_name}", $lines[$x]['display_name'], $device_key_label);
-							}
-
-						//add variables with the index
-							$device_key_value = str_replace("\${user_id_$x}", $lines[$x]['user_id'], $device_key_value);
-							$device_key_value = str_replace("\${auth_id_$x}", $lines[$x]['auth_id'], $device_key_value);
-							$device_key_value = str_replace("\${extension_$x}", $lines[$x]['user_id'], $device_key_value);
-							$device_key_value = str_replace("\${password_$x}", $lines[$x]['password'], $device_key_value);
-							$device_key_value = str_replace("\${register_expires_$x}", $lines[$x]['register_expires'], $device_key_value);
-							$device_key_value = str_replace("\${sip_transport_$x}", $lines[$x]['sip_transport'], $device_key_value);
-							$device_key_value = str_replace("\${sip_port_$x}", $lines[$x]['sip_port'], $device_key_value);
-							$device_key_value = str_replace("\${server_address_$x}", $lines[$x]['server_address'], $device_key_value);
-							$device_key_value = str_replace("\${outbound_proxy_$x}", $lines[$x]['outbound_proxy'], $device_key_value);
-							$device_key_value = str_replace("\${display_name_$x}", $lines[$x]['display_name'], $device_key_value);
-
-							$device_key_extension = str_replace("\${user_id_$x}", $lines[$x]['user_id'], $device_key_label);
-							$device_key_extension = str_replace("\${auth_id_$x}", $lines[$x]['auth_id'], $device_key_label);
-							$device_key_extension = str_replace("\${extension_$x}", $lines[$x]['user_id'], $device_key_label);
-							$device_key_extension = str_replace("\${password_$x}", $lines[$x]['password'], $device_key_label);
-							$device_key_extension = str_replace("\${register_expires_$x}", $lines[$x]['register_expires'], $device_key_label);
-							$device_key_extension = str_replace("\${sip_transport_$x}", $lines[$x]['sip_transport'], $device_key_label);
-							$device_key_extension = str_replace("\${sip_port_$x}", $lines[$x]['sip_port'], $device_key_label);
-							$device_key_extension = str_replace("\${server_address_$x}", $lines[$x]['server_address'], $device_key_label);
-							$device_key_extension = str_replace("\${outbound_proxy_$x}", $lines[$x]['outbound_proxy'], $device_key_label);
-							$device_key_extension = str_replace("\${display_name_$x}", $lines[$x]['display_name'], $device_key_label);
-
-							$device_key_label = str_replace("\${user_id_$x}", $lines[$x]['user_id'], $device_key_label);
-							$device_key_label = str_replace("\${auth_id_$x}", $lines[$x]['auth_id'], $device_key_label);
-							$device_key_label = str_replace("\${extension_$x}", $lines[$x]['user_id'], $device_key_label);
-							$device_key_label = str_replace("\${password_$x}", $lines[$x]['password'], $device_key_label);
-							$device_key_label = str_replace("\${register_expires_$x}", $lines[$x]['register_expires'], $device_key_label);
-							$device_key_label = str_replace("\${sip_transport_$x}", $lines[$x]['sip_transport'], $device_key_label);
-							$device_key_label = str_replace("\${sip_port_$x}", $lines[$x]['sip_port'], $device_key_label);
-							$device_key_label = str_replace("\${server_address_$x}", $lines[$x]['server_address'], $device_key_label);
-							$device_key_label = str_replace("\${outbound_proxy_$x}", $lines[$x]['outbound_proxy'], $device_key_label);
-							$device_key_label = str_replace("\${display_name_$x}", $lines[$x]['display_name'], $device_key_label);
-
-						//add general variables
-							$device_key_value = str_replace("\${domain_name}", $domain_name, $device_key_value);
-							$device_key_extension = str_replace("\${domain_name}", $domain_name, $device_key_extension);
-							$device_key_label = str_replace("\${domain_name}", $domain_name, $device_key_label);
-
-						//grandstream modes are different based on the category
-							if ($device_vendor == "grandstream") {
-								if ($device_key_category == "line") {
-									switch ($device_key_type) {
-										case "line": $device_key_type  = "0"; break;
-										case "shared line": $device_key_type  = "1"; break;
-										case "speed dial": $device_key_type  = "10"; break;
-										case "blf": $device_key_type  = "11"; break;
-										case "presence watcher": $device_key_type  = "12"; break;
-										case "eventlist blf": $device_key_type  = "13"; break;
-										case "speed dial active": $device_key_type  = "14"; break;
-										case "dial dtmf": $device_key_type  = "15"; break;
-										case "voicemail": $device_key_type  = "16"; break;
-										case "call return": $device_key_type  = "17"; break;
-										case "transfer": $device_key_type  = "18"; break;
-										case "call park": $device_key_type  = "19"; break;
-										case "intercom": $device_key_type  = "20"; break;
-										case "ldap search": $device_key_type  = "21"; break;
-									}
-								}
-								if ($device_key_category == "memory" || $device_key_category == "expansion") {
-									switch ($device_key_type) {
-										case "speed dial": $device_key_type  = "0"; break;
-										case "blf": $device_key_type  = "1"; break;
-										case "presence watcher": $device_key_type  = "2"; break;
-										case "eventlist blf": $device_key_type  = "3"; break;
-										case "speed dial active": $device_key_type  = "4"; break;
-										case "dial dtmf": $device_key_type  = "5"; break;
-										case "voicemail": $device_key_type  = "6"; break;
-										case "call return": $device_key_type  = "7"; break;
-										case "transfer": $device_key_type  = "8"; break;
-										case "call park": $device_key_type  = "9"; break;
-										case "intercom": $device_key_type  = "10"; break;
-										case "ldap search": $device_key_type  = "11"; break;
-									}
-								}
-							}
-
-						//assign the variables
-							if (strlen($device_key_category) == 0) {
-								$view->assign("key_id_".$device_key_id, $device_key_id);
-								$view->assign("key_type_".$device_key_id, $device_key_type);
-								$view->assign("key_line_".$device_key_id, $device_key_line);
-								$view->assign("key_value_".$device_key_id, $device_key_value);
-								$view->assign("key_extension_".$device_key_id, $device_key_extension);
-								$view->assign("key_label_".$device_key_id, $device_key_label);
-							}
-							else {
-								$view->assign($device_key_category."_key_id_".$device_key_id, $device_key_id);
-								$view->assign($device_key_category."_key_type_".$device_key_id, $device_key_type);
-								$view->assign($device_key_category."_key_line_".$device_key_id, $device_key_line);
-								$view->assign($device_key_category."_key_value_".$device_key_id, $device_key_value);
-								$view->assign($device_key_category."_key_extension_".$device_key_id, $device_key_extension);
-								$view->assign($device_key_category."_key_label_".$device_key_id, $device_key_label);
-							}
-					}
-					unset ($prep_statement);
-
-				//set the mac address in the correct format
-					$mac = $this->format_mac($mac, $device_vendor);
-
-				//replace the variables in the template in the future loop through all the line numbers to do a replace for each possible line number
-					$view->assign("mac" , $mac);
-					$view->assign("label", $device_label);
-					$view->assign("firmware_version", $device_firmware_version);
-					$view->assign("domain_name", $domain_name);
-					$view->assign("project_path", PROJECT_PATH);
-					$view->assign("server1_address", $server1_address);
-					$view->assign("proxy1_address", $proxy1_address);
-					$view->assign("user_id",$user_id);
-					$view->assign("password",$password);
-					$view->assign("template",$device_template);
-
-				//replace the dynamic provision variables that are defined in default, domain, and device settings
-					foreach($provision as $key=>$val) {
-						$view->assign($key, $val);
-					}
-
-				//set the template directory
-					if (strlen($provision["template_dir"]) > 0) {
-						$template_dir = $provision["template_dir"];
-					}
-
-				//if the domain name directory exists then only use templates from it
-					if (is_dir($template_dir.'/'.$domain_name)) {
-						$device_template = $domain_name.'/'.$device_template;
-					}
-
-				//if $file is not provided then look for a default file that exists
-					if (strlen($file) == 0) {
-						if (file_exists($template_dir."/".$device_template ."/{\$mac}")) {
-							$file = "{\$mac}";
-						}
-						elseif (file_exists($template_dir."/".$device_template ."/{\$mac}.xml")) {
-							$file = "{\$mac}.xml";
-						}
-						elseif (file_exists($template_dir."/".$device_template ."/{\$mac}.cfg")) {
-							$file = "{\$mac}.cfg";
-						}
-						else {
-							echo "file not found";
-							exit;
-						}
-					}
-					else {
-						//make sure the file exists
-						if (!file_exists($template_dir."/".$device_template ."/".$file)) {
-							echo "file not found";
-							if ($_SESSION['provision']['debug']['boolean'] == 'true'){
-								echo ":$template_dir/$device_template/$file
"; - echo "template_dir: $template_dir
"; - echo "device_template: $device_template
"; - echo "file: $file"; - } - exit; - } - } - - //output template to string for header processing - $file_contents = $view->render($file); - - //log file for testing - if ($_SESSION['provision']['debug']['boolean'] == 'true'){ - $tmp_file = "/tmp/provisioning_log.txt"; - $fh = fopen($tmp_file, 'w') or die("can't open file"); - $tmp_string = $mac."\n"; - fwrite($fh, $tmp_string); - fclose($fh); - } - //returned the rendered template - return $file_contents; - - } //end render function - - - function write() { - - //set default variables - $dir_count = 0; - $file_count = 0; - $row_count = 0; - $tmp_array = ''; - $i = 0; - - //build the provision array - foreach($_SESSION['provision'] as $key=>$val) { - if (strlen($val['var']) > 0) { $value = $val['var']; } - if (strlen($val['text']) > 0) { $value = $val['text']; } - $provision[$key] = $value; - } - - //get the devices - $sql = "select * from v_devices "; - //$sql .= "where domain_uuid = '".$this->domain_uuid."' "; - $prep_statement = $this->db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - //get the values from the database and set as variables - $domain_uuid = $row["domain_uuid"]; - $device_uuid = $row["device_uuid"]; - $device_mac_address = $row["device_mac_address"]; - $device_label = $row["device_label"]; - $device_vendor = strtolower($row["device_vendor"]); - $device_model = $row["device_model"]; - $device_firmware_version = $row["device_firmware_version"]; - $device_enabled = $row["device_enabled"]; - $device_template = $row["device_template"]; - $device_username = $row["device_username"]; - $device_password = $row["device_password"]; - $device_description = $row["device_description"]; - - //loop through the provision template directory - clearstatcache(); - $dir_list = ''; - $file_list = ''; - if (strlen($device_template) > 0) { - $dir_list = opendir($this->template_dir."/".$device_template); - $dir_array = array(); - while (false !== ($file = readdir($dir_list))) { - if ($file != "." AND $file != ".."){ - $new_path = $dir.'/'.$file; - $level = explode('/',$new_path); - if (substr($new_path, -4) == ".svn" || - substr($new_path, -4) == ".git") { - //ignore .svn and .git dir and subdir - } - elseif (substr($new_path, -3) == ".db") { - //ignore .db files - } - else { - $dir_array[] = $new_path; - } - if ($x > 1000) { break; }; - $x++; - } - } - } - - //asort($dir_array); - foreach ($dir_array as $new_path){ - $level = explode('/',$new_path); - if (is_dir($new_path)) { - $dir_name = end($level); - //$file_list .= "$dir_name\n"; - //$dir_list .= recur_dir($new_path); - } - else { - $file_name = end($level); - //debug information - //$file_size = round(filesize($new_path)/1024, 2); - //echo $this->template_dir."/".$device_template."/".$file_name." $file_size\n"; - //write the configuration to the directory - if (strlen($provision["path"]) > 0) { - $dir_array = explode(";", $provision["path"]); - foreach($dir_array as $directory) { - - if (file_exists($this->template_dir."/".$device_template."/".$file_name)) { - //output template to string for header processing - //output template to string for header processing - $prov->domain_uuid = $domain_uuid; - $this->mac = $device_mac_address; - $this->file = $file_name; - $file_contents = $this->render(); - - //format the mac address - $mac = $this->format_mac($device_mac_address, $device_vendor); - - //replace {$mac} in the file name - $file_name = str_replace("{\$mac}", $mac, $file_name); - - //write the file - //echo $directory.'/'.$file_name."\n"; - $fh = fopen($directory.'/'.$file_name,"w") or die("Unable to write to $directory for provisioning. Make sure the path exists and permissons are set correctly."); - fwrite($fh, $file_contents); - fclose($fh); - } - } - unset($file_name); - } - } - } //end for each - closedir($dir_list); - //echo "
\n"; - } - unset ($prep_statement); - } //end write function - } //end provision class - + + Copyright (C) 2014-2016 + All Rights Reserved. + + Contributor(s): + Mark J Crane + Luis Daniel Lucio Quiroz +*/ +include "root.php"; + +//define the provision class + class provision { + public $db; + public $domain_uuid; + public $domain_name; + public $template_dir; + public $mac; + + public function __construct() { + //get the database object + global $db; + $this->db = $db; + //set the default template directory + if (PHP_OS == "Linux") { + //set the default template dir + if (strlen($this->template_dir) == 0) { + if (file_exists('/etc/fusionpbx/resources/templates/provision')) { + $this->template_dir = '/etc/fusionpbx/resources/templates/provision'; + } + else { + $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; + } + } + } elseif (PHP_OS == "FreeBSD") { + //if the FreeBSD port is installed use the following paths by default. + if (file_exists('/usr/local/etc/fusionpbx/resources/templates/provision')) { + if (strlen($this->template_dir) == 0) { + $this->template_dir = '/usr/local/etc/fusionpbx/resources/templates/provision'; + } + else { + $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; + } + } + else { + if (strlen($this->template_dir) == 0) { + $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; + } + else { + $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; + } + } + } elseif (PHP_OS == "NetBSD") { + //set the default template_dir + if (strlen($this->template_dir) == 0) { + $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; + } + } elseif (PHP_OS == "OpenBSD") { + //set the default template_dir + if (strlen($this->template_dir) == 0) { + $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; + } + } else { + //set the default template_dir + if (strlen($this->template_dir) == 0) { + $this->template_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/templates/provision'; + } + } + + //normalize the mac address + if (isset($this->mac)) { + $this->mac = strtolower(preg_replace('#[^a-fA-F0-9./]#', '', $this->mac)); + } + } + + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + public function get_domain_uuid() { + return $this->domain_uuid; + } + + //define the function which checks to see if the mac address exists in devices + private function mac_exists($mac) { + //normalize the mac address + $mac = strtolower(preg_replace('#[^a-fA-F0-9./]#', '', $mac)); + //check in the devices table for a specific mac address + $sql = "SELECT count(*) as count FROM v_devices "; + $sql .= "WHERE device_mac_address=:mac "; + $prep_statement = $this->db->prepare(check_sql($sql)); + if ($prep_statement) { + //$prep_statement->bindParam(':domain_uuid', $domain_uuid); + $prep_statement->bindParam(':mac', $mac); + $prep_statement->execute(); + $row = $prep_statement->fetch(); + $count = $row['count']; + if ($row['count'] > 0) { + return true; + } + else { + return false; + } + } + else { + return false; + } + } + + //set the mac address in the correct format for the specific vendor + public function format_mac($mac, $vendor) { + switch (strtolower($vendor)) { + case "aastra": + $mac = strtoupper($mac); + break; + case "cisco": + $mac = strtoupper($mac); + break; + case "linksys": + $mac = strtolower($mac); + break; + case "mitel": + $mac = strtoupper($mac); + break; + case "polycom": + $mac = strtolower($mac); + break; + case "snom": + $mac = strtolower($mac); + break; + default: + $mac = strtolower($mac); + $mac = substr($mac, 0,2).'-'.substr($mac, 2,2).'-'.substr($mac, 4,2).'-'.substr($mac, 6,2).'-'.substr($mac, 8,2).'-'.substr($mac, 10,2); + } + return $mac; + } + + //define a function to check if a contact exists in the contacts array + private function contact_exists($contacts, $uuid) { + if (is_array($contacts[$uuid])) { + return true; + } + else { + return false; + } + } + + public function render() { + + //debug + $debug = $_REQUEST['debug']; // array + + //get the variables + $domain_uuid = $this->domain_uuid; + $device_template = $this->device_template; + $template_dir = $this->template_dir; + $mac = $this->mac; + $file = $this->file; + + //set the mac address to lower case to be consistent with the database + $mac = strtolower($mac); + + //get the device template + if (strlen($_REQUEST['template']) > 0) { + $device_template = $_REQUEST['template']; + $search = array('..', '/./'); + $device_template = str_replace($search, "", $device_template); + $device_template = str_replace('//', '/', $device_template); + } + + //remove ../ and slashes in the file name + $search = array('..', '/', '\\', '/./', '//'); + $file = str_replace($search, "", $file); + + //get the domain_name + if (strlen($domain_name) == 0) { + $sql = "SELECT domain_name FROM v_domains "; + $sql .= "WHERE domain_uuid=:domain_uuid "; + $prep_statement = $this->db->prepare(check_sql($sql)); + if ($prep_statement) { + //use the prepared statement + $prep_statement->bindParam(':domain_uuid', $domain_uuid); + $prep_statement->execute(); + $row = $prep_statement->fetch(); + unset($prep_statement); + //set the variables from values in the database + $domain_name = $row["domain_name"]; + } + } + + //build the provision array + foreach($_SESSION['provision'] as $key=>$val) { + if (strlen($val['var']) > 0) { $value = $val['var']; } + if (strlen($val['text']) > 0) { $value = $val['text']; } + $provision[$key] = $value; + } + + //check to see if the mac_address exists in devices + if (strlen($_REQUEST['user_id']) == 0 || strlen($_REQUEST['userid']) == 0) { + if ($this->mac_exists($mac)) { + //get the device_template + if (strlen($device_template) == 0) { + $sql = "SELECT * FROM v_devices "; + $sql .= "WHERE device_mac_address=:mac "; + if($provision['http_domain_filter'] == "true") { + $sql .= "AND domain_uuid=:domain_uuid "; + } + //$sql .= "WHERE device_mac_address= '$mac' "; + $prep_statement_2 = $this->db->prepare(check_sql($sql)); + if ($prep_statement_2) { + //use the prepared statement + $prep_statement_2->bindParam(':mac', $mac); + if($provision['http_domain_filter'] == "true") { + $prep_statement_2->bindParam(':domain_uuid', $domain_uuid); + } + $prep_statement_2->execute(); + $row = $prep_statement_2->fetch(); + //set the variables from values in the database + $device_uuid = $row["device_uuid"]; + $device_label = $row["device_label"]; + if (strlen($row["device_vendor"]) > 0) { + $device_vendor = strtolower($row["device_vendor"]); + } + $device_model = $row["device_model"]; + $device_firmware_version = $row["device_firmware_version"]; + $device_enabled = $row["device_enabled"]; + $device_template = $row["device_template"]; + $device_profile_uuid = $row["device_profile_uuid"]; + $device_description = $row["device_description"]; + } + } + + //find a template that was defined on another phone and use that as the default. + if (strlen($device_template) == 0) { + $sql = "SELECT * FROM v_devices "; + $sql .= "WHERE domain_uuid=:domain_uuid "; + $sql .= "limit 1 "; + $prep_statement_3 = $this->db->prepare(check_sql($sql)); + if ($prep_statement_3) { + $prep_statement_3->bindParam(':domain_uuid', $domain_uuid); + $prep_statement_3->execute(); + $row = $prep_statement_3->fetch(); + $device_label = $row["device_label"]; + $device_vendor = strtolower($row["device_vendor"]); + $device_model = $row["device_model"]; + $device_firmware_version = $row["device_firmware_version"]; + $device_enabled = $row["device_enabled"]; + $device_template = $row["device_template"]; + $device_profile_uuid = $row["device_profile_uuid"]; + $device_description = $row["device_description"]; + } + } + } + else { + //use the user_agent to pre-assign a template for 1-hit provisioning. Enter the a unique string to match in the user agent, and the template it should match. + $template_list=array( + "Linksys/SPA-2102"=>"linksys/spa2102", + "Linksys/SPA-3102"=>"linksys/spa3102", + "Linksys/SPA-9212"=>"linksys/spa921", + "Cisco/SPA301"=>"cisco/spa301", + "Cisco/SPA301D"=>"cisco/spa302d", + "Cisco/SPA303"=>"cisco/spa303", + "Cisco/SPA501G"=>"cisco/spa501g", + "Cisco/SPA502G"=>"cisco/spa502g", + "Cisco/SPA504G"=>"cisco/spa504g", + "Cisco/SPA508G"=>"cisco/spa508g", + "Cisco/SPA509G"=>"cisco/spa509g", + "Cisco/SPA512G"=>"cisco/spa512g", + "Cisco/SPA514G"=>"cisco/spa514g", + "Cisco/SPA525G2"=>"cisco/spa525g2", + "snom300-SIP"=>"snom/300", + "snom320-SIP"=>"snom/320", + "snom360-SIP"=>"snom/360", + "snom370-SIP"=>"snom/370", + "snom820-SIP"=>"snom/820", + "snom-m3-SIP"=>"snom/m3", + "yealink SIP-T20"=>"yealink/t20", + "yealink SIP-T22"=>"yealink/t22", + "yealink SIP-T26"=>"yealink/t26", + "Yealink SIP-T32"=>"yealink/t32", + "HW GXP1450"=>"grandstream/gxp1450", + "HW GXP2124"=>"grandstream/gxp2124", + "HW GXV3140"=>"grandstream/gxv3140", + "HW GXV3175"=>"grandstream/gxv3175", + "Wget/1.11.3"=>"konftel/kt300ip" + ); + + foreach ($template_list as $key=>$val){ + if(stripos($_SERVER['HTTP_USER_AGENT'],$key)!== false) { + $device_template = $val; + break; + } + } + unset($template_list); + + //mac address does not exist in the table so add it + if ($_SESSION['provision']['auto_insert_enabled']['boolean'] == "true" and strlen($domain_uuid) > 0) { + $device_uuid = uuid(); + $sql = "INSERT INTO v_devices "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "device_uuid, "; + $sql .= "device_mac_address, "; + $sql .= "device_vendor, "; + $sql .= "device_model, "; + $sql .= "device_enabled, "; + $sql .= "device_template, "; + $sql .= "device_description "; + $sql .= ") "; + $sql .= "VALUES "; + $sql .= "("; + $sql .= "'".$domain_uuid."', "; + $sql .= "'$device_uuid', "; + $sql .= "'$mac', "; + $sql .= "'$device_vendor', "; + $sql .= "'', "; + $sql .= "'true', "; + $sql .= "'$device_template', "; + $sql .= "'auto {$_SERVER['HTTP_USER_AGENT']}' "; + $sql .= ")"; + $this->db->exec(check_sql($sql)); + unset($sql); + } + } + } + + //alternate device_uuid + if (strlen($device_uuid) > 0) { + $sql = "SELECT * FROM v_devices "; + $sql .= "WHERE device_uuid = '".$device_uuid."' "; + if($provision['http_domain_filter'] == "true") { + $sql .= "AND domain_uuid=:domain_uuid "; + } + $prep_statement_3 = $this->db->prepare(check_sql($sql)); + if ($prep_statement_3) { + if($provision['http_domain_filter'] == "true") { + $prep_statement_3->bindParam(':domain_uuid', $domain_uuid); + } + $prep_statement_3->execute(); + $row = $prep_statement_3->fetch(); + $device_uuid_alternate = $row["device_uuid_alternate"]; + if (is_uuid($device_uuid_alternate)) { + //override the original device_uuid + $device_uuid = $device_uuid_alternate; + //get the new devices information + $sql = "SELECT * FROM v_devices "; + $sql .= "WHERE device_uuid = '".$device_uuid."' "; + if($provision['http_domain_filter'] == "true") { + $sql .= "AND domain_uuid=:domain_uuid "; + } + $prep_statement_4 = $this->db->prepare(check_sql($sql)); + if ($prep_statement_4) { + if($provision['http_domain_filter'] == "true") { + $prep_statement_4->bindParam(':domain_uuid', $domain_uuid); + } + $prep_statement_4->execute(); + $row = $prep_statement_4->fetch(); + $device_label = $row["device_label"]; + $device_firmware_version = $row["device_firmware_version"]; + $device_enabled = $row["device_enabled"]; + //keep the original template + $device_profile_uuid = $row["device_profile_uuid"]; + $device_description = $row["device_description"]; + } + unset($prep_statement_4); + } + } + unset($prep_statement_3); + } + + //get the device settings table in the provision category and update the provision array + if (strlen($device_uuid) > 0) { + $sql = "SELECT * FROM v_device_settings "; + $sql .= "WHERE device_uuid = '".$device_uuid."' "; + $sql .= "AND device_setting_enabled = 'true' "; + $prep_statement = $this->db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + foreach($result as $row) { + $key = $row['device_setting_subcategory']; + $value = $row['device_setting_value']; + $provision[$key] = $value; + } + unset ($prep_statement); + } + + //initialize a template object + $view = new template(); + if (strlen($_SESSION['provision']['template_engine']['text']) > 0) { + $view->engine = $_SESSION['provision']['template_engine']['text']; //raintpl, smarty, twig + } + else { + $view->engine = "smarty"; + } + $view->template_dir = $template_dir ."/".$device_template."/"; + $view->cache_dir = $_SESSION['server']['temp']['dir']; + $view->init(); + + //replace the variables in the template in the future loop through all the line numbers to do a replace for each possible line number + + //get the time zone + $time_zone_name = $_SESSION['domain']['time_zone']['name']; + if (strlen($time_zone_name) > 0) { + $time_zone_offset_raw = get_time_zone_offset($time_zone_name)/3600; + $time_zone_offset_hours = floor($time_zone_offset_raw); + $time_zone_offset_minutes = ($time_zone_offset_raw - $time_zone_offset_hours) * 60; + $time_zone_offset_minutes = number_pad($time_zone_offset_minutes, 2); + if ($time_zone_offset_raw > 0) { + $time_zone_offset_hours = number_pad($time_zone_offset_hours, 2); + $time_zone_offset_hours = "+".$time_zone_offset_hours; + } + else { + $time_zone_offset_hours = str_replace("-", "", $time_zone_offset_hours); + $time_zone_offset_hours = "-".number_pad($time_zone_offset_hours, 2); + } + $time_zone_offset = $time_zone_offset_hours.":".$time_zone_offset_minutes; + $view->assign("time_zone_offset" , $time_zone_offset); + } + + //create a mac address with back slashes for backwards compatability + $mac_dash = substr($mac, 0,2).'-'.substr($mac, 2,2).'-'.substr($mac, 4,2).'-'.substr($mac, 6,2).'-'.substr($mac, 8,2).'-'.substr($mac, 10,2); + + //get the provisioning information from device lines table + if (strlen($device_uuid) > 0) { + //get the device lines array + $sql = "select * from v_device_lines "; + $sql .= "where device_uuid = '".$device_uuid."' "; + $sql .= "and (enabled = 'true' or enabled is null or enabled = '') "; + $prep_statement = $this->db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_lines = $prep_statement->fetchAll(PDO::FETCH_NAMED); + //assign the keys array + $view->assign("lines", $device_lines); + //set the variables + foreach($device_lines as $row) { + //set the variables + $line_number = $row['line_number']; + $register_expires = $row['register_expires']; + $sip_transport = strtolower($row['sip_transport']); + $sip_port = $row['sip_port']; + + //set defaults + if (strlen($register_expires) == 0) { $register_expires = "120"; } + if (strlen($sip_transport) == 0) { $sip_transport = "tcp"; } + if (strlen($sip_port) == 0) { + if ($line_number == "" || $line_number == "1") { + $sip_port = "5060"; + } + else { + $sip_port = "506".($line_number + 1); + } + } + + //set a lines array index is the line number + $lines[$line_number]['register_expires'] = $register_expires; + $lines[$line_number]['sip_transport'] = strtolower($sip_transport); + $lines[$line_number]['sip_port'] = $sip_port; + $lines[$line_number]['server_address'] = $row["server_address"]; + $lines[$line_number]['outbound_proxy'] = $row["outbound_proxy"]; + $lines[$line_number]['display_name'] = $row["display_name"]; + $lines[$line_number]['auth_id'] = $row["auth_id"]; + $lines[$line_number]['user_id'] = $row["user_id"]; + $lines[$line_number]['password'] = $row["password"]; + + //assign the variables + $view->assign("server_address_".$line_number, $row["server_address"]); + $view->assign("outbound_proxy_".$line_number, $row["outbound_proxy"]); + $view->assign("display_name_".$line_number, $row["display_name"]); + $view->assign("auth_id_".$line_number, $row["auth_id"]); + $view->assign("user_id_".$line_number, $row["user_id"]); + $view->assign("user_password_".$line_number, $row["password"]); + $view->assign("sip_transport_".$line_number, $sip_transport); + $view->assign("sip_port_".$line_number, $sip_port); + $view->assign("register_expires_".$line_number, $register_expires); + } + unset ($prep_statement); + } + + //get the list of contact directly assigned to the user + //get the user_uuid to find the contacts assigned to the user and the groups the user is a member of. + if (strlen($device_uuid) > 0 and strlen($domain_uuid) > 0) { + foreach ($device_lines as &$line) { + //get the user_uuid assigned to the extension_uuid + if ($_SESSION['provision']['contact_users']['boolean'] == "true" || $_SESSION['provision']['contact_groups']['boolean'] == "true") { + $sql = "select user_uuid from v_extension_users "; + $sql .= "where extension_uuid in ( "; + $sql .= " select extension_uuid from v_extensions "; + $sql .= " where (extension = '".$line["user_id"]."' or number_alias = '".$line["user_id"]."') "; + $sql .= " and domain_uuid = '$domain_uuid' "; + $sql .= ") "; + $sql .= "and domain_uuid = '$domain_uuid' "; + $prep_statement = $this->db->prepare(check_sql($sql)); + $prep_statement->execute(); + $extension_users = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset($prep_statement); + foreach ($extension_users as &$row) { + $user_uuid = $row["user_uuid"]; + } + } + + //get the contacts assigned to the groups and add to the contacts array + if ($_SESSION['provision']['contact_groups']['boolean'] == "true") { + $sql = "select c.contact_uuid, c.contact_organization, c.contact_name_given, c.contact_name_family, "; + $sql .= "c.contact_type, c.contact_category, p.phone_label,"; + $sql .= "p.phone_number, p.phone_extension "; + $sql .= "from v_contacts as c, v_contact_phones as p "; + $sql .= "where c.contact_uuid in ( "; + $sql .= " select contact_uuid from v_contact_groups "; + $sql .= " where group_uuid in (' "; + $sql .= " select group_uuid from v_group_users "; + $sql .= " where user_uuid = '".$user_uuid."' "; + $sql .= " and domain_uuid = '$domain_uuid' "; + $sql .= " ) "; + $sql .= "and domain_uuid = '$domain_uuid' "; + $sql .= ") "; + //echo $sql."\n"; + $prep_statement = $this->db->prepare(check_sql($sql)); + $prep_statement->execute(); + $contact_groups = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset($prep_statement); + foreach ($contact_groups as $row) { + //get the contact_uuid + $uuid = $row['contact_uuid']; + //add the contacts to the contact array + if (!$this->contact_exists($contacts, $uuid)) { + $contacts[$uuid]['category'] = 'groups'; + $contacts[$uuid]['contact_uuid'] = $row['contact_uuid']; + $contacts[$uuid]['contact_type'] = $row['contact_type']; + $contacts[$uuid]['contact_category'] = $row['contact_category']; + $contacts[$uuid]['contact_organization'] = $row['contact_organization']; + $contacts[$uuid]['contact_name_given'] = $row['contact_name_given']; + $contacts[$uuid]['contact_name_family'] = $row['contact_name_family']; + $contacts[$uuid]['phone_label'] = $row['phone_label']; + $contacts[$uuid]['phone_number'] = $row['phone_number']; + $contacts[$uuid]['phone_extension'] = $row['phone_extension']; + } + } + } + + //get the contacts assigned to the user and add to the contacts array + if ($_SESSION['provision']['contact_users']['boolean'] == "true") { + $sql = "select c.contact_uuid, c.contact_organization, c.contact_name_given, c.contact_name_family, "; + $sql .= "c.contact_type, c.contact_category, p.phone_label,"; + $sql .= "p.phone_number, p.phone_extension "; + $sql .= "from v_contacts as c, v_contact_phones as p "; + $sql .= "where c.contact_uuid in ( "; + $sql .= " select contact_uuid from v_contact_users "; + $sql .= " where user_uuid = '".$user_uuid."' "; + $sql .= " and domain_uuid = '$domain_uuid' "; + $sql .= ") "; + $sql .= "and c.contact_uuid = p.contact_uuid "; + $sql .= "and p.phone_type_voice = '1' "; + $sql .= "and c.domain_uuid = '$domain_uuid' "; + //echo $sql."\n"; + $prep_statement = $this->db->prepare(check_sql($sql)); + $prep_statement->execute(); + $user_contacts = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset($prep_statement); + foreach ($user_contacts as $row) { + //get the contact_uuid + $uuid = $row['contact_uuid']; + //add the contacts to the contact array + if (!$this->contact_exists($contacts, $uuid)) { + $contacts[$uuid]['category'] = 'users'; + $contacts[$uuid]['contact_uuid'] = $row['contact_uuid']; + $contacts[$uuid]['contact_type'] = $row['contact_type']; + $contacts[$uuid]['contact_category'] = $row['contact_category']; + $contacts[$uuid]['contact_organization'] = $row['contact_organization']; + $contacts[$uuid]['contact_name_given'] = $row['contact_name_given']; + $contacts[$uuid]['contact_name_family'] = $row['contact_name_family']; + $contacts[$uuid]['phone_label'] = $row['phone_label']; + $contacts[$uuid]['phone_number'] = $row['phone_number']; + $contacts[$uuid]['phone_extension'] = $row['phone_extension']; + } + } + } + } + } + + //get the extensions and add them to the contacts array + if (strlen($device_uuid) > 0 and strlen($domain_uuid) > 0 and $_SESSION['provision']['contact_extensions']['boolean'] == "true") { + //get contacts from the database + $sql = "select extension_uuid as contact_uuid, directory_full_name, "; + $sql .= "effective_caller_id_name, effective_caller_id_number, "; + $sql .= "number_alias, extension "; + $sql .= "from v_extensions "; + $sql .= "where domain_uuid = '".$domain_uuid."' "; + $sql .= "and enabled = 'true' "; + $sql .= "order by number_alias, extension asc "; + $prep_statement = $this->db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $extensions = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($extensions as $row) { + //get the contact_uuid + $uuid = $row['contact_uuid']; + //get the names + if (strlen($row['directory_full_name']) > 0) { + $name_array = explode(" ", $row['directory_full_name']); + } else { + $name_array = explode(" ", $row['effective_caller_id_name']); + } + $contact_name_given = array_shift($name_array); + $contact_name_family = trim(implode(' ', $name_array)); + //get the phone_extension + if (is_numeric($row['extension'])) { + $phone_extension = $row['extension']; + } + else { + $phone_extension = $row['number_alias']; + } + //save the contact array values + $contacts[$uuid]['category'] = 'extensions'; + $contacts[$uuid]['contact_uuid'] = $row['contact_uuid']; + $contacts[$uuid]['contact_category'] = 'extensions'; + $contacts[$uuid]['contact_name_given'] = $contact_name_given; + $contacts[$uuid]['contact_name_family'] = $contact_name_family; + $contacts[$uuid]['phone_extension'] = $phone_extension; + //unset the variables + unset($name_array, $contact_name_given, $contact_name_family, $phone_extension); + } + } + } + + //assign the contacts array to the template + if (is_array($contacts)) { + $view->assign("contacts", $contacts); + unset($contacts); + } + + //get the provisioning information from device keys + if (strlen($device_uuid) > 0) { + //get the device keys array + $sql = "SELECT * FROM v_device_keys "; + $sql .= "WHERE ("; + $sql .= "device_uuid = '".$device_uuid."' "; + if (strlen($device_profile_uuid) > 0) { + $sql .= "or device_profile_uuid = '".$device_profile_uuid."' "; + } + $sql .= ") "; + $sql .= "AND (lower(device_key_vendor) = '".$device_vendor."' or device_key_vendor is null) "; + $sql .= "ORDER BY device_key_category asc, device_key_id asc, device_uuid desc"; + $prep_statement = $this->db->prepare(check_sql($sql)); + $prep_statement->execute(); + $device_keys = $prep_statement->fetchAll(PDO::FETCH_NAMED); + + //rebuild the array to allow profile keys to be overridden by keys assigned to this device + $x = 0; + $previous_category = ''; + $previous_id = ''; + foreach($device_keys as $row) { + //set the variables + if ($row['device_key_category'] == $previous_category && $row['device_key_id'] == $previous_id) { + $device_keys[$x]['device_key_override'] = "true"; + $device_keys[$x]['device_key_message'] = "value=".$device_keys[$x-1]['device_key_value']."&label=".$device_keys[$x-1]['device_key_label']; + unset($device_keys[$x-1]); + } + $device_keys[$x]['device_key_category'] = $row['device_key_category']; + $device_keys[$x]['device_key_id'] = $row['device_key_id']; //1 + $device_keys[$x]['device_key_type'] = $row['device_key_type']; //line, memory, expansion + $device_keys[$x]['device_key_line'] = $row['device_key_line']; + $device_keys[$x]['device_key_value'] = $row['device_key_value']; //1 + $device_keys[$x]['device_key_extension'] = $row['device_key_extension']; + $device_keys[$x]['device_key_label'] = $row['device_key_label']; //label + if (is_uuid($row['device_profile_uuid'])) { + $device_keys[$x]['device_key_owner'] = "profile"; + } + else { + $device_keys[$x]['device_key_owner'] = "device"; + } + //set previous values + $previous_category = $row['device_key_category']; + $previous_id = $row['device_key_id']; + //increment the key + $x++; + } + } + + //debug information + if ($debug == "array") { + echo "
\n";
+						print_r($device_keys);
+						echo "
\n";
+						exit;
+					}
+
+				//assign the keys array
+					$view->assign("keys", $device_keys);
+
+				//set the variables
+					foreach($device_keys as $row) {
+						//set the variables
+							$device_key_category = $row['device_key_category'];
+							$device_key_id = $row['device_key_id']; //1
+							$device_key_type = $row['device_key_type']; //line
+							$device_key_line = $row['device_key_line'];
+							$device_key_value = $row['device_key_value']; //1
+							$device_key_extension = $row['device_key_extension'];
+							$device_key_label = $row['device_key_label']; //label
+
+						//set the line key
+							$x = $device_key_line;
+
+						//add a simple variable with the index
+							if ($x === 0 || $x === 1) {
+								$device_key_value = str_replace("\${user_id}", $lines[$x]['user_id'], $device_key_value);
+								$device_key_value = str_replace("\${auth_id}", $lines[$x]['auth_id'], $device_key_value);
+								$device_key_value = str_replace("\${extension}", $lines[$x]['user_id'], $device_key_value);
+								$device_key_value = str_replace("\${password}", $lines[$x]['password'], $device_key_value);
+								$device_key_value = str_replace("\${register_expires}", $lines[$x]['register_expires'], $device_key_value);
+								$device_key_value = str_replace("\${sip_transport}", $lines[$x]['sip_transport'], $device_key_value);
+								$device_key_value = str_replace("\${sip_port}", $lines[$x]['sip_port'], $device_key_value);
+								$device_key_value = str_replace("\${server_address}", $lines[$x]['server_address'], $device_key_value);
+								$device_key_value = str_replace("\${outbound_proxy}", $lines[$x]['outbound_proxy'], $device_key_value);
+								$device_key_value = str_replace("\${display_name}", $lines[$x]['display_name'], $device_key_value);
+
+								$device_key_extension = str_replace("\${user_id}", $lines[$x]['user_id'], $device_key_extension);
+								$device_key_extension = str_replace("\${auth_id}", $lines[$x]['auth_id'], $device_key_extension);
+								$device_key_extension = str_replace("\${extension}", $lines[$x]['user_id'], $device_key_extension);
+								$device_key_extension = str_replace("\${password}", $lines[$x]['password'], $device_key_extension);
+								$device_key_extension = str_replace("\${register_expires}", $lines[$x]['register_expires'], $device_key_extension);
+								$device_key_extension = str_replace("\${sip_transport}", $lines[$x]['sip_transport'], $device_key_extension);
+								$device_key_extension = str_replace("\${sip_port}", $lines[$x]['sip_port'], $device_key_extension);
+								$device_key_extension = str_replace("\${server_address}", $lines[$x]['server_address'], $device_key_extension);
+								$device_key_extension = str_replace("\${outbound_proxy}", $lines[$x]['outbound_proxy'], $device_key_extension);
+								$device_key_extension = str_replace("\${display_name}", $lines[$x]['display_name'], $device_key_extension);
+
+								$device_key_label = str_replace("\${user_id}", $lines[$x]['user_id'], $device_key_label);
+								$device_key_label = str_replace("\${auth_id}", $lines[$x]['auth_id'], $device_key_label);
+								$device_key_label = str_replace("\${extension}", $lines[$x]['user_id'], $device_key_label);
+								$device_key_label = str_replace("\${password}", $lines[$x]['password'], $device_key_label);
+								$device_key_label = str_replace("\${register_expires}", $lines[$x]['register_expires'], $device_key_label);
+								$device_key_label = str_replace("\${sip_transport}", $lines[$x]['sip_transport'], $device_key_label);
+								$device_key_label = str_replace("\${sip_port}", $lines[$x]['sip_port'], $device_key_label);
+								$device_key_label = str_replace("\${server_address}", $lines[$x]['server_address'], $device_key_label);
+								$device_key_label = str_replace("\${outbound_proxy}", $lines[$x]['outbound_proxy'], $device_key_label);
+								$device_key_label = str_replace("\${display_name}", $lines[$x]['display_name'], $device_key_label);
+							}
+
+						//add variables with the index
+							$device_key_value = str_replace("\${user_id_$x}", $lines[$x]['user_id'], $device_key_value);
+							$device_key_value = str_replace("\${auth_id_$x}", $lines[$x]['auth_id'], $device_key_value);
+							$device_key_value = str_replace("\${extension_$x}", $lines[$x]['user_id'], $device_key_value);
+							$device_key_value = str_replace("\${password_$x}", $lines[$x]['password'], $device_key_value);
+							$device_key_value = str_replace("\${register_expires_$x}", $lines[$x]['register_expires'], $device_key_value);
+							$device_key_value = str_replace("\${sip_transport_$x}", $lines[$x]['sip_transport'], $device_key_value);
+							$device_key_value = str_replace("\${sip_port_$x}", $lines[$x]['sip_port'], $device_key_value);
+							$device_key_value = str_replace("\${server_address_$x}", $lines[$x]['server_address'], $device_key_value);
+							$device_key_value = str_replace("\${outbound_proxy_$x}", $lines[$x]['outbound_proxy'], $device_key_value);
+							$device_key_value = str_replace("\${display_name_$x}", $lines[$x]['display_name'], $device_key_value);
+
+							$device_key_extension = str_replace("\${user_id_$x}", $lines[$x]['user_id'], $device_key_label);
+							$device_key_extension = str_replace("\${auth_id_$x}", $lines[$x]['auth_id'], $device_key_label);
+							$device_key_extension = str_replace("\${extension_$x}", $lines[$x]['user_id'], $device_key_label);
+							$device_key_extension = str_replace("\${password_$x}", $lines[$x]['password'], $device_key_label);
+							$device_key_extension = str_replace("\${register_expires_$x}", $lines[$x]['register_expires'], $device_key_label);
+							$device_key_extension = str_replace("\${sip_transport_$x}", $lines[$x]['sip_transport'], $device_key_label);
+							$device_key_extension = str_replace("\${sip_port_$x}", $lines[$x]['sip_port'], $device_key_label);
+							$device_key_extension = str_replace("\${server_address_$x}", $lines[$x]['server_address'], $device_key_label);
+							$device_key_extension = str_replace("\${outbound_proxy_$x}", $lines[$x]['outbound_proxy'], $device_key_label);
+							$device_key_extension = str_replace("\${display_name_$x}", $lines[$x]['display_name'], $device_key_label);
+
+							$device_key_label = str_replace("\${user_id_$x}", $lines[$x]['user_id'], $device_key_label);
+							$device_key_label = str_replace("\${auth_id_$x}", $lines[$x]['auth_id'], $device_key_label);
+							$device_key_label = str_replace("\${extension_$x}", $lines[$x]['user_id'], $device_key_label);
+							$device_key_label = str_replace("\${password_$x}", $lines[$x]['password'], $device_key_label);
+							$device_key_label = str_replace("\${register_expires_$x}", $lines[$x]['register_expires'], $device_key_label);
+							$device_key_label = str_replace("\${sip_transport_$x}", $lines[$x]['sip_transport'], $device_key_label);
+							$device_key_label = str_replace("\${sip_port_$x}", $lines[$x]['sip_port'], $device_key_label);
+							$device_key_label = str_replace("\${server_address_$x}", $lines[$x]['server_address'], $device_key_label);
+							$device_key_label = str_replace("\${outbound_proxy_$x}", $lines[$x]['outbound_proxy'], $device_key_label);
+							$device_key_label = str_replace("\${display_name_$x}", $lines[$x]['display_name'], $device_key_label);
+
+						//add general variables
+							$device_key_value = str_replace("\${domain_name}", $domain_name, $device_key_value);
+							$device_key_extension = str_replace("\${domain_name}", $domain_name, $device_key_extension);
+							$device_key_label = str_replace("\${domain_name}", $domain_name, $device_key_label);
+
+						//grandstream modes are different based on the category
+							if ($device_vendor == "grandstream") {
+								if ($device_key_category == "line") {
+									switch ($device_key_type) {
+										case "line": $device_key_type  = "0"; break;
+										case "shared line": $device_key_type  = "1"; break;
+										case "speed dial": $device_key_type  = "10"; break;
+										case "blf": $device_key_type  = "11"; break;
+										case "presence watcher": $device_key_type  = "12"; break;
+										case "eventlist blf": $device_key_type  = "13"; break;
+										case "speed dial active": $device_key_type  = "14"; break;
+										case "dial dtmf": $device_key_type  = "15"; break;
+										case "voicemail": $device_key_type  = "16"; break;
+										case "call return": $device_key_type  = "17"; break;
+										case "transfer": $device_key_type  = "18"; break;
+										case "call park": $device_key_type  = "19"; break;
+										case "intercom": $device_key_type  = "20"; break;
+										case "ldap search": $device_key_type  = "21"; break;
+									}
+								}
+								if ($device_key_category == "memory" || $device_key_category == "expansion") {
+									switch ($device_key_type) {
+										case "speed dial": $device_key_type  = "0"; break;
+										case "blf": $device_key_type  = "1"; break;
+										case "presence watcher": $device_key_type  = "2"; break;
+										case "eventlist blf": $device_key_type  = "3"; break;
+										case "speed dial active": $device_key_type  = "4"; break;
+										case "dial dtmf": $device_key_type  = "5"; break;
+										case "voicemail": $device_key_type  = "6"; break;
+										case "call return": $device_key_type  = "7"; break;
+										case "transfer": $device_key_type  = "8"; break;
+										case "call park": $device_key_type  = "9"; break;
+										case "intercom": $device_key_type  = "10"; break;
+										case "ldap search": $device_key_type  = "11"; break;
+									}
+								}
+							}
+
+						//assign the variables
+							if (strlen($device_key_category) == 0) {
+								$view->assign("key_id_".$device_key_id, $device_key_id);
+								$view->assign("key_type_".$device_key_id, $device_key_type);
+								$view->assign("key_line_".$device_key_id, $device_key_line);
+								$view->assign("key_value_".$device_key_id, $device_key_value);
+								$view->assign("key_extension_".$device_key_id, $device_key_extension);
+								$view->assign("key_label_".$device_key_id, $device_key_label);
+							}
+							else {
+								$view->assign($device_key_category."_key_id_".$device_key_id, $device_key_id);
+								$view->assign($device_key_category."_key_type_".$device_key_id, $device_key_type);
+								$view->assign($device_key_category."_key_line_".$device_key_id, $device_key_line);
+								$view->assign($device_key_category."_key_value_".$device_key_id, $device_key_value);
+								$view->assign($device_key_category."_key_extension_".$device_key_id, $device_key_extension);
+								$view->assign($device_key_category."_key_label_".$device_key_id, $device_key_label);
+							}
+					}
+					unset ($prep_statement);
+
+				//set the mac address in the correct format
+					$mac = $this->format_mac($mac, $device_vendor);
+
+				//replace the variables in the template in the future loop through all the line numbers to do a replace for each possible line number
+					$view->assign("mac" , $mac);
+					$view->assign("label", $device_label);
+					$view->assign("firmware_version", $device_firmware_version);
+					$view->assign("domain_name", $domain_name);
+					$view->assign("project_path", PROJECT_PATH);
+					$view->assign("server1_address", $server1_address);
+					$view->assign("proxy1_address", $proxy1_address);
+					$view->assign("user_id",$user_id);
+					$view->assign("password",$password);
+					$view->assign("template",$device_template);
+
+				//replace the dynamic provision variables that are defined in default, domain, and device settings
+					foreach($provision as $key=>$val) {
+						$view->assign($key, $val);
+					}
+
+				//set the template directory
+					if (strlen($provision["template_dir"]) > 0) {
+						$template_dir = $provision["template_dir"];
+					}
+
+				//if the domain name directory exists then only use templates from it
+					if (is_dir($template_dir.'/'.$domain_name)) {
+						$device_template = $domain_name.'/'.$device_template;
+					}
+
+				//if $file is not provided then look for a default file that exists
+					if (strlen($file) == 0) {
+						if (file_exists($template_dir."/".$device_template ."/{\$mac}")) {
+							$file = "{\$mac}";
+						}
+						elseif (file_exists($template_dir."/".$device_template ."/{\$mac}.xml")) {
+							$file = "{\$mac}.xml";
+						}
+						elseif (file_exists($template_dir."/".$device_template ."/{\$mac}.cfg")) {
+							$file = "{\$mac}.cfg";
+						}
+						else {
+							echo "file not found";
+							exit;
+						}
+					}
+					else {
+						//make sure the file exists
+						if (!file_exists($template_dir."/".$device_template ."/".$file)) {
+							echo "file not found";
+							if ($_SESSION['provision']['debug']['boolean'] == 'true'){
+								echo ":$template_dir/$device_template/$file
"; + echo "template_dir: $template_dir
"; + echo "device_template: $device_template
"; + echo "file: $file"; + } + exit; + } + } + + //output template to string for header processing + $file_contents = $view->render($file); + + //log file for testing + if ($_SESSION['provision']['debug']['boolean'] == 'true'){ + $tmp_file = "/tmp/provisioning_log.txt"; + $fh = fopen($tmp_file, 'w') or die("can't open file"); + $tmp_string = $mac."\n"; + fwrite($fh, $tmp_string); + fclose($fh); + } + //returned the rendered template + return $file_contents; + + } //end render function + + + function write() { + + //set default variables + $dir_count = 0; + $file_count = 0; + $row_count = 0; + $tmp_array = ''; + $i = 0; + + //build the provision array + foreach($_SESSION['provision'] as $key=>$val) { + if (strlen($val['var']) > 0) { $value = $val['var']; } + if (strlen($val['text']) > 0) { $value = $val['text']; } + $provision[$key] = $value; + } + + //get the devices + $sql = "select * from v_devices "; + //$sql .= "where domain_uuid = '".$this->domain_uuid."' "; + $prep_statement = $this->db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + //get the values from the database and set as variables + $domain_uuid = $row["domain_uuid"]; + $device_uuid = $row["device_uuid"]; + $device_mac_address = $row["device_mac_address"]; + $device_label = $row["device_label"]; + $device_vendor = strtolower($row["device_vendor"]); + $device_model = $row["device_model"]; + $device_firmware_version = $row["device_firmware_version"]; + $device_enabled = $row["device_enabled"]; + $device_template = $row["device_template"]; + $device_username = $row["device_username"]; + $device_password = $row["device_password"]; + $device_description = $row["device_description"]; + + //loop through the provision template directory + clearstatcache(); + $dir_list = ''; + $file_list = ''; + if (strlen($device_template) > 0) { + $dir_list = opendir($this->template_dir."/".$device_template); + $dir_array = array(); + while (false !== ($file = readdir($dir_list))) { + if ($file != "." AND $file != ".."){ + $new_path = $dir.'/'.$file; + $level = explode('/',$new_path); + if (substr($new_path, -4) == ".svn" || + substr($new_path, -4) == ".git") { + //ignore .svn and .git dir and subdir + } + elseif (substr($new_path, -3) == ".db") { + //ignore .db files + } + else { + $dir_array[] = $new_path; + } + if ($x > 1000) { break; }; + $x++; + } + } + } + + //asort($dir_array); + foreach ($dir_array as $new_path){ + $level = explode('/',$new_path); + if (is_dir($new_path)) { + $dir_name = end($level); + //$file_list .= "$dir_name\n"; + //$dir_list .= recur_dir($new_path); + } + else { + $file_name = end($level); + //debug information + //$file_size = round(filesize($new_path)/1024, 2); + //echo $this->template_dir."/".$device_template."/".$file_name." $file_size\n"; + //write the configuration to the directory + if (strlen($provision["path"]) > 0) { + $dir_array = explode(";", $provision["path"]); + foreach($dir_array as $directory) { + + if (file_exists($this->template_dir."/".$device_template."/".$file_name)) { + //output template to string for header processing + //output template to string for header processing + $prov->domain_uuid = $domain_uuid; + $this->mac = $device_mac_address; + $this->file = $file_name; + $file_contents = $this->render(); + + //format the mac address + $mac = $this->format_mac($device_mac_address, $device_vendor); + + //replace {$mac} in the file name + $file_name = str_replace("{\$mac}", $mac, $file_name); + + //write the file + //echo $directory.'/'.$file_name."\n"; + $fh = fopen($directory.'/'.$file_name,"w") or die("Unable to write to $directory for provisioning. Make sure the path exists and permissons are set correctly."); + fwrite($fh, $file_contents); + fclose($fh); + } + } + unset($file_name); + } + } + } //end for each + closedir($dir_list); + //echo "
\n"; + } + unset ($prep_statement); + } //end write function + } //end provision class + ?> \ No newline at end of file diff --git a/app/ring_groups/app_languages.php b/app/ring_groups/app_languages.php index 878084920b..450eb5c3dc 100644 --- a/app/ring_groups/app_languages.php +++ b/app/ring_groups/app_languages.php @@ -1,785 +1,785 @@ - \ No newline at end of file diff --git a/app/scripts/app_defaults.php b/app/scripts/app_defaults.php index 2cb75df991..6d9c3cb37f 100644 --- a/app/scripts/app_defaults.php +++ b/app/scripts/app_defaults.php @@ -1,34 +1,34 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2016 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -//process this only one time -if ($domains_processed == 1) { - $obj = new scripts; - $obj->copy_files(); - $obj->write_config(); -} - + + Portions created by the Initial Developer are Copyright (C) 2008-2016 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +//process this only one time +if ($domains_processed == 1) { + $obj = new scripts; + $obj->copy_files(); + $obj->write_config(); +} + ?> \ No newline at end of file diff --git a/app/scripts/resources/classes/scripts.php b/app/scripts/resources/classes/scripts.php index 6ead2e7db9..53936fc59f 100644 --- a/app/scripts/resources/classes/scripts.php +++ b/app/scripts/resources/classes/scripts.php @@ -1,286 +1,286 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2016 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - - -/** - * scripts class provides methods for creating the config.lua and copying switch scripts - * - * @method string correct_path - * @method string copy_files - * @method string write_config - */ -if (!class_exists('scripts')) { - class scripts { - - public $db; - public $db_type; - public $db_name; - public $db_host; - public $db_port; - public $db_path; - public $db_username; - public $db_password; - public $dsn_name; - public $dsn_username; - public $dsn_password; - - /** - * Called when the object is created - */ - public function __construct() { - //connect to the database if not connected - require_once "resources/classes/database.php"; - $database = new database; - $database->connect(); - $this->db = $database->db; - $this->db_type = $database->type; - $this->db_name = $database->db_name; - $this->db_host = $database->host; - $this->db_port = $database->port; - $this->db_path = $database->path; - $this->db_username = $database->username; - $this->db_password = $database->password; - } - - /** - * Called when there are no references to a particular object - * unset the variables used in the class - */ - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - /** - * Corrects the path for specifically for windows - */ - private function correct_path($path) { - global $IS_WINDOWS; - if ($IS_WINDOWS == null) { - if (stristr(PHP_OS, 'WIN')) { $IS_WINDOWS = true; } else { $IS_WINDOWS = false; } - } - if ($IS_WINDOWS) { - return str_replace('\\', '/', $path); - } - return $path; - } - - /** - * Copy the switch scripts from the web directory to the switch directory - */ - public function copy_files() { - if (strlen($_SESSION['switch']['scripts']['dir']) > 0) { - $dst_dir = $_SESSION['switch']['scripts']['dir']; - if(strlen($dst_dir) == 0) { - throw new Exception("Cannot copy scripts the 'script_dir' is empty"); - } - if (file_exists($dst_dir)) { - //get the source directory - if (file_exists('/usr/share/examples/fusionpbx/resources/install/scripts')){ - $src_dir = '/usr/share/examples/fusionpbx/resources/install/scripts'; - } - else { - $src_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/scripts'; - } - if (is_readable($dst_dir)) { - recursive_copy($src_dir, $dst_dir); - unset($src_dir, $dst_dir); - }else{ - throw new Exception("Cannot read from '$src_dir' to get the scripts"); - } - chmod($dst_dir, 0774); - } else { - throw new Exception("Scripts directory doesn't exist"); - } - } - } - - /** - * Writes the config.lua - */ - public function write_config() { - if (is_dir($_SESSION['switch']['scripts']['dir'])) { - - //replace the backslash with a forward slash - $this->db_path = str_replace("\\", "/", $this->db_path); - - //get the odbc information - $sql = "select count(*) as num_rows from v_databases "; - $sql .= "where database_driver = 'odbc' "; - $prep_statement = $this->db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - unset($prep_statement); - if ($row['num_rows'] > 0) { - $odbc_num_rows = $row['num_rows']; - - $sql = "select * from v_databases "; - $sql .= "where database_driver = 'odbc' "; - $prep_statement = $this->db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $this->dsn_name = $row["database_name"]; - $this->dsn_username = $row["database_username"]; - $this->dsn_password = $row["database_password"]; - break; //limit to 1 row - } - unset ($prep_statement); - } - else { - $odbc_num_rows = '0'; - } - } - - //get the recordings directory - $recordings_dir = $_SESSION['switch']['recordings']['dir']; - - //find the location to write the config.lua - if (is_dir("/etc/fusionpbx")){ - $config = "/etc/fusionpbx/config.lua"; - } elseif (is_dir("/usr/local/etc/fusionpbx")){ - $config = "/usr/local/etc/fusionpbx/config.lua"; - } - else { - $config = $_SESSION['switch']['scripts']['dir']."/resources/config.lua"; - } - $fout = fopen($config,"w"); - if(!$fout){ - return; - } - - //make the config.lua - $tmp = "\n"; - $tmp .= "--set the variables\n"; - if (strlen($_SESSION['switch']['sounds']['dir']) > 0) { - $tmp .= $this->correct_path(" sounds_dir = [[".$_SESSION['switch']['sounds']['dir']."]];\n"); - } - if (strlen($_SESSION['switch']['phrases']['dir']) > 0) { - $tmp .= $this->correct_path(" phrases_dir = [[".$_SESSION['switch']['phrases']['dir']."]];\n"); - } - if (strlen($_SESSION['switch']['db']['dir']) > 0) { - $tmp .= $this->correct_path(" database_dir = [[".$_SESSION['switch']['db']['dir']."]];\n"); - } - if (strlen($_SESSION['switch']['recordings']['dir']) > 0) { - $tmp .= $this->correct_path(" recordings_dir = [[".$recordings_dir."]];\n"); - } - if (strlen($_SESSION['switch']['storage']['dir']) > 0) { - $tmp .= $this->correct_path(" storage_dir = [[".$_SESSION['switch']['storage']['dir']."]];\n"); - } - if (strlen($_SESSION['switch']['voicemail']['dir']) > 0) { - $tmp .= $this->correct_path(" voicemail_dir = [[".$_SESSION['switch']['voicemail']['dir']."]];\n"); - } - if (strlen($_SESSION['switch']['scripts']['dir']) > 0) { - $tmp .= $this->correct_path(" scripts_dir = [[".$_SESSION['switch']['scripts']['dir']."]];\n"); - } - $tmp .= $this->correct_path(" php_dir = [[".PHP_BINDIR."]];\n"); - if (substr(strtoupper(PHP_OS), 0, 3) == "WIN") { - $tmp .= " php_bin = \"php.exe\";\n"; - } - else { - $tmp .= " php_bin = \"php\";\n"; - } - $tmp .= $this->correct_path(" document_root = [[".$_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."]];\n"); - $tmp .= "\n"; - - if ((strlen($this->db_type) > 0) || (strlen($this->dsn_name) > 0)) { - $tmp .= "--database information\n"; - $tmp .= " database = {}\n"; - $tmp .= " database.type = \"".$this->db_type."\";\n"; - $tmp .= " database.name = \"".$this->db_name."\";\n"; - $tmp .= $this->correct_path(" database.path = [[".$this->db_path."]];\n"); - - if (strlen($this->dsn_name) > 0) { - $tmp .= " database.system = \"odbc://".$this->dsn_name.":".$this->dsn_username.":".$this->dsn_password."\";\n"; - $tmp .= " database.switch = \"odbc://freeswitch:".$this->dsn_username.":".$this->dsn_password."\";\n"; - } - elseif ($this->db_type == "pgsql") { - if ($this->db_host == "localhost") { $this->db_host = "127.0.0.1"; } - $tmp .= " database.system = \"pgsql://hostaddr=".$this->db_host." port=".$this->db_port." dbname=".$this->db_name." user=".$this->db_username." password=".$this->db_password." options='' application_name='".$this->db_name."'\";\n"; - $tmp .= " database.switch = \"pgsql://hostaddr=".$this->db_host." port=".$this->db_port." dbname=freeswitch user=".$this->db_username." password=".$this->db_password." options='' application_name='freeswitch'\";\n"; - } - elseif ($this->db_type == "sqlite") { - $tmp .= " database.system = \"sqlite://".$this->db_path."/".$this->db_name."\";\n"; - $tmp .= " database.switch = \"sqlite://".$_SESSION['switch']['db']['dir']."\";\n"; - } - elseif ($this->db_type == "mysql") { - $tmp .= " database.system = \"\";\n"; - $tmp .= " database.switch = \"\";\n"; - } - $tmp .= "\n"; - } - $tmp .= "--set defaults\n"; - $tmp .= " expire = {}\n"; - $tmp .= " expire.directory = \"3600\";\n"; - $tmp .= " expire.dialplan = \"3600\";\n"; - $tmp .= " expire.languages = \"3600\";\n"; - $tmp .= " expire.sofia = \"3600\";\n"; - $tmp .= " expire.acl = \"3600\";\n"; - $tmp .= "\n"; - $tmp .= "--set xml_handler\n"; - $tmp .= " xml_handler = {}\n"; - $tmp .= " xml_handler.fs_path = false;\n"; - $tmp .= "\n"; - $tmp .= "--set the debug options\n"; - $tmp .= " debug.params = false;\n"; - $tmp .= " debug.sql = false;\n"; - $tmp .= " debug.xml_request = false;\n"; - $tmp .= " debug.xml_string = false;\n"; - $tmp .= " debug.cache = false;\n"; - $tmp .= "\n"; - $tmp .= "--additional info\n"; - $tmp .= " domain_count = ".count($_SESSION["domains"]).";\n"; - $tmp .= $this->correct_path(" temp_dir = [[".$_SESSION['server']['temp']['dir']."]];\n"); - if (isset($_SESSION['domain']['dial_string']['text'])) { - $tmp .= " dial_string = \"".$_SESSION['domain']['dial_string']['text']."\";\n"; - } - $tmp .= "\n"; - $tmp .= "--include local.lua\n"; - $tmp .= " require(\"resources.functions.file_exists\");\n"; - $tmp .= " if (file_exists(\"/etc/fusionpbx/local.lua\")) then\n"; - $tmp .= " dofile(\"/etc/fusionpbx/local.lua\");\n"; - $tmp .= " elseif (file_exists(\"/usr/local/etc/fusionpbx/local.lua\")) then\n"; - $tmp .= " dofile(\"/usr/local/etc/fusionpbx/local.lua\");\n"; - $tmp .= " elseif (file_exists(scripts_dir..\"/resources/local.lua\")) then\n"; - $tmp .= " require(\"resources.local\");\n"; - $tmp .= " end\n"; - fwrite($fout, $tmp); - unset($tmp); - fclose($fout); - } - } //end config_lua - } //end scripts class -} -/* -//example use - -//update config.lua - $obj = new scripts; - $obj->write_config(); -*/ + + Portions created by the Initial Developer are Copyright (C) 2008-2016 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + + +/** + * scripts class provides methods for creating the config.lua and copying switch scripts + * + * @method string correct_path + * @method string copy_files + * @method string write_config + */ +if (!class_exists('scripts')) { + class scripts { + + public $db; + public $db_type; + public $db_name; + public $db_host; + public $db_port; + public $db_path; + public $db_username; + public $db_password; + public $dsn_name; + public $dsn_username; + public $dsn_password; + + /** + * Called when the object is created + */ + public function __construct() { + //connect to the database if not connected + require_once "resources/classes/database.php"; + $database = new database; + $database->connect(); + $this->db = $database->db; + $this->db_type = $database->type; + $this->db_name = $database->db_name; + $this->db_host = $database->host; + $this->db_port = $database->port; + $this->db_path = $database->path; + $this->db_username = $database->username; + $this->db_password = $database->password; + } + + /** + * Called when there are no references to a particular object + * unset the variables used in the class + */ + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + /** + * Corrects the path for specifically for windows + */ + private function correct_path($path) { + global $IS_WINDOWS; + if ($IS_WINDOWS == null) { + if (stristr(PHP_OS, 'WIN')) { $IS_WINDOWS = true; } else { $IS_WINDOWS = false; } + } + if ($IS_WINDOWS) { + return str_replace('\\', '/', $path); + } + return $path; + } + + /** + * Copy the switch scripts from the web directory to the switch directory + */ + public function copy_files() { + if (strlen($_SESSION['switch']['scripts']['dir']) > 0) { + $dst_dir = $_SESSION['switch']['scripts']['dir']; + if(strlen($dst_dir) == 0) { + throw new Exception("Cannot copy scripts the 'script_dir' is empty"); + } + if (file_exists($dst_dir)) { + //get the source directory + if (file_exists('/usr/share/examples/fusionpbx/resources/install/scripts')){ + $src_dir = '/usr/share/examples/fusionpbx/resources/install/scripts'; + } + else { + $src_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/scripts'; + } + if (is_readable($dst_dir)) { + recursive_copy($src_dir, $dst_dir); + unset($src_dir, $dst_dir); + }else{ + throw new Exception("Cannot read from '$src_dir' to get the scripts"); + } + chmod($dst_dir, 0774); + } else { + throw new Exception("Scripts directory doesn't exist"); + } + } + } + + /** + * Writes the config.lua + */ + public function write_config() { + if (is_dir($_SESSION['switch']['scripts']['dir'])) { + + //replace the backslash with a forward slash + $this->db_path = str_replace("\\", "/", $this->db_path); + + //get the odbc information + $sql = "select count(*) as num_rows from v_databases "; + $sql .= "where database_driver = 'odbc' "; + $prep_statement = $this->db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + unset($prep_statement); + if ($row['num_rows'] > 0) { + $odbc_num_rows = $row['num_rows']; + + $sql = "select * from v_databases "; + $sql .= "where database_driver = 'odbc' "; + $prep_statement = $this->db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $this->dsn_name = $row["database_name"]; + $this->dsn_username = $row["database_username"]; + $this->dsn_password = $row["database_password"]; + break; //limit to 1 row + } + unset ($prep_statement); + } + else { + $odbc_num_rows = '0'; + } + } + + //get the recordings directory + $recordings_dir = $_SESSION['switch']['recordings']['dir']; + + //find the location to write the config.lua + if (is_dir("/etc/fusionpbx")){ + $config = "/etc/fusionpbx/config.lua"; + } elseif (is_dir("/usr/local/etc/fusionpbx")){ + $config = "/usr/local/etc/fusionpbx/config.lua"; + } + else { + $config = $_SESSION['switch']['scripts']['dir']."/resources/config.lua"; + } + $fout = fopen($config,"w"); + if(!$fout){ + return; + } + + //make the config.lua + $tmp = "\n"; + $tmp .= "--set the variables\n"; + if (strlen($_SESSION['switch']['sounds']['dir']) > 0) { + $tmp .= $this->correct_path(" sounds_dir = [[".$_SESSION['switch']['sounds']['dir']."]];\n"); + } + if (strlen($_SESSION['switch']['phrases']['dir']) > 0) { + $tmp .= $this->correct_path(" phrases_dir = [[".$_SESSION['switch']['phrases']['dir']."]];\n"); + } + if (strlen($_SESSION['switch']['db']['dir']) > 0) { + $tmp .= $this->correct_path(" database_dir = [[".$_SESSION['switch']['db']['dir']."]];\n"); + } + if (strlen($_SESSION['switch']['recordings']['dir']) > 0) { + $tmp .= $this->correct_path(" recordings_dir = [[".$recordings_dir."]];\n"); + } + if (strlen($_SESSION['switch']['storage']['dir']) > 0) { + $tmp .= $this->correct_path(" storage_dir = [[".$_SESSION['switch']['storage']['dir']."]];\n"); + } + if (strlen($_SESSION['switch']['voicemail']['dir']) > 0) { + $tmp .= $this->correct_path(" voicemail_dir = [[".$_SESSION['switch']['voicemail']['dir']."]];\n"); + } + if (strlen($_SESSION['switch']['scripts']['dir']) > 0) { + $tmp .= $this->correct_path(" scripts_dir = [[".$_SESSION['switch']['scripts']['dir']."]];\n"); + } + $tmp .= $this->correct_path(" php_dir = [[".PHP_BINDIR."]];\n"); + if (substr(strtoupper(PHP_OS), 0, 3) == "WIN") { + $tmp .= " php_bin = \"php.exe\";\n"; + } + else { + $tmp .= " php_bin = \"php\";\n"; + } + $tmp .= $this->correct_path(" document_root = [[".$_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."]];\n"); + $tmp .= "\n"; + + if ((strlen($this->db_type) > 0) || (strlen($this->dsn_name) > 0)) { + $tmp .= "--database information\n"; + $tmp .= " database = {}\n"; + $tmp .= " database.type = \"".$this->db_type."\";\n"; + $tmp .= " database.name = \"".$this->db_name."\";\n"; + $tmp .= $this->correct_path(" database.path = [[".$this->db_path."]];\n"); + + if (strlen($this->dsn_name) > 0) { + $tmp .= " database.system = \"odbc://".$this->dsn_name.":".$this->dsn_username.":".$this->dsn_password."\";\n"; + $tmp .= " database.switch = \"odbc://freeswitch:".$this->dsn_username.":".$this->dsn_password."\";\n"; + } + elseif ($this->db_type == "pgsql") { + if ($this->db_host == "localhost") { $this->db_host = "127.0.0.1"; } + $tmp .= " database.system = \"pgsql://hostaddr=".$this->db_host." port=".$this->db_port." dbname=".$this->db_name." user=".$this->db_username." password=".$this->db_password." options='' application_name='".$this->db_name."'\";\n"; + $tmp .= " database.switch = \"pgsql://hostaddr=".$this->db_host." port=".$this->db_port." dbname=freeswitch user=".$this->db_username." password=".$this->db_password." options='' application_name='freeswitch'\";\n"; + } + elseif ($this->db_type == "sqlite") { + $tmp .= " database.system = \"sqlite://".$this->db_path."/".$this->db_name."\";\n"; + $tmp .= " database.switch = \"sqlite://".$_SESSION['switch']['db']['dir']."\";\n"; + } + elseif ($this->db_type == "mysql") { + $tmp .= " database.system = \"\";\n"; + $tmp .= " database.switch = \"\";\n"; + } + $tmp .= "\n"; + } + $tmp .= "--set defaults\n"; + $tmp .= " expire = {}\n"; + $tmp .= " expire.directory = \"3600\";\n"; + $tmp .= " expire.dialplan = \"3600\";\n"; + $tmp .= " expire.languages = \"3600\";\n"; + $tmp .= " expire.sofia = \"3600\";\n"; + $tmp .= " expire.acl = \"3600\";\n"; + $tmp .= "\n"; + $tmp .= "--set xml_handler\n"; + $tmp .= " xml_handler = {}\n"; + $tmp .= " xml_handler.fs_path = false;\n"; + $tmp .= "\n"; + $tmp .= "--set the debug options\n"; + $tmp .= " debug.params = false;\n"; + $tmp .= " debug.sql = false;\n"; + $tmp .= " debug.xml_request = false;\n"; + $tmp .= " debug.xml_string = false;\n"; + $tmp .= " debug.cache = false;\n"; + $tmp .= "\n"; + $tmp .= "--additional info\n"; + $tmp .= " domain_count = ".count($_SESSION["domains"]).";\n"; + $tmp .= $this->correct_path(" temp_dir = [[".$_SESSION['server']['temp']['dir']."]];\n"); + if (isset($_SESSION['domain']['dial_string']['text'])) { + $tmp .= " dial_string = \"".$_SESSION['domain']['dial_string']['text']."\";\n"; + } + $tmp .= "\n"; + $tmp .= "--include local.lua\n"; + $tmp .= " require(\"resources.functions.file_exists\");\n"; + $tmp .= " if (file_exists(\"/etc/fusionpbx/local.lua\")) then\n"; + $tmp .= " dofile(\"/etc/fusionpbx/local.lua\");\n"; + $tmp .= " elseif (file_exists(\"/usr/local/etc/fusionpbx/local.lua\")) then\n"; + $tmp .= " dofile(\"/usr/local/etc/fusionpbx/local.lua\");\n"; + $tmp .= " elseif (file_exists(scripts_dir..\"/resources/local.lua\")) then\n"; + $tmp .= " require(\"resources.local\");\n"; + $tmp .= " end\n"; + fwrite($fout, $tmp); + unset($tmp); + fclose($fout); + } + } //end config_lua + } //end scripts class +} +/* +//example use + +//update config.lua + $obj = new scripts; + $obj->write_config(); +*/ ?> \ No newline at end of file diff --git a/app/services/resources/classes/lib_win.php b/app/services/resources/classes/lib_win.php index 4469e4898c..a79ad98037 100644 --- a/app/services/resources/classes/lib_win.php +++ b/app/services/resources/classes/lib_win.php @@ -1,227 +1,227 @@ -'CONTINUE_PENDING', - WIN32_SERVICE_PAUSE_PENDING =>'PAUSE_PENDING', - WIN32_SERVICE_PAUSED =>'PAUSED', - WIN32_SERVICE_RUNNING =>'RUNNING', - WIN32_SERVICE_START_PENDING =>'START_PENDING', - WIN32_SERVICE_STOP_PENDING =>'STOP_PENDING', - WIN32_SERVICE_STOPPED =>'STOPPED', - ); - - private static $win_error = array( - WIN32_NO_ERROR => 'NO_ERROR', - WIN32_ERROR_ACCESS_DENIED => 'ACCESS_DENIED', - WIN32_ERROR_CIRCULAR_DEPENDENCY => 'CIRCULAR_DEPENDENCY', - WIN32_ERROR_DATABASE_DOES_NOT_EXIST => 'DATABASE_DOES_NOT_EXIST', - WIN32_ERROR_DEPENDENT_SERVICES_RUNNING => 'DEPENDENT_SERVICES_RUNNING', - WIN32_ERROR_DUPLICATE_SERVICE_NAME => 'DUPLICATE_SERVICE_NAME', - WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT => 'FAILED_SERVICE_CONTROLLER_CONNECT', - WIN32_ERROR_INSUFFICIENT_BUFFER => 'INSUFFICIENT_BUFFER', - WIN32_ERROR_INVALID_DATA => 'INVALID_DATA', - WIN32_ERROR_INVALID_HANDLE => 'INVALID_HANDLE', - WIN32_ERROR_INVALID_LEVEL => 'INVALID_LEVEL', - WIN32_ERROR_INVALID_NAME => 'INVALID_NAME', - WIN32_ERROR_INVALID_PARAMETER => 'INVALID_PARAMETER', - WIN32_ERROR_INVALID_SERVICE_ACCOUNT => 'INVALID_SERVICE_ACCOUNT', - WIN32_ERROR_INVALID_SERVICE_CONTROL => 'INVALID_SERVICE_CONTROL', - WIN32_ERROR_PATH_NOT_FOUND => 'PATH_NOT_FOUND', - WIN32_ERROR_SERVICE_ALREADY_RUNNING => 'SERVICE_ALREADY_RUNNING', - WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL => 'SERVICE_CANNOT_ACCEPT_CTRL', - WIN32_ERROR_SERVICE_DATABASE_LOCKED => 'SERVICE_DATABASE_LOCKED', - WIN32_ERROR_SERVICE_DEPENDENCY_DELETED => 'SERVICE_DEPENDENCY_DELETED', - WIN32_ERROR_SERVICE_DEPENDENCY_FAIL => 'SERVICE_DEPENDENCY_FAIL', - WIN32_ERROR_SERVICE_DISABLED => 'SERVICE_DISABLED', - WIN32_ERROR_SERVICE_DOES_NOT_EXIST => 'SERVICE_DOES_NOT_EXIST', - WIN32_ERROR_SERVICE_EXISTS => 'SERVICE_EXISTS', - WIN32_ERROR_SERVICE_LOGON_FAILED => 'SERVICE_LOGON_FAILED', - WIN32_ERROR_SERVICE_MARKED_FOR_DELETE => 'SERVICE_MARKED_FOR_DELETE', - WIN32_ERROR_SERVICE_NO_THREAD => 'SERVICE_NO_THREAD', - WIN32_ERROR_SERVICE_NOT_ACTIVE => 'SERVICE_NOT_ACTIVE', - WIN32_ERROR_SERVICE_REQUEST_TIMEOUT => 'SERVICE_REQUEST_TIMEOUT', - WIN32_ERROR_SHUTDOWN_IN_PROGRESS => 'SHUTDOWN_IN_PROGRESS' - ); - - private static function val2val($val,$map,$default){ - if(isset($map[$val])) return $map[$val]; - return $default; - } - - var $status; - var $last_error; - var $name; - var $description; - var $machine; - - function win_service($srvname, $machine=null){ - $this->name = $srvname; - $this->machine = $machine; - $this->status = null; - $this->last_error = WIN32_NO_ERROR; - } - - function refresh_status(){ - $status = win32_query_service_status($this->name,$this->machine); - if(is_array($status)){ - $this->status = (object)$status; - $this->last_error = WIN32_NO_ERROR; - return true; - } - $this->status = null; - $last_error = $status; - return false; - } - - function start(){ - $this->last_error = win32_start_service($this->name, $this->machine); - return ($this->last_error === WIN32_NO_ERROR) or ($this->last_error === WIN32_ERROR_SERVICE_ALREADY_RUNNING); - } - - function stop(){ - $this->last_error = win32_stop_service($this->name, $this->machine); - return $this->last_error === WIN32_NO_ERROR; - } - - function last_error($as_string = true){ - if($as_string){ - return self::val2val( - $this->last_error, self::$win_error, $this->last_error - ); - } - return $this->last_error; - } - - function state($as_string = true){ - if((!$this->status)and(!$this->refresh_status())) return false; - if($as_string){ - return self::val2val( - $this->status->CurrentState, self::$service_state, 'UNKNOWN' - ); - } - return $this->status->CurrentState; - } - - function pid(){ - if((!$this->status)and(!$this->refresh_status())) return false; - return $this->status->ProcessId; - } - - } - -} - -if(function_exists('reg_open_key')){ - - class win_reg_key{ - - private static $HK = array( - HKEY_CLASSES_ROOT => "HKCR", - HKEY_CURRENT_USER => "HKCU", - HKEY_LOCAL_MACHINE => "HKLM", - HKEY_USERS => "HKU", - HKEY_CURRENT_CONFIG => "HKCC", - ); - - function __construct($haiv, $key){ - $this->h = $haiv; - $this->k = $key; - $this->r = reg_open_key($this->h, $this->k); - $this->shell = new COM('WScript.Shell'); - if(!$this->shell){ - throw new Exception("Cannot create shell object."); - } - if(!$this->r){ - throw new Exception("Cannot access registry."); - } - $this->path = self::$HK[$this->h] . '\\' . $this->k; - } - - function __destruct(){ - if($this->r){ - reg_close_key($this->r); - $this->r = false; - } - } - - function keys(){ - return reg_enum_key($this->r); - } - - function values($as_hash = false){ - $values = reg_enum_value($this->r); - if(!$as_hash) return $values; - $result = Array(); - foreach($values as $key){ - $result[$key] = reg_get_value($this->r, $key); - } - return $result; - } - - function value($key){ - return reg_get_value($this->r, $key); - } - - function exists($key){ - $v = $this->value($key); - if($v === NULL) return false; - if($v === false) return false; - return true; - } - - private function write_raw($key, $type, $value){ - return reg_set_value($this->r, $key, $type, $value); - } - - function write_dword($key, $value){ - return $this->write_raw($key, REG_DWORD, $value); - } - - function write_string($key, $value){ - return $this->write_raw($key, REG_SZ, $value); - } - - function remove_value($key){ - if(!$this->exists($key)) return; - $key = $this->path . '\\' . $key; - $this->shell->RegDelete($key); - } - - } - -} +'CONTINUE_PENDING', + WIN32_SERVICE_PAUSE_PENDING =>'PAUSE_PENDING', + WIN32_SERVICE_PAUSED =>'PAUSED', + WIN32_SERVICE_RUNNING =>'RUNNING', + WIN32_SERVICE_START_PENDING =>'START_PENDING', + WIN32_SERVICE_STOP_PENDING =>'STOP_PENDING', + WIN32_SERVICE_STOPPED =>'STOPPED', + ); + + private static $win_error = array( + WIN32_NO_ERROR => 'NO_ERROR', + WIN32_ERROR_ACCESS_DENIED => 'ACCESS_DENIED', + WIN32_ERROR_CIRCULAR_DEPENDENCY => 'CIRCULAR_DEPENDENCY', + WIN32_ERROR_DATABASE_DOES_NOT_EXIST => 'DATABASE_DOES_NOT_EXIST', + WIN32_ERROR_DEPENDENT_SERVICES_RUNNING => 'DEPENDENT_SERVICES_RUNNING', + WIN32_ERROR_DUPLICATE_SERVICE_NAME => 'DUPLICATE_SERVICE_NAME', + WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT => 'FAILED_SERVICE_CONTROLLER_CONNECT', + WIN32_ERROR_INSUFFICIENT_BUFFER => 'INSUFFICIENT_BUFFER', + WIN32_ERROR_INVALID_DATA => 'INVALID_DATA', + WIN32_ERROR_INVALID_HANDLE => 'INVALID_HANDLE', + WIN32_ERROR_INVALID_LEVEL => 'INVALID_LEVEL', + WIN32_ERROR_INVALID_NAME => 'INVALID_NAME', + WIN32_ERROR_INVALID_PARAMETER => 'INVALID_PARAMETER', + WIN32_ERROR_INVALID_SERVICE_ACCOUNT => 'INVALID_SERVICE_ACCOUNT', + WIN32_ERROR_INVALID_SERVICE_CONTROL => 'INVALID_SERVICE_CONTROL', + WIN32_ERROR_PATH_NOT_FOUND => 'PATH_NOT_FOUND', + WIN32_ERROR_SERVICE_ALREADY_RUNNING => 'SERVICE_ALREADY_RUNNING', + WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL => 'SERVICE_CANNOT_ACCEPT_CTRL', + WIN32_ERROR_SERVICE_DATABASE_LOCKED => 'SERVICE_DATABASE_LOCKED', + WIN32_ERROR_SERVICE_DEPENDENCY_DELETED => 'SERVICE_DEPENDENCY_DELETED', + WIN32_ERROR_SERVICE_DEPENDENCY_FAIL => 'SERVICE_DEPENDENCY_FAIL', + WIN32_ERROR_SERVICE_DISABLED => 'SERVICE_DISABLED', + WIN32_ERROR_SERVICE_DOES_NOT_EXIST => 'SERVICE_DOES_NOT_EXIST', + WIN32_ERROR_SERVICE_EXISTS => 'SERVICE_EXISTS', + WIN32_ERROR_SERVICE_LOGON_FAILED => 'SERVICE_LOGON_FAILED', + WIN32_ERROR_SERVICE_MARKED_FOR_DELETE => 'SERVICE_MARKED_FOR_DELETE', + WIN32_ERROR_SERVICE_NO_THREAD => 'SERVICE_NO_THREAD', + WIN32_ERROR_SERVICE_NOT_ACTIVE => 'SERVICE_NOT_ACTIVE', + WIN32_ERROR_SERVICE_REQUEST_TIMEOUT => 'SERVICE_REQUEST_TIMEOUT', + WIN32_ERROR_SHUTDOWN_IN_PROGRESS => 'SHUTDOWN_IN_PROGRESS' + ); + + private static function val2val($val,$map,$default){ + if(isset($map[$val])) return $map[$val]; + return $default; + } + + var $status; + var $last_error; + var $name; + var $description; + var $machine; + + function win_service($srvname, $machine=null){ + $this->name = $srvname; + $this->machine = $machine; + $this->status = null; + $this->last_error = WIN32_NO_ERROR; + } + + function refresh_status(){ + $status = win32_query_service_status($this->name,$this->machine); + if(is_array($status)){ + $this->status = (object)$status; + $this->last_error = WIN32_NO_ERROR; + return true; + } + $this->status = null; + $last_error = $status; + return false; + } + + function start(){ + $this->last_error = win32_start_service($this->name, $this->machine); + return ($this->last_error === WIN32_NO_ERROR) or ($this->last_error === WIN32_ERROR_SERVICE_ALREADY_RUNNING); + } + + function stop(){ + $this->last_error = win32_stop_service($this->name, $this->machine); + return $this->last_error === WIN32_NO_ERROR; + } + + function last_error($as_string = true){ + if($as_string){ + return self::val2val( + $this->last_error, self::$win_error, $this->last_error + ); + } + return $this->last_error; + } + + function state($as_string = true){ + if((!$this->status)and(!$this->refresh_status())) return false; + if($as_string){ + return self::val2val( + $this->status->CurrentState, self::$service_state, 'UNKNOWN' + ); + } + return $this->status->CurrentState; + } + + function pid(){ + if((!$this->status)and(!$this->refresh_status())) return false; + return $this->status->ProcessId; + } + + } + +} + +if(function_exists('reg_open_key')){ + + class win_reg_key{ + + private static $HK = array( + HKEY_CLASSES_ROOT => "HKCR", + HKEY_CURRENT_USER => "HKCU", + HKEY_LOCAL_MACHINE => "HKLM", + HKEY_USERS => "HKU", + HKEY_CURRENT_CONFIG => "HKCC", + ); + + function __construct($haiv, $key){ + $this->h = $haiv; + $this->k = $key; + $this->r = reg_open_key($this->h, $this->k); + $this->shell = new COM('WScript.Shell'); + if(!$this->shell){ + throw new Exception("Cannot create shell object."); + } + if(!$this->r){ + throw new Exception("Cannot access registry."); + } + $this->path = self::$HK[$this->h] . '\\' . $this->k; + } + + function __destruct(){ + if($this->r){ + reg_close_key($this->r); + $this->r = false; + } + } + + function keys(){ + return reg_enum_key($this->r); + } + + function values($as_hash = false){ + $values = reg_enum_value($this->r); + if(!$as_hash) return $values; + $result = Array(); + foreach($values as $key){ + $result[$key] = reg_get_value($this->r, $key); + } + return $result; + } + + function value($key){ + return reg_get_value($this->r, $key); + } + + function exists($key){ + $v = $this->value($key); + if($v === NULL) return false; + if($v === false) return false; + return true; + } + + private function write_raw($key, $type, $value){ + return reg_set_value($this->r, $key, $type, $value); + } + + function write_dword($key, $value){ + return $this->write_raw($key, REG_DWORD, $value); + } + + function write_string($key, $value){ + return $this->write_raw($key, REG_SZ, $value); + } + + function remove_value($key){ + if(!$this->exists($key)) return; + $key = $this->path . '\\' . $key; + $this->shell->RegDelete($key); + } + + } + +} diff --git a/app/time_conditions/app_defaults.php b/app/time_conditions/app_defaults.php index 7160318b06..564346674b 100644 --- a/app/time_conditions/app_defaults.php +++ b/app/time_conditions/app_defaults.php @@ -1,117 +1,117 @@ - array("mday" => "1", "mon" => "1"))); - $preset['usa'][] = json_encode(array("martin_luther_king_jr_day" => array("wday" => "2", "mon" => "1", "mweek" => "3"))); - $preset['usa'][] = json_encode(array("presidents_day" => array("wday" => "2", "mon" => "2", "mweek" => "3"))); - $preset['usa'][] = json_encode(array("memorial_day" => array("mday" => "25-31", "wday" => "2", "mon" => "5"))); - $preset['usa'][] = json_encode(array("independence_day" => array("mday" => "4", "mon" => "7"))); - $preset['usa'][] = json_encode(array("labor_day" => array("wday" => "2", "mon" => "9", "mweek" => "1"))); - $preset['usa'][] = json_encode(array("columbus_day" => array("wday" => "2", "mon" => "10", "mweek" => "2"))); - $preset['usa'][] = json_encode(array("veterans_day" => array("mday" => "11", "mon" => "11"))); - $preset['usa'][] = json_encode(array("thanksgiving_day" => array("wday" => "5-6", "mon" => "11", "mweek" => "4"))); - $preset['usa'][] = json_encode(array("christmas_day" => array("mday" => "25", "mon" => "12"))); - - $preset['england'][] = json_encode(array("new_years_day" => array("mday" => "1", "mon" => "1"))); - $preset['england'][] = json_encode(array("christmas_day" => array("mday" => "25", "mon" => "12"))); - $preset['england'][] = json_encode(array("boxing_day" => array("mday" => "26", "mon" => "12"))); - $preset['england'][] = json_encode(array("may_day" => array("mon" => "5", "mweek" => "1", "wday" => "2"))); - $preset['england'][] = json_encode(array("spring_bank_holiday" => array("mon" => "5", "mday" => "25-31", "wday" => "2"))); - $preset['england'][] = json_encode(array("august_bank_holiday" => array("mon" => "8", "mday" => "25-31", "wday" => "2"))); - - //iterate and migrate old presets first - $sql = "update v_default_settings "; - $sql .= "set default_setting_subcategory = 'preset_usa' "; - $sql .= ", default_setting_description = 'usa Holiday' "; - $sql .= "where default_setting_category = 'time_conditions' "; - $sql .= "and default_setting_subcategory = 'preset' "; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - unset ($prep_statement, $sql); - } - - //iterate and add each, if necessary - $x = 0; - foreach ($preset as $region => $data) { - $sql = "select * from v_default_settings "; - $sql .= "where default_setting_category = 'time_conditions' "; - $sql .= "and default_setting_subcategory = 'preset_$region' "; - $sql .= "and default_setting_name = 'array' "; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - foreach ($data as $json) { - $found = false; - $missing[$x]['default_setting_category'] = 'time_conditions'; - $missing[$x]['default_setting_subcategory'] = "preset_$region"; - $missing[$x]['default_setting_name'] = 'array'; - $missing[$x]['default_setting_value'] = $json; - $missing[$x]['default_setting_enabled'] = 'true'; - $missing[$x]['default_setting_description'] = "$region Holiday"; - foreach ($default_settings as $row) { - if (trim($row['default_setting_value']) == trim($json)) { - $found = true; - //remove items from the array that were found - unset($missing[$x]); - } - } - $x++; - } - } - } - - //add the missing default settings - foreach ($missing as $row) { - //add the default settings - $orm = new orm; - $orm->name('default_settings'); - $orm->save($row); - $message = $orm->message; - unset($orm); - //print_r($message); - } - unset($missing); - - $array[$x]['default_setting_category'] = 'time_conditions'; - $array[$x]['default_setting_subcategory'] = 'region'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'usa'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'What region to use by default when choosing Time Conditions'; - $x++; - - //iterate and add each, if necessary - foreach ($array as $index => $default_settings) { - - //add the default setting - $sql = "select count(*) as num_rows from v_default_settings "; - $sql .= "where default_setting_category = '".$default_settings['default_setting_category']."' "; - $sql .= "and default_setting_subcategory = '".$default_settings['default_setting_subcategory']."' "; - $sql .= "and default_setting_name = '".$default_settings['default_setting_name']."' "; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - unset($prep_statement); - if ($row['num_rows'] == 0) { - $orm = new orm; - $orm->name('default_settings'); - $orm->save($array[$index]); - $message = $orm->message; - //print_r($message); - } - unset($row); - } - - } - - //unset the array variable - unset($array); -} - + array("mday" => "1", "mon" => "1"))); + $preset['usa'][] = json_encode(array("martin_luther_king_jr_day" => array("wday" => "2", "mon" => "1", "mweek" => "3"))); + $preset['usa'][] = json_encode(array("presidents_day" => array("wday" => "2", "mon" => "2", "mweek" => "3"))); + $preset['usa'][] = json_encode(array("memorial_day" => array("mday" => "25-31", "wday" => "2", "mon" => "5"))); + $preset['usa'][] = json_encode(array("independence_day" => array("mday" => "4", "mon" => "7"))); + $preset['usa'][] = json_encode(array("labor_day" => array("wday" => "2", "mon" => "9", "mweek" => "1"))); + $preset['usa'][] = json_encode(array("columbus_day" => array("wday" => "2", "mon" => "10", "mweek" => "2"))); + $preset['usa'][] = json_encode(array("veterans_day" => array("mday" => "11", "mon" => "11"))); + $preset['usa'][] = json_encode(array("thanksgiving_day" => array("wday" => "5-6", "mon" => "11", "mweek" => "4"))); + $preset['usa'][] = json_encode(array("christmas_day" => array("mday" => "25", "mon" => "12"))); + + $preset['england'][] = json_encode(array("new_years_day" => array("mday" => "1", "mon" => "1"))); + $preset['england'][] = json_encode(array("christmas_day" => array("mday" => "25", "mon" => "12"))); + $preset['england'][] = json_encode(array("boxing_day" => array("mday" => "26", "mon" => "12"))); + $preset['england'][] = json_encode(array("may_day" => array("mon" => "5", "mweek" => "1", "wday" => "2"))); + $preset['england'][] = json_encode(array("spring_bank_holiday" => array("mon" => "5", "mday" => "25-31", "wday" => "2"))); + $preset['england'][] = json_encode(array("august_bank_holiday" => array("mon" => "8", "mday" => "25-31", "wday" => "2"))); + + //iterate and migrate old presets first + $sql = "update v_default_settings "; + $sql .= "set default_setting_subcategory = 'preset_usa' "; + $sql .= ", default_setting_description = 'usa Holiday' "; + $sql .= "where default_setting_category = 'time_conditions' "; + $sql .= "and default_setting_subcategory = 'preset' "; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + unset ($prep_statement, $sql); + } + + //iterate and add each, if necessary + $x = 0; + foreach ($preset as $region => $data) { + $sql = "select * from v_default_settings "; + $sql .= "where default_setting_category = 'time_conditions' "; + $sql .= "and default_setting_subcategory = 'preset_$region' "; + $sql .= "and default_setting_name = 'array' "; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + foreach ($data as $json) { + $found = false; + $missing[$x]['default_setting_category'] = 'time_conditions'; + $missing[$x]['default_setting_subcategory'] = "preset_$region"; + $missing[$x]['default_setting_name'] = 'array'; + $missing[$x]['default_setting_value'] = $json; + $missing[$x]['default_setting_enabled'] = 'true'; + $missing[$x]['default_setting_description'] = "$region Holiday"; + foreach ($default_settings as $row) { + if (trim($row['default_setting_value']) == trim($json)) { + $found = true; + //remove items from the array that were found + unset($missing[$x]); + } + } + $x++; + } + } + } + + //add the missing default settings + foreach ($missing as $row) { + //add the default settings + $orm = new orm; + $orm->name('default_settings'); + $orm->save($row); + $message = $orm->message; + unset($orm); + //print_r($message); + } + unset($missing); + + $array[$x]['default_setting_category'] = 'time_conditions'; + $array[$x]['default_setting_subcategory'] = 'region'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'usa'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'What region to use by default when choosing Time Conditions'; + $x++; + + //iterate and add each, if necessary + foreach ($array as $index => $default_settings) { + + //add the default setting + $sql = "select count(*) as num_rows from v_default_settings "; + $sql .= "where default_setting_category = '".$default_settings['default_setting_category']."' "; + $sql .= "and default_setting_subcategory = '".$default_settings['default_setting_subcategory']."' "; + $sql .= "and default_setting_name = '".$default_settings['default_setting_name']."' "; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + unset($prep_statement); + if ($row['num_rows'] == 0) { + $orm = new orm; + $orm->name('default_settings'); + $orm->save($array[$index]); + $message = $orm->message; + //print_r($message); + } + unset($row); + } + + } + + //unset the array variable + unset($array); +} + ?> \ No newline at end of file diff --git a/app/time_conditions/time_condition_edit.php b/app/time_conditions/time_condition_edit.php index cfc49de505..e8f8536490 100644 --- a/app/time_conditions/time_condition_edit.php +++ b/app/time_conditions/time_condition_edit.php @@ -1,1115 +1,1115 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('time_condition_add') || permission_exists('time_condition_edit')) { - //access granted -} -else { - echo "access denied"; - exit; -} -require_once "resources/header.php"; - - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//initialize the destinations object - $destination = new destinations; - -//load available presets - $preset_region = "preset_".$_SESSION['time_conditions']['region']['text']; - foreach ($_SESSION['time_conditions'][$preset_region] as $json) { - $available_presets[] = json_decode($json, true); - } - unset($preset_region); - -//set the action as an add or an update - if (isset($_REQUEST["id"])) { - $action = "update"; - $dialplan_uuid = check_str($_REQUEST["id"]); - } - else { - $action = "add"; - } - -//get the post variables - if (count($_POST) > 0) { - $dialplan_name = check_str($_POST["dialplan_name"]); - $dialplan_number = check_str($_POST["dialplan_number"]); - $dialplan_order = check_str($_POST["dialplan_order"]); - - $dialplan_anti_action = check_str($_POST["dialplan_anti_action"]); - $dialplan_anti_action_array = explode(":", $dialplan_anti_action); - $dialplan_anti_action_app = array_shift($dialplan_anti_action_array); - $dialplan_anti_action_data = join(':', $dialplan_anti_action_array); - - $dialplan_enabled = check_str($_POST["dialplan_enabled"]); - $dialplan_description = check_str($_POST["dialplan_description"]); - } - - if (count($_POST) > 0 && strlen($_POST["persistformvar"]) == 0) { - //check for all required data - if (strlen($domain_uuid) == 0) { $msg .= $text['label-required-domain_uuid']."
\n"; } - if (strlen($dialplan_name) == 0) { $msg .= $text['label-required-dialplan_name']."
\n"; } - if (strlen($dialplan_number) == 0) { $msg .= $text['label-required-dialplan_number']."
\n"; } - //if (strlen($dialplan_action) == 0) { $msg .= $text['label-required-action']."
\n"; } - if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) { - require_once "resources/header.php"; - require_once "resources/persist_form_var.php"; - echo "
\n"; - echo "
\n"; - echo $msg."
"; - echo "
\n"; - persistformvar($_POST); - echo "
\n"; - require_once "resources/footer.php"; - return; - } - - //remove the invalid characters from the dialplan name - $dialplan_name = str_replace(' ', '_', $dialplan_name); - $dialplan_name = str_replace('/', '', $dialplan_name); - - //start the atomic transaction - $count = $db->exec("BEGIN;"); //returns affected rows - - //process main dialplan entry - if ($action == "add") { - - //add main dialplan entry - $dialplan_uuid = uuid(); - $sql = "insert into v_dialplans "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "dialplan_uuid, "; - $sql .= "app_uuid, "; - $sql .= "dialplan_name, "; - $sql .= "dialplan_number, "; - $sql .= "dialplan_order, "; - $sql .= "dialplan_continue, "; - $sql .= "dialplan_context, "; - $sql .= "dialplan_enabled, "; - $sql .= "dialplan_description "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$dialplan_uuid."', "; - $sql .= "'4b821450-926b-175a-af93-a03c441818b1', "; - $sql .= "'".$dialplan_name."', "; - $sql .= "'".$dialplan_number."', "; - $sql .= "'".$dialplan_order."', "; - $sql .= "'true', "; - $sql .= "'".$_SESSION['context']."', "; - $sql .= "'".$dialplan_enabled."', "; - $sql .= "'".$dialplan_description."' "; - $sql .= ")"; - - //execute query - $db->exec(check_sql($sql)); - unset($sql); - } - else if ($action == "update") { - //update main dialplan entry - $sql = "update v_dialplans set "; - $sql .= "dialplan_name = '".$dialplan_name."', "; - $sql .= "dialplan_number = '".$dialplan_number."', "; - $sql .= "dialplan_order = '".$dialplan_order."', "; - $sql .= "dialplan_continue = 'true', "; - $sql .= "dialplan_context = '".$_SESSION['context']."', "; - $sql .= "dialplan_enabled = '".$dialplan_enabled."', "; - $sql .= "dialplan_description = '".$dialplan_description."' "; - $sql .= "where domain_uuid = '".$domain_uuid."' "; - $sql .= "and dialplan_uuid = '".$dialplan_uuid."' "; - $db->exec(check_sql($sql)); - unset($sql); - - //delete existing dialplan details - $sql = "delete from v_dialplan_details "; - $sql .= "where dialplan_uuid = '".$dialplan_uuid."'; "; - $db->query($sql); - unset($sql); - } - - //initialize dialplan detail group and order numbers - $dialplan_detail_group = 0; - $dialplan_detail_order = 0; - - //clean up array - //remove presets not checked, restructure variable array - foreach ($_REQUEST['variable']['preset'] as $group_id => $conditions) { - if (!in_array($group_id, $_REQUEST['preset'])) { - unset($_REQUEST['variable']['preset'][$group_id]); - unset($_REQUEST['value'][$group_id]); - unset($_REQUEST['dialplan_action'][$group_id]); - continue; - } - $_REQUEST['variable'][$group_id] = $conditions; - } - foreach ($_REQUEST['variable']['custom'] as $group_id => $conditions) { - $_REQUEST['variable'][$group_id] = $conditions; - } - unset($_REQUEST['variable']['custom'], $_REQUEST['variable']['preset']); - - //remove invalid conditions and values by checking conditions - foreach ($_REQUEST['variable'] as $group_id => $conditions) { - foreach ($conditions as $condition_id => $condition_variable) { - if ($condition_variable == '') { - unset($_REQUEST['variable'][$group_id][$condition_id]); - unset($_REQUEST['value'][$group_id][$condition_id]); - } - } - } - - //remove invalid conditions and values by checking start value - foreach ($_REQUEST['value'] as $group_id => $values) { - foreach ($values as $value_id => $value_range) { - if ($value_range['start'] == '') { - unset($_REQUEST['variable'][$group_id][$value_id]); - unset($_REQUEST['value'][$group_id][$value_id]); - } - } - } - - //remove any empty groups (where conditions no longer exist) - foreach ($_REQUEST['variable'] as $group_id => $conditions) { - if (sizeof($conditions) == 0) { - unset($_REQUEST['variable'][$group_id]); - unset($_REQUEST['value'][$group_id]); - unset($_REQUEST['dialplan_action'][$group_id]); - } - } - - //remove groups where an action (or default_preset_action - if a preset group - or dialplan_anti_action) isn't defined - foreach ($_REQUEST['variable'] as $group_id => $meh) { - if ( - (in_array($group_id, $_REQUEST['preset']) && $_REQUEST['dialplan_action'][$group_id] == '' && $_REQUEST['default_preset_action'] == '' && $_REQUEST['dialplan_anti_action'] == '') || - (!in_array($group_id, $_REQUEST['preset']) && $_REQUEST['dialplan_action'][$group_id] == '') - ) { - unset($_REQUEST['variable'][$group_id]); - unset($_REQUEST['value'][$group_id]); - unset($_REQUEST['dialplan_action'][$group_id]); - foreach ($_REQUEST['preset'] as $preset_id => $preset_group_id) { - if ($group_id == $preset_group_id) { unset($_REQUEST['preset'][$preset_id]); } - } - } - } - - //process conditions - $conditions_exist = false; - - //begin insert query for custom and preset conditions - $sql = "insert into v_dialplan_details "; - $sql .= "( "; - $sql .= "domain_uuid, "; - $sql .= "dialplan_uuid, "; - $sql .= "dialplan_detail_uuid, "; - $sql .= "dialplan_detail_tag, "; - $sql .= "dialplan_detail_type, "; - $sql .= "dialplan_detail_data, "; - $sql .= "dialplan_detail_break, "; - $sql .= "dialplan_detail_inline, "; - $sql .= "dialplan_detail_group, "; - $sql .= "dialplan_detail_order "; - $sql .= ") "; - $sql .= "values "; - - //add conditions - foreach ($_REQUEST['variable'] as $group_id => $conditions) { - - $group_conditions_exist[$group_id] = false; - - //determine if preset - $is_preset = (in_array($group_id, $_REQUEST['preset'])) ? true : false; - - //set group and order number - - $dialplan_detail_group_user = check_str($_POST["group_$group_id"]); - if($dialplan_detail_group_user!='') { - $dialplan_detail_group = $dialplan_detail_group_user; - } else { - $dialplan_detail_group = $group_id; - } - - $dialplan_detail_order = 0; - - foreach ($conditions as $cond_num => $cond_var) { - if ($cond_var != '') { - $cond_start = $_REQUEST['value'][$group_id][$cond_num]['start']; - $cond_stop = $_REQUEST['value'][$group_id][$cond_num]['stop']; - - //convert time-of-day to minute-of-day (due to inconsistencies with time-of-day on some systems) - if ($cond_var == 'time-of-day') { - $cond_var = 'minute-of-day'; - $array_cond_start = explode(':', $cond_start); - $cond_start = ($array_cond_start[0] * 60) + $array_cond_start[1]; - if ($cond_stop != '') { - $array_cond_stop = explode(':', $cond_stop); - $cond_stop = ($array_cond_stop[0] * 60) + $array_cond_stop[1]; - } - } - - $cond_value = $cond_start; - if ($cond_stop != '') { - $range_indicator = ($cond_var == 'date-time') ? '~' : '-'; - $cond_value .= $range_indicator.$cond_stop; - } - - if (!$group_conditions_exist[$group_id]) { - //add destination number condition - $dialplan_detail_order += 10; - $sql .= ($conditions_exist) ? ", ( " : "( "; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$dialplan_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= "'condition', "; - $sql .= "'destination_number', "; - $sql .= "'^".$dialplan_number."$', "; - $sql .= "null, "; - $sql .= "null, "; - $sql .= "'".$dialplan_detail_group."', "; - $sql .= "'".$dialplan_detail_order."' "; - $sql .= ") "; - } - - //add condition to query string - $dialplan_detail_order += 10; - $sql .= ", ( "; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$dialplan_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= "'condition', "; - $sql .= "'".$cond_var."', "; - $sql .= "'".$cond_value."', "; - $sql .= "'never', "; - $sql .= "null, "; - $sql .= "'".$dialplan_detail_group."', "; - $sql .= "'".$dialplan_detail_order."' "; - $sql .= ") "; - - $conditions_exist = true; - $group_conditions_exist[$group_id] = true; - } //if - } //for each - - - //continue adding to query only if conditions exist in current group - if ($group_conditions_exist[$group_id]) { - - //determine group action app and data - $dialplan_action = check_str($_REQUEST["dialplan_action"][$group_id]); - if ($dialplan_action == '') { - if ($is_preset) { - if (check_str($_REQUEST['default_preset_action']) != '') { - $dialplan_action = check_str($_REQUEST['default_preset_action']); - } - else if (check_str($_REQUEST['dialplan_anti_action']) != '') { - $dialplan_action = check_str($_REQUEST['dialplan_anti_action']); - } - } - } - - if ($dialplan_action != '') { - //if preset, set log variable - if ($is_preset) { - foreach ($_REQUEST['preset'] as $preset_number => $preset_group_id) { - if ($group_id == $preset_group_id) { - foreach ($available_presets[$preset_number] as $available_preset_name => $meh) { - $dialplan_detail_order += 10; - $sql .= ", ( "; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$dialplan_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= "'action', "; - $sql .= "'set', "; - $sql .= "'preset=".$available_preset_name."', "; - $sql .= "null, "; - $sql .= "'true', "; - $sql .= "'".$dialplan_detail_group."', "; - $sql .= "'".$dialplan_detail_order."' "; - $sql .= ") "; - } - } - } - } - - //parse group app and data - if (substr_count($dialplan_action, ":") > 0) { - $dialplan_action_array = explode(":", $dialplan_action); - $dialplan_action_app = array_shift($dialplan_action_array); - $dialplan_action_data = join(':', $dialplan_action_array); - } - else { - $dialplan_action_app = $dialplan_action; - $dialplan_action_data = ''; - } - - //add group action to query - $dialplan_detail_order += 10; - $sql .= ", ( "; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$dialplan_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= "'action', "; - $sql .= "'".$dialplan_action_app."', "; - $sql .= "'".$dialplan_action_data."', "; - $sql .= "null, "; - $sql .= "null, "; - $sql .= "'".$dialplan_detail_group."', "; - $sql .= "'".$dialplan_detail_order."' "; - $sql .= ") "; - } - - } - - } //for each - - - //add to query for default anti-action (if defined) - if (strlen($dialplan_anti_action_app) > 0) { - - //increment group number, reset order number - $dialplan_detail_group = 999; - $dialplan_detail_order = 0; - - //add destination number condition - $dialplan_detail_order += 10; - $sql .= ", ( "; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$dialplan_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= "'condition', "; - $sql .= "'destination_number', "; - $sql .= "'^".$dialplan_number."$', "; - $sql .= "null, "; - $sql .= "null, "; - $sql .= "'".$dialplan_detail_group."', "; - $sql .= "'".$dialplan_detail_order."' "; - $sql .= ") "; - - //add anti-action - $dialplan_detail_order += 10; - $sql .= ", ( "; - $sql .= "'".$domain_uuid."', "; - $sql .= "'".$dialplan_uuid."', "; - $sql .= "'".uuid()."', "; - $sql .= "'action', "; - $sql .= "'".$dialplan_anti_action_app."', "; - $sql .= "'".$dialplan_anti_action_data."', "; - $sql .= "null, "; - $sql .= "null, "; - $sql .= "'".$dialplan_detail_group."', "; - $sql .= "'".$dialplan_detail_order."' "; - $sql .= ") "; - - } - - //execute query - if ($conditions_exist) { - $db->exec(check_sql($sql)); - unset($sql); - } - - //commit the atomic transaction - $count = $db->exec("COMMIT;"); //returns affected rows - - //clear the cache - $cache = new cache; - $cache->delete("dialplan:".$_SESSION["context"]); - - //synchronize the xml config - save_dialplan_xml(); - - //set the message - if ($action == "add") { - $_SESSION['message'] = $text['message-add']; - } - else if ($action == "update") { - $_SESSION['message'] = $text['message-update']; - } - header("Location: time_condition_edit.php?id=".$dialplan_uuid.(($app_uuid != '') ? "&app_uuid=".$app_uuid : null)); - return; - - } //end if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) - - -//get existing data to pre-populate form - if ($dialplan_uuid != '' && $_POST["persistformvar"] != "true") { - - //add the dialplan permission - $p = new permissions; - $p->add("dialplan_add", 'temp'); - $p->add("dialplan_detail_add", 'temp'); - $p->add("dialplan_edit", 'temp'); - $p->add("dialplan_detail_edit", 'temp'); - - //get main dialplan entry - $orm = new orm; - $orm->name('dialplans'); - $orm->uuid($dialplan_uuid); - $result = $orm->find()->get(); - //$message = $orm->message; - foreach ($result as &$row) { - $domain_uuid = $row["domain_uuid"]; - //$app_uuid = $row["app_uuid"]; - $dialplan_name = $row["dialplan_name"]; - $dialplan_number = $row["dialplan_number"]; - $dialplan_order = $row["dialplan_order"]; - $dialplan_continue = $row["dialplan_continue"]; - $dialplan_context = $row["dialplan_context"]; - $dialplan_enabled = $row["dialplan_enabled"]; - $dialplan_description = $row["dialplan_description"]; - } - unset ($prep_statement); - - //remove the temporary permission - $p->delete("dialplan_add", 'temp'); - $p->delete("dialplan_detail_add", 'temp'); - $p->delete("dialplan_edit", 'temp'); - $p->delete("dialplan_detail_edit", 'temp'); - - //get dialplan detail conditions - $sql = "select dialplan_detail_group, dialplan_detail_tag, dialplan_detail_type, dialplan_detail_data from v_dialplan_details "; - $sql .= "where dialplan_uuid = '".$dialplan_uuid."' "; - $sql .= "and "; - $sql .= "( "; - $sql .= " ( "; - $sql .= " dialplan_detail_tag = 'condition' "; - $sql .= " and dialplan_detail_type in ('year','mon','mday','wday','yday','week','mweek','hour','minute','minute-of-day','time-of-day','date-time') "; - $sql .= " ) "; - $sql .= " or ( "; - $sql .= " dialplan_detail_tag = 'action' "; - $sql .= " and dialplan_detail_data not like 'preset=%' "; - $sql .= " ) "; - $sql .= ") "; - $sql .= "order by dialplan_detail_group asc, dialplan_detail_order asc"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $result_count = count($result); - unset ($prep_statement, $sql); - - //load current conditions into array (combined by group), and retrieve action and anti-action - $c = 0; - foreach ($result as $row) { - if ($row['dialplan_detail_tag'] == 'action') { - if ($row['dialplan_detail_group'] == '999') { - $dialplan_anti_action = $row['dialplan_detail_type'].(($row['dialplan_detail_data'] != '') ? ':'.$row['dialplan_detail_data'] : null); - } - else { - $dialplan_actions[$row['dialplan_detail_group']] = $row['dialplan_detail_type'].(($row['dialplan_detail_data'] != '') ? ':'.$row['dialplan_detail_data'] : null); - } - } - else if ($row['dialplan_detail_tag'] == 'condition') { - $current_conditions[$row['dialplan_detail_group']][$row['dialplan_detail_type']] = $row['dialplan_detail_data']; - } - } - - //loop through available presets (if any) - if (isset($available_presets) && sizeof($available_presets) > 0) { - foreach ($available_presets as $preset_number => $preset) { - foreach ($preset as $preset_name => $preset_variables) { - //loop through each condition group - foreach ($current_conditions as $group_id => $condition_variables) { - $matches = 0; - foreach ($condition_variables as $condition_variable_name => $condition_variable_value) { - //count matching variable values - if ($preset_variables[$condition_variable_name] == $condition_variable_value) { $matches++; } - } - //if all preset variables found, then condition is a preset - if ($matches == sizeof($preset_variables)) { - $current_presets[$preset_number] = $group_id; - } - } - } - } - } - - } - -?> - - - -\n"; - -echo "\n"; -echo " \n"; -echo " \n"; -echo " \n"; -echo " \n"; -echo "
\n"; -echo " ".$text['title-time_conditions'].""; -echo "

\n"; -echo " ".$text['description-time_conditions']."\n"; -echo "
\n"; -echo " \n"; -if (if_group("superadmin") && $action == 'update') { - echo " \n"; -} -echo " \n"; -echo "
"; -echo "
\n"; - -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -function add_custom_condition($destination, $group_id, $dialplan_action = '') { - global $text, $v_link_label_add; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; -} - -if ($action == 'update') { - $largest_group_id = 0; - foreach ($current_conditions as $group_id => $conditions) { - if (!is_array($current_presets) || (is_array($current_presets) && !in_array($group_id, $current_presets))) { - add_custom_condition($destination, $group_id, $dialplan_actions[$group_id]); - foreach ($conditions as $cond_var => $cond_val) { - $range_indicator = ($cond_var == 'date-time') ? '~' : '-'; - $tmp = explode($range_indicator, $cond_val); - $cond_val_start = $tmp[0]; - $cond_val_stop = $tmp[1]; - unset($tmp); - - //convert minute-of-day to time-of-day values - if ($cond_var == 'minute-of-day') { - $cond_var = 'time-of-day'; - $cond_val_start = number_pad(floor($cond_val_start / 60),2).":".number_pad(fmod($cond_val_start, 60),2); - if ($cond_val_stop != '') { - $cond_val_stop = number_pad(floor($cond_val_stop / 60),2).":".number_pad(fmod($cond_val_stop, 60),2); - } - } - - echo ""; - } - //used to determine largest custom group id in use - $largest_group_id = ($group_id > $largest_group_id) ? $group_id : $largest_group_id; - } - } -} - -//add first/new set of custom condition fields - if ($action != 'update' || ($action == 'update' && $largest_group_id == 0)) { - $group_id = 500; - } - else { - $group_id = $largest_group_id += 5; - } - add_custom_condition($destination, $group_id); - echo ""; - -//if presets exist, show the preset section - if (isset($available_presets) && sizeof($available_presets) > 0) { - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - } - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "\n"; -echo "\n"; -echo "\n"; -echo "\n"; - -echo "
\n"; -echo " ".$text['label-name']."\n"; -echo "\n"; -echo " \n"; -echo "
\n"; -echo " ".$text['description-name']."\n"; -echo "
\n"; -echo "\n"; -echo "
\n"; -echo " ".$text['label-extension']."\n"; -echo "\n"; -echo " \n"; -echo "
\n"; -echo " ".$text['description-extension']."
\n"; -echo "
\n"; - echo " ".$text['label-settings']; - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " "; - echo " "; - echo " "; - echo " "; - echo " \n"; - echo " \n"; - echo "
".$text['label-condition']."".$text['label-condition_value']."".$text['label-condition_range']."".$v_link_label_add."
"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " "; - echo "
\n"; - //$destination = new destinations; - echo $destination->select('dialplan', 'dialplan_action['.$group_id.']', $dialplan_action); - echo "
\n"; - echo "
"; - echo "
"; - echo " ".$text['description-settings']; - echo "
\n"; - echo " ".$text['label-presets']."\n"; - echo "\n"; - - foreach ($available_presets as $preset_number => $preset) { - foreach ($preset as $preset_name => $preset_variables) { - $checked = (is_array($current_presets) && $current_presets[$preset_number] != '') ? "checked='checked'" : null; - $preset_group_id = ($checked) ? $current_presets[$preset_number] : $preset_group_id = $preset_number * 5 + 100; - if (strlen($text['label-preset_'.$preset_name]) > 0) { - $label_preset_name = $text['label-preset_'.$preset_name]; - } - else { - $label_preset_name = ucwords(str_replace(array("-", "_"), " ", $preset_name)); - } - echo "
\n"; - echo ""; - if ($action == 'update' && is_array($current_presets) && $current_presets[$preset_number] != '') { - //add (potentially customized) preset conditions and populate - foreach ($current_conditions[$preset_group_id] as $cond_var => $cond_val) { - $range_indicator = ($cond_var == 'date-time') ? '~' : '-'; - $tmp = explode($range_indicator, $cond_val); - $cond_val_start = $tmp[0]; - $cond_val_stop = $tmp[1]; - unset($tmp); - - //convert minute-of-day to time-of-day values - if ($cond_var == 'minute-of-day') { - $cond_var = 'time-of-day'; - $cond_val_start = number_pad(floor($cond_val_start / 60),2).":".number_pad(fmod($cond_val_start, 60),2); - if ($cond_val_stop != '') { - $cond_val_stop = number_pad(floor($cond_val_stop / 60),2).":".number_pad(fmod($cond_val_stop, 60),2); - } - } - - echo ""; - } - } - else { - //add default preset conditions and populate - foreach ($preset_variables as $preset_variable => $preset_value) { - $range_indicator = ($preset_variable == 'date-time') ? '~' : '-'; - $tmp = explode($range_indicator, $preset_value); - $preset_value_start = $tmp[0]; - $preset_value_stop = $tmp[1]; - unset($tmp); - echo "\n\n"; - } - } - } - } - - echo "
\n"; - echo " \n"; - echo " "; - echo " "; - echo " "; - echo "
"; - echo " \n"; - echo " "; - echo $destination->select('dialplan', 'default_preset_action', $dialplan_action); - echo " "; - echo "
"; - echo "
"; - echo " ".$text['description-presets']."
\n"; - echo "
\n"; -echo " ".$text['label-alternate-destination']."\n"; -echo "\n"; -echo $destination->select('dialplan', 'dialplan_anti_action', $dialplan_anti_action); -echo "
\n"; -echo " ".$text['label-order']."\n"; -echo "\n"; -echo " \n"; -echo "
\n"; -echo "
\n"; -echo " ".$text['label-enabled']."\n"; -echo "\n"; -echo "\n"; -echo "
\n"; -echo "
\n"; -echo " ".$text['label-description']."\n"; -echo "\n"; -echo " \n"; -echo "
\n"; -echo "
\n"; -echo "
"; - -echo "
\n"; -if ($action == "update") { - echo " \n"; -} -echo " \n"; -echo "
"; - -echo ""; -echo "
"; - -//include the footer - require_once "resources/footer.php"; - + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('time_condition_add') || permission_exists('time_condition_edit')) { + //access granted +} +else { + echo "access denied"; + exit; +} +require_once "resources/header.php"; + + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//initialize the destinations object + $destination = new destinations; + +//load available presets + $preset_region = "preset_".$_SESSION['time_conditions']['region']['text']; + foreach ($_SESSION['time_conditions'][$preset_region] as $json) { + $available_presets[] = json_decode($json, true); + } + unset($preset_region); + +//set the action as an add or an update + if (isset($_REQUEST["id"])) { + $action = "update"; + $dialplan_uuid = check_str($_REQUEST["id"]); + } + else { + $action = "add"; + } + +//get the post variables + if (count($_POST) > 0) { + $dialplan_name = check_str($_POST["dialplan_name"]); + $dialplan_number = check_str($_POST["dialplan_number"]); + $dialplan_order = check_str($_POST["dialplan_order"]); + + $dialplan_anti_action = check_str($_POST["dialplan_anti_action"]); + $dialplan_anti_action_array = explode(":", $dialplan_anti_action); + $dialplan_anti_action_app = array_shift($dialplan_anti_action_array); + $dialplan_anti_action_data = join(':', $dialplan_anti_action_array); + + $dialplan_enabled = check_str($_POST["dialplan_enabled"]); + $dialplan_description = check_str($_POST["dialplan_description"]); + } + + if (count($_POST) > 0 && strlen($_POST["persistformvar"]) == 0) { + //check for all required data + if (strlen($domain_uuid) == 0) { $msg .= $text['label-required-domain_uuid']."
\n"; } + if (strlen($dialplan_name) == 0) { $msg .= $text['label-required-dialplan_name']."
\n"; } + if (strlen($dialplan_number) == 0) { $msg .= $text['label-required-dialplan_number']."
\n"; } + //if (strlen($dialplan_action) == 0) { $msg .= $text['label-required-action']."
\n"; } + if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) { + require_once "resources/header.php"; + require_once "resources/persist_form_var.php"; + echo "
\n"; + echo "
\n"; + echo $msg."
"; + echo "
\n"; + persistformvar($_POST); + echo "
\n"; + require_once "resources/footer.php"; + return; + } + + //remove the invalid characters from the dialplan name + $dialplan_name = str_replace(' ', '_', $dialplan_name); + $dialplan_name = str_replace('/', '', $dialplan_name); + + //start the atomic transaction + $count = $db->exec("BEGIN;"); //returns affected rows + + //process main dialplan entry + if ($action == "add") { + + //add main dialplan entry + $dialplan_uuid = uuid(); + $sql = "insert into v_dialplans "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "dialplan_uuid, "; + $sql .= "app_uuid, "; + $sql .= "dialplan_name, "; + $sql .= "dialplan_number, "; + $sql .= "dialplan_order, "; + $sql .= "dialplan_continue, "; + $sql .= "dialplan_context, "; + $sql .= "dialplan_enabled, "; + $sql .= "dialplan_description "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$dialplan_uuid."', "; + $sql .= "'4b821450-926b-175a-af93-a03c441818b1', "; + $sql .= "'".$dialplan_name."', "; + $sql .= "'".$dialplan_number."', "; + $sql .= "'".$dialplan_order."', "; + $sql .= "'true', "; + $sql .= "'".$_SESSION['context']."', "; + $sql .= "'".$dialplan_enabled."', "; + $sql .= "'".$dialplan_description."' "; + $sql .= ")"; + + //execute query + $db->exec(check_sql($sql)); + unset($sql); + } + else if ($action == "update") { + //update main dialplan entry + $sql = "update v_dialplans set "; + $sql .= "dialplan_name = '".$dialplan_name."', "; + $sql .= "dialplan_number = '".$dialplan_number."', "; + $sql .= "dialplan_order = '".$dialplan_order."', "; + $sql .= "dialplan_continue = 'true', "; + $sql .= "dialplan_context = '".$_SESSION['context']."', "; + $sql .= "dialplan_enabled = '".$dialplan_enabled."', "; + $sql .= "dialplan_description = '".$dialplan_description."' "; + $sql .= "where domain_uuid = '".$domain_uuid."' "; + $sql .= "and dialplan_uuid = '".$dialplan_uuid."' "; + $db->exec(check_sql($sql)); + unset($sql); + + //delete existing dialplan details + $sql = "delete from v_dialplan_details "; + $sql .= "where dialplan_uuid = '".$dialplan_uuid."'; "; + $db->query($sql); + unset($sql); + } + + //initialize dialplan detail group and order numbers + $dialplan_detail_group = 0; + $dialplan_detail_order = 0; + + //clean up array + //remove presets not checked, restructure variable array + foreach ($_REQUEST['variable']['preset'] as $group_id => $conditions) { + if (!in_array($group_id, $_REQUEST['preset'])) { + unset($_REQUEST['variable']['preset'][$group_id]); + unset($_REQUEST['value'][$group_id]); + unset($_REQUEST['dialplan_action'][$group_id]); + continue; + } + $_REQUEST['variable'][$group_id] = $conditions; + } + foreach ($_REQUEST['variable']['custom'] as $group_id => $conditions) { + $_REQUEST['variable'][$group_id] = $conditions; + } + unset($_REQUEST['variable']['custom'], $_REQUEST['variable']['preset']); + + //remove invalid conditions and values by checking conditions + foreach ($_REQUEST['variable'] as $group_id => $conditions) { + foreach ($conditions as $condition_id => $condition_variable) { + if ($condition_variable == '') { + unset($_REQUEST['variable'][$group_id][$condition_id]); + unset($_REQUEST['value'][$group_id][$condition_id]); + } + } + } + + //remove invalid conditions and values by checking start value + foreach ($_REQUEST['value'] as $group_id => $values) { + foreach ($values as $value_id => $value_range) { + if ($value_range['start'] == '') { + unset($_REQUEST['variable'][$group_id][$value_id]); + unset($_REQUEST['value'][$group_id][$value_id]); + } + } + } + + //remove any empty groups (where conditions no longer exist) + foreach ($_REQUEST['variable'] as $group_id => $conditions) { + if (sizeof($conditions) == 0) { + unset($_REQUEST['variable'][$group_id]); + unset($_REQUEST['value'][$group_id]); + unset($_REQUEST['dialplan_action'][$group_id]); + } + } + + //remove groups where an action (or default_preset_action - if a preset group - or dialplan_anti_action) isn't defined + foreach ($_REQUEST['variable'] as $group_id => $meh) { + if ( + (in_array($group_id, $_REQUEST['preset']) && $_REQUEST['dialplan_action'][$group_id] == '' && $_REQUEST['default_preset_action'] == '' && $_REQUEST['dialplan_anti_action'] == '') || + (!in_array($group_id, $_REQUEST['preset']) && $_REQUEST['dialplan_action'][$group_id] == '') + ) { + unset($_REQUEST['variable'][$group_id]); + unset($_REQUEST['value'][$group_id]); + unset($_REQUEST['dialplan_action'][$group_id]); + foreach ($_REQUEST['preset'] as $preset_id => $preset_group_id) { + if ($group_id == $preset_group_id) { unset($_REQUEST['preset'][$preset_id]); } + } + } + } + + //process conditions + $conditions_exist = false; + + //begin insert query for custom and preset conditions + $sql = "insert into v_dialplan_details "; + $sql .= "( "; + $sql .= "domain_uuid, "; + $sql .= "dialplan_uuid, "; + $sql .= "dialplan_detail_uuid, "; + $sql .= "dialplan_detail_tag, "; + $sql .= "dialplan_detail_type, "; + $sql .= "dialplan_detail_data, "; + $sql .= "dialplan_detail_break, "; + $sql .= "dialplan_detail_inline, "; + $sql .= "dialplan_detail_group, "; + $sql .= "dialplan_detail_order "; + $sql .= ") "; + $sql .= "values "; + + //add conditions + foreach ($_REQUEST['variable'] as $group_id => $conditions) { + + $group_conditions_exist[$group_id] = false; + + //determine if preset + $is_preset = (in_array($group_id, $_REQUEST['preset'])) ? true : false; + + //set group and order number + + $dialplan_detail_group_user = check_str($_POST["group_$group_id"]); + if($dialplan_detail_group_user!='') { + $dialplan_detail_group = $dialplan_detail_group_user; + } else { + $dialplan_detail_group = $group_id; + } + + $dialplan_detail_order = 0; + + foreach ($conditions as $cond_num => $cond_var) { + if ($cond_var != '') { + $cond_start = $_REQUEST['value'][$group_id][$cond_num]['start']; + $cond_stop = $_REQUEST['value'][$group_id][$cond_num]['stop']; + + //convert time-of-day to minute-of-day (due to inconsistencies with time-of-day on some systems) + if ($cond_var == 'time-of-day') { + $cond_var = 'minute-of-day'; + $array_cond_start = explode(':', $cond_start); + $cond_start = ($array_cond_start[0] * 60) + $array_cond_start[1]; + if ($cond_stop != '') { + $array_cond_stop = explode(':', $cond_stop); + $cond_stop = ($array_cond_stop[0] * 60) + $array_cond_stop[1]; + } + } + + $cond_value = $cond_start; + if ($cond_stop != '') { + $range_indicator = ($cond_var == 'date-time') ? '~' : '-'; + $cond_value .= $range_indicator.$cond_stop; + } + + if (!$group_conditions_exist[$group_id]) { + //add destination number condition + $dialplan_detail_order += 10; + $sql .= ($conditions_exist) ? ", ( " : "( "; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$dialplan_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= "'condition', "; + $sql .= "'destination_number', "; + $sql .= "'^".$dialplan_number."$', "; + $sql .= "null, "; + $sql .= "null, "; + $sql .= "'".$dialplan_detail_group."', "; + $sql .= "'".$dialplan_detail_order."' "; + $sql .= ") "; + } + + //add condition to query string + $dialplan_detail_order += 10; + $sql .= ", ( "; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$dialplan_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= "'condition', "; + $sql .= "'".$cond_var."', "; + $sql .= "'".$cond_value."', "; + $sql .= "'never', "; + $sql .= "null, "; + $sql .= "'".$dialplan_detail_group."', "; + $sql .= "'".$dialplan_detail_order."' "; + $sql .= ") "; + + $conditions_exist = true; + $group_conditions_exist[$group_id] = true; + } //if + } //for each + + + //continue adding to query only if conditions exist in current group + if ($group_conditions_exist[$group_id]) { + + //determine group action app and data + $dialplan_action = check_str($_REQUEST["dialplan_action"][$group_id]); + if ($dialplan_action == '') { + if ($is_preset) { + if (check_str($_REQUEST['default_preset_action']) != '') { + $dialplan_action = check_str($_REQUEST['default_preset_action']); + } + else if (check_str($_REQUEST['dialplan_anti_action']) != '') { + $dialplan_action = check_str($_REQUEST['dialplan_anti_action']); + } + } + } + + if ($dialplan_action != '') { + //if preset, set log variable + if ($is_preset) { + foreach ($_REQUEST['preset'] as $preset_number => $preset_group_id) { + if ($group_id == $preset_group_id) { + foreach ($available_presets[$preset_number] as $available_preset_name => $meh) { + $dialplan_detail_order += 10; + $sql .= ", ( "; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$dialplan_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= "'action', "; + $sql .= "'set', "; + $sql .= "'preset=".$available_preset_name."', "; + $sql .= "null, "; + $sql .= "'true', "; + $sql .= "'".$dialplan_detail_group."', "; + $sql .= "'".$dialplan_detail_order."' "; + $sql .= ") "; + } + } + } + } + + //parse group app and data + if (substr_count($dialplan_action, ":") > 0) { + $dialplan_action_array = explode(":", $dialplan_action); + $dialplan_action_app = array_shift($dialplan_action_array); + $dialplan_action_data = join(':', $dialplan_action_array); + } + else { + $dialplan_action_app = $dialplan_action; + $dialplan_action_data = ''; + } + + //add group action to query + $dialplan_detail_order += 10; + $sql .= ", ( "; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$dialplan_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= "'action', "; + $sql .= "'".$dialplan_action_app."', "; + $sql .= "'".$dialplan_action_data."', "; + $sql .= "null, "; + $sql .= "null, "; + $sql .= "'".$dialplan_detail_group."', "; + $sql .= "'".$dialplan_detail_order."' "; + $sql .= ") "; + } + + } + + } //for each + + + //add to query for default anti-action (if defined) + if (strlen($dialplan_anti_action_app) > 0) { + + //increment group number, reset order number + $dialplan_detail_group = 999; + $dialplan_detail_order = 0; + + //add destination number condition + $dialplan_detail_order += 10; + $sql .= ", ( "; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$dialplan_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= "'condition', "; + $sql .= "'destination_number', "; + $sql .= "'^".$dialplan_number."$', "; + $sql .= "null, "; + $sql .= "null, "; + $sql .= "'".$dialplan_detail_group."', "; + $sql .= "'".$dialplan_detail_order."' "; + $sql .= ") "; + + //add anti-action + $dialplan_detail_order += 10; + $sql .= ", ( "; + $sql .= "'".$domain_uuid."', "; + $sql .= "'".$dialplan_uuid."', "; + $sql .= "'".uuid()."', "; + $sql .= "'action', "; + $sql .= "'".$dialplan_anti_action_app."', "; + $sql .= "'".$dialplan_anti_action_data."', "; + $sql .= "null, "; + $sql .= "null, "; + $sql .= "'".$dialplan_detail_group."', "; + $sql .= "'".$dialplan_detail_order."' "; + $sql .= ") "; + + } + + //execute query + if ($conditions_exist) { + $db->exec(check_sql($sql)); + unset($sql); + } + + //commit the atomic transaction + $count = $db->exec("COMMIT;"); //returns affected rows + + //clear the cache + $cache = new cache; + $cache->delete("dialplan:".$_SESSION["context"]); + + //synchronize the xml config + save_dialplan_xml(); + + //set the message + if ($action == "add") { + $_SESSION['message'] = $text['message-add']; + } + else if ($action == "update") { + $_SESSION['message'] = $text['message-update']; + } + header("Location: time_condition_edit.php?id=".$dialplan_uuid.(($app_uuid != '') ? "&app_uuid=".$app_uuid : null)); + return; + + } //end if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) + + +//get existing data to pre-populate form + if ($dialplan_uuid != '' && $_POST["persistformvar"] != "true") { + + //add the dialplan permission + $p = new permissions; + $p->add("dialplan_add", 'temp'); + $p->add("dialplan_detail_add", 'temp'); + $p->add("dialplan_edit", 'temp'); + $p->add("dialplan_detail_edit", 'temp'); + + //get main dialplan entry + $orm = new orm; + $orm->name('dialplans'); + $orm->uuid($dialplan_uuid); + $result = $orm->find()->get(); + //$message = $orm->message; + foreach ($result as &$row) { + $domain_uuid = $row["domain_uuid"]; + //$app_uuid = $row["app_uuid"]; + $dialplan_name = $row["dialplan_name"]; + $dialplan_number = $row["dialplan_number"]; + $dialplan_order = $row["dialplan_order"]; + $dialplan_continue = $row["dialplan_continue"]; + $dialplan_context = $row["dialplan_context"]; + $dialplan_enabled = $row["dialplan_enabled"]; + $dialplan_description = $row["dialplan_description"]; + } + unset ($prep_statement); + + //remove the temporary permission + $p->delete("dialplan_add", 'temp'); + $p->delete("dialplan_detail_add", 'temp'); + $p->delete("dialplan_edit", 'temp'); + $p->delete("dialplan_detail_edit", 'temp'); + + //get dialplan detail conditions + $sql = "select dialplan_detail_group, dialplan_detail_tag, dialplan_detail_type, dialplan_detail_data from v_dialplan_details "; + $sql .= "where dialplan_uuid = '".$dialplan_uuid."' "; + $sql .= "and "; + $sql .= "( "; + $sql .= " ( "; + $sql .= " dialplan_detail_tag = 'condition' "; + $sql .= " and dialplan_detail_type in ('year','mon','mday','wday','yday','week','mweek','hour','minute','minute-of-day','time-of-day','date-time') "; + $sql .= " ) "; + $sql .= " or ( "; + $sql .= " dialplan_detail_tag = 'action' "; + $sql .= " and dialplan_detail_data not like 'preset=%' "; + $sql .= " ) "; + $sql .= ") "; + $sql .= "order by dialplan_detail_group asc, dialplan_detail_order asc"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $result_count = count($result); + unset ($prep_statement, $sql); + + //load current conditions into array (combined by group), and retrieve action and anti-action + $c = 0; + foreach ($result as $row) { + if ($row['dialplan_detail_tag'] == 'action') { + if ($row['dialplan_detail_group'] == '999') { + $dialplan_anti_action = $row['dialplan_detail_type'].(($row['dialplan_detail_data'] != '') ? ':'.$row['dialplan_detail_data'] : null); + } + else { + $dialplan_actions[$row['dialplan_detail_group']] = $row['dialplan_detail_type'].(($row['dialplan_detail_data'] != '') ? ':'.$row['dialplan_detail_data'] : null); + } + } + else if ($row['dialplan_detail_tag'] == 'condition') { + $current_conditions[$row['dialplan_detail_group']][$row['dialplan_detail_type']] = $row['dialplan_detail_data']; + } + } + + //loop through available presets (if any) + if (isset($available_presets) && sizeof($available_presets) > 0) { + foreach ($available_presets as $preset_number => $preset) { + foreach ($preset as $preset_name => $preset_variables) { + //loop through each condition group + foreach ($current_conditions as $group_id => $condition_variables) { + $matches = 0; + foreach ($condition_variables as $condition_variable_name => $condition_variable_value) { + //count matching variable values + if ($preset_variables[$condition_variable_name] == $condition_variable_value) { $matches++; } + } + //if all preset variables found, then condition is a preset + if ($matches == sizeof($preset_variables)) { + $current_presets[$preset_number] = $group_id; + } + } + } + } + } + + } + +?> + + + +\n"; + +echo "\n"; +echo " \n"; +echo " \n"; +echo " \n"; +echo " \n"; +echo "
\n"; +echo " ".$text['title-time_conditions'].""; +echo "

\n"; +echo " ".$text['description-time_conditions']."\n"; +echo "
\n"; +echo " \n"; +if (if_group("superadmin") && $action == 'update') { + echo " \n"; +} +echo " \n"; +echo "
"; +echo "
\n"; + +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +function add_custom_condition($destination, $group_id, $dialplan_action = '') { + global $text, $v_link_label_add; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; +} + +if ($action == 'update') { + $largest_group_id = 0; + foreach ($current_conditions as $group_id => $conditions) { + if (!is_array($current_presets) || (is_array($current_presets) && !in_array($group_id, $current_presets))) { + add_custom_condition($destination, $group_id, $dialplan_actions[$group_id]); + foreach ($conditions as $cond_var => $cond_val) { + $range_indicator = ($cond_var == 'date-time') ? '~' : '-'; + $tmp = explode($range_indicator, $cond_val); + $cond_val_start = $tmp[0]; + $cond_val_stop = $tmp[1]; + unset($tmp); + + //convert minute-of-day to time-of-day values + if ($cond_var == 'minute-of-day') { + $cond_var = 'time-of-day'; + $cond_val_start = number_pad(floor($cond_val_start / 60),2).":".number_pad(fmod($cond_val_start, 60),2); + if ($cond_val_stop != '') { + $cond_val_stop = number_pad(floor($cond_val_stop / 60),2).":".number_pad(fmod($cond_val_stop, 60),2); + } + } + + echo ""; + } + //used to determine largest custom group id in use + $largest_group_id = ($group_id > $largest_group_id) ? $group_id : $largest_group_id; + } + } +} + +//add first/new set of custom condition fields + if ($action != 'update' || ($action == 'update' && $largest_group_id == 0)) { + $group_id = 500; + } + else { + $group_id = $largest_group_id += 5; + } + add_custom_condition($destination, $group_id); + echo ""; + +//if presets exist, show the preset section + if (isset($available_presets) && sizeof($available_presets) > 0) { + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + } + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "\n"; +echo "\n"; +echo "\n"; +echo "\n"; + +echo "
\n"; +echo " ".$text['label-name']."\n"; +echo "\n"; +echo " \n"; +echo "
\n"; +echo " ".$text['description-name']."\n"; +echo "
\n"; +echo "\n"; +echo "
\n"; +echo " ".$text['label-extension']."\n"; +echo "\n"; +echo " \n"; +echo "
\n"; +echo " ".$text['description-extension']."
\n"; +echo "
\n"; + echo " ".$text['label-settings']; + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " "; + echo " "; + echo " "; + echo " "; + echo " \n"; + echo " \n"; + echo "
".$text['label-condition']."".$text['label-condition_value']."".$text['label-condition_range']."".$v_link_label_add."
"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " "; + echo "
\n"; + //$destination = new destinations; + echo $destination->select('dialplan', 'dialplan_action['.$group_id.']', $dialplan_action); + echo "
\n"; + echo "
"; + echo "
"; + echo " ".$text['description-settings']; + echo "
\n"; + echo " ".$text['label-presets']."\n"; + echo "\n"; + + foreach ($available_presets as $preset_number => $preset) { + foreach ($preset as $preset_name => $preset_variables) { + $checked = (is_array($current_presets) && $current_presets[$preset_number] != '') ? "checked='checked'" : null; + $preset_group_id = ($checked) ? $current_presets[$preset_number] : $preset_group_id = $preset_number * 5 + 100; + if (strlen($text['label-preset_'.$preset_name]) > 0) { + $label_preset_name = $text['label-preset_'.$preset_name]; + } + else { + $label_preset_name = ucwords(str_replace(array("-", "_"), " ", $preset_name)); + } + echo "
\n"; + echo ""; + if ($action == 'update' && is_array($current_presets) && $current_presets[$preset_number] != '') { + //add (potentially customized) preset conditions and populate + foreach ($current_conditions[$preset_group_id] as $cond_var => $cond_val) { + $range_indicator = ($cond_var == 'date-time') ? '~' : '-'; + $tmp = explode($range_indicator, $cond_val); + $cond_val_start = $tmp[0]; + $cond_val_stop = $tmp[1]; + unset($tmp); + + //convert minute-of-day to time-of-day values + if ($cond_var == 'minute-of-day') { + $cond_var = 'time-of-day'; + $cond_val_start = number_pad(floor($cond_val_start / 60),2).":".number_pad(fmod($cond_val_start, 60),2); + if ($cond_val_stop != '') { + $cond_val_stop = number_pad(floor($cond_val_stop / 60),2).":".number_pad(fmod($cond_val_stop, 60),2); + } + } + + echo ""; + } + } + else { + //add default preset conditions and populate + foreach ($preset_variables as $preset_variable => $preset_value) { + $range_indicator = ($preset_variable == 'date-time') ? '~' : '-'; + $tmp = explode($range_indicator, $preset_value); + $preset_value_start = $tmp[0]; + $preset_value_stop = $tmp[1]; + unset($tmp); + echo "\n\n"; + } + } + } + } + + echo "
\n"; + echo " \n"; + echo " "; + echo " "; + echo " "; + echo "
"; + echo " \n"; + echo " "; + echo $destination->select('dialplan', 'default_preset_action', $dialplan_action); + echo " "; + echo "
"; + echo "
"; + echo " ".$text['description-presets']."
\n"; + echo "
\n"; +echo " ".$text['label-alternate-destination']."\n"; +echo "\n"; +echo $destination->select('dialplan', 'dialplan_anti_action', $dialplan_anti_action); +echo "
\n"; +echo " ".$text['label-order']."\n"; +echo "\n"; +echo " \n"; +echo "
\n"; +echo "
\n"; +echo " ".$text['label-enabled']."\n"; +echo "\n"; +echo "\n"; +echo "
\n"; +echo "
\n"; +echo " ".$text['label-description']."\n"; +echo "\n"; +echo " \n"; +echo "
\n"; +echo "
\n"; +echo "
"; + +echo "
\n"; +if ($action == "update") { + echo " \n"; +} +echo " \n"; +echo "
"; + +echo ""; +echo "
"; + +//include the footer + require_once "resources/footer.php"; + ?> \ No newline at end of file diff --git a/app/voicemail_greetings/app_defaults.php b/app/voicemail_greetings/app_defaults.php index 7db79cb0ae..f16d463a6e 100644 --- a/app/voicemail_greetings/app_defaults.php +++ b/app/voicemail_greetings/app_defaults.php @@ -1,123 +1,123 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -if ($domains_processed == 1) { - //if greeting filename field empty, copy greeting name field value - $sql = "update v_voicemail_greetings "; - $sql .= "set greeting_filename = greeting_name "; - $sql .= "where greeting_filename is null "; - $sql .= "or greeting_filename = '' "; - $db->exec(check_sql($sql)); - unset($sql); - - //populate greeting id number if empty - $sql = "select voicemail_greeting_uuid, greeting_filename "; - $sql .= "from v_voicemail_greetings "; - $sql .= "where greeting_id is null "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $voicemail_greeting_uuid = $row['voicemail_greeting_uuid']; - $greeting_id = preg_replace('{\D}', '', $row['greeting_filename']); - $sqlu = "update v_voicemail_greetings "; - $sqlu .= "set greeting_id = ".$greeting_id." "; - $sqlu .= "where voicemail_greeting_uuid = '".$voicemail_greeting_uuid."' "; - $db->exec(check_sql($sqlu)); - unset($sqlu, $voicemail_greeting_uuid, $greeting_id); - } - unset ($sql, $prep_statement); - - //if base64, populate from existing greeting files, then remove - if ($_SESSION['voicemail']['storage_type']['text'] == 'base64') { - //get greetings without base64 in db - $sql = "select voicemail_greeting_uuid, domain_uuid, voicemail_id, greeting_filename "; - $sql .= "from v_voicemail_greetings where greeting_base64 is null or greeting_base64 = '' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) > 0) { - foreach ($result as &$row) { - $voicemail_greeting_uuid = $row['voicemail_greeting_uuid']; - $greeting_domain_uuid = $row['domain_uuid']; - $voicemail_id = $row['voicemail_id']; - $greeting_filename = $row['greeting_filename']; - //set greeting directory - $greeting_directory = $_SESSION['switch']['storage']['dir'].'/voicemail/default/'.$_SESSION['domains'][$greeting_domain_uuid]['domain_name'].'/'.$voicemail_id; - //encode greeting file (if exists) - if (file_exists($greeting_directory.'/'.$greeting_filename)) { - $greeting_base64 = base64_encode(file_get_contents($greeting_directory.'/'.$greeting_filename)); - //update greeting record with base64 - $sql = "update v_voicemail_greetings set "; - $sql .= "greeting_base64 = '".$greeting_base64."' "; - $sql .= "where domain_uuid = '".$greeting_domain_uuid."' "; - $sql .= "and voicemail_greeting_uuid = '".$voicemail_greeting_uuid."' "; - $db->exec(check_sql($sql)); - unset($sql); - //remove local greeting file - @unlink($greeting_directory.'/'.$greeting_filename); - } - } - } - unset($sql, $prep_statement, $result, $row); - } - //if not base64, decode to local files, remove base64 data from db - else if ($_SESSION['voicemail']['storage_type']['text'] != 'base64') { - //get greetings with base64 in db - $sql = "select voicemail_greeting_uuid, domain_uuid, voicemail_id, greeting_filename, greeting_base64 "; - $sql .= "from v_voicemail_greetings where greeting_base64 is not null "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - if (count($result) > 0) { - foreach ($result as &$row) { - $voicemail_greeting_uuid = $row['voicemail_greeting_uuid']; - $greeting_domain_uuid = $row['domain_uuid']; - $voicemail_id = $row['voicemail_id']; - $greeting_filename = $row['greeting_filename']; - $greeting_base64 = $row['greeting_base64']; - //set greeting directory - $greeting_directory = $_SESSION['switch']['storage']['dir'].'/voicemail/default/'.$_SESSION['domains'][$greeting_domain_uuid]['domain_name'].'/'.$voicemail_id; - //remove local file, if any - if (file_exists($greeting_directory.'/'.$greeting_filename)) { - @unlink($greeting_directory.'/'.$greeting_filename); - } - //decode base64, save to local file - $greeting_decoded = base64_decode($greeting_base64); - file_put_contents($greeting_directory.'/'.$greeting_filename, $greeting_decoded); - $sql = "update v_voicemail_greetings "; - $sql .= "set greeting_base64 = null "; - $sql .= "where domain_uuid = '".$greeting_domain_uuid."' "; - $sql .= "and voicemail_greeting_uuid = '".$voicemail_greeting_uuid."' "; - $db->exec(check_sql($sql)); - unset($sql); - } - } - unset($sql, $prep_statement, $result, $row); - } -} - + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +if ($domains_processed == 1) { + //if greeting filename field empty, copy greeting name field value + $sql = "update v_voicemail_greetings "; + $sql .= "set greeting_filename = greeting_name "; + $sql .= "where greeting_filename is null "; + $sql .= "or greeting_filename = '' "; + $db->exec(check_sql($sql)); + unset($sql); + + //populate greeting id number if empty + $sql = "select voicemail_greeting_uuid, greeting_filename "; + $sql .= "from v_voicemail_greetings "; + $sql .= "where greeting_id is null "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $voicemail_greeting_uuid = $row['voicemail_greeting_uuid']; + $greeting_id = preg_replace('{\D}', '', $row['greeting_filename']); + $sqlu = "update v_voicemail_greetings "; + $sqlu .= "set greeting_id = ".$greeting_id." "; + $sqlu .= "where voicemail_greeting_uuid = '".$voicemail_greeting_uuid."' "; + $db->exec(check_sql($sqlu)); + unset($sqlu, $voicemail_greeting_uuid, $greeting_id); + } + unset ($sql, $prep_statement); + + //if base64, populate from existing greeting files, then remove + if ($_SESSION['voicemail']['storage_type']['text'] == 'base64') { + //get greetings without base64 in db + $sql = "select voicemail_greeting_uuid, domain_uuid, voicemail_id, greeting_filename "; + $sql .= "from v_voicemail_greetings where greeting_base64 is null or greeting_base64 = '' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) > 0) { + foreach ($result as &$row) { + $voicemail_greeting_uuid = $row['voicemail_greeting_uuid']; + $greeting_domain_uuid = $row['domain_uuid']; + $voicemail_id = $row['voicemail_id']; + $greeting_filename = $row['greeting_filename']; + //set greeting directory + $greeting_directory = $_SESSION['switch']['storage']['dir'].'/voicemail/default/'.$_SESSION['domains'][$greeting_domain_uuid]['domain_name'].'/'.$voicemail_id; + //encode greeting file (if exists) + if (file_exists($greeting_directory.'/'.$greeting_filename)) { + $greeting_base64 = base64_encode(file_get_contents($greeting_directory.'/'.$greeting_filename)); + //update greeting record with base64 + $sql = "update v_voicemail_greetings set "; + $sql .= "greeting_base64 = '".$greeting_base64."' "; + $sql .= "where domain_uuid = '".$greeting_domain_uuid."' "; + $sql .= "and voicemail_greeting_uuid = '".$voicemail_greeting_uuid."' "; + $db->exec(check_sql($sql)); + unset($sql); + //remove local greeting file + @unlink($greeting_directory.'/'.$greeting_filename); + } + } + } + unset($sql, $prep_statement, $result, $row); + } + //if not base64, decode to local files, remove base64 data from db + else if ($_SESSION['voicemail']['storage_type']['text'] != 'base64') { + //get greetings with base64 in db + $sql = "select voicemail_greeting_uuid, domain_uuid, voicemail_id, greeting_filename, greeting_base64 "; + $sql .= "from v_voicemail_greetings where greeting_base64 is not null "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + if (count($result) > 0) { + foreach ($result as &$row) { + $voicemail_greeting_uuid = $row['voicemail_greeting_uuid']; + $greeting_domain_uuid = $row['domain_uuid']; + $voicemail_id = $row['voicemail_id']; + $greeting_filename = $row['greeting_filename']; + $greeting_base64 = $row['greeting_base64']; + //set greeting directory + $greeting_directory = $_SESSION['switch']['storage']['dir'].'/voicemail/default/'.$_SESSION['domains'][$greeting_domain_uuid]['domain_name'].'/'.$voicemail_id; + //remove local file, if any + if (file_exists($greeting_directory.'/'.$greeting_filename)) { + @unlink($greeting_directory.'/'.$greeting_filename); + } + //decode base64, save to local file + $greeting_decoded = base64_decode($greeting_base64); + file_put_contents($greeting_directory.'/'.$greeting_filename, $greeting_decoded); + $sql = "update v_voicemail_greetings "; + $sql .= "set greeting_base64 = null "; + $sql .= "where domain_uuid = '".$greeting_domain_uuid."' "; + $sql .= "and voicemail_greeting_uuid = '".$voicemail_greeting_uuid."' "; + $db->exec(check_sql($sql)); + unset($sql); + } + } + unset($sql, $prep_statement, $result, $row); + } +} + ?> \ No newline at end of file diff --git a/app/voicemails/app_defaults.php b/app/voicemails/app_defaults.php index 8845132c68..6987fef7c6 100644 --- a/app/voicemails/app_defaults.php +++ b/app/voicemails/app_defaults.php @@ -1,97 +1,97 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -//proccess this only one time -if ($domains_processed == 1) { - - //migrate existing attachment preferences to new column, where appropriate - $sql = "update v_voicemails set voicemail_file = 'attach' where voicemail_attach_file = 'true'"; - $db->exec(check_sql($sql)); - unset($sql); - - //define array of settings - $x = 0; - $array[$x]['default_setting_category'] = 'voicemail'; - $array[$x]['default_setting_subcategory'] = 'voicemail_file'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'attach'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Define whether to attach voicemail files to email notifications, or only include a link.'; - $x++; - $array[$x]['default_setting_category'] = 'voicemail'; - $array[$x]['default_setting_subcategory'] = 'keep_local'; - $array[$x]['default_setting_name'] = 'boolean'; - $array[$x]['default_setting_value'] = 'true'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Define whether to keep voicemail files on the local system after sending attached via email.'; - $x++; - $array[$x]['default_setting_category'] = 'voicemail'; - $array[$x]['default_setting_subcategory'] = 'storage_type'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'base64'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Define which storage type (base_64 stores in the database).'; - $x++; - - //iterate and add each, if necessary - foreach ($array as $index => $default_settings) { - //add the default setting - $sql = "select count(*) as num_rows from v_default_settings "; - $sql .= "where default_setting_category = '".$default_settings['default_setting_category']."' "; - $sql .= "and default_setting_subcategory = '".$default_settings['default_setting_subcategory']."' "; - $sql .= "and default_setting_name = '".$default_settings['default_setting_name']."' "; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - unset($prep_statement); - if ($row['num_rows'] == 0) { - $orm = new orm; - $orm->name('default_settings'); - $orm->save($array[$index]); - $message = $orm->message; - //print_r($message); - } - unset($row); - } - } - - //add that the directory structure for voicemail each domain and voicemail id is - $sql = "select d.domain_name, v.voicemail_id "; - $sql .= "from v_domains as d, v_voicemails as v "; - $sql .= "where v.domain_uuid = d.domain_uuid "; - $prep_statement = $db->prepare($sql); - $prep_statement->execute(); - $voicemails = $prep_statement->fetchAll(PDO::FETCH_ASSOC); - foreach ($voicemails as $row) { - $path = $_SESSION['switch']['voicemail']['dir'].'/default/'.$row['domain_name'].'/'.$row['voicemail_id']; - mkdir($path, 0777, true); - } - unset ($prep_statement, $sql); - -} - + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +//proccess this only one time +if ($domains_processed == 1) { + + //migrate existing attachment preferences to new column, where appropriate + $sql = "update v_voicemails set voicemail_file = 'attach' where voicemail_attach_file = 'true'"; + $db->exec(check_sql($sql)); + unset($sql); + + //define array of settings + $x = 0; + $array[$x]['default_setting_category'] = 'voicemail'; + $array[$x]['default_setting_subcategory'] = 'voicemail_file'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'attach'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Define whether to attach voicemail files to email notifications, or only include a link.'; + $x++; + $array[$x]['default_setting_category'] = 'voicemail'; + $array[$x]['default_setting_subcategory'] = 'keep_local'; + $array[$x]['default_setting_name'] = 'boolean'; + $array[$x]['default_setting_value'] = 'true'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Define whether to keep voicemail files on the local system after sending attached via email.'; + $x++; + $array[$x]['default_setting_category'] = 'voicemail'; + $array[$x]['default_setting_subcategory'] = 'storage_type'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'base64'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Define which storage type (base_64 stores in the database).'; + $x++; + + //iterate and add each, if necessary + foreach ($array as $index => $default_settings) { + //add the default setting + $sql = "select count(*) as num_rows from v_default_settings "; + $sql .= "where default_setting_category = '".$default_settings['default_setting_category']."' "; + $sql .= "and default_setting_subcategory = '".$default_settings['default_setting_subcategory']."' "; + $sql .= "and default_setting_name = '".$default_settings['default_setting_name']."' "; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + unset($prep_statement); + if ($row['num_rows'] == 0) { + $orm = new orm; + $orm->name('default_settings'); + $orm->save($array[$index]); + $message = $orm->message; + //print_r($message); + } + unset($row); + } + } + + //add that the directory structure for voicemail each domain and voicemail id is + $sql = "select d.domain_name, v.voicemail_id "; + $sql .= "from v_domains as d, v_voicemails as v "; + $sql .= "where v.domain_uuid = d.domain_uuid "; + $prep_statement = $db->prepare($sql); + $prep_statement->execute(); + $voicemails = $prep_statement->fetchAll(PDO::FETCH_ASSOC); + foreach ($voicemails as $row) { + $path = $_SESSION['switch']['voicemail']['dir'].'/default/'.$row['domain_name'].'/'.$row['voicemail_id']; + mkdir($path, 0777, true); + } + unset ($prep_statement, $sql); + +} + ?> \ No newline at end of file diff --git a/app/voicemails/app_languages.php b/app/voicemails/app_languages.php index 6596ee0001..d7bfe0ed64 100644 --- a/app/voicemails/app_languages.php +++ b/app/voicemails/app_languages.php @@ -1,715 +1,715 @@ - \ No newline at end of file diff --git a/app/voicemails/voicemail_message_toggle.php b/app/voicemails/voicemail_message_toggle.php index 8dd367eb5f..f2da870c5a 100644 --- a/app/voicemails/voicemail_message_toggle.php +++ b/app/voicemails/voicemail_message_toggle.php @@ -1,78 +1,78 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('voicemail_message_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get submitted variables - $voicemail_messages = $_REQUEST["voicemail_messages"]; - -//toggle the voicemail message - $toggled = 0; - if (is_array($voicemail_messages) && sizeof($voicemail_messages) > 0) { - require_once "resources/classes/voicemail.php"; - foreach ($voicemail_messages as $voicemail_uuid => $voicemail_message_uuids) { - foreach ($voicemail_message_uuids as $voicemail_message_uuid) { - $voicemail = new voicemail; - $voicemail->db = $db; - $voicemail->domain_uuid = $_SESSION['domain_uuid']; - $voicemail->voicemail_uuid = check_str($voicemail_uuid); - $voicemail->voicemail_message_uuid = check_str($voicemail_message_uuid); - $result = $voicemail->message_toggle(); - unset($voicemail); - $toggled++; - } - } - } - -//set the referrer - $http_referer = parse_url($_SERVER["HTTP_REFERER"]); - $referer_path = $http_referer['path']; - $referer_query = $http_referer['query']; - -//redirect the user - if ($toggled > 0) { - $_SESSION["message"] = $text['message-toggled'].': '.$toggled; - } - if ($referer_path == PROJECT_PATH."/app/voicemails/voicemail_messages.php") { - header("Location: voicemail_messages.php?".$referer_query); - } - else { - header("Location: voicemails.php"); - } - + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('voicemail_message_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get submitted variables + $voicemail_messages = $_REQUEST["voicemail_messages"]; + +//toggle the voicemail message + $toggled = 0; + if (is_array($voicemail_messages) && sizeof($voicemail_messages) > 0) { + require_once "resources/classes/voicemail.php"; + foreach ($voicemail_messages as $voicemail_uuid => $voicemail_message_uuids) { + foreach ($voicemail_message_uuids as $voicemail_message_uuid) { + $voicemail = new voicemail; + $voicemail->db = $db; + $voicemail->domain_uuid = $_SESSION['domain_uuid']; + $voicemail->voicemail_uuid = check_str($voicemail_uuid); + $voicemail->voicemail_message_uuid = check_str($voicemail_message_uuid); + $result = $voicemail->message_toggle(); + unset($voicemail); + $toggled++; + } + } + } + +//set the referrer + $http_referer = parse_url($_SERVER["HTTP_REFERER"]); + $referer_path = $http_referer['path']; + $referer_query = $http_referer['query']; + +//redirect the user + if ($toggled > 0) { + $_SESSION["message"] = $text['message-toggled'].': '.$toggled; + } + if ($referer_path == PROJECT_PATH."/app/voicemails/voicemail_messages.php") { + header("Location: voicemail_messages.php?".$referer_query); + } + else { + header("Location: voicemails.php"); + } + ?> \ No newline at end of file diff --git a/app/xml_cdr/app_languages.php b/app/xml_cdr/app_languages.php index d36ac75e4c..8d9a3f2c79 100644 --- a/app/xml_cdr/app_languages.php +++ b/app/xml_cdr/app_languages.php @@ -1,1283 +1,1283 @@ -Note: Source, Destination and Caller ID (CID) Name fields support the use of an asterisk ('*') as a wildcard character."; -$text['description_search']['es-cl'] = "Atención: Origen, Destino y el identificador de llamadas (CID) campos Nombre apoyan el uso de un asterisco ('*') como carácter comodín."; -$text['description_search']['pt-pt'] = "Atenção: origem, destino e identificação do chamador (CID) campos Nome apoiar o uso de um asterisco ('*') como um caractere curinga."; -$text['description_search']['fr-fr'] = "Attention: Source, Destination et identification de l'appelant (CID) champs Nom appuient l'utilisation de l'astérisque ('*') comme un caractère générique."; -$text['description_search']['pt-br'] = "Atenção: origem, destino e identificação do chamador (CID) campos Nome apoiar o uso de um asterisco ('*') como um caractere curinga. "; -$text['description_search']['pl'] = "Uwaga: Następujące pola: numer dzwoniącego i odbiorcy rozmowy, prezentacja numeru oraz nazwy wspierają gwiazdkę (‘*’) jako symbol wieloznaczny."; -$text['description_search']['sv-se'] = "Notera : Källa, Destination och Nummerpresentation ( CID ) Namn fält stödjer användningen av en asterisk ( ' * ' ) som jokertecken."; -$text['description_search']['uk'] = ""; -$text['description_search']['de-at'] = "Info: Quelle, Ziel und Anruferkennung (CID) Name Felder unterstützen die Verwendung von Stern ('*') als Wildcard Zeichen."; -$text['description_search']['he'] = ""; - -$text['description-7']['en-us'] = "Call variables, call flow, timing information, and other useful call details."; -$text['description-7']['es-cl'] = "variables de llamada, flujo, información temporal y otros detalles útiles."; -$text['description-7']['pt-pt'] = "variáveis de chamada, fluxo da chamada, informações de tempo e outras informações úteis."; -$text['description-7']['fr-fr'] = "les variables de l'appel, le chemin, les compteurs et d'autres détails."; -$text['description-7']['pt-br'] = "Variáveis de chamada, fluxo da chamada, informações de tempo e outras informações úteis. "; -$text['description-7']['pl'] = "Zmienne związane z rozmowami, przepływ połączeń, informacje o czasach rozmów oraz inne przydatne szczegóły "; -$text['description-7']['sv-se'] = "Samtalsvariabler, samtalsflöden, tidsinformation och andra nyttiga samtalsdetaljer."; -$text['description-7']['uk'] = ""; -$text['description-7']['de-at'] = "Anruf Variablen, Ruf-Ablauf, Zeit Information und andere nützliche Anruf Details"; -$text['description-7']['he'] = ""; - -$text['description-6']['en-us'] = "The information contains caller id name and number, channel data, "; -$text['description-6']['es-cl'] = "La información contiene el nombre y número del caller id, datos del canal, "; -$text['description-6']['pt-pt'] = "A informação contem o nome e o número de origem, dados do canal, "; -$text['description-6']['fr-fr'] = "L'information contient le nom et le numéro d'appelant, données du canal, "; -$text['description-6']['pt-br'] = "A informação contém o nome e número de origem, dados do canal."; -$text['description-6']['pl'] = "Informacja zawiera prezentacje numeru i nazwy dzwoniącego oraz informacje o kanale."; -$text['description-6']['sv-se'] = "Informationen innehåller presentation av namn och nummer, channel data,"; -$text['description-6']['uk'] = ""; -$text['description-6']['de-at'] = "Die Information beinhaltet Anruferkennung (Name, Nummer) und Kanal Daten."; -$text['description-6']['he'] = ""; - -$text['description-5']['en-us'] = "A detailed view of the call and all information regarding it."; -$text['description-5']['es-cl'] = "Una vista detallada de la información de la llamada."; -$text['description-5']['pt-pt'] = "Uma visão detalhada da chamada e de todas as informações sobre ela."; -$text['description-5']['fr-fr'] = "Une vue détaillée de l'appel et toutes les informations en relation."; -$text['description-5']['pt-br'] = "Uma visão detalhada da chamada "; -$text['description-5']['pl'] = "Przeglądaj szczegóły rozmowy i inne informacje z nią związane."; -$text['description-5']['sv-se'] = "En detaljerad vy av samtalet och information kring samtalet."; -$text['description-5']['uk'] = ""; -$text['description-5']['de-at'] = "Eine detaillierte Ansicht des Anrufes mit allen zugehörigen Informationen."; -$text['description-5']['he'] = ""; - -$text['description-4']['en-us'] = "Records in the call list can be saved locally using the Export button."; -$text['description-4']['es-cl'] = "A continuación, ver las llamadas de la lista o descargarlos usando el botón Exportar."; -$text['description-4']['pt-pt'] = "Em seguida, visualizar as chamadas na lista ou baixá-los utilizando o botão Export."; -$text['description-4']['fr-fr'] = "Puis afficher les appels dans la liste ou les télécharger en utilisant le bouton Exporter."; -$text['description-4']['pt-br'] = "Em seguida, visualizar as chamadas na lista ou baixá-los utilizando o botão Export."; -$text['description-4']['pl'] = "Następnie przejrzeć połączenia z listy lub pobrać je za pomocą przycisku Eksportuj."; -$text['description-4']['sv-se'] = "Sedan visa samtalen i listan eller hämta dem med knappen Export."; -$text['description-4']['uk'] = ""; -$text['description-4']['de-at'] = "Sehen Sie dann die Anrufe in der Liste oder laden Sie sie auf die Schaltfläche Export verwenden."; -$text['description-4']['he'] = ""; - -$text['description-3']['en-us'] = "Use the fields to filter the information for the specific call records that are desired."; -$text['description-3']['es-cl'] = "Use los campos para filtrar la información. "; -$text['description-3']['pt-pt'] = "Utilize os campos para filtrar a informação sobre os registos de chamadas desejados."; -$text['description-3']['fr-fr'] = "Utiliser les filtres pour afficher les appels désirés. "; -$text['description-3']['pt-br'] = "Utilize os campos para filtrar a informação sobre os registos de chamadas desejados. "; -$text['description-3']['pl'] = "Użyj tych pól do filtrowania wymaganych informacji o konkretnych rozmowach. "; -$text['description-3']['sv-se'] = "Använd fälten för att filtrera fram det önskade resultatet."; -$text['description-3']['uk'] = ""; -$text['description-3']['de-at'] = "Benutzen Sie die Felder um Informationen betreffend spezifischer Anrufe zu filtern."; -$text['description-3']['he'] = ""; - -$text['description-2']['en-us'] = "The information contains source, destination, duration, and other useful call details."; -$text['description-2']['es-cl'] = "La información contiene origen, destino, duración y otra información útil."; -$text['description-2']['pt-pt'] = "A informação contem a origem, destino, duração e outros detalhes úteis da chamada."; -$text['description-2']['fr-fr'] = "Les informations contiennent la source, la destination, la durée et pleins d'autres informations utiles."; -$text['description-2']['pt-br'] = "A informação contem a origem, destino, duração e outros detalhes úteis da chamada. "; -$text['description-2']['pl'] = "Informacja zawiera numer dzwoniącego i odbiorcy rozmowy, czas trwania oraz inne przydatne szczegóły."; -$text['description-2']['sv-se'] = "Informationen innehåller källa, destination, samtalstid, och annan nyttig information."; -$text['description-2']['uk'] = ""; -$text['description-2']['de-at'] = "Die Information beinhaltet Quelle, Ziel, Dauer und andere nützliche Details."; -$text['description-2']['he'] = ""; - -$text['description']['en-us'] = "Call Detail Records (CDRs) are detailed information on the calls."; -$text['description']['es-cl'] = "Los registros de detalle de llamadas (CDR) contienen información detallada de las llamadas."; -$text['description']['pt-pt'] = "O registo detalhado de chamadas mostra informações detalhadas sobre as chamadas."; -$text['description']['fr-fr'] = "Ici se trouve l'historique des tous les appels passés sur cette plateforme. En Anglais: Call Detail Records (CDR)."; -$text['description']['pt-br'] = "Editar informações da conta."; -$text['description']['pl'] = "Wykaz rozmów prezentuje szczegółowe informacje o zrealizowanych rozmowach."; -$text['description']['sv-se'] = "Detaljerad Samtalsinformation (CDR) är detaljerad information från samtalen."; -$text['description']['uk'] = "Редагування інформації облікового запису"; -$text['description']['de-at'] = "Kontoinformationen bearbeiten"; -$text['description']['he'] = "ערוך את פרטי החשבון"; - -$text['button-update']['en-us'] = "Update"; -$text['button-update']['es-cl'] = "Actualización"; -$text['button-update']['pt-pt'] = "Atualizar"; -$text['button-update']['fr-fr'] = "Mise à jour"; -$text['button-update']['pt-br'] = "Atualização"; -$text['button-update']['pl'] = "Uaktualnij"; -$text['button-update']['sv-se'] = "Uppdatera"; -$text['button-update']['uk'] = "Оновити"; -$text['button-update']['de-at'] = "Aktualisieren"; -$text['button-update']['he'] = "עדכון"; - -$text['button-statistics']['en-us'] = "Statistics"; -$text['button-statistics']['es-cl'] = "Estadísticas"; -$text['button-statistics']['pt-pt'] = "Estatísticas"; -$text['button-statistics']['fr-fr'] = "Statistiques"; -$text['button-statistics']['pt-br'] = "Estatísticas "; -$text['button-statistics']['pl'] = "Ststystyki"; -$text['button-statistics']['sv-se'] = "Statistik"; -$text['button-statistics']['uk'] = ""; -$text['button-statistics']['de-at'] = "Statistik"; -$text['button-statistics']['he'] = "סטטיסטיקה"; - -$text['button-missed']['en-us'] = "Missed Calls"; -$text['button-missed']['es-cl'] = "Llamadas Perdidas"; -$text['button-missed']['pt-pt'] = "Chamadas Perdidas"; -$text['button-missed']['fr-fr'] = "Appels Perdus"; -$text['button-missed']['pt-br'] = "Chamadas Perdidas "; -$text['button-missed']['pl'] = "NIeodebrane rozmowy"; -$text['button-missed']['sv-se'] = "Missade Samtal"; -$text['button-missed']['uk'] = ""; -$text['button-missed']['de-at'] = "Verpasste Anrufe"; -$text['button-missed']['he'] = "שיחות שלא נענו"; - -$text['button-extension_summary']['en-us'] = "Extension Summary"; -$text['button-extension_summary']['es-cl'] = "Resumen Extensión"; -$text['button-extension_summary']['pt-pt'] = "Resumo Extensão"; -$text['button-extension_summary']['fr-fr'] = "Résumé par Extension"; -$text['button-extension_summary']['pt-br'] = "Resumo Extensão "; -$text['button-extension_summary']['pl'] = "Podsumowanie numerów wewnętrznych"; -$text['button-extension_summary']['sv-se'] = "Anknytning Summering"; -$text['button-extension_summary']['uk'] = ""; -$text['button-extension_summary']['de-at'] = "Nebenstellen Statistik"; -$text['button-extension_summary']['he'] = ""; - -$text['button-download_csv']['en-us'] = "Download CSV"; -$text['button-download_csv']['es-cl'] = "Descarga CSV"; -$text['button-download_csv']['pt-pt'] = "Baixar CSV"; -$text['button-download_csv']['fr-fr'] = "Télécharger CSV"; -$text['button-download_csv']['pt-br'] = "Baixar CSV "; -$text['button-download_csv']['pl'] = "Pobierz CSV"; -$text['button-download_csv']['sv-se'] = "Ladda Ned CSV"; -$text['button-download_csv']['uk'] = ""; -$text['button-download_csv']['de-at'] = "CSV Herunterladen"; -$text['button-download_csv']['he'] = ""; - -$text['button-advanced_search']['en-us'] = "Advanced Search"; -$text['button-advanced_search']['es-cl'] = "Búsqueda Avanzada"; -$text['button-advanced_search']['pt-pt'] = "Pesquisa Avançada"; -$text['button-advanced_search']['fr-fr'] = "Recherche Avancée"; -$text['button-advanced_search']['pt-br'] = "Pesquisa Avançada "; -$text['button-advanced_search']['pl'] = "Zaawansowane wyszukiwanie"; -$text['button-advanced_search']['sv-se'] = "Avancerad Sökning"; -$text['button-advanced_search']['uk'] = ""; -$text['button-advanced_search']['de-at'] = "Erweiterte Suche"; -$text['button-advanced_search']['he'] = "חיפוש מתקדם"; - +Note: Source, Destination and Caller ID (CID) Name fields support the use of an asterisk ('*') as a wildcard character."; +$text['description_search']['es-cl'] = "Atención: Origen, Destino y el identificador de llamadas (CID) campos Nombre apoyan el uso de un asterisco ('*') como carácter comodín."; +$text['description_search']['pt-pt'] = "Atenção: origem, destino e identificação do chamador (CID) campos Nome apoiar o uso de um asterisco ('*') como um caractere curinga."; +$text['description_search']['fr-fr'] = "Attention: Source, Destination et identification de l'appelant (CID) champs Nom appuient l'utilisation de l'astérisque ('*') comme un caractère générique."; +$text['description_search']['pt-br'] = "Atenção: origem, destino e identificação do chamador (CID) campos Nome apoiar o uso de um asterisco ('*') como um caractere curinga. "; +$text['description_search']['pl'] = "Uwaga: Następujące pola: numer dzwoniącego i odbiorcy rozmowy, prezentacja numeru oraz nazwy wspierają gwiazdkę (‘*’) jako symbol wieloznaczny."; +$text['description_search']['sv-se'] = "Notera : Källa, Destination och Nummerpresentation ( CID ) Namn fält stödjer användningen av en asterisk ( ' * ' ) som jokertecken."; +$text['description_search']['uk'] = ""; +$text['description_search']['de-at'] = "Info: Quelle, Ziel und Anruferkennung (CID) Name Felder unterstützen die Verwendung von Stern ('*') als Wildcard Zeichen."; +$text['description_search']['he'] = ""; + +$text['description-7']['en-us'] = "Call variables, call flow, timing information, and other useful call details."; +$text['description-7']['es-cl'] = "variables de llamada, flujo, información temporal y otros detalles útiles."; +$text['description-7']['pt-pt'] = "variáveis de chamada, fluxo da chamada, informações de tempo e outras informações úteis."; +$text['description-7']['fr-fr'] = "les variables de l'appel, le chemin, les compteurs et d'autres détails."; +$text['description-7']['pt-br'] = "Variáveis de chamada, fluxo da chamada, informações de tempo e outras informações úteis. "; +$text['description-7']['pl'] = "Zmienne związane z rozmowami, przepływ połączeń, informacje o czasach rozmów oraz inne przydatne szczegóły "; +$text['description-7']['sv-se'] = "Samtalsvariabler, samtalsflöden, tidsinformation och andra nyttiga samtalsdetaljer."; +$text['description-7']['uk'] = ""; +$text['description-7']['de-at'] = "Anruf Variablen, Ruf-Ablauf, Zeit Information und andere nützliche Anruf Details"; +$text['description-7']['he'] = ""; + +$text['description-6']['en-us'] = "The information contains caller id name and number, channel data, "; +$text['description-6']['es-cl'] = "La información contiene el nombre y número del caller id, datos del canal, "; +$text['description-6']['pt-pt'] = "A informação contem o nome e o número de origem, dados do canal, "; +$text['description-6']['fr-fr'] = "L'information contient le nom et le numéro d'appelant, données du canal, "; +$text['description-6']['pt-br'] = "A informação contém o nome e número de origem, dados do canal."; +$text['description-6']['pl'] = "Informacja zawiera prezentacje numeru i nazwy dzwoniącego oraz informacje o kanale."; +$text['description-6']['sv-se'] = "Informationen innehåller presentation av namn och nummer, channel data,"; +$text['description-6']['uk'] = ""; +$text['description-6']['de-at'] = "Die Information beinhaltet Anruferkennung (Name, Nummer) und Kanal Daten."; +$text['description-6']['he'] = ""; + +$text['description-5']['en-us'] = "A detailed view of the call and all information regarding it."; +$text['description-5']['es-cl'] = "Una vista detallada de la información de la llamada."; +$text['description-5']['pt-pt'] = "Uma visão detalhada da chamada e de todas as informações sobre ela."; +$text['description-5']['fr-fr'] = "Une vue détaillée de l'appel et toutes les informations en relation."; +$text['description-5']['pt-br'] = "Uma visão detalhada da chamada "; +$text['description-5']['pl'] = "Przeglądaj szczegóły rozmowy i inne informacje z nią związane."; +$text['description-5']['sv-se'] = "En detaljerad vy av samtalet och information kring samtalet."; +$text['description-5']['uk'] = ""; +$text['description-5']['de-at'] = "Eine detaillierte Ansicht des Anrufes mit allen zugehörigen Informationen."; +$text['description-5']['he'] = ""; + +$text['description-4']['en-us'] = "Records in the call list can be saved locally using the Export button."; +$text['description-4']['es-cl'] = "A continuación, ver las llamadas de la lista o descargarlos usando el botón Exportar."; +$text['description-4']['pt-pt'] = "Em seguida, visualizar as chamadas na lista ou baixá-los utilizando o botão Export."; +$text['description-4']['fr-fr'] = "Puis afficher les appels dans la liste ou les télécharger en utilisant le bouton Exporter."; +$text['description-4']['pt-br'] = "Em seguida, visualizar as chamadas na lista ou baixá-los utilizando o botão Export."; +$text['description-4']['pl'] = "Następnie przejrzeć połączenia z listy lub pobrać je za pomocą przycisku Eksportuj."; +$text['description-4']['sv-se'] = "Sedan visa samtalen i listan eller hämta dem med knappen Export."; +$text['description-4']['uk'] = ""; +$text['description-4']['de-at'] = "Sehen Sie dann die Anrufe in der Liste oder laden Sie sie auf die Schaltfläche Export verwenden."; +$text['description-4']['he'] = ""; + +$text['description-3']['en-us'] = "Use the fields to filter the information for the specific call records that are desired."; +$text['description-3']['es-cl'] = "Use los campos para filtrar la información. "; +$text['description-3']['pt-pt'] = "Utilize os campos para filtrar a informação sobre os registos de chamadas desejados."; +$text['description-3']['fr-fr'] = "Utiliser les filtres pour afficher les appels désirés. "; +$text['description-3']['pt-br'] = "Utilize os campos para filtrar a informação sobre os registos de chamadas desejados. "; +$text['description-3']['pl'] = "Użyj tych pól do filtrowania wymaganych informacji o konkretnych rozmowach. "; +$text['description-3']['sv-se'] = "Använd fälten för att filtrera fram det önskade resultatet."; +$text['description-3']['uk'] = ""; +$text['description-3']['de-at'] = "Benutzen Sie die Felder um Informationen betreffend spezifischer Anrufe zu filtern."; +$text['description-3']['he'] = ""; + +$text['description-2']['en-us'] = "The information contains source, destination, duration, and other useful call details."; +$text['description-2']['es-cl'] = "La información contiene origen, destino, duración y otra información útil."; +$text['description-2']['pt-pt'] = "A informação contem a origem, destino, duração e outros detalhes úteis da chamada."; +$text['description-2']['fr-fr'] = "Les informations contiennent la source, la destination, la durée et pleins d'autres informations utiles."; +$text['description-2']['pt-br'] = "A informação contem a origem, destino, duração e outros detalhes úteis da chamada. "; +$text['description-2']['pl'] = "Informacja zawiera numer dzwoniącego i odbiorcy rozmowy, czas trwania oraz inne przydatne szczegóły."; +$text['description-2']['sv-se'] = "Informationen innehåller källa, destination, samtalstid, och annan nyttig information."; +$text['description-2']['uk'] = ""; +$text['description-2']['de-at'] = "Die Information beinhaltet Quelle, Ziel, Dauer und andere nützliche Details."; +$text['description-2']['he'] = ""; + +$text['description']['en-us'] = "Call Detail Records (CDRs) are detailed information on the calls."; +$text['description']['es-cl'] = "Los registros de detalle de llamadas (CDR) contienen información detallada de las llamadas."; +$text['description']['pt-pt'] = "O registo detalhado de chamadas mostra informações detalhadas sobre as chamadas."; +$text['description']['fr-fr'] = "Ici se trouve l'historique des tous les appels passés sur cette plateforme. En Anglais: Call Detail Records (CDR)."; +$text['description']['pt-br'] = "Editar informações da conta."; +$text['description']['pl'] = "Wykaz rozmów prezentuje szczegółowe informacje o zrealizowanych rozmowach."; +$text['description']['sv-se'] = "Detaljerad Samtalsinformation (CDR) är detaljerad information från samtalen."; +$text['description']['uk'] = "Редагування інформації облікового запису"; +$text['description']['de-at'] = "Kontoinformationen bearbeiten"; +$text['description']['he'] = "ערוך את פרטי החשבון"; + +$text['button-update']['en-us'] = "Update"; +$text['button-update']['es-cl'] = "Actualización"; +$text['button-update']['pt-pt'] = "Atualizar"; +$text['button-update']['fr-fr'] = "Mise à jour"; +$text['button-update']['pt-br'] = "Atualização"; +$text['button-update']['pl'] = "Uaktualnij"; +$text['button-update']['sv-se'] = "Uppdatera"; +$text['button-update']['uk'] = "Оновити"; +$text['button-update']['de-at'] = "Aktualisieren"; +$text['button-update']['he'] = "עדכון"; + +$text['button-statistics']['en-us'] = "Statistics"; +$text['button-statistics']['es-cl'] = "Estadísticas"; +$text['button-statistics']['pt-pt'] = "Estatísticas"; +$text['button-statistics']['fr-fr'] = "Statistiques"; +$text['button-statistics']['pt-br'] = "Estatísticas "; +$text['button-statistics']['pl'] = "Ststystyki"; +$text['button-statistics']['sv-se'] = "Statistik"; +$text['button-statistics']['uk'] = ""; +$text['button-statistics']['de-at'] = "Statistik"; +$text['button-statistics']['he'] = "סטטיסטיקה"; + +$text['button-missed']['en-us'] = "Missed Calls"; +$text['button-missed']['es-cl'] = "Llamadas Perdidas"; +$text['button-missed']['pt-pt'] = "Chamadas Perdidas"; +$text['button-missed']['fr-fr'] = "Appels Perdus"; +$text['button-missed']['pt-br'] = "Chamadas Perdidas "; +$text['button-missed']['pl'] = "NIeodebrane rozmowy"; +$text['button-missed']['sv-se'] = "Missade Samtal"; +$text['button-missed']['uk'] = ""; +$text['button-missed']['de-at'] = "Verpasste Anrufe"; +$text['button-missed']['he'] = "שיחות שלא נענו"; + +$text['button-extension_summary']['en-us'] = "Extension Summary"; +$text['button-extension_summary']['es-cl'] = "Resumen Extensión"; +$text['button-extension_summary']['pt-pt'] = "Resumo Extensão"; +$text['button-extension_summary']['fr-fr'] = "Résumé par Extension"; +$text['button-extension_summary']['pt-br'] = "Resumo Extensão "; +$text['button-extension_summary']['pl'] = "Podsumowanie numerów wewnętrznych"; +$text['button-extension_summary']['sv-se'] = "Anknytning Summering"; +$text['button-extension_summary']['uk'] = ""; +$text['button-extension_summary']['de-at'] = "Nebenstellen Statistik"; +$text['button-extension_summary']['he'] = ""; + +$text['button-download_csv']['en-us'] = "Download CSV"; +$text['button-download_csv']['es-cl'] = "Descarga CSV"; +$text['button-download_csv']['pt-pt'] = "Baixar CSV"; +$text['button-download_csv']['fr-fr'] = "Télécharger CSV"; +$text['button-download_csv']['pt-br'] = "Baixar CSV "; +$text['button-download_csv']['pl'] = "Pobierz CSV"; +$text['button-download_csv']['sv-se'] = "Ladda Ned CSV"; +$text['button-download_csv']['uk'] = ""; +$text['button-download_csv']['de-at'] = "CSV Herunterladen"; +$text['button-download_csv']['he'] = ""; + +$text['button-advanced_search']['en-us'] = "Advanced Search"; +$text['button-advanced_search']['es-cl'] = "Búsqueda Avanzada"; +$text['button-advanced_search']['pt-pt'] = "Pesquisa Avançada"; +$text['button-advanced_search']['fr-fr'] = "Recherche Avancée"; +$text['button-advanced_search']['pt-br'] = "Pesquisa Avançada "; +$text['button-advanced_search']['pl'] = "Zaawansowane wyszukiwanie"; +$text['button-advanced_search']['sv-se'] = "Avancerad Sökning"; +$text['button-advanced_search']['uk'] = ""; +$text['button-advanced_search']['de-at'] = "Erweiterte Suche"; +$text['button-advanced_search']['he'] = "חיפוש מתקדם"; + ?> \ No newline at end of file diff --git a/app/xml_cdr/report.php b/app/xml_cdr/report.php index 3ee08e26c8..b88db6a8a6 100644 --- a/app/xml_cdr/report.php +++ b/app/xml_cdr/report.php @@ -1,214 +1,214 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - James Rose - Mark J Crane -*/ - -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -require_once "resources/header.php"; -require_once "resources/schema.php"; -//require_once "xml_cdr_statistics_inc.php"; -if (permission_exists('xml_cdr_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//additional includes - //require_once "xml_cdr_statistics_inc.php"; -require_once "resources/header.php"; - -global $db; - -$dom = date('m'); -$year = date('Y'); - -if (strlen($where) == 0) { - $duuid = "domain_uuid = '".$_SESSION['domain_uuid']."' "; -} - -for ($y=0; $y<4; $y++) { - $fileheader = array( 'month', 'total calls' , 'total seconds' , 'total minutes' , 'total hours' , 'billing periods', 'rate', 'approx cost'); - - - if ( $y == 0) { - $tablename = "Previous 12 Months Inbound Call Summary
"; - $sql1 = "select billsec as seconds from v_xml_cdr where (".$duuid."and direction='inbound') "; - $sql3 = ";"; - //really we should set rate in domain settings or something and pull it from the php session. - $rate=0.012; - $bill_period=60; - } - elseif ($y == 1) { - $tablename = "Previous 12 Months Outbound Metered Call Summary
"; - $sql1 = "select billsec as seconds from v_xml_cdr where (".$duuid."and direction='outbound') "; - $sql3 = "and destination_number not like '%800_______' and destination_number not like '%888_______' and destination_number not like '%877_______' and destination_number not like '%866_______' and destination_number not like '%855_______' ;"; - $rate=0.0098; - $rate=$rate/10; - $bill_period=6; - } - elseif ($y == 2) { - $tablename = "Previous 12 Months Toll Free Call Summary
"; - $sql1 = "select billsec as seconds from v_xml_cdr where (".$duuid."and direction='outbound') "; - $sql3 = "and (destination_number like '%800_______' or destination_number like '%888_______' or destination_number like '%877_______' or destination_number like '%866_______' or destination_number like '%855_______');"; - $rate=0; - $bill_period=6; - } - elseif ($y == 3) { - $tablename = "Previous 12 Months Local Free Call Summary
"; - $sql1 = "select billsec as seconds from v_xml_cdr where (".$duuid."and direction='local') "; - $sql3 = ";"; - $rate=0; - $bill_period=6; - } - else { - echo "whoops
"; - } - - -//set the style - $c = 0; - $row_style["0"] = "row_style0"; - $row_style["1"] = "row_style1"; - - echo ""; - - $dom = date('m'); - $year = date('Y'); - $lyear=$year; - $lastmonth = $year."-".$dolm."-01"; - $thismonth = $year."-".$dom."-01"; - - echo $tablename; - - foreach ($fileheader as $tr){ - echo ""; - } - - for ($x=0; $x < 12; $x++) - { - if ($dom == 1){ - $dom=12; - $year=$year-1; - } - elseif ($x == 0){ - $dom=$dom; - } - else { - $dom=$dom-1; - } - if ($dom == 1) { - $dolm=12; - $lyear=$lyear-1; - } - else { - $dolm=$dom-1; - } - - //convert to int - $dom=$dom*1; - $dolm=$dolm*1; - - //back to string, prepend 0) - if ( $dolm < 10 ) { - $dolm = "0".$dolm; - } - if ( $dom < 10 ) { - $dom = "0".$dom; - } - $lastmonth = $lyear."-".$dolm."-01"; - $thismonth = $year."-".$dom."-01"; - - $sql2 = "and (start_stamp >= '" . $lastmonth . "' AND start_stamp < '" . $thismonth. "') "; - - $sql = $sql1; - $sql .= $sql2; - $sql .= $sql3; - $sql .= $callsort; - //echo "
" . $sql . "
"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_ASSOC); - unset ($prep_statement, $sql); - $max = sizeof($result) -1; - - $i=0; - - - echo ""; - //echo " \n"; - if ( $max > 0 ) { - foreach($result as $row) { - $result = $row['seconds']; - $billtime_1 = intval($result/$bill_period); - $billtime_2 = $result%$bill_period; - - if (($result%$bill_period) != 0 ) { - //need to round up for billing period - $billtime = $billtime + intval($result/$bill_period) + 1; - //echo " mod worked "; - } - else { - //no need to round up for billing period - $billtime = $billtime + intval($result/$bill_period); - } - $tottime = $tottime + $result; - } - - echo ""; - echo ""; - echo ""; - $mintime = $tottime/$bill_period; - echo ""; - $hourtime = $tottime/3600; - echo ""; - $tot_cost = $rate * $billtime ; - echo ""; - echo ""; - echo ""; - - if ($c==0) { $c=1; } else { $c=0; } - - - } - echo ""; - $max=0; - $tottime=0; - $hourtime=0; - $billtime=0; - $tot_cost=0; - $mintime=0; - } - echo "
" . $tr . "
".($i+1)."".$dolm."/".$lyear."".$max."".$tottime."".round($mintime,1)."".round($hourtime,1)."".$billtime."".$rate."$".round($tot_cost,2)."
"; - echo "
"; - -} -//show the footer - require_once "resources/footer.php"; -?> + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + James Rose + Mark J Crane +*/ + +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +require_once "resources/header.php"; +require_once "resources/schema.php"; +//require_once "xml_cdr_statistics_inc.php"; +if (permission_exists('xml_cdr_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//additional includes + //require_once "xml_cdr_statistics_inc.php"; +require_once "resources/header.php"; + +global $db; + +$dom = date('m'); +$year = date('Y'); + +if (strlen($where) == 0) { + $duuid = "domain_uuid = '".$_SESSION['domain_uuid']."' "; +} + +for ($y=0; $y<4; $y++) { + $fileheader = array( 'month', 'total calls' , 'total seconds' , 'total minutes' , 'total hours' , 'billing periods', 'rate', 'approx cost'); + + + if ( $y == 0) { + $tablename = "Previous 12 Months Inbound Call Summary
"; + $sql1 = "select billsec as seconds from v_xml_cdr where (".$duuid."and direction='inbound') "; + $sql3 = ";"; + //really we should set rate in domain settings or something and pull it from the php session. + $rate=0.012; + $bill_period=60; + } + elseif ($y == 1) { + $tablename = "Previous 12 Months Outbound Metered Call Summary
"; + $sql1 = "select billsec as seconds from v_xml_cdr where (".$duuid."and direction='outbound') "; + $sql3 = "and destination_number not like '%800_______' and destination_number not like '%888_______' and destination_number not like '%877_______' and destination_number not like '%866_______' and destination_number not like '%855_______' ;"; + $rate=0.0098; + $rate=$rate/10; + $bill_period=6; + } + elseif ($y == 2) { + $tablename = "Previous 12 Months Toll Free Call Summary
"; + $sql1 = "select billsec as seconds from v_xml_cdr where (".$duuid."and direction='outbound') "; + $sql3 = "and (destination_number like '%800_______' or destination_number like '%888_______' or destination_number like '%877_______' or destination_number like '%866_______' or destination_number like '%855_______');"; + $rate=0; + $bill_period=6; + } + elseif ($y == 3) { + $tablename = "Previous 12 Months Local Free Call Summary
"; + $sql1 = "select billsec as seconds from v_xml_cdr where (".$duuid."and direction='local') "; + $sql3 = ";"; + $rate=0; + $bill_period=6; + } + else { + echo "whoops
"; + } + + +//set the style + $c = 0; + $row_style["0"] = "row_style0"; + $row_style["1"] = "row_style1"; + + echo ""; + + $dom = date('m'); + $year = date('Y'); + $lyear=$year; + $lastmonth = $year."-".$dolm."-01"; + $thismonth = $year."-".$dom."-01"; + + echo $tablename; + + foreach ($fileheader as $tr){ + echo ""; + } + + for ($x=0; $x < 12; $x++) + { + if ($dom == 1){ + $dom=12; + $year=$year-1; + } + elseif ($x == 0){ + $dom=$dom; + } + else { + $dom=$dom-1; + } + if ($dom == 1) { + $dolm=12; + $lyear=$lyear-1; + } + else { + $dolm=$dom-1; + } + + //convert to int + $dom=$dom*1; + $dolm=$dolm*1; + + //back to string, prepend 0) + if ( $dolm < 10 ) { + $dolm = "0".$dolm; + } + if ( $dom < 10 ) { + $dom = "0".$dom; + } + $lastmonth = $lyear."-".$dolm."-01"; + $thismonth = $year."-".$dom."-01"; + + $sql2 = "and (start_stamp >= '" . $lastmonth . "' AND start_stamp < '" . $thismonth. "') "; + + $sql = $sql1; + $sql .= $sql2; + $sql .= $sql3; + $sql .= $callsort; + //echo "
" . $sql . "
"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_ASSOC); + unset ($prep_statement, $sql); + $max = sizeof($result) -1; + + $i=0; + + + echo ""; + //echo " \n"; + if ( $max > 0 ) { + foreach($result as $row) { + $result = $row['seconds']; + $billtime_1 = intval($result/$bill_period); + $billtime_2 = $result%$bill_period; + + if (($result%$bill_period) != 0 ) { + //need to round up for billing period + $billtime = $billtime + intval($result/$bill_period) + 1; + //echo " mod worked "; + } + else { + //no need to round up for billing period + $billtime = $billtime + intval($result/$bill_period); + } + $tottime = $tottime + $result; + } + + echo ""; + echo ""; + echo ""; + $mintime = $tottime/$bill_period; + echo ""; + $hourtime = $tottime/3600; + echo ""; + $tot_cost = $rate * $billtime ; + echo ""; + echo ""; + echo ""; + + if ($c==0) { $c=1; } else { $c=0; } + + + } + echo ""; + $max=0; + $tottime=0; + $hourtime=0; + $billtime=0; + $tot_cost=0; + $mintime=0; + } + echo "
" . $tr . "
".($i+1)."".$dolm."/".$lyear."".$max."".$tottime."".round($mintime,1)."".round($hourtime,1)."".$billtime."".$rate."$".round($tot_cost,2)."
"; + echo "
"; + +} +//show the footer + require_once "resources/footer.php"; +?> diff --git a/app/xml_cdr/xml_cdr_export.php b/app/xml_cdr/xml_cdr_export.php index 48a5909ff8..099af9477c 100644 --- a/app/xml_cdr/xml_cdr_export.php +++ b/app/xml_cdr/xml_cdr_export.php @@ -1,289 +1,289 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2014 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('xml_cdr_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//additional includes - $rows_per_page = ($_SESSION['domain']['paging']['numeric'] != '') ? $_SESSION['domain']['paging']['numeric'] : 50; - require_once "xml_cdr_inc.php"; - -//get the format - $export_format = check_str($_REQUEST['export_format']); - -//get the format - $showall = check_str($_REQUEST['showall']); - -//exprot the csv - if ($export_format == 'csv') { - - //define file name - if ($_REQUEST['showall'] == 'true') { - $csv_filename = "cdr_".date("Ymd_His").".csv"; - } - else { - $csv_filename = "cdr_".$_SESSION['domain_name']."_".date("Ymd_His").".csv"; - } - - //set the http headers - header('Content-type: application/octet-binary'); - header('Content-Disposition: attachment; filename='.$csv_filename); - - //set the csv headers - $z = 0; - foreach($result[0] as $key => $val) { - if ($key != "xml" && $key != "json") { - if ($z == 0) { - echo '"'.$key.'"'; - } - else { - echo ',"'.$key.'"'; - } - } - $z++; - } - echo "\n"; - - //show the csv data - $x=0; - while(true) { - $z = 0; - foreach($result[0] as $key => $val) { - if ($key != "xml" && $key != "json") { - if ($z == 0) { - echo '"'.$result[$x][$key].'"'; - } - else { - echo ',"'.$result[$x][$key].'"'; - } - } - $z++; - } - echo "\n"; - ++$x; - if ($x > ($result_count-1)) { - break; - } - } - } - -//export as a PDF - if ($export_format == 'pdf') { - - //load pdf libraries - require_once("resources/tcpdf/tcpdf.php"); - require_once("resources/fpdi/fpdi.php"); - - //determine page size - switch ($_SESSION['fax']['page_size']['text']) { - case 'a4' : - $page_width = 11.7; //in - $page_height = 8.3; //in - break; - case 'legal' : - $page_width = 14; //in - $page_height = 8.5; //in - break; - case 'letter' : - default : - $page_width = 11; //in - $page_height = 8.5; //in - } - - // initialize pdf - $pdf = new FPDI('L', 'in'); - $pdf -> SetAutoPageBreak(false); - $pdf -> setPrintHeader(false); - $pdf -> setPrintFooter(false); - $pdf -> SetMargins(0.5, 0.5, 0.5, true); - - //set default font - $pdf -> SetFont('helvetica', '', 7); - //add new page - $pdf -> AddPage('L', array($page_width, $page_height)); - - $chunk = 0; - - //write the table column headers - $data_start = ''; - $data_end = '
'; - - $data_head = ''; - $data_head .= ''.$text['label-direction'].''; - $data_head .= ''.$text['label-cid-name'].''; - $data_head .= ''.$text['label-cid-number'].''; - $data_head .= ''.$text['label-destination'].''; - $data_head .= ''.$text['label-start'].''; - $data_head .= ''.$text['label-tta'].''; - $data_head .= ''.$text['label-duration'].''; - $data_head .= ''.$text['label-billsec'].''; - $data_head .= ''."PDD".''; - $data_head .= ''."MOS".''; - $data_head .= ''; - $data_head .= ''.$text['label-hangup_cause'].''; - $data_head .= ''; - $data_head .= '
'; - - //initialize total variables - $total['duration'] = 0; - $total['billmsec'] = 0; - $total['pdd_ms'] = 0; - $total['rtp_audio_in_mos'] = 0; - $total['tta'] = 0; - - //write the row cells - $z = 0; // total counter - $p = 0; // per page counter - if (sizeof($result) > 0) { - foreach($result as $cdr_num => $fields) { - $data_body[$p] .= ''; - $data_body[$p] .= ''.$text['label-'.$fields['direction']].''; - $data_body[$p] .= ''.$fields['caller_id_name'].''; - $data_body[$p] .= ''.$fields['caller_id_number'].''; - $data_body[$p] .= ''.format_phone($fields['destination_number']).''; - $data_body[$p] .= ''.$fields['start_stamp'].''; - $total['tta'] += ($fields['tta'] > 0) ? $fields['tta'] : 0; - $data_body[$p] .= ''.(($fields['tta'] > 0) ? $fields['tta'].'s' : null).''; - $seconds = ($fields['hangup_cause'] == "ORIGINATOR_CANCEL") ? $fields['duration'] : round(($fields['billmsec'] / 1000), 0, PHP_ROUND_HALF_UP); - $total['duration'] += $seconds; - $data_body[$p] .= ''.gmdate("G:i:s", $seconds).''; - $total['billmsec'] += $fields['billmsec']; - $data_body[$p] .= ''.number_format(round($fields['billmsec'] / 1000, 2), 2).'s'; - $data_body[$p] .= ''; - if (permission_exists("xml_cdr_pdd")) { - $total['pdd_ms'] += $fields['pdd_ms']; - $data_body[$p] .= number_format(round($fields['pdd_ms'] / 1000, 2), 2).'s'; - } - $data_body[$p] .= ''; - $data_body[$p] .= ''; - if (permission_exists("xml_cdr_mos")) { - $total['rtp_audio_in_mos'] += $fields['rtp_audio_in_mos']; - $data_body[$p] .= (strlen($total['rtp_audio_in_mos']) > 0) ? $fields['rtp_audio_in_mos'] : null; - } - $data_body[$p] .= ''; - $data_body[$p] .= ''; - $data_body[$p] .= ''.ucwords(strtolower(str_replace("_", " ", $fields['hangup_cause']))).''; - $data_body[$p] .= ''; - - $z++; - $p++; - - if ($p == 60) { - //output data - $data_body_chunk = $data_start.$data_head; - foreach ($data_body as $data_body_row) { - $data_body_chunk .= $data_body_row; - } - $data_body_chunk .= $data_end; - $pdf -> writeHTML($data_body_chunk, true, false, false, false, ''); - unset($data_body_chunk); - unset($data_body); - $p = 0; - - //add new page - $pdf -> AddPage('L', array($page_width, $page_height)); - } - - } - - } - - //write divider - $data_footer = ''; - - //write totals - $data_footer .= ''; - $data_footer .= ''.$text['label-total'].''; - $data_footer .= ''.$z.''; - $data_footer .= ''; - $data_footer .= ''.number_format(round($total['tta'], 1), 0).'s'; - $data_footer .= ''.gmdate("G:i:s", $total['duration']).''; - $data_footer .= ''.gmdate("G:i:s", round($total['billmsec'] / 1000, 0)).''; - $data_footer .= ''.number_format(round(($total['pdd_ms'] / 1000), 2), 2).'s'; - $data_footer .= ''; - $data_footer .= ''; - - //write divider - $data_footer .= '
'; - - //write averages - $data_footer .= ''; - $data_footer .= ''.$text['label-average'].''; - $data_footer .= ''; - $data_footer .= ''.round(($total['tta'] / $z), 1).''; - $data_footer .= ''.gmdate("G:i:s", ($total['duration'] / $z)).''; - $data_footer .= ''.gmdate("G:i:s", round($total['billmsec'] / $z / 1000, 0)).''; - $data_footer .= ''.number_format(round(($total['pdd_ms'] / $z / 1000), 2), 2).'s'; - $data_footer .= ''.round(($total['rtp_audio_in_mos'] / $z), 2).''; - $data_footer .= ''; - $data_footer .= ''; - - //write divider - $data_footer .= '
'; - - //add last page - if ($p >= 55) { - $pdf -> AddPage('L', array($page_width, $page_height)); - } - //output remaining data - $data_body_chunk = $data_start.$data_head; - foreach ($data_body as $data_body_row) { - $data_body_chunk .= $data_body_row; - } - $data_body_chunk .= $data_footer.$data_end; - $pdf -> writeHTML($data_body_chunk, true, false, false, false, ''); - unset($data_body_chunk); - - //define file name - $pdf_filename = "cdr_".$_SESSION['domain_name']."_".date("Ymd_His").".pdf"; - - header("Content-Type: application/force-download"); - header("Content-Type: application/octet-stream"); - header("Content-Type: application/download"); - header("Content-Description: File Transfer"); - header('Content-Disposition: attachment; filename="'.$pdf_filename.'"'); - header("Content-Type: application/pdf"); - header('Accept-Ranges: bytes'); - header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 - header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // date in the past - - // push pdf download - $pdf -> Output($pdf_filename, 'D'); // Display [I]nline, Save to [F]ile, [D]ownload - - } - + + Portions created by the Initial Developer are Copyright (C) 2008-2014 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('xml_cdr_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//additional includes + $rows_per_page = ($_SESSION['domain']['paging']['numeric'] != '') ? $_SESSION['domain']['paging']['numeric'] : 50; + require_once "xml_cdr_inc.php"; + +//get the format + $export_format = check_str($_REQUEST['export_format']); + +//get the format + $showall = check_str($_REQUEST['showall']); + +//exprot the csv + if ($export_format == 'csv') { + + //define file name + if ($_REQUEST['showall'] == 'true') { + $csv_filename = "cdr_".date("Ymd_His").".csv"; + } + else { + $csv_filename = "cdr_".$_SESSION['domain_name']."_".date("Ymd_His").".csv"; + } + + //set the http headers + header('Content-type: application/octet-binary'); + header('Content-Disposition: attachment; filename='.$csv_filename); + + //set the csv headers + $z = 0; + foreach($result[0] as $key => $val) { + if ($key != "xml" && $key != "json") { + if ($z == 0) { + echo '"'.$key.'"'; + } + else { + echo ',"'.$key.'"'; + } + } + $z++; + } + echo "\n"; + + //show the csv data + $x=0; + while(true) { + $z = 0; + foreach($result[0] as $key => $val) { + if ($key != "xml" && $key != "json") { + if ($z == 0) { + echo '"'.$result[$x][$key].'"'; + } + else { + echo ',"'.$result[$x][$key].'"'; + } + } + $z++; + } + echo "\n"; + ++$x; + if ($x > ($result_count-1)) { + break; + } + } + } + +//export as a PDF + if ($export_format == 'pdf') { + + //load pdf libraries + require_once("resources/tcpdf/tcpdf.php"); + require_once("resources/fpdi/fpdi.php"); + + //determine page size + switch ($_SESSION['fax']['page_size']['text']) { + case 'a4' : + $page_width = 11.7; //in + $page_height = 8.3; //in + break; + case 'legal' : + $page_width = 14; //in + $page_height = 8.5; //in + break; + case 'letter' : + default : + $page_width = 11; //in + $page_height = 8.5; //in + } + + // initialize pdf + $pdf = new FPDI('L', 'in'); + $pdf -> SetAutoPageBreak(false); + $pdf -> setPrintHeader(false); + $pdf -> setPrintFooter(false); + $pdf -> SetMargins(0.5, 0.5, 0.5, true); + + //set default font + $pdf -> SetFont('helvetica', '', 7); + //add new page + $pdf -> AddPage('L', array($page_width, $page_height)); + + $chunk = 0; + + //write the table column headers + $data_start = ''; + $data_end = '
'; + + $data_head = ''; + $data_head .= ''.$text['label-direction'].''; + $data_head .= ''.$text['label-cid-name'].''; + $data_head .= ''.$text['label-cid-number'].''; + $data_head .= ''.$text['label-destination'].''; + $data_head .= ''.$text['label-start'].''; + $data_head .= ''.$text['label-tta'].''; + $data_head .= ''.$text['label-duration'].''; + $data_head .= ''.$text['label-billsec'].''; + $data_head .= ''."PDD".''; + $data_head .= ''."MOS".''; + $data_head .= ''; + $data_head .= ''.$text['label-hangup_cause'].''; + $data_head .= ''; + $data_head .= '
'; + + //initialize total variables + $total['duration'] = 0; + $total['billmsec'] = 0; + $total['pdd_ms'] = 0; + $total['rtp_audio_in_mos'] = 0; + $total['tta'] = 0; + + //write the row cells + $z = 0; // total counter + $p = 0; // per page counter + if (sizeof($result) > 0) { + foreach($result as $cdr_num => $fields) { + $data_body[$p] .= ''; + $data_body[$p] .= ''.$text['label-'.$fields['direction']].''; + $data_body[$p] .= ''.$fields['caller_id_name'].''; + $data_body[$p] .= ''.$fields['caller_id_number'].''; + $data_body[$p] .= ''.format_phone($fields['destination_number']).''; + $data_body[$p] .= ''.$fields['start_stamp'].''; + $total['tta'] += ($fields['tta'] > 0) ? $fields['tta'] : 0; + $data_body[$p] .= ''.(($fields['tta'] > 0) ? $fields['tta'].'s' : null).''; + $seconds = ($fields['hangup_cause'] == "ORIGINATOR_CANCEL") ? $fields['duration'] : round(($fields['billmsec'] / 1000), 0, PHP_ROUND_HALF_UP); + $total['duration'] += $seconds; + $data_body[$p] .= ''.gmdate("G:i:s", $seconds).''; + $total['billmsec'] += $fields['billmsec']; + $data_body[$p] .= ''.number_format(round($fields['billmsec'] / 1000, 2), 2).'s'; + $data_body[$p] .= ''; + if (permission_exists("xml_cdr_pdd")) { + $total['pdd_ms'] += $fields['pdd_ms']; + $data_body[$p] .= number_format(round($fields['pdd_ms'] / 1000, 2), 2).'s'; + } + $data_body[$p] .= ''; + $data_body[$p] .= ''; + if (permission_exists("xml_cdr_mos")) { + $total['rtp_audio_in_mos'] += $fields['rtp_audio_in_mos']; + $data_body[$p] .= (strlen($total['rtp_audio_in_mos']) > 0) ? $fields['rtp_audio_in_mos'] : null; + } + $data_body[$p] .= ''; + $data_body[$p] .= ''; + $data_body[$p] .= ''.ucwords(strtolower(str_replace("_", " ", $fields['hangup_cause']))).''; + $data_body[$p] .= ''; + + $z++; + $p++; + + if ($p == 60) { + //output data + $data_body_chunk = $data_start.$data_head; + foreach ($data_body as $data_body_row) { + $data_body_chunk .= $data_body_row; + } + $data_body_chunk .= $data_end; + $pdf -> writeHTML($data_body_chunk, true, false, false, false, ''); + unset($data_body_chunk); + unset($data_body); + $p = 0; + + //add new page + $pdf -> AddPage('L', array($page_width, $page_height)); + } + + } + + } + + //write divider + $data_footer = ''; + + //write totals + $data_footer .= ''; + $data_footer .= ''.$text['label-total'].''; + $data_footer .= ''.$z.''; + $data_footer .= ''; + $data_footer .= ''.number_format(round($total['tta'], 1), 0).'s'; + $data_footer .= ''.gmdate("G:i:s", $total['duration']).''; + $data_footer .= ''.gmdate("G:i:s", round($total['billmsec'] / 1000, 0)).''; + $data_footer .= ''.number_format(round(($total['pdd_ms'] / 1000), 2), 2).'s'; + $data_footer .= ''; + $data_footer .= ''; + + //write divider + $data_footer .= '
'; + + //write averages + $data_footer .= ''; + $data_footer .= ''.$text['label-average'].''; + $data_footer .= ''; + $data_footer .= ''.round(($total['tta'] / $z), 1).''; + $data_footer .= ''.gmdate("G:i:s", ($total['duration'] / $z)).''; + $data_footer .= ''.gmdate("G:i:s", round($total['billmsec'] / $z / 1000, 0)).''; + $data_footer .= ''.number_format(round(($total['pdd_ms'] / $z / 1000), 2), 2).'s'; + $data_footer .= ''.round(($total['rtp_audio_in_mos'] / $z), 2).''; + $data_footer .= ''; + $data_footer .= ''; + + //write divider + $data_footer .= '
'; + + //add last page + if ($p >= 55) { + $pdf -> AddPage('L', array($page_width, $page_height)); + } + //output remaining data + $data_body_chunk = $data_start.$data_head; + foreach ($data_body as $data_body_row) { + $data_body_chunk .= $data_body_row; + } + $data_body_chunk .= $data_footer.$data_end; + $pdf -> writeHTML($data_body_chunk, true, false, false, false, ''); + unset($data_body_chunk); + + //define file name + $pdf_filename = "cdr_".$_SESSION['domain_name']."_".date("Ymd_His").".pdf"; + + header("Content-Type: application/force-download"); + header("Content-Type: application/octet-stream"); + header("Content-Type: application/download"); + header("Content-Description: File Transfer"); + header('Content-Disposition: attachment; filename="'.$pdf_filename.'"'); + header("Content-Type: application/pdf"); + header('Accept-Ranges: bytes'); + header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 + header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // date in the past + + // push pdf download + $pdf -> Output($pdf_filename, 'D'); // Display [I]nline, Save to [F]ile, [D]ownload + + } + ?> \ No newline at end of file diff --git a/core/default_settings/app_defaults.php b/core/default_settings/app_defaults.php index 09bc1833d5..9e904342d3 100644 --- a/core/default_settings/app_defaults.php +++ b/core/default_settings/app_defaults.php @@ -1,565 +1,565 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -//process this only one time -if ($domains_processed == 1) { - - //define array of settings - $x = 0; - $array[$x]['default_setting_category'] = 'domain'; - $array[$x]['default_setting_subcategory'] = 'time_zone'; - $array[$x]['default_setting_name'] = 'name'; - $array[$x]['default_setting_value'] = ''; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'domain'; - $array[$x]['default_setting_subcategory'] = 'language'; - $array[$x]['default_setting_name'] = 'code'; - $array[$x]['default_setting_value'] = 'en-us'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'domain'; - $array[$x]['default_setting_subcategory'] = 'bridge'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'outbound'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'outbound,loopback,lcr'; - $x++; - $array[$x]['default_setting_category'] = 'domain'; - $array[$x]['default_setting_subcategory'] = 'paging'; - $array[$x]['default_setting_name'] = 'numeric'; - $array[$x]['default_setting_value'] = '100'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the maximum number of records displayed per page. (Default: 50)'; - $x++; - $array[$x]['default_setting_category'] = 'security'; - $array[$x]['default_setting_subcategory'] = 'password_length'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = '10'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Sets the default length for system generated passwords.'; - $x++; - $array[$x]['default_setting_category'] = 'security'; - $array[$x]['default_setting_subcategory'] = 'password_strength'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = '4'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the default strength for system generated passwords. Valid Options: 1 - Numeric Only, 2 - Include Lower Apha, 3 - Include Upper Alpha, 4 - Include Special Characters.'; - $x++; - $array[$x]['default_setting_category'] = 'security'; - $array[$x]['default_setting_subcategory'] = 'session_rotate'; - $array[$x]['default_setting_name'] = 'boolean'; - $array[$x]['default_setting_value'] = 'true'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Whether to regenerate the session ID.'; - $x++; - $array[$x]['default_setting_category'] = 'email'; - $array[$x]['default_setting_subcategory'] = 'smtp_auth'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = 'true'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'email'; - $array[$x]['default_setting_subcategory'] = 'smtp_from'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = ''; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'email'; - $array[$x]['default_setting_subcategory'] = 'smtp_from_name'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = ''; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'email'; - $array[$x]['default_setting_subcategory'] = 'smtp_host'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = ''; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'email'; - $array[$x]['default_setting_subcategory'] = 'smtp_username'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = ''; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'email'; - $array[$x]['default_setting_subcategory'] = 'smtp_password'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = ''; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'email'; - $array[$x]['default_setting_subcategory'] = 'smtp_secure'; - $array[$x]['default_setting_name'] = 'var'; - $array[$x]['default_setting_value'] = 'true'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'login'; - $array[$x]['default_setting_subcategory'] = 'password_reset_key'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = generate_password('20', '4'); - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Display a Reset Password link on the login box (requires smtp_host be defined).'; - $x++; - $array[$x]['default_setting_category'] = 'login'; - $array[$x]['default_setting_subcategory'] = 'domain_name_visible'; - $array[$x]['default_setting_name'] = 'boolean'; - $array[$x]['default_setting_value'] = 'true'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Displays a domain input or select box (if domain_name array defined) on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'login'; - $array[$x]['default_setting_subcategory'] = 'domain_name'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'pbx1.yourdomain.com'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Domain select option displayed on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'admin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'voicemail'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Voicemail block for users in the admin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'admin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'missed'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Missed Calls block for users in the admin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'admin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'recent'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Recent Calls block for users in the admin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'admin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'limits'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Domain Limits block for users in the admin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'admin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'counts'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Domain Counts block for users in the admin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'admin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'call_routing'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Call Routing controls for users in the admin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'admin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'ring_groups'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Ring Group Forwarding controls for users in the admin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'superadmin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'voicemail'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Voicemail block for users in the superadmin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'superadmin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'missed'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Missed Calls block for users in the superadmin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'superadmin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'recent'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Recent Calls block for users in the superadmin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'superadmin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'limits'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Domain Limits block for users in the superadmin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'superadmin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'counts'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard System Counts block for users in the superadmin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'superadmin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'system'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard System Status block for users in the superadmin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'superadmin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'call_routing'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Call Routing controls for users in the superadmin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'superadmin'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'ring_groups'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Ring Group Forwarding controls for users in the superadmin group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'user'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'voicemail'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Voicemail block for users in the users group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'user'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'missed'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Missed Calls block for users in the users group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'user'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'recent'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Recent Calls block for users in the users group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'user'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'call_routing'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Call Routing controls for users in the users group.'; - $x++; - $array[$x]['default_setting_category'] = 'dashboard'; - $array[$x]['default_setting_subcategory'] = 'user'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = 'ring_groups'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Enable Dashboard Ring Group Forwarding controls for users in the users group.'; - - //get an array of the default settings - $sql = "select * from v_default_settings "; - $prep_statement = $db->prepare($sql); - $prep_statement->execute(); - $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - - //find the missing default settings - $x = 0; - foreach ($array as $setting) { - $found = false; - $missing[$x] = $setting; - foreach ($default_settings as $row) { - if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { - $found = true; - //remove items from the array that were found - unset($missing[$x]); - } - } - $x++; - } - - //get the missing count - $i = 0; - foreach ($missing as $row) { $i++; } - $missing_count = $i; - - //add the missing default settings - $sql = "insert into v_default_settings ("; - $sql .= "default_setting_uuid, "; - $sql .= "default_setting_category, "; - $sql .= "default_setting_subcategory, "; - $sql .= "default_setting_name, "; - $sql .= "default_setting_value, "; - $sql .= "default_setting_enabled, "; - $sql .= "default_setting_description "; - $sql .= ") values \n"; - $i = 1; - foreach ($missing as $row) { - $sql .= "("; - $sql .= "'".uuid()."', "; - $sql .= "'".check_str($row['default_setting_category'])."', "; - $sql .= "'".check_str($row['default_setting_subcategory'])."', "; - $sql .= "'".check_str($row['default_setting_name'])."', "; - $sql .= "'".check_str($row['default_setting_value'])."', "; - $sql .= "'".check_str($row['default_setting_enabled'])."', "; - $sql .= "'".check_str($row['default_setting_description'])."' "; - $sql .= ")"; - if ($missing_count != $i) { - $sql .= ",\n"; - } - $i++; - } - $db->exec(check_sql($sql)); - unset($missing); - - //move the dynamic provision variables that from v_vars table to v_default_settings - if (count($_SESSION['provision']) == 0) { - $sql = "select * from v_vars "; - $sql .= "where var_cat = 'Provision' "; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - //set the variable - $var_name = check_str($row['var_name']); - //remove the 'v_' prefix from the variable name - if (substr($var_name, 0, 2) == "v_") { - $var_name = substr($var_name, 2); - } - //add the provision variable to the default settings table - $sql = "insert into v_default_settings "; - $sql .= "("; - $sql .= "default_setting_uuid, "; - $sql .= "default_setting_category, "; - $sql .= "default_setting_subcategory, "; - $sql .= "default_setting_name, "; - $sql .= "default_setting_value, "; - $sql .= "default_setting_enabled, "; - $sql .= "default_setting_description "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".uuid()."', "; - $sql .= "'provision', "; - $sql .= "'".$var_name."', "; - $sql .= "'var', "; - $sql .= "'".check_str($row['var_value'])."', "; - $sql .= "'".check_str($row['var_enabled'])."', "; - $sql .= "'".check_str($row['var_description'])."' "; - $sql .= ")"; - $db->exec(check_sql($sql)); - unset($sql); - } - unset($prep_statement); - //delete the provision variables from system -> variables - //$sql = "delete from v_vars "; - //$sql .= "where var_cat = 'Provision' "; - //echo $sql ."\n"; - //$db->exec(check_sql($sql)); - //echo "$var_name $var_value \n"; - } - - //populate the languages table, if necessary - $sql = "select count(*) as num_rows from v_languages"; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - if ($row['num_rows'] == 0) { - $sql = "insert into v_languages (language_uuid, language, code) values "; - $sql .= "('".uuid()."', 'Afrikaans', 'af'), "; - $sql .= "('".uuid()."', 'Albanian', 'sq'), "; - $sql .= "('".uuid()."', 'Amharic', 'am'), "; - $sql .= "('".uuid()."', 'Arabic - Algeria', 'ar-dz'), "; - $sql .= "('".uuid()."', 'Arabic - Bahrain', 'ar-bh'), "; - $sql .= "('".uuid()."', 'Arabic - Egypt', 'ar-eg'), "; - $sql .= "('".uuid()."', 'Arabic - Iraq', 'ar-iq'), "; - $sql .= "('".uuid()."', 'Arabic - Jordan', 'ar-jo'), "; - $sql .= "('".uuid()."', 'Arabic - Kuwait', 'ar-kw'), "; - $sql .= "('".uuid()."', 'Arabic - Lebanon', 'ar-lb'), "; - $sql .= "('".uuid()."', 'Arabic - Libya', 'ar-ly'), "; - $sql .= "('".uuid()."', 'Arabic - Morocco', 'ar-ma'), "; - $sql .= "('".uuid()."', 'Arabic - Oman', 'ar-om'), "; - $sql .= "('".uuid()."', 'Arabic - Qatar', 'ar-qa'), "; - $sql .= "('".uuid()."', 'Arabic - Saudi Arabia', 'ar-sa'), "; - $sql .= "('".uuid()."', 'Arabic - Syria', 'ar-sy'), "; - $sql .= "('".uuid()."', 'Arabic - Tunisia', 'ar-tn'), "; - $sql .= "('".uuid()."', 'Arabic - United Arab Emirates', 'ar-ae'), "; - $sql .= "('".uuid()."', 'Arabic - Yemen', 'ar-ye'), "; - $sql .= "('".uuid()."', 'Armenian', 'hy'), "; - $sql .= "('".uuid()."', 'Assamese', 'as'), "; - $sql .= "('".uuid()."', 'Azeri - Cyrillic, Latin', 'az-az'), "; - $sql .= "('".uuid()."', 'Basque', 'eu'), "; - $sql .= "('".uuid()."', 'Belarusian', 'be'), "; - $sql .= "('".uuid()."', 'Bengali - India, Bangladesh', 'bn'), "; - $sql .= "('".uuid()."', 'Bosnian', 'bs'), "; - $sql .= "('".uuid()."', 'Bulgarian', 'bg'), "; - $sql .= "('".uuid()."', 'Burmese', 'my'), "; - $sql .= "('".uuid()."', 'Catalan', 'ca'), "; - $sql .= "('".uuid()."', 'Chinese - China', 'zh-cn'), "; - $sql .= "('".uuid()."', 'Chinese - Hong Kong SAR', 'zh-hk'), "; - $sql .= "('".uuid()."', 'Chinese - Macau SAR', 'zh-mo'), "; - $sql .= "('".uuid()."', 'Chinese - Singapore', 'zh-sg'), "; - $sql .= "('".uuid()."', 'Chinese - Taiwan', 'zh-tw'), "; - $sql .= "('".uuid()."', 'Croatian', 'hr'), "; - $sql .= "('".uuid()."', 'Czech', 'cs'), "; - $sql .= "('".uuid()."', 'Danish', 'da'), "; - $sql .= "('".uuid()."', 'Divehi, Dhivehi, Maldivian', 'dv'), "; - $sql .= "('".uuid()."', 'Dutch - Belgium', 'nl-be'), "; - $sql .= "('".uuid()."', 'Dutch - Netherlands', 'nl-nl'), "; - $sql .= "('".uuid()."', 'English - Australia', 'en-au'), "; - $sql .= "('".uuid()."', 'English - Belize', 'en-bz'), "; - $sql .= "('".uuid()."', 'English - Canada', 'en-ca'), "; - $sql .= "('".uuid()."', 'English - Caribbean', 'en-cb'), "; - $sql .= "('".uuid()."', 'English - Great Britain', 'en-gb'), "; - $sql .= "('".uuid()."', 'English - India', 'en-in'), "; - $sql .= "('".uuid()."', 'English - Ireland', 'en-ie'), "; - $sql .= "('".uuid()."', 'English - Jamaica', 'en-jm'), "; - $sql .= "('".uuid()."', 'English - New Zealand', 'en-nz'), "; - $sql .= "('".uuid()."', 'English - Phillippines', 'en-ph'), "; - $sql .= "('".uuid()."', 'English - Southern Africa', 'en-za'), "; - $sql .= "('".uuid()."', 'English - Trinidad', 'en-tt'), "; - $sql .= "('".uuid()."', 'English - United States', 'en-us'), "; - $sql .= "('".uuid()."', 'Estonian', 'et'), "; - $sql .= "('".uuid()."', 'Faroese', 'fo'), "; - $sql .= "('".uuid()."', 'Farsi - Persian', 'fa'), "; - $sql .= "('".uuid()."', 'Finnish', 'fi'), "; - $sql .= "('".uuid()."', 'French - Belgium', 'fr-be'), "; - $sql .= "('".uuid()."', 'French - Canada', 'fr-ca'), "; - $sql .= "('".uuid()."', 'French - France', 'fr-fr'), "; - $sql .= "('".uuid()."', 'French - Luxembourg', 'fr-lu'), "; - $sql .= "('".uuid()."', 'French - Switzerland', 'fr-ch'), "; - $sql .= "('".uuid()."', 'FYRO Macedonia', 'mk'), "; - $sql .= "('".uuid()."', 'Gaelic - Ireland', 'gd-ie'), "; - $sql .= "('".uuid()."', 'Gaelic - Scotland', 'gd'), "; - $sql .= "('".uuid()."', 'German - Austria', 'de-at'), "; - $sql .= "('".uuid()."', 'German - Germany', 'de-de'), "; - $sql .= "('".uuid()."', 'German - Liechtenstein', 'de-li'), "; - $sql .= "('".uuid()."', 'German - Luxembourg', 'de-lu'), "; - $sql .= "('".uuid()."', 'German - Switzerland', 'de-ch'), "; - $sql .= "('".uuid()."', 'Greek', 'el'), "; - $sql .= "('".uuid()."', 'Guarani - Paraguay', 'gn'), "; - $sql .= "('".uuid()."', 'Gujarati', 'gu'), "; - $sql .= "('".uuid()."', 'Hebrew', 'he'), "; - $sql .= "('".uuid()."', 'Hindi', 'hi'), "; - $sql .= "('".uuid()."', 'Hungarian', 'hu'), "; - $sql .= "('".uuid()."', 'Icelandic', 'is'), "; - $sql .= "('".uuid()."', 'Indonesian', 'id'), "; - $sql .= "('".uuid()."', 'Italian - Italy', 'it-it'), "; - $sql .= "('".uuid()."', 'Italian - Switzerland', 'it-ch'), "; - $sql .= "('".uuid()."', 'Japanese', 'ja'), "; - $sql .= "('".uuid()."', 'Kannada', 'kn'), "; - $sql .= "('".uuid()."', 'Kashmiri', 'ks'), "; - $sql .= "('".uuid()."', 'Kazakh', 'kk'), "; - $sql .= "('".uuid()."', 'Khmer', 'km'), "; - $sql .= "('".uuid()."', 'Korean', 'ko'), "; - $sql .= "('".uuid()."', 'Lao', 'lo'), "; - $sql .= "('".uuid()."', 'Latin', 'la'), "; - $sql .= "('".uuid()."', 'Latvian', 'lv'), "; - $sql .= "('".uuid()."', 'Lithuanian', 'lt'), "; - $sql .= "('".uuid()."', 'Malayalam', 'ml'), "; - $sql .= "('".uuid()."', 'Malay - Brunei', 'ms-bn'), "; - $sql .= "('".uuid()."', 'Malay - Malaysia', 'ms-my'), "; - $sql .= "('".uuid()."', 'Maltese', 'mt'), "; - $sql .= "('".uuid()."', 'Maori', 'mi'), "; - $sql .= "('".uuid()."', 'Marathi', 'mr'), "; - $sql .= "('".uuid()."', 'Nepali', 'ne'), "; - $sql .= "('".uuid()."', 'Norwegian - Bokml, Nynorsk', 'no-no'), "; - $sql .= "('".uuid()."', 'Oriya', 'or'), "; - $sql .= "('".uuid()."', 'Polish', 'pl'), "; - $sql .= "('".uuid()."', 'Portuguese - Brazil', 'pt-br'), "; - $sql .= "('".uuid()."', 'Portuguese - Portugal', 'pt-pt'), "; - $sql .= "('".uuid()."', 'Punjabi', 'pa'), "; - $sql .= "('".uuid()."', 'Raeto-Romance', 'rm'), "; - $sql .= "('".uuid()."', 'Romanian - Moldova', 'ro-mo'), "; - $sql .= "('".uuid()."', 'Romanian - Romania', 'ro'), "; - $sql .= "('".uuid()."', 'Russian', 'ru'), "; - $sql .= "('".uuid()."', 'Russian - Moldova', 'ru-mo'), "; - $sql .= "('".uuid()."', 'Sanskrit', 'sa'), "; - $sql .= "('".uuid()."', 'Serbian - Cyrillic, Latin', 'sr-sp'), "; - $sql .= "('".uuid()."', 'Setsuana', 'tn'), "; - $sql .= "('".uuid()."', 'Sindhi', 'sd'), "; - $sql .= "('".uuid()."', 'Sinhala, Sinhalese', 'si'), "; - $sql .= "('".uuid()."', 'Slovak', 'sk'), "; - $sql .= "('".uuid()."', 'Slovenian', 'sl'), "; - $sql .= "('".uuid()."', 'Somali', 'so'), "; - $sql .= "('".uuid()."', 'Sorbian', 'sb'), "; - $sql .= "('".uuid()."', 'Spanish - Argentina', 'es-ar'), "; - $sql .= "('".uuid()."', 'Spanish - Bolivia', 'es-bo'), "; - $sql .= "('".uuid()."', 'Spanish - Chile', 'es-cl'), "; - $sql .= "('".uuid()."', 'Spanish - Colombia', 'es-co'), "; - $sql .= "('".uuid()."', 'Spanish - Costa Rica', 'es-cr'), "; - $sql .= "('".uuid()."', 'Spanish - Dominican Republic', 'es-do'), "; - $sql .= "('".uuid()."', 'Spanish - Ecuador', 'es-ec'), "; - $sql .= "('".uuid()."', 'Spanish - El Salvador', 'es-sv'), "; - $sql .= "('".uuid()."', 'Spanish - Guatemala', 'es-gt'), "; - $sql .= "('".uuid()."', 'Spanish - Honduras', 'es-hn'), "; - $sql .= "('".uuid()."', 'Spanish - Mexico', 'es-mx'), "; - $sql .= "('".uuid()."', 'Spanish - Nicaragua', 'es-ni'), "; - $sql .= "('".uuid()."', 'Spanish - Panama', 'es-pa'), "; - $sql .= "('".uuid()."', 'Spanish - Paraguay', 'es-py'), "; - $sql .= "('".uuid()."', 'Spanish - Peru', 'es-pe'), "; - $sql .= "('".uuid()."', 'Spanish - Puerto Rico', 'es-pr'), "; - $sql .= "('".uuid()."', 'Spanish - Spain (Traditional)', 'es-es'), "; - $sql .= "('".uuid()."', 'Spanish - Uruguay', 'es-uy'), "; - $sql .= "('".uuid()."', 'Spanish - Venezuela', 'es-ve'), "; - $sql .= "('".uuid()."', 'Swahili', 'sw'), "; - $sql .= "('".uuid()."', 'Swedish - Finland', 'sv-fi'), "; - $sql .= "('".uuid()."', 'Swedish - Sweden', 'sv-se'), "; - $sql .= "('".uuid()."', 'Tajik', 'tg'), "; - $sql .= "('".uuid()."', 'Tamil', 'ta'), "; - $sql .= "('".uuid()."', 'Tatar', 'tt'), "; - $sql .= "('".uuid()."', 'Telugu', 'te'), "; - $sql .= "('".uuid()."', 'Thai', 'th'), "; - $sql .= "('".uuid()."', 'Tibetan', 'bo'), "; - $sql .= "('".uuid()."', 'Tsonga', 'ts'), "; - $sql .= "('".uuid()."', 'Turkish', 'tr'), "; - $sql .= "('".uuid()."', 'Turkmen', 'tk'), "; - $sql .= "('".uuid()."', 'Ukrainian', 'uk'), "; - $sql .= "('".uuid()."', 'Urdu', 'ur'), "; - $sql .= "('".uuid()."', 'Uzbek - Cyrillic, Latin', 'uz-uz'), "; - $sql .= "('".uuid()."', 'Vietnamese', 'vi'), "; - $sql .= "('".uuid()."', 'Welsh', 'cy'), "; - $sql .= "('".uuid()."', 'Xhosa', 'xh'), "; - $sql .= "('".uuid()."', 'Yiddish', 'yi') "; - $db->exec(check_sql($sql)); - unset($sql); - } - unset($prep_statement, $row); - } - -} - + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +//process this only one time +if ($domains_processed == 1) { + + //define array of settings + $x = 0; + $array[$x]['default_setting_category'] = 'domain'; + $array[$x]['default_setting_subcategory'] = 'time_zone'; + $array[$x]['default_setting_name'] = 'name'; + $array[$x]['default_setting_value'] = ''; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'domain'; + $array[$x]['default_setting_subcategory'] = 'language'; + $array[$x]['default_setting_name'] = 'code'; + $array[$x]['default_setting_value'] = 'en-us'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'domain'; + $array[$x]['default_setting_subcategory'] = 'bridge'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'outbound'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'outbound,loopback,lcr'; + $x++; + $array[$x]['default_setting_category'] = 'domain'; + $array[$x]['default_setting_subcategory'] = 'paging'; + $array[$x]['default_setting_name'] = 'numeric'; + $array[$x]['default_setting_value'] = '100'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the maximum number of records displayed per page. (Default: 50)'; + $x++; + $array[$x]['default_setting_category'] = 'security'; + $array[$x]['default_setting_subcategory'] = 'password_length'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = '10'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Sets the default length for system generated passwords.'; + $x++; + $array[$x]['default_setting_category'] = 'security'; + $array[$x]['default_setting_subcategory'] = 'password_strength'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = '4'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the default strength for system generated passwords. Valid Options: 1 - Numeric Only, 2 - Include Lower Apha, 3 - Include Upper Alpha, 4 - Include Special Characters.'; + $x++; + $array[$x]['default_setting_category'] = 'security'; + $array[$x]['default_setting_subcategory'] = 'session_rotate'; + $array[$x]['default_setting_name'] = 'boolean'; + $array[$x]['default_setting_value'] = 'true'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Whether to regenerate the session ID.'; + $x++; + $array[$x]['default_setting_category'] = 'email'; + $array[$x]['default_setting_subcategory'] = 'smtp_auth'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = 'true'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'email'; + $array[$x]['default_setting_subcategory'] = 'smtp_from'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = ''; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'email'; + $array[$x]['default_setting_subcategory'] = 'smtp_from_name'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = ''; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'email'; + $array[$x]['default_setting_subcategory'] = 'smtp_host'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = ''; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'email'; + $array[$x]['default_setting_subcategory'] = 'smtp_username'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = ''; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'email'; + $array[$x]['default_setting_subcategory'] = 'smtp_password'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = ''; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'email'; + $array[$x]['default_setting_subcategory'] = 'smtp_secure'; + $array[$x]['default_setting_name'] = 'var'; + $array[$x]['default_setting_value'] = 'true'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'login'; + $array[$x]['default_setting_subcategory'] = 'password_reset_key'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = generate_password('20', '4'); + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Display a Reset Password link on the login box (requires smtp_host be defined).'; + $x++; + $array[$x]['default_setting_category'] = 'login'; + $array[$x]['default_setting_subcategory'] = 'domain_name_visible'; + $array[$x]['default_setting_name'] = 'boolean'; + $array[$x]['default_setting_value'] = 'true'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Displays a domain input or select box (if domain_name array defined) on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'login'; + $array[$x]['default_setting_subcategory'] = 'domain_name'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'pbx1.yourdomain.com'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Domain select option displayed on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'admin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'voicemail'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Voicemail block for users in the admin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'admin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'missed'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Missed Calls block for users in the admin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'admin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'recent'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Recent Calls block for users in the admin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'admin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'limits'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Domain Limits block for users in the admin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'admin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'counts'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Domain Counts block for users in the admin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'admin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'call_routing'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Call Routing controls for users in the admin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'admin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'ring_groups'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Ring Group Forwarding controls for users in the admin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'superadmin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'voicemail'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Voicemail block for users in the superadmin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'superadmin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'missed'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Missed Calls block for users in the superadmin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'superadmin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'recent'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Recent Calls block for users in the superadmin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'superadmin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'limits'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Domain Limits block for users in the superadmin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'superadmin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'counts'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard System Counts block for users in the superadmin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'superadmin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'system'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard System Status block for users in the superadmin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'superadmin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'call_routing'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Call Routing controls for users in the superadmin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'superadmin'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'ring_groups'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Ring Group Forwarding controls for users in the superadmin group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'user'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'voicemail'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Voicemail block for users in the users group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'user'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'missed'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Missed Calls block for users in the users group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'user'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'recent'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Recent Calls block for users in the users group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'user'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'call_routing'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Call Routing controls for users in the users group.'; + $x++; + $array[$x]['default_setting_category'] = 'dashboard'; + $array[$x]['default_setting_subcategory'] = 'user'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = 'ring_groups'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Enable Dashboard Ring Group Forwarding controls for users in the users group.'; + + //get an array of the default settings + $sql = "select * from v_default_settings "; + $prep_statement = $db->prepare($sql); + $prep_statement->execute(); + $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + + //find the missing default settings + $x = 0; + foreach ($array as $setting) { + $found = false; + $missing[$x] = $setting; + foreach ($default_settings as $row) { + if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { + $found = true; + //remove items from the array that were found + unset($missing[$x]); + } + } + $x++; + } + + //get the missing count + $i = 0; + foreach ($missing as $row) { $i++; } + $missing_count = $i; + + //add the missing default settings + $sql = "insert into v_default_settings ("; + $sql .= "default_setting_uuid, "; + $sql .= "default_setting_category, "; + $sql .= "default_setting_subcategory, "; + $sql .= "default_setting_name, "; + $sql .= "default_setting_value, "; + $sql .= "default_setting_enabled, "; + $sql .= "default_setting_description "; + $sql .= ") values \n"; + $i = 1; + foreach ($missing as $row) { + $sql .= "("; + $sql .= "'".uuid()."', "; + $sql .= "'".check_str($row['default_setting_category'])."', "; + $sql .= "'".check_str($row['default_setting_subcategory'])."', "; + $sql .= "'".check_str($row['default_setting_name'])."', "; + $sql .= "'".check_str($row['default_setting_value'])."', "; + $sql .= "'".check_str($row['default_setting_enabled'])."', "; + $sql .= "'".check_str($row['default_setting_description'])."' "; + $sql .= ")"; + if ($missing_count != $i) { + $sql .= ",\n"; + } + $i++; + } + $db->exec(check_sql($sql)); + unset($missing); + + //move the dynamic provision variables that from v_vars table to v_default_settings + if (count($_SESSION['provision']) == 0) { + $sql = "select * from v_vars "; + $sql .= "where var_cat = 'Provision' "; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + //set the variable + $var_name = check_str($row['var_name']); + //remove the 'v_' prefix from the variable name + if (substr($var_name, 0, 2) == "v_") { + $var_name = substr($var_name, 2); + } + //add the provision variable to the default settings table + $sql = "insert into v_default_settings "; + $sql .= "("; + $sql .= "default_setting_uuid, "; + $sql .= "default_setting_category, "; + $sql .= "default_setting_subcategory, "; + $sql .= "default_setting_name, "; + $sql .= "default_setting_value, "; + $sql .= "default_setting_enabled, "; + $sql .= "default_setting_description "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".uuid()."', "; + $sql .= "'provision', "; + $sql .= "'".$var_name."', "; + $sql .= "'var', "; + $sql .= "'".check_str($row['var_value'])."', "; + $sql .= "'".check_str($row['var_enabled'])."', "; + $sql .= "'".check_str($row['var_description'])."' "; + $sql .= ")"; + $db->exec(check_sql($sql)); + unset($sql); + } + unset($prep_statement); + //delete the provision variables from system -> variables + //$sql = "delete from v_vars "; + //$sql .= "where var_cat = 'Provision' "; + //echo $sql ."\n"; + //$db->exec(check_sql($sql)); + //echo "$var_name $var_value \n"; + } + + //populate the languages table, if necessary + $sql = "select count(*) as num_rows from v_languages"; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + if ($row['num_rows'] == 0) { + $sql = "insert into v_languages (language_uuid, language, code) values "; + $sql .= "('".uuid()."', 'Afrikaans', 'af'), "; + $sql .= "('".uuid()."', 'Albanian', 'sq'), "; + $sql .= "('".uuid()."', 'Amharic', 'am'), "; + $sql .= "('".uuid()."', 'Arabic - Algeria', 'ar-dz'), "; + $sql .= "('".uuid()."', 'Arabic - Bahrain', 'ar-bh'), "; + $sql .= "('".uuid()."', 'Arabic - Egypt', 'ar-eg'), "; + $sql .= "('".uuid()."', 'Arabic - Iraq', 'ar-iq'), "; + $sql .= "('".uuid()."', 'Arabic - Jordan', 'ar-jo'), "; + $sql .= "('".uuid()."', 'Arabic - Kuwait', 'ar-kw'), "; + $sql .= "('".uuid()."', 'Arabic - Lebanon', 'ar-lb'), "; + $sql .= "('".uuid()."', 'Arabic - Libya', 'ar-ly'), "; + $sql .= "('".uuid()."', 'Arabic - Morocco', 'ar-ma'), "; + $sql .= "('".uuid()."', 'Arabic - Oman', 'ar-om'), "; + $sql .= "('".uuid()."', 'Arabic - Qatar', 'ar-qa'), "; + $sql .= "('".uuid()."', 'Arabic - Saudi Arabia', 'ar-sa'), "; + $sql .= "('".uuid()."', 'Arabic - Syria', 'ar-sy'), "; + $sql .= "('".uuid()."', 'Arabic - Tunisia', 'ar-tn'), "; + $sql .= "('".uuid()."', 'Arabic - United Arab Emirates', 'ar-ae'), "; + $sql .= "('".uuid()."', 'Arabic - Yemen', 'ar-ye'), "; + $sql .= "('".uuid()."', 'Armenian', 'hy'), "; + $sql .= "('".uuid()."', 'Assamese', 'as'), "; + $sql .= "('".uuid()."', 'Azeri - Cyrillic, Latin', 'az-az'), "; + $sql .= "('".uuid()."', 'Basque', 'eu'), "; + $sql .= "('".uuid()."', 'Belarusian', 'be'), "; + $sql .= "('".uuid()."', 'Bengali - India, Bangladesh', 'bn'), "; + $sql .= "('".uuid()."', 'Bosnian', 'bs'), "; + $sql .= "('".uuid()."', 'Bulgarian', 'bg'), "; + $sql .= "('".uuid()."', 'Burmese', 'my'), "; + $sql .= "('".uuid()."', 'Catalan', 'ca'), "; + $sql .= "('".uuid()."', 'Chinese - China', 'zh-cn'), "; + $sql .= "('".uuid()."', 'Chinese - Hong Kong SAR', 'zh-hk'), "; + $sql .= "('".uuid()."', 'Chinese - Macau SAR', 'zh-mo'), "; + $sql .= "('".uuid()."', 'Chinese - Singapore', 'zh-sg'), "; + $sql .= "('".uuid()."', 'Chinese - Taiwan', 'zh-tw'), "; + $sql .= "('".uuid()."', 'Croatian', 'hr'), "; + $sql .= "('".uuid()."', 'Czech', 'cs'), "; + $sql .= "('".uuid()."', 'Danish', 'da'), "; + $sql .= "('".uuid()."', 'Divehi, Dhivehi, Maldivian', 'dv'), "; + $sql .= "('".uuid()."', 'Dutch - Belgium', 'nl-be'), "; + $sql .= "('".uuid()."', 'Dutch - Netherlands', 'nl-nl'), "; + $sql .= "('".uuid()."', 'English - Australia', 'en-au'), "; + $sql .= "('".uuid()."', 'English - Belize', 'en-bz'), "; + $sql .= "('".uuid()."', 'English - Canada', 'en-ca'), "; + $sql .= "('".uuid()."', 'English - Caribbean', 'en-cb'), "; + $sql .= "('".uuid()."', 'English - Great Britain', 'en-gb'), "; + $sql .= "('".uuid()."', 'English - India', 'en-in'), "; + $sql .= "('".uuid()."', 'English - Ireland', 'en-ie'), "; + $sql .= "('".uuid()."', 'English - Jamaica', 'en-jm'), "; + $sql .= "('".uuid()."', 'English - New Zealand', 'en-nz'), "; + $sql .= "('".uuid()."', 'English - Phillippines', 'en-ph'), "; + $sql .= "('".uuid()."', 'English - Southern Africa', 'en-za'), "; + $sql .= "('".uuid()."', 'English - Trinidad', 'en-tt'), "; + $sql .= "('".uuid()."', 'English - United States', 'en-us'), "; + $sql .= "('".uuid()."', 'Estonian', 'et'), "; + $sql .= "('".uuid()."', 'Faroese', 'fo'), "; + $sql .= "('".uuid()."', 'Farsi - Persian', 'fa'), "; + $sql .= "('".uuid()."', 'Finnish', 'fi'), "; + $sql .= "('".uuid()."', 'French - Belgium', 'fr-be'), "; + $sql .= "('".uuid()."', 'French - Canada', 'fr-ca'), "; + $sql .= "('".uuid()."', 'French - France', 'fr-fr'), "; + $sql .= "('".uuid()."', 'French - Luxembourg', 'fr-lu'), "; + $sql .= "('".uuid()."', 'French - Switzerland', 'fr-ch'), "; + $sql .= "('".uuid()."', 'FYRO Macedonia', 'mk'), "; + $sql .= "('".uuid()."', 'Gaelic - Ireland', 'gd-ie'), "; + $sql .= "('".uuid()."', 'Gaelic - Scotland', 'gd'), "; + $sql .= "('".uuid()."', 'German - Austria', 'de-at'), "; + $sql .= "('".uuid()."', 'German - Germany', 'de-de'), "; + $sql .= "('".uuid()."', 'German - Liechtenstein', 'de-li'), "; + $sql .= "('".uuid()."', 'German - Luxembourg', 'de-lu'), "; + $sql .= "('".uuid()."', 'German - Switzerland', 'de-ch'), "; + $sql .= "('".uuid()."', 'Greek', 'el'), "; + $sql .= "('".uuid()."', 'Guarani - Paraguay', 'gn'), "; + $sql .= "('".uuid()."', 'Gujarati', 'gu'), "; + $sql .= "('".uuid()."', 'Hebrew', 'he'), "; + $sql .= "('".uuid()."', 'Hindi', 'hi'), "; + $sql .= "('".uuid()."', 'Hungarian', 'hu'), "; + $sql .= "('".uuid()."', 'Icelandic', 'is'), "; + $sql .= "('".uuid()."', 'Indonesian', 'id'), "; + $sql .= "('".uuid()."', 'Italian - Italy', 'it-it'), "; + $sql .= "('".uuid()."', 'Italian - Switzerland', 'it-ch'), "; + $sql .= "('".uuid()."', 'Japanese', 'ja'), "; + $sql .= "('".uuid()."', 'Kannada', 'kn'), "; + $sql .= "('".uuid()."', 'Kashmiri', 'ks'), "; + $sql .= "('".uuid()."', 'Kazakh', 'kk'), "; + $sql .= "('".uuid()."', 'Khmer', 'km'), "; + $sql .= "('".uuid()."', 'Korean', 'ko'), "; + $sql .= "('".uuid()."', 'Lao', 'lo'), "; + $sql .= "('".uuid()."', 'Latin', 'la'), "; + $sql .= "('".uuid()."', 'Latvian', 'lv'), "; + $sql .= "('".uuid()."', 'Lithuanian', 'lt'), "; + $sql .= "('".uuid()."', 'Malayalam', 'ml'), "; + $sql .= "('".uuid()."', 'Malay - Brunei', 'ms-bn'), "; + $sql .= "('".uuid()."', 'Malay - Malaysia', 'ms-my'), "; + $sql .= "('".uuid()."', 'Maltese', 'mt'), "; + $sql .= "('".uuid()."', 'Maori', 'mi'), "; + $sql .= "('".uuid()."', 'Marathi', 'mr'), "; + $sql .= "('".uuid()."', 'Nepali', 'ne'), "; + $sql .= "('".uuid()."', 'Norwegian - Bokml, Nynorsk', 'no-no'), "; + $sql .= "('".uuid()."', 'Oriya', 'or'), "; + $sql .= "('".uuid()."', 'Polish', 'pl'), "; + $sql .= "('".uuid()."', 'Portuguese - Brazil', 'pt-br'), "; + $sql .= "('".uuid()."', 'Portuguese - Portugal', 'pt-pt'), "; + $sql .= "('".uuid()."', 'Punjabi', 'pa'), "; + $sql .= "('".uuid()."', 'Raeto-Romance', 'rm'), "; + $sql .= "('".uuid()."', 'Romanian - Moldova', 'ro-mo'), "; + $sql .= "('".uuid()."', 'Romanian - Romania', 'ro'), "; + $sql .= "('".uuid()."', 'Russian', 'ru'), "; + $sql .= "('".uuid()."', 'Russian - Moldova', 'ru-mo'), "; + $sql .= "('".uuid()."', 'Sanskrit', 'sa'), "; + $sql .= "('".uuid()."', 'Serbian - Cyrillic, Latin', 'sr-sp'), "; + $sql .= "('".uuid()."', 'Setsuana', 'tn'), "; + $sql .= "('".uuid()."', 'Sindhi', 'sd'), "; + $sql .= "('".uuid()."', 'Sinhala, Sinhalese', 'si'), "; + $sql .= "('".uuid()."', 'Slovak', 'sk'), "; + $sql .= "('".uuid()."', 'Slovenian', 'sl'), "; + $sql .= "('".uuid()."', 'Somali', 'so'), "; + $sql .= "('".uuid()."', 'Sorbian', 'sb'), "; + $sql .= "('".uuid()."', 'Spanish - Argentina', 'es-ar'), "; + $sql .= "('".uuid()."', 'Spanish - Bolivia', 'es-bo'), "; + $sql .= "('".uuid()."', 'Spanish - Chile', 'es-cl'), "; + $sql .= "('".uuid()."', 'Spanish - Colombia', 'es-co'), "; + $sql .= "('".uuid()."', 'Spanish - Costa Rica', 'es-cr'), "; + $sql .= "('".uuid()."', 'Spanish - Dominican Republic', 'es-do'), "; + $sql .= "('".uuid()."', 'Spanish - Ecuador', 'es-ec'), "; + $sql .= "('".uuid()."', 'Spanish - El Salvador', 'es-sv'), "; + $sql .= "('".uuid()."', 'Spanish - Guatemala', 'es-gt'), "; + $sql .= "('".uuid()."', 'Spanish - Honduras', 'es-hn'), "; + $sql .= "('".uuid()."', 'Spanish - Mexico', 'es-mx'), "; + $sql .= "('".uuid()."', 'Spanish - Nicaragua', 'es-ni'), "; + $sql .= "('".uuid()."', 'Spanish - Panama', 'es-pa'), "; + $sql .= "('".uuid()."', 'Spanish - Paraguay', 'es-py'), "; + $sql .= "('".uuid()."', 'Spanish - Peru', 'es-pe'), "; + $sql .= "('".uuid()."', 'Spanish - Puerto Rico', 'es-pr'), "; + $sql .= "('".uuid()."', 'Spanish - Spain (Traditional)', 'es-es'), "; + $sql .= "('".uuid()."', 'Spanish - Uruguay', 'es-uy'), "; + $sql .= "('".uuid()."', 'Spanish - Venezuela', 'es-ve'), "; + $sql .= "('".uuid()."', 'Swahili', 'sw'), "; + $sql .= "('".uuid()."', 'Swedish - Finland', 'sv-fi'), "; + $sql .= "('".uuid()."', 'Swedish - Sweden', 'sv-se'), "; + $sql .= "('".uuid()."', 'Tajik', 'tg'), "; + $sql .= "('".uuid()."', 'Tamil', 'ta'), "; + $sql .= "('".uuid()."', 'Tatar', 'tt'), "; + $sql .= "('".uuid()."', 'Telugu', 'te'), "; + $sql .= "('".uuid()."', 'Thai', 'th'), "; + $sql .= "('".uuid()."', 'Tibetan', 'bo'), "; + $sql .= "('".uuid()."', 'Tsonga', 'ts'), "; + $sql .= "('".uuid()."', 'Turkish', 'tr'), "; + $sql .= "('".uuid()."', 'Turkmen', 'tk'), "; + $sql .= "('".uuid()."', 'Ukrainian', 'uk'), "; + $sql .= "('".uuid()."', 'Urdu', 'ur'), "; + $sql .= "('".uuid()."', 'Uzbek - Cyrillic, Latin', 'uz-uz'), "; + $sql .= "('".uuid()."', 'Vietnamese', 'vi'), "; + $sql .= "('".uuid()."', 'Welsh', 'cy'), "; + $sql .= "('".uuid()."', 'Xhosa', 'xh'), "; + $sql .= "('".uuid()."', 'Yiddish', 'yi') "; + $db->exec(check_sql($sql)); + unset($sql); + } + unset($prep_statement, $row); + } + +} + ?> \ No newline at end of file diff --git a/core/default_settings/app_languages.php b/core/default_settings/app_languages.php index 30eb1196fa..432ac90a4a 100644 --- a/core/default_settings/app_languages.php +++ b/core/default_settings/app_languages.php @@ -1,433 +1,433 @@ - \ No newline at end of file diff --git a/core/default_settings/default_setting_toggle.php b/core/default_settings/default_setting_toggle.php index 330c6b84d1..0f26ade8a6 100644 --- a/core/default_settings/default_setting_toggle.php +++ b/core/default_settings/default_setting_toggle.php @@ -1,72 +1,72 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2016 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('voicemail_message_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//get submitted variables - $search = $_REQUEST['search']; - $default_setting_uuids = $_REQUEST["id"]; - -//toggle the setting - $toggled = 0; - if (is_array($default_setting_uuids) && sizeof($default_setting_uuids) > 0) { - foreach ($default_setting_uuids as $default_setting_uuid) { - //get current status - $sql = "select default_setting_enabled from v_default_settings where default_setting_uuid = '".check_str($default_setting_uuid)."'"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_NAMED); - $new_status = ($row['default_setting_enabled'] == 'true') ? 'false' : "true"; - unset ($sql, $prep_statement, $row); - //set new status - $sql = "update v_default_settings set default_setting_enabled = '".$new_status."' where default_setting_uuid = '".check_str($default_setting_uuid)."'"; - $prep_statement = $db->prepare(check_sql($sql)); - $prep_statement->execute(); - unset ($sql, $prep_statement); - - $toggled++; - } - } - -//redirect the user - if ($toggled > 0) { - $_SESSION["message"] = $text['message-toggled'].': '.$toggled; - } - header("Location: default_settings.php".(($search != '') ? '?search='.$search : null)); - + + Portions created by the Initial Developer are Copyright (C) 2008-2016 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('voicemail_message_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//get submitted variables + $search = $_REQUEST['search']; + $default_setting_uuids = $_REQUEST["id"]; + +//toggle the setting + $toggled = 0; + if (is_array($default_setting_uuids) && sizeof($default_setting_uuids) > 0) { + foreach ($default_setting_uuids as $default_setting_uuid) { + //get current status + $sql = "select default_setting_enabled from v_default_settings where default_setting_uuid = '".check_str($default_setting_uuid)."'"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_NAMED); + $new_status = ($row['default_setting_enabled'] == 'true') ? 'false' : "true"; + unset ($sql, $prep_statement, $row); + //set new status + $sql = "update v_default_settings set default_setting_enabled = '".$new_status."' where default_setting_uuid = '".check_str($default_setting_uuid)."'"; + $prep_statement = $db->prepare(check_sql($sql)); + $prep_statement->execute(); + unset ($sql, $prep_statement); + + $toggled++; + } + } + +//redirect the user + if ($toggled > 0) { + $_SESSION["message"] = $text['message-toggled'].': '.$toggled; + } + header("Location: default_settings.php".(($search != '') ? '?search='.$search : null)); + ?> \ No newline at end of file diff --git a/core/default_settings/default_settings_reload.php b/core/default_settings/default_settings_reload.php index 7bc17ff5ae..ad1668fe17 100644 --- a/core/default_settings/default_settings_reload.php +++ b/core/default_settings/default_settings_reload.php @@ -1,51 +1,51 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2014 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (permission_exists('default_setting_view')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -$search = check_str($_REQUEST['search']); - -require "resources/classes/domains.php"; -$domain = new domains(); -$domain->db = $db; -$domain->set(); - -$_SESSION["message"] = $text['message-settings_reloaded']; -header("Location: default_settings.php".(($search != '') ? "?search=".$search : null)); - + + Portions created by the Initial Developer are Copyright (C) 2008-2014 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (permission_exists('default_setting_view')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +$search = check_str($_REQUEST['search']); + +require "resources/classes/domains.php"; +$domain = new domains(); +$domain->db = $db; +$domain->set(); + +$_SESSION["message"] = $text['message-settings_reloaded']; +header("Location: default_settings.php".(($search != '') ? "?search=".$search : null)); + ?> \ No newline at end of file diff --git a/core/domain_settings/app_defaults.php b/core/domain_settings/app_defaults.php index dc350e8dbc..069cc56825 100644 --- a/core/domain_settings/app_defaults.php +++ b/core/domain_settings/app_defaults.php @@ -1,35 +1,35 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2010 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -//proccess this only one time - if ($domains_processed == 1) { - //set domains with enabled status of empty or null to true - $sql = "update v_domains set domain_enabled = 'true' where domain_enabled = '' or domain_enabled is null"; - $db->exec(check_sql($sql)); - unset($sql); - } - + + Portions created by the Initial Developer are Copyright (C) 2008-2010 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +//proccess this only one time + if ($domains_processed == 1) { + //set domains with enabled status of empty or null to true + $sql = "update v_domains set domain_enabled = 'true' where domain_enabled = '' or domain_enabled is null"; + $db->exec(check_sql($sql)); + unset($sql); + } + ?> \ No newline at end of file diff --git a/core/domain_settings/app_languages.php b/core/domain_settings/app_languages.php index d7082818ae..944c59f841 100644 --- a/core/domain_settings/app_languages.php +++ b/core/domain_settings/app_languages.php @@ -1,445 +1,445 @@ - \ No newline at end of file diff --git a/core/events/resources/classes/events.php b/core/events/resources/classes/events.php index 72025e1480..bcf9dc314d 100644 --- a/core/events/resources/classes/events.php +++ b/core/events/resources/classes/events.php @@ -1,164 +1,164 @@ -connect(); - $this->db = $database->db; - return $this->db = $database->db; - - //load the plugins - $this->load_plugins(); - - //add values to the required array - $this->required['headers'][] = "content-type"; - $this->required['headers'][] = "date"; - $this->required['headers'][] = "host"; - $this->required['headers'][] = "status"; - $this->required['headers'][] = "app_name"; - $this->required['headers'][] = "app_uuid"; - $this->required['headers'][] = "domain_uuid"; - $this->required['headers'][] = "user_uuid"; - } - - /** - * Called when there are no references to a particular object - * unset the variables used in the class - */ - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - /** - * This function will load all available plugins into the memory - * Rules: - * plugins are stored in ./plugins - * plugin class is named plugin_ - * php file is named .php - */ - private function load_plugins() { - $base = realpath(dirname(__FILE__)) . "/plugins"; - $this->plugins = glob($base . "/*.php"); - foreach($this->plugins as $plugin) { - //include the plugin php file and define the class name - include_once $plugin; - $plugin_name = basename($plugin, ".php"); - $class_name = "plugin_".$plugin_name; - - //create the plugin object so that it can be stored and called later - $obj = new $class_name(); - $this->plugins[$plugin_name] = $obj; - - //store all methods found in the plugin - foreach (get_class_methods($obj) as $method ) { - $this->methods[$method] = $plugin_name; - } - - } - } - - /** - * Run the plugin method - * @param strint $method - * @param string $args - * - */ - public function __call($method, $args) { - if (! key_exists($method, $this->methods)) { - throw new Exception ("Call to undefined method: " . $method); - } - array_unshift($args, $this); - try { - $obj = call_user_func_array(array($this->plugins[$this->methods[$method]], $method), $args); - } - catch (Exception $e) { - echo 'Exception: ', $e->getMessage(), "\n"; - } - return $obj; - } - - /** - * Set a new event header - * @param string $category - * @param string $name - * @param string $value - */ - public function set_header($category, $name, $value) { - $this->headers[$category][$name] = $value; - } - - /** - * check for required headers - * @param string $category - * @return bolean $value - */ - public function check_required($category) { - foreach ($this->required['headers'] as &$header) { - if ($category == $header) { - return true; - } - } - return false; - } - - /** - * Send the event - */ - public function send() { - //check for required headers are present return false if any are missing - foreach ($this->headers as &$header) { - if (!$this->check_required($header)) { - return false; - } - } - - //$this->content; - } - - /** - * Serialize the event headers - * @param string $type values: array, json - */ - public function serialize($type) { - $array = $this->headers; - if ($type == "array") { - return $array; - } elseif ($type == "json") { - return json_encode($array); - } - } - -} - +connect(); + $this->db = $database->db; + return $this->db = $database->db; + + //load the plugins + $this->load_plugins(); + + //add values to the required array + $this->required['headers'][] = "content-type"; + $this->required['headers'][] = "date"; + $this->required['headers'][] = "host"; + $this->required['headers'][] = "status"; + $this->required['headers'][] = "app_name"; + $this->required['headers'][] = "app_uuid"; + $this->required['headers'][] = "domain_uuid"; + $this->required['headers'][] = "user_uuid"; + } + + /** + * Called when there are no references to a particular object + * unset the variables used in the class + */ + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + /** + * This function will load all available plugins into the memory + * Rules: + * plugins are stored in ./plugins + * plugin class is named plugin_ + * php file is named .php + */ + private function load_plugins() { + $base = realpath(dirname(__FILE__)) . "/plugins"; + $this->plugins = glob($base . "/*.php"); + foreach($this->plugins as $plugin) { + //include the plugin php file and define the class name + include_once $plugin; + $plugin_name = basename($plugin, ".php"); + $class_name = "plugin_".$plugin_name; + + //create the plugin object so that it can be stored and called later + $obj = new $class_name(); + $this->plugins[$plugin_name] = $obj; + + //store all methods found in the plugin + foreach (get_class_methods($obj) as $method ) { + $this->methods[$method] = $plugin_name; + } + + } + } + + /** + * Run the plugin method + * @param strint $method + * @param string $args + * + */ + public function __call($method, $args) { + if (! key_exists($method, $this->methods)) { + throw new Exception ("Call to undefined method: " . $method); + } + array_unshift($args, $this); + try { + $obj = call_user_func_array(array($this->plugins[$this->methods[$method]], $method), $args); + } + catch (Exception $e) { + echo 'Exception: ', $e->getMessage(), "\n"; + } + return $obj; + } + + /** + * Set a new event header + * @param string $category + * @param string $name + * @param string $value + */ + public function set_header($category, $name, $value) { + $this->headers[$category][$name] = $value; + } + + /** + * check for required headers + * @param string $category + * @return bolean $value + */ + public function check_required($category) { + foreach ($this->required['headers'] as &$header) { + if ($category == $header) { + return true; + } + } + return false; + } + + /** + * Send the event + */ + public function send() { + //check for required headers are present return false if any are missing + foreach ($this->headers as &$header) { + if (!$this->check_required($header)) { + return false; + } + } + + //$this->content; + } + + /** + * Serialize the event headers + * @param string $type values: array, json + */ + public function serialize($type) { + $array = $this->headers; + if ($type == "array") { + return $array; + } elseif ($type == "json") { + return json_encode($array); + } + } + +} + ?> \ No newline at end of file diff --git a/core/install/app_languages.php b/core/install/app_languages.php index 9459deef76..4b4acc49e0 100644 --- a/core/install/app_languages.php +++ b/core/install/app_languages.php @@ -1,421 +1,421 @@ - \ No newline at end of file diff --git a/core/install/index.php b/core/install/index.php index 639a266dd5..71b8a8aa8a 100644 --- a/core/install/index.php +++ b/core/install/index.php @@ -1,83 +1,83 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - Matthew Vale -*/ -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; - -//detect install state -$install_enabled = true; -if (file_exists($_SERVER["PROJECT_ROOT"]."/resources/config.php")) { - $install_enabled = false; -} elseif (file_exists("/etc/fusionpbx/config.php")) { - //linux - $install_enabled = false; -} elseif (file_exists("/usr/local/etc/fusionpbx/config.php")) { - $install_enabled = false; -} - -if($install_enabled) { - header("Location: ".PROJECT_PATH."/core/install/install.php"); - exit; -} -require_once "resources/check_auth.php"; -if (!if_group("superadmin")) { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//includes and title - require_once "resources/header.php"; - $document['title'] = $text['title-install']; - - echo "".$text['header-install'].""; - echo "

"; - echo $text['description-install']; - echo "

"; - - echo "
\n"; - echo "\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - echo "
\n"; - echo " "; - echo " \n"; - echo " \n"; - echo "
\n"; - echo "
\n"; - -//include the footer - require_once "resources/footer.php"; - + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Matthew Vale +*/ +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; + +//detect install state +$install_enabled = true; +if (file_exists($_SERVER["PROJECT_ROOT"]."/resources/config.php")) { + $install_enabled = false; +} elseif (file_exists("/etc/fusionpbx/config.php")) { + //linux + $install_enabled = false; +} elseif (file_exists("/usr/local/etc/fusionpbx/config.php")) { + $install_enabled = false; +} + +if($install_enabled) { + header("Location: ".PROJECT_PATH."/core/install/install.php"); + exit; +} +require_once "resources/check_auth.php"; +if (!if_group("superadmin")) { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//includes and title + require_once "resources/header.php"; + $document['title'] = $text['title-install']; + + echo "".$text['header-install'].""; + echo "

"; + echo $text['description-install']; + echo "

"; + + echo "
\n"; + echo "\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + echo "
\n"; + echo " "; + echo " \n"; + echo " \n"; + echo "
\n"; + echo "
\n"; + +//include the footer + require_once "resources/footer.php"; + ?> \ No newline at end of file diff --git a/core/install/install.php b/core/install/install.php index cb095eef6b..c7478f4c05 100644 --- a/core/install/install.php +++ b/core/install/install.php @@ -1,367 +1,367 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2016 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - Matthew Vale -*/ -//add the required includes - require_once "root.php"; - require_once "resources/functions.php"; - require_once "resources/classes/text.php"; - -//initialize variables we are going to use - $event_host = ''; - $event_port = ''; - $event_password = ''; - $install_language = 'en-us'; - $admin_username = ''; - $admin_password = ''; - $install_default_country = 'US'; - $install_template_name = ''; - $domain_name = ''; - $db_type = ''; - $db_path = ''; - $db_host = ''; - $db_port = ''; - $db_name = ''; - $db_username = ''; - $db_password = ''; - $db_create = ''; - $db_create_username = ''; - $db_create_password = ''; - -//detect the iso country code from the locale - //$locale = Locale::getDefault(); - $timezone = 'UTC'; - if (is_link('/etc/localtime')) { - // Mac OS X (and older Linuxes) - // /etc/localtime is a symlink to the - // timezone in /usr/share/zoneinfo. - $filename = readlink('/etc/localtime'); - if (strpos($filename, '/usr/share/zoneinfo/') === 0) { - $timezone = substr($filename, 20); - } - } elseif (file_exists('/etc/timezone')) { - // Ubuntu / Debian. - $data = file_get_contents('/etc/timezone'); - if ($data) { - $timezone = rtrim($data); - } - } elseif (file_exists('/etc/sysconfig/clock')) { - // RHEL / CentOS - $data = parse_ini_file('/etc/sysconfig/clock'); - if (!empty($data['ZONE'])) { - $timezone = $data['ZONE']; - } - } - -//set the time zone - date_default_timezone_set($timezone); - -//if the config.php exists deny access to install.php - if (file_exists($_SERVER["PROJECT_ROOT"]."/resources/config.php")) { - echo "access denied"; - exit; - } elseif (file_exists("/etc/fusionpbx/config.php")) { - echo "access denied"; - exit; - } elseif (file_exists("/usr/local/etc/fusionpbx/config.php")) { - echo "access denied"; - exit; - } - -//intialize variables - $install_step = ''; - $return_install_step = ''; - -//process the the HTTP POST - if (count($_POST) > 0) { - $install_language = check_str($_POST["install_language"]); - $install_step = check_str($_POST["install_step"]); - $return_install_step = check_str($_POST["return_install_step"]); - if(isset($_POST["event_host"])){ - $event_host = check_str($_POST["event_host"]); - $event_port = check_str($_POST["event_port"]); - $event_password = check_str($_POST["event_password"]); - } - if(isset($_POST["db_type"])){ - $db_type = $_POST["db_type"]; - $admin_username = $_POST["admin_username"]; - $admin_password = $_POST["admin_password"]; - $install_default_country = $_POST["install_default_country"]; - $install_template_name = $_POST["install_template_name"]; - $domain_name = $_POST["domain_name"]; - } - } - -//set the install step if it is not set - if(!$install_step) { $install_step = 'select_language'; } - -//set the language for the install - $_SESSION['domain']['language']['code'] = $install_language; - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//set a default enviroment if first_time - //initialize some varibles to cut down on warnings - $_SESSION['message'] = ''; - $v_link_label_play = ''; - $v_link_label_pause = ''; - $default_login = 0; - $onload = ''; - -//buffer the content - ob_end_clean(); //clean the buffer - ob_start(); - - $messages = array(); - if (!extension_loaded('PDO')) { - $messages[] = "PHP PDO was not detected. Please install it before proceeding"; - } - - echo "
\n"; - $msg = ''; - //make sure the includes directory is writable so the config.php file can be written. - if (!is_writable($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/pdo.php")) { - $messages[] = "Write access to ".$_SERVER["DOCUMENT_ROOT"].PROJECT_PATH." and its sub-directories are required during the install."; - } - //test for selinux - if (file_exists('/usr/sbin/getenforce')) { - $enforcing; - exec('getenforce', $enforcing); - if($enforcing[0] == 'Enforcing'){ - $messages[] = "SELinux is enabled and enforcing you must have a policy installed to let the webserver connect to the switch event socket
". - "You can use the following to find what ports are allowed
semanage port -l | grep '^http_port_t'
"; - } - } - //test for windows and non sqlite - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' and strlen($db_type) > 0 and $db_type !='sqlite') { - $messages[] = "Windows requires a system DSN ODBC connection this must be configured."; - } - - //action code - if($return_install_step == 'config_detail'){ - //check for all required data - $existing_errors = count($messages); - if (strlen($admin_username) == 0) { $messages[] = "Please provide the Admin Username"; } - if (strlen($admin_password) == 0) { $messages[] = "Please provide the Admin Password"; } - elseif (strlen($admin_password) < 5) { $messages[] = "Please provide an Admin Password that is 5 or more characters.
\n"; } - if ( count($messages) > $existing_errors) { $install_step = 'config_detail'; } - } - - if($install_step =='execute') { - //set the max execution time to 1 hour - ini_set('max_execution_time',3600); - } - - //display messages - if (count($messages)>0) { - echo "
\n"; - echo "
\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "
Messages
    \n"; - foreach ($messages as $message){ - echo "
  • $message
  • \n"; - } - echo "
\n"; - echo "
\n"; - } - - //includes and title - $document['title'] = $text['title-install']; - - //view code - if($install_step == 'select_language'){ - echo "
\n"; - include "resources/page_parts/install_select_language.php"; - echo " \n"; - echo " \n"; - echo "
\n"; - } elseif($install_step == 'detect_config'){ - if(!($event_host == '' || $event_host == 'localhost' || $event_host == '::1' || $event_host == '127.0.0.1' )){ - echo "

Warning you have choosen a value other than localhost for event_host, this is unsoported at present

\n"; - } - //if($detect_ok){ - echo "
\n"; - include "resources/page_parts/install_event_socket.php"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - //echo "
\n"; - //echo " \n"; - //echo " \n"; - //echo "
\n"; - echo "
\n"; - //} else { - // echo "
\n"; - // echo "
\n"; - // echo " \n"; - // echo "
\n"; - // echo "
\n"; - //} - } - elseif($install_step == 'config_detail'){ - //get the domain - if(!$domain_name){ - $domain_array = explode(":", $_SERVER["HTTP_HOST"]); - $domain_name = $domain_array[0]; - } - include "resources/page_parts/install_config_detail.php"; - } - elseif($install_step == 'config_database'){ - include "resources/page_parts/install_config_database.php"; - } - elseif($install_step == 'execute'){ - echo "

".$text['header-installing']."

\n"; - //$protocol = 'http'; - //if($_SERVER['HTTPS']) { $protocol = 'https'; } - //echo ""; - require_once "core/install/resources/classes/detect_switch.php"; - $detect_switch = new detect_switch($event_host, $event_port, $event_password); - $detect_ok = true; - try { - $detect_switch->detect(); - } catch(Exception $e){ - //echo "

Failed to detect configuration detect_switch reported: " . $e->getMessage() . "

\n"; - //$detect_ok = false; - } - if($detect_ok){ - $install_ok = true; - echo "
\n";
-			function error_handler($err_severity, $errstr, $errfile, $errline ) {
-				if (0 === error_reporting()) { return false;}
-				switch($err_severity)
-				{
-					case E_ERROR:               throw new Exception ($errstr . " in $errfile line: $errline");
-					case E_PARSE:               throw new Exception ($errstr . " in $errfile line: $errline");
-					case E_CORE_ERROR:          throw new Exception ($errstr . " in $errfile line: $errline");
-					case E_COMPILE_ERROR:       throw new Exception ($errstr . " in $errfile line: $errline");
-					case E_USER_ERROR:          throw new Exception ($errstr . " in $errfile line: $errline");
-					case E_STRICT:              throw new Exception ($errstr . " in $errfile line: $errline");
-					case E_RECOVERABLE_ERROR:   throw new Exception ($errstr . " in $errfile line: $errline");
-					default:                    return false;
-				}
-			}
-			#set_error_handler("error_handler");
-			try {
-				require_once "resources/classes/global_settings.php";
-				$global_settings = new global_settings($detect_switch, $domain_name);
-				if(is_null($global_settings)){ throw new Exception("Error global_settings came back with null"); }
-				require_once "resources/classes/install_fusionpbx.php";
-				$system = new install_fusionpbx($global_settings);
-				$system->admin_username = $admin_username;
-				$system->admin_password = $admin_password;
-				$system->default_country = $install_default_country;
-				$system->install_language = $install_language;
-				$system->template_name = $install_template_name;
-
-				require_once "resources/classes/install_switch.php";
-				$switch = new install_switch($global_settings);
-				//$switch->debug = true;
-				//$system->debug = true;
-				$switch->echo_progress = true;
-				$system->echo_progress = true;
-				$system->install_phase_1();
-				$switch->install_phase_1();
-				$system->install_phase_2();
-				$switch->install_phase_2();
-			} catch(Exception $e){
-				echo "
\n"; - echo "

Failed to install
" . $e->getMessage() . "

\n"; - try { - require_once "resources/classes/install_fusionpbx.php"; - $system = new install_fusionpbx($global_settings); - $system->remove_config(); - } catch(Exception $e){ - echo "

Failed to remove config: " . $e->getMessage() . "

\n"; - } - $install_ok = false; - } - restore_error_handler(); - if($install_ok){ - echo "
\n"; - header("Location: ".PROJECT_PATH."/logout.php"); - $_SESSION['message'] = 'Install complete'; - } else { - echo "
\n"; - echo "
\n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo "
\n"; - } - } - } - else { - echo "

Unkown install_step '$install_step'

\n"; - } - -//initialize some defaults so we can be 'logged in' - $_SESSION['username'] = 'install_enabled'; - $_SESSION['permissions'][]['permission_name'] = 'superadmin'; - $_SESSION['menu'] = ''; - -//add the content to the template and then send output - $body = ob_get_contents(); //get the output from the buffer - ob_end_clean(); //clean the buffer - -//set a default template - $default_template = 'default'; - $_SESSION['domain']['template']['name'] = $default_template; - $_SESSION['theme']['menu_brand_type']['text'] = "text"; - -//set the default template path - $template_path = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/themes/'.$default_template.'/template.php'; - -//get the content of the template - $template_content = file_get_contents($template_path); - -//replace the variables in the template - $template_content = str_replace ("", $document['title'], $template_content); // defined in each individual page - $template_content = str_replace ("", '', $template_content); // defined in each individual page - //$template_content = str_replace ("", $_SESSION["menu"], $template_content); //included in the theme - $template_content = str_replace ("", $body, $template_content); //defined in /themes/default/template.php - $template_content = str_replace ("", PROJECT_PATH, $template_content); //defined in /themes/default/template.php - -//get the contents of the template and save it to the template variable - ob_start(); - require_once "resources/classes/menu.php"; - eval('?>' . $template_content . ' + Portions created by the Initial Developer are Copyright (C) 2008-2016 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Matthew Vale +*/ +//add the required includes + require_once "root.php"; + require_once "resources/functions.php"; + require_once "resources/classes/text.php"; + +//initialize variables we are going to use + $event_host = ''; + $event_port = ''; + $event_password = ''; + $install_language = 'en-us'; + $admin_username = ''; + $admin_password = ''; + $install_default_country = 'US'; + $install_template_name = ''; + $domain_name = ''; + $db_type = ''; + $db_path = ''; + $db_host = ''; + $db_port = ''; + $db_name = ''; + $db_username = ''; + $db_password = ''; + $db_create = ''; + $db_create_username = ''; + $db_create_password = ''; + +//detect the iso country code from the locale + //$locale = Locale::getDefault(); + $timezone = 'UTC'; + if (is_link('/etc/localtime')) { + // Mac OS X (and older Linuxes) + // /etc/localtime is a symlink to the + // timezone in /usr/share/zoneinfo. + $filename = readlink('/etc/localtime'); + if (strpos($filename, '/usr/share/zoneinfo/') === 0) { + $timezone = substr($filename, 20); + } + } elseif (file_exists('/etc/timezone')) { + // Ubuntu / Debian. + $data = file_get_contents('/etc/timezone'); + if ($data) { + $timezone = rtrim($data); + } + } elseif (file_exists('/etc/sysconfig/clock')) { + // RHEL / CentOS + $data = parse_ini_file('/etc/sysconfig/clock'); + if (!empty($data['ZONE'])) { + $timezone = $data['ZONE']; + } + } + +//set the time zone + date_default_timezone_set($timezone); + +//if the config.php exists deny access to install.php + if (file_exists($_SERVER["PROJECT_ROOT"]."/resources/config.php")) { + echo "access denied"; + exit; + } elseif (file_exists("/etc/fusionpbx/config.php")) { + echo "access denied"; + exit; + } elseif (file_exists("/usr/local/etc/fusionpbx/config.php")) { + echo "access denied"; + exit; + } + +//intialize variables + $install_step = ''; + $return_install_step = ''; + +//process the the HTTP POST + if (count($_POST) > 0) { + $install_language = check_str($_POST["install_language"]); + $install_step = check_str($_POST["install_step"]); + $return_install_step = check_str($_POST["return_install_step"]); + if(isset($_POST["event_host"])){ + $event_host = check_str($_POST["event_host"]); + $event_port = check_str($_POST["event_port"]); + $event_password = check_str($_POST["event_password"]); + } + if(isset($_POST["db_type"])){ + $db_type = $_POST["db_type"]; + $admin_username = $_POST["admin_username"]; + $admin_password = $_POST["admin_password"]; + $install_default_country = $_POST["install_default_country"]; + $install_template_name = $_POST["install_template_name"]; + $domain_name = $_POST["domain_name"]; + } + } + +//set the install step if it is not set + if(!$install_step) { $install_step = 'select_language'; } + +//set the language for the install + $_SESSION['domain']['language']['code'] = $install_language; + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//set a default enviroment if first_time + //initialize some varibles to cut down on warnings + $_SESSION['message'] = ''; + $v_link_label_play = ''; + $v_link_label_pause = ''; + $default_login = 0; + $onload = ''; + +//buffer the content + ob_end_clean(); //clean the buffer + ob_start(); + + $messages = array(); + if (!extension_loaded('PDO')) { + $messages[] = "PHP PDO was not detected. Please install it before proceeding"; + } + + echo "
\n"; + $msg = ''; + //make sure the includes directory is writable so the config.php file can be written. + if (!is_writable($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/pdo.php")) { + $messages[] = "Write access to ".$_SERVER["DOCUMENT_ROOT"].PROJECT_PATH." and its sub-directories are required during the install."; + } + //test for selinux + if (file_exists('/usr/sbin/getenforce')) { + $enforcing; + exec('getenforce', $enforcing); + if($enforcing[0] == 'Enforcing'){ + $messages[] = "SELinux is enabled and enforcing you must have a policy installed to let the webserver connect to the switch event socket
". + "You can use the following to find what ports are allowed
semanage port -l | grep '^http_port_t'
"; + } + } + //test for windows and non sqlite + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' and strlen($db_type) > 0 and $db_type !='sqlite') { + $messages[] = "Windows requires a system DSN ODBC connection this must be configured."; + } + + //action code + if($return_install_step == 'config_detail'){ + //check for all required data + $existing_errors = count($messages); + if (strlen($admin_username) == 0) { $messages[] = "Please provide the Admin Username"; } + if (strlen($admin_password) == 0) { $messages[] = "Please provide the Admin Password"; } + elseif (strlen($admin_password) < 5) { $messages[] = "Please provide an Admin Password that is 5 or more characters.
\n"; } + if ( count($messages) > $existing_errors) { $install_step = 'config_detail'; } + } + + if($install_step =='execute') { + //set the max execution time to 1 hour + ini_set('max_execution_time',3600); + } + + //display messages + if (count($messages)>0) { + echo "
\n"; + echo "
\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "
Messages
    \n"; + foreach ($messages as $message){ + echo "
  • $message
  • \n"; + } + echo "
\n"; + echo "
\n"; + } + + //includes and title + $document['title'] = $text['title-install']; + + //view code + if($install_step == 'select_language'){ + echo "
\n"; + include "resources/page_parts/install_select_language.php"; + echo " \n"; + echo " \n"; + echo "
\n"; + } elseif($install_step == 'detect_config'){ + if(!($event_host == '' || $event_host == 'localhost' || $event_host == '::1' || $event_host == '127.0.0.1' )){ + echo "

Warning you have choosen a value other than localhost for event_host, this is unsoported at present

\n"; + } + //if($detect_ok){ + echo "
\n"; + include "resources/page_parts/install_event_socket.php"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + //echo "
\n"; + //echo " \n"; + //echo " \n"; + //echo "
\n"; + echo "
\n"; + //} else { + // echo "
\n"; + // echo "
\n"; + // echo " \n"; + // echo "
\n"; + // echo "
\n"; + //} + } + elseif($install_step == 'config_detail'){ + //get the domain + if(!$domain_name){ + $domain_array = explode(":", $_SERVER["HTTP_HOST"]); + $domain_name = $domain_array[0]; + } + include "resources/page_parts/install_config_detail.php"; + } + elseif($install_step == 'config_database'){ + include "resources/page_parts/install_config_database.php"; + } + elseif($install_step == 'execute'){ + echo "

".$text['header-installing']."

\n"; + //$protocol = 'http'; + //if($_SERVER['HTTPS']) { $protocol = 'https'; } + //echo ""; + require_once "core/install/resources/classes/detect_switch.php"; + $detect_switch = new detect_switch($event_host, $event_port, $event_password); + $detect_ok = true; + try { + $detect_switch->detect(); + } catch(Exception $e){ + //echo "

Failed to detect configuration detect_switch reported: " . $e->getMessage() . "

\n"; + //$detect_ok = false; + } + if($detect_ok){ + $install_ok = true; + echo "
\n";
+			function error_handler($err_severity, $errstr, $errfile, $errline ) {
+				if (0 === error_reporting()) { return false;}
+				switch($err_severity)
+				{
+					case E_ERROR:               throw new Exception ($errstr . " in $errfile line: $errline");
+					case E_PARSE:               throw new Exception ($errstr . " in $errfile line: $errline");
+					case E_CORE_ERROR:          throw new Exception ($errstr . " in $errfile line: $errline");
+					case E_COMPILE_ERROR:       throw new Exception ($errstr . " in $errfile line: $errline");
+					case E_USER_ERROR:          throw new Exception ($errstr . " in $errfile line: $errline");
+					case E_STRICT:              throw new Exception ($errstr . " in $errfile line: $errline");
+					case E_RECOVERABLE_ERROR:   throw new Exception ($errstr . " in $errfile line: $errline");
+					default:                    return false;
+				}
+			}
+			#set_error_handler("error_handler");
+			try {
+				require_once "resources/classes/global_settings.php";
+				$global_settings = new global_settings($detect_switch, $domain_name);
+				if(is_null($global_settings)){ throw new Exception("Error global_settings came back with null"); }
+				require_once "resources/classes/install_fusionpbx.php";
+				$system = new install_fusionpbx($global_settings);
+				$system->admin_username = $admin_username;
+				$system->admin_password = $admin_password;
+				$system->default_country = $install_default_country;
+				$system->install_language = $install_language;
+				$system->template_name = $install_template_name;
+
+				require_once "resources/classes/install_switch.php";
+				$switch = new install_switch($global_settings);
+				//$switch->debug = true;
+				//$system->debug = true;
+				$switch->echo_progress = true;
+				$system->echo_progress = true;
+				$system->install_phase_1();
+				$switch->install_phase_1();
+				$system->install_phase_2();
+				$switch->install_phase_2();
+			} catch(Exception $e){
+				echo "
\n"; + echo "

Failed to install
" . $e->getMessage() . "

\n"; + try { + require_once "resources/classes/install_fusionpbx.php"; + $system = new install_fusionpbx($global_settings); + $system->remove_config(); + } catch(Exception $e){ + echo "

Failed to remove config: " . $e->getMessage() . "

\n"; + } + $install_ok = false; + } + restore_error_handler(); + if($install_ok){ + echo "
\n"; + header("Location: ".PROJECT_PATH."/logout.php"); + $_SESSION['message'] = 'Install complete'; + } else { + echo "
\n"; + echo "
\n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo "
\n"; + } + } + } + else { + echo "

Unkown install_step '$install_step'

\n"; + } + +//initialize some defaults so we can be 'logged in' + $_SESSION['username'] = 'install_enabled'; + $_SESSION['permissions'][]['permission_name'] = 'superadmin'; + $_SESSION['menu'] = ''; + +//add the content to the template and then send output + $body = ob_get_contents(); //get the output from the buffer + ob_end_clean(); //clean the buffer + +//set a default template + $default_template = 'default'; + $_SESSION['domain']['template']['name'] = $default_template; + $_SESSION['theme']['menu_brand_type']['text'] = "text"; + +//set the default template path + $template_path = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/themes/'.$default_template.'/template.php'; + +//get the content of the template + $template_content = file_get_contents($template_path); + +//replace the variables in the template + $template_content = str_replace ("", $document['title'], $template_content); // defined in each individual page + $template_content = str_replace ("", '', $template_content); // defined in each individual page + //$template_content = str_replace ("", $_SESSION["menu"], $template_content); //included in the theme + $template_content = str_replace ("", $body, $template_content); //defined in /themes/default/template.php + $template_content = str_replace ("", PROJECT_PATH, $template_content); //defined in /themes/default/template.php + +//get the contents of the template and save it to the template variable + ob_start(); + require_once "resources/classes/menu.php"; + eval('?>' . $template_content . ' \ No newline at end of file diff --git a/core/install/resources/classes/detect_switch.php b/core/install/resources/classes/detect_switch.php index 7ce789a6b9..f2e4af5604 100644 --- a/core/install/resources/classes/detect_switch.php +++ b/core/install/resources/classes/detect_switch.php @@ -1,170 +1,170 @@ - - Copyright (C) 2010-2015 - All Rights Reserved. - - Contributor(s): - Matthew Vale - -*/ -require_once "root.php"; -require_once "resources/classes/event_socket.php"; - -//define the install class - class detect_switch { - - // cached data - protected $_dirs; - protected $_vdirs; - public function get_dirs() { return $this->_dirs; } - public function get_vdirs() { return $this->_vdirs; } - - // version information - protected $_major; - protected $_minor; - protected $_build; - protected $_bits; - public function major() { return $this->_major; } - public function minor() { return $this->_minor; } - public function build() { return $this->_build; } - public function bits() { return $this->_bits; } - public function version() { return $this->_major.".".$this->_minor.".".$this->_build." (".$this->_bits.")"; } - - // dirs - detected by from the switch - protected $_base_dir = ''; - protected $_cache_dir = ''; - protected $_conf_dir = ''; - protected $_db_dir = ''; - protected $_grammar_dir = ''; - protected $_htdocs_dir = ''; - protected $_log_dir = ''; - protected $_mod_dir = ''; - protected $_recordings_dir = ''; - protected $_run_dir = ''; - protected $_script_dir = ''; - protected $_sounds_dir = ''; - protected $_storage_dir = ''; - protected $_temp_dir = ''; - public function base_dir() { return $this->_base_dir; } - public function cache_dir() { return $this->_cache_dir; } - public function conf_dir() { return $this->_conf_dir; } - public function db_dir() { return $this->_db_dir; } - public function grammar_dir() { return $this->_grammar_dir; } - public function htdocs_dir() { return $this->_htdocs_dir; } - public function log_dir() { return $this->_log_dir; } - public function mod_dir() { return $this->_mod_dir; } - public function recordings_dir() { return $this->_recordings_dir; } - public function run_dir() { return $this->_run_dir; } - public function script_dir() { return $this->_script_dir; } - public function sounds_dir() { return $this->_sounds_dir; } - public function storage_dir() { return $this->_storage_dir; } - public function temp_dir() { return $this->_temp_dir; } - - // virtual dirs - assumed based on the detected dirs - protected $_voicemail_vdir = ''; - protected $_phrases_vdir = ''; - protected $_extensions_vdir = ''; - protected $_sip_profiles_vdir = ''; - protected $_dialplan_vdir = ''; - protected $_backup_vdir = ''; - public function voicemail_vdir() { return $this->_voicemail_vdir; } - public function phrases_vdir() { return $this->_phrases_vdir; } - public function extensions_vdir() { return $this->_extensions_vdir; } - public function sip_profiles_vdir() { return $this->_sip_profiles_vdir; } - public function dialplan_vdir() { return $this->_dialplan_vdir; } - public function backup_vdir() { return $this->_backup_vdir; } - - // event socket - public $event_host = 'localhost'; - public $event_port = '8021'; - public $event_password = 'ClueCon'; - protected $event_socket; - - public function __construct($event_host, $event_port, $event_password) { - //do not take these settings from session as they be detecting a new switch - if($event_host){ $this->event_host = $event_host; } - if($event_port){ $this->event_port = $event_port; } - if($event_password){ $this->event_password = $event_password; } - $this->connect_event_socket(); - if(!$this->event_socket){ - $this->detect_event_socket(); - } - $this->_dirs = preg_grep ('/.*_dir$/', get_class_methods('detect_switch') ); - sort( $this->_dirs ); - $this->_vdirs = preg_grep ('/.*_vdir$/', get_class_methods('detect_switch') ); - sort( $this->_vdirs ); - } - - protected function detect_event_socket() { - //perform searches for user's config here - } - - public function detect() { - $this->connect_event_socket(); - if(!$this->event_socket){ - throw new Exception('Failed to use event socket'); - } - $FS_Version = $this->event_socket_request('api version'); - preg_match("/FreeSWITCH Version (\d+)\.(\d+)\.(\d+(?:\.\d+)?).*\(.*?(\d+\w+)\s*\)/", $FS_Version, $matches); - $this->_major = $matches[1]; - $this->_minor = $matches[2]; - $this->_build = $matches[3]; - $this->_bits = $matches[4]; - $FS_Vars = $this->event_socket_request('api global_getvar'); - foreach (explode("\n",$FS_Vars) as $FS_Var){ - preg_match("/(\w+_dir)=(.*)/", $FS_Var, $matches); - if(count($matches) > 0 and property_exists($this, "_" . $matches[1])){ - $field = "_" . $matches[1]; - $this->$field = normalize_path($matches[2]); - } - } - $this->_voicemail_vdir = normalize_path($this->_storage_dir . DIRECTORY_SEPARATOR . "voicemail"); - $this->_phrases_vdir = normalize_path($this->_conf_dir . DIRECTORY_SEPARATOR . "lang"); - $this->_extensions_vdir = normalize_path($this->_conf_dir . DIRECTORY_SEPARATOR . "directory"); - $this->_sip_profiles_vdir = normalize_path($this->_conf_dir . DIRECTORY_SEPARATOR . "sip_profiles"); - $this->_dialplan_vdir = normalize_path($this->_conf_dir . DIRECTORY_SEPARATOR . "dialplan"); - $this->_backup_vdir = normalize_path(sys_get_temp_dir()); - } - - protected function connect_event_socket(){ - $esl = new event_socket; - if ($esl->connect($this->event_host, $this->event_port, $this->event_password)) { - $this->event_socket = $esl->reset_fp(); - return true; - } - return false; - } - - protected function event_socket_request($cmd) { - $esl = new event_socket($this->event_socket); - $result = $esl->request($cmd); - $esl->reset_fp(); - return $result; - } - - public function restart_switch() { - $this->connect_event_socket(); - if(!$this->event_socket){ - throw new Exception('Failed to use event socket'); - } - $this->event_socket_request('api fsctl shutdown restart elegant'); - } - } + + Copyright (C) 2010-2015 + All Rights Reserved. + + Contributor(s): + Matthew Vale + +*/ +require_once "root.php"; +require_once "resources/classes/event_socket.php"; + +//define the install class + class detect_switch { + + // cached data + protected $_dirs; + protected $_vdirs; + public function get_dirs() { return $this->_dirs; } + public function get_vdirs() { return $this->_vdirs; } + + // version information + protected $_major; + protected $_minor; + protected $_build; + protected $_bits; + public function major() { return $this->_major; } + public function minor() { return $this->_minor; } + public function build() { return $this->_build; } + public function bits() { return $this->_bits; } + public function version() { return $this->_major.".".$this->_minor.".".$this->_build." (".$this->_bits.")"; } + + // dirs - detected by from the switch + protected $_base_dir = ''; + protected $_cache_dir = ''; + protected $_conf_dir = ''; + protected $_db_dir = ''; + protected $_grammar_dir = ''; + protected $_htdocs_dir = ''; + protected $_log_dir = ''; + protected $_mod_dir = ''; + protected $_recordings_dir = ''; + protected $_run_dir = ''; + protected $_script_dir = ''; + protected $_sounds_dir = ''; + protected $_storage_dir = ''; + protected $_temp_dir = ''; + public function base_dir() { return $this->_base_dir; } + public function cache_dir() { return $this->_cache_dir; } + public function conf_dir() { return $this->_conf_dir; } + public function db_dir() { return $this->_db_dir; } + public function grammar_dir() { return $this->_grammar_dir; } + public function htdocs_dir() { return $this->_htdocs_dir; } + public function log_dir() { return $this->_log_dir; } + public function mod_dir() { return $this->_mod_dir; } + public function recordings_dir() { return $this->_recordings_dir; } + public function run_dir() { return $this->_run_dir; } + public function script_dir() { return $this->_script_dir; } + public function sounds_dir() { return $this->_sounds_dir; } + public function storage_dir() { return $this->_storage_dir; } + public function temp_dir() { return $this->_temp_dir; } + + // virtual dirs - assumed based on the detected dirs + protected $_voicemail_vdir = ''; + protected $_phrases_vdir = ''; + protected $_extensions_vdir = ''; + protected $_sip_profiles_vdir = ''; + protected $_dialplan_vdir = ''; + protected $_backup_vdir = ''; + public function voicemail_vdir() { return $this->_voicemail_vdir; } + public function phrases_vdir() { return $this->_phrases_vdir; } + public function extensions_vdir() { return $this->_extensions_vdir; } + public function sip_profiles_vdir() { return $this->_sip_profiles_vdir; } + public function dialplan_vdir() { return $this->_dialplan_vdir; } + public function backup_vdir() { return $this->_backup_vdir; } + + // event socket + public $event_host = 'localhost'; + public $event_port = '8021'; + public $event_password = 'ClueCon'; + protected $event_socket; + + public function __construct($event_host, $event_port, $event_password) { + //do not take these settings from session as they be detecting a new switch + if($event_host){ $this->event_host = $event_host; } + if($event_port){ $this->event_port = $event_port; } + if($event_password){ $this->event_password = $event_password; } + $this->connect_event_socket(); + if(!$this->event_socket){ + $this->detect_event_socket(); + } + $this->_dirs = preg_grep ('/.*_dir$/', get_class_methods('detect_switch') ); + sort( $this->_dirs ); + $this->_vdirs = preg_grep ('/.*_vdir$/', get_class_methods('detect_switch') ); + sort( $this->_vdirs ); + } + + protected function detect_event_socket() { + //perform searches for user's config here + } + + public function detect() { + $this->connect_event_socket(); + if(!$this->event_socket){ + throw new Exception('Failed to use event socket'); + } + $FS_Version = $this->event_socket_request('api version'); + preg_match("/FreeSWITCH Version (\d+)\.(\d+)\.(\d+(?:\.\d+)?).*\(.*?(\d+\w+)\s*\)/", $FS_Version, $matches); + $this->_major = $matches[1]; + $this->_minor = $matches[2]; + $this->_build = $matches[3]; + $this->_bits = $matches[4]; + $FS_Vars = $this->event_socket_request('api global_getvar'); + foreach (explode("\n",$FS_Vars) as $FS_Var){ + preg_match("/(\w+_dir)=(.*)/", $FS_Var, $matches); + if(count($matches) > 0 and property_exists($this, "_" . $matches[1])){ + $field = "_" . $matches[1]; + $this->$field = normalize_path($matches[2]); + } + } + $this->_voicemail_vdir = normalize_path($this->_storage_dir . DIRECTORY_SEPARATOR . "voicemail"); + $this->_phrases_vdir = normalize_path($this->_conf_dir . DIRECTORY_SEPARATOR . "lang"); + $this->_extensions_vdir = normalize_path($this->_conf_dir . DIRECTORY_SEPARATOR . "directory"); + $this->_sip_profiles_vdir = normalize_path($this->_conf_dir . DIRECTORY_SEPARATOR . "sip_profiles"); + $this->_dialplan_vdir = normalize_path($this->_conf_dir . DIRECTORY_SEPARATOR . "dialplan"); + $this->_backup_vdir = normalize_path(sys_get_temp_dir()); + } + + protected function connect_event_socket(){ + $esl = new event_socket; + if ($esl->connect($this->event_host, $this->event_port, $this->event_password)) { + $this->event_socket = $esl->reset_fp(); + return true; + } + return false; + } + + protected function event_socket_request($cmd) { + $esl = new event_socket($this->event_socket); + $result = $esl->request($cmd); + $esl->reset_fp(); + return $result; + } + + public function restart_switch() { + $this->connect_event_socket(); + if(!$this->event_socket){ + throw new Exception('Failed to use event socket'); + } + $this->event_socket_request('api fsctl shutdown restart elegant'); + } + } ?> \ No newline at end of file diff --git a/core/install/resources/classes/global_settings.php b/core/install/resources/classes/global_settings.php index 0c9c1c6120..db91e29a31 100644 --- a/core/install/resources/classes/global_settings.php +++ b/core/install/resources/classes/global_settings.php @@ -1,214 +1,214 @@ - - Copyright (C) 2010-2015 - All Rights Reserved. - - Contributor(s): - Matthew Vale - -*/ -require_once "root.php"; - -//define the install class - class global_settings { - - // cached data - protected $_switch_dirs; - protected $_switch_vdirs; - public function get_switch_dirs() { return $this->_switch_dirs; } - public function get_switch_vdirs() { return $this->_switch_vdirs; } - - // dirs - detected from the switch - protected $_switch_base_dir = ''; - protected $_switch_cache_dir = ''; - protected $_switch_conf_dir = ''; - protected $_switch_db_dir = ''; - protected $_switch_grammar_dir = ''; - protected $_switch_htdocs_dir = ''; - protected $_switch_log_dir = ''; - protected $_switch_mod_dir = ''; - protected $_switch_recordings_dir = ''; - protected $_switch_run_dir = ''; - protected $_switch_script_dir = ''; - protected $_switch_sounds_dir = ''; - protected $_switch_storage_dir = ''; - protected $_switch_temp_dir = ''; - public function switch_base_dir() { return $this->_switch_base_dir; } - public function switch_cache_dir() { return $this->_switch_cache_dir; } - public function switch_conf_dir() { return $this->_switch_conf_dir; } - public function switch_db_dir() { return $this->_switch_db_dir; } - public function switch_grammar_dir() { return $this->_switch_grammar_dir; } - public function switch_htdocs_dir() { return $this->_switch_htdocs_dir; } - public function switch_log_dir() { return $this->_switch_log_dir; } - public function switch_mod_dir() { return $this->_switch_mod_dir; } - public function switch_recordings_dir() { return $this->_switch_recordings_dir; } - public function switch_run_dir() { return $this->_switch_run_dir; } - public function switch_script_dir() { return $this->_switch_script_dir; } - public function switch_sounds_dir() { return $this->_switch_sounds_dir; } - public function switch_storage_dir() { return $this->_switch_storage_dir; } - public function switch_temp_dir() { return $this->_switch_temp_dir; } - - // virtual dirs - assumed based on the detected dirs - protected $_switch_voicemail_vdir = ''; - protected $_switch_phrases_vdir = ''; - protected $_switch_extensions_vdir = ''; - protected $_switch_sip_profiles_vdir = ''; - protected $_switch_dialplan_vdir = ''; - protected $_switch_backup_vdir = ''; - public function switch_voicemail_vdir() { return $this->_switch_voicemail_vdir; } - public function switch_phrases_vdir() { return $this->_switch_phrases_vdir; } - public function switch_extensions_vdir() { return $this->_switch_extensions_vdir; } - public function switch_sip_profiles_vdir() { return $this->_switch_sip_profiles_vdir; } - public function switch_dialplan_vdir() { return $this->_switch_dialplan_vdir; } - public function switch_backup_vdir() { return $this->_switch_backup_vdir; } - - // event socket - protected $_switch_event_host; - protected $_switch_event_port; - protected $_switch_event_password; - public function switch_event_host() { return $this->_switch_event_host; } - public function switch_event_port() { return $this->_switch_event_port; } - public function switch_event_password() { return $this->_switch_event_password; } - - // database information - protected $_db_type; - protected $_db_path; - protected $_db_host; - protected $_db_port; - protected $_db_name; - protected $_db_username; - protected $_db_password; - protected $_db_create; - protected $_db_create_username; - protected $_db_create_password; - public function db_type() { return $this->_db_type; } - public function db_path() { return $this->_db_path; } - public function db_host() { return $this->_db_host; } - public function db_port() { return $this->_db_port; } - public function db_name() { return $this->_db_name; } - public function db_username() { return $this->_db_username; } - public function db_password() { return $this->_db_password; } - public function db_create() { return $this->_db_create; } - public function db_create_username() { return $this->_db_create_username; } - public function db_create_password() { return $this->_db_create_password; } - - //misc information - protected $_domain_uuid; - protected $_domain_name; - protected $_domain_count; - public function domain_uuid() { return $this->_domain_uuid; } - public function domain_name() { return $this->_domain_name; } - public function domain_count() { return $this->_domain_count; } - public function set_domain_uuid($domain_uuid) { - $e = new Exception(); - $trace = $e->getTrace(); - if($trace[1]['function'] != 'create_domain'){ - throw new Exception('Only create_domain is allowed to update the domain_uuid'); - } - $this->_domain_uuid = $domain_uuid; - } - - public function __construct($detect_switch = null, $domain_name = null, $domain_uuid = null) { - $this->_switch_dirs = preg_grep ('/^switch_.*_dir$/', get_class_methods('global_settings') ); - sort( $this->_switch_dirs ); - $this->_switch_vdirs = preg_grep ('/^switch_.*_vdir$/', get_class_methods('global_settings') ); - sort( $this->_switch_vdirs ); - if(is_null($detect_switch)){ - //take settings from session - foreach ($this->_switch_dirs as $dir){ - $category = 'switch'; - $session_var; - preg_match( '/^switch_(.*)_dir$/', $dir, $session_var); - $dir = "_$dir"; - if($session_var[1] == 'script'){ $session_var[1] = 'scripts'; } - if($session_var[1] == 'temp'){ $category = 'server'; } - $this->$dir = $_SESSION[$category][$session_var[1]]['dir']; - } - foreach ($this->_switch_vdirs as $vdir){ - $category = 'switch'; - $session_var; - preg_match( '/^switch_(.*)_vdir$/', $vdir, $session_var); - $vdir = "_$vdir"; - if($session_var[1] == 'backup'){ $category = 'server'; } - $this->$vdir = $_SESSION[$category][$session_var[1]]['dir']; - } - $this->_switch_event_host = $_SESSION['event_socket_ip_address']; - $this->_switch_event_port = $_SESSION['event_socket_port']; - $this->_switch_event_password = $_SESSION['event_socket_password']; - - // domain info - $this->_domain_name = $_SESSION['domain_name']; - $this->_domain_uuid = $_SESSION['domain_uuid']; - - // collect misc info - $this->_domain_count = count($_SESSION["domains"]); - - // collect db_info - global $db_type, $db_path, $db_host, $db_port, $db_name, $db_username, $db_password; - $this->_db_type = $db_type; - $this->_db_path = $db_path; - $this->_db_host = $db_host; - $this->_db_port = $db_port; - $this->_db_name = $db_name; - $this->_db_username = $db_username; - $this->_db_password = $db_password; - - }elseif(!is_a($detect_switch, 'detect_switch')){ - throw new Exception('The parameter $detect_switch must be a detect_switch object (or a subclass of)'); - - }else{ - //copy from detect_switch - foreach($detect_switch->get_dirs() as $dir){ - $t_dir = "_switch_$dir"; - $this->$t_dir = $detect_switch->$dir(); - } - foreach($detect_switch->get_vdirs() as $vdir){ - $t_vdir = "_switch_$vdir"; - $this->$t_vdir = $detect_switch->$vdir(); - } - $this->_switch_event_host = $detect_switch->event_host; - $this->_switch_event_port = $detect_switch->event_port; - $this->_switch_event_password = $detect_switch->event_password; - - //copy from _POST - foreach($_POST as $key=>$value){ - if(substr($key,0,3) == "db_"){ - $o_key = "_$key"; - $this->$o_key = $value; - } - } - if($this->_db_create and strlen($this->_db_create_username) == 0) - { - $this->_db_create_username = $this->_db_username; - $this->_db_create_password = $this->_db_password; - } - if (strlen($this->_db_port) == 0) { $this->_db_port = "5432"; } - - // domain info - if(strlen($domain_uuid) == 0){ $domain_uuid = uuid(); } - $this->_domain_name = $domain_name; - $this->_domain_uuid = $domain_uuid; - - //collect misc info - $this->_domain_count = 1; //assumed to be one - } - } - } + + Copyright (C) 2010-2015 + All Rights Reserved. + + Contributor(s): + Matthew Vale + +*/ +require_once "root.php"; + +//define the install class + class global_settings { + + // cached data + protected $_switch_dirs; + protected $_switch_vdirs; + public function get_switch_dirs() { return $this->_switch_dirs; } + public function get_switch_vdirs() { return $this->_switch_vdirs; } + + // dirs - detected from the switch + protected $_switch_base_dir = ''; + protected $_switch_cache_dir = ''; + protected $_switch_conf_dir = ''; + protected $_switch_db_dir = ''; + protected $_switch_grammar_dir = ''; + protected $_switch_htdocs_dir = ''; + protected $_switch_log_dir = ''; + protected $_switch_mod_dir = ''; + protected $_switch_recordings_dir = ''; + protected $_switch_run_dir = ''; + protected $_switch_script_dir = ''; + protected $_switch_sounds_dir = ''; + protected $_switch_storage_dir = ''; + protected $_switch_temp_dir = ''; + public function switch_base_dir() { return $this->_switch_base_dir; } + public function switch_cache_dir() { return $this->_switch_cache_dir; } + public function switch_conf_dir() { return $this->_switch_conf_dir; } + public function switch_db_dir() { return $this->_switch_db_dir; } + public function switch_grammar_dir() { return $this->_switch_grammar_dir; } + public function switch_htdocs_dir() { return $this->_switch_htdocs_dir; } + public function switch_log_dir() { return $this->_switch_log_dir; } + public function switch_mod_dir() { return $this->_switch_mod_dir; } + public function switch_recordings_dir() { return $this->_switch_recordings_dir; } + public function switch_run_dir() { return $this->_switch_run_dir; } + public function switch_script_dir() { return $this->_switch_script_dir; } + public function switch_sounds_dir() { return $this->_switch_sounds_dir; } + public function switch_storage_dir() { return $this->_switch_storage_dir; } + public function switch_temp_dir() { return $this->_switch_temp_dir; } + + // virtual dirs - assumed based on the detected dirs + protected $_switch_voicemail_vdir = ''; + protected $_switch_phrases_vdir = ''; + protected $_switch_extensions_vdir = ''; + protected $_switch_sip_profiles_vdir = ''; + protected $_switch_dialplan_vdir = ''; + protected $_switch_backup_vdir = ''; + public function switch_voicemail_vdir() { return $this->_switch_voicemail_vdir; } + public function switch_phrases_vdir() { return $this->_switch_phrases_vdir; } + public function switch_extensions_vdir() { return $this->_switch_extensions_vdir; } + public function switch_sip_profiles_vdir() { return $this->_switch_sip_profiles_vdir; } + public function switch_dialplan_vdir() { return $this->_switch_dialplan_vdir; } + public function switch_backup_vdir() { return $this->_switch_backup_vdir; } + + // event socket + protected $_switch_event_host; + protected $_switch_event_port; + protected $_switch_event_password; + public function switch_event_host() { return $this->_switch_event_host; } + public function switch_event_port() { return $this->_switch_event_port; } + public function switch_event_password() { return $this->_switch_event_password; } + + // database information + protected $_db_type; + protected $_db_path; + protected $_db_host; + protected $_db_port; + protected $_db_name; + protected $_db_username; + protected $_db_password; + protected $_db_create; + protected $_db_create_username; + protected $_db_create_password; + public function db_type() { return $this->_db_type; } + public function db_path() { return $this->_db_path; } + public function db_host() { return $this->_db_host; } + public function db_port() { return $this->_db_port; } + public function db_name() { return $this->_db_name; } + public function db_username() { return $this->_db_username; } + public function db_password() { return $this->_db_password; } + public function db_create() { return $this->_db_create; } + public function db_create_username() { return $this->_db_create_username; } + public function db_create_password() { return $this->_db_create_password; } + + //misc information + protected $_domain_uuid; + protected $_domain_name; + protected $_domain_count; + public function domain_uuid() { return $this->_domain_uuid; } + public function domain_name() { return $this->_domain_name; } + public function domain_count() { return $this->_domain_count; } + public function set_domain_uuid($domain_uuid) { + $e = new Exception(); + $trace = $e->getTrace(); + if($trace[1]['function'] != 'create_domain'){ + throw new Exception('Only create_domain is allowed to update the domain_uuid'); + } + $this->_domain_uuid = $domain_uuid; + } + + public function __construct($detect_switch = null, $domain_name = null, $domain_uuid = null) { + $this->_switch_dirs = preg_grep ('/^switch_.*_dir$/', get_class_methods('global_settings') ); + sort( $this->_switch_dirs ); + $this->_switch_vdirs = preg_grep ('/^switch_.*_vdir$/', get_class_methods('global_settings') ); + sort( $this->_switch_vdirs ); + if(is_null($detect_switch)){ + //take settings from session + foreach ($this->_switch_dirs as $dir){ + $category = 'switch'; + $session_var; + preg_match( '/^switch_(.*)_dir$/', $dir, $session_var); + $dir = "_$dir"; + if($session_var[1] == 'script'){ $session_var[1] = 'scripts'; } + if($session_var[1] == 'temp'){ $category = 'server'; } + $this->$dir = $_SESSION[$category][$session_var[1]]['dir']; + } + foreach ($this->_switch_vdirs as $vdir){ + $category = 'switch'; + $session_var; + preg_match( '/^switch_(.*)_vdir$/', $vdir, $session_var); + $vdir = "_$vdir"; + if($session_var[1] == 'backup'){ $category = 'server'; } + $this->$vdir = $_SESSION[$category][$session_var[1]]['dir']; + } + $this->_switch_event_host = $_SESSION['event_socket_ip_address']; + $this->_switch_event_port = $_SESSION['event_socket_port']; + $this->_switch_event_password = $_SESSION['event_socket_password']; + + // domain info + $this->_domain_name = $_SESSION['domain_name']; + $this->_domain_uuid = $_SESSION['domain_uuid']; + + // collect misc info + $this->_domain_count = count($_SESSION["domains"]); + + // collect db_info + global $db_type, $db_path, $db_host, $db_port, $db_name, $db_username, $db_password; + $this->_db_type = $db_type; + $this->_db_path = $db_path; + $this->_db_host = $db_host; + $this->_db_port = $db_port; + $this->_db_name = $db_name; + $this->_db_username = $db_username; + $this->_db_password = $db_password; + + }elseif(!is_a($detect_switch, 'detect_switch')){ + throw new Exception('The parameter $detect_switch must be a detect_switch object (or a subclass of)'); + + }else{ + //copy from detect_switch + foreach($detect_switch->get_dirs() as $dir){ + $t_dir = "_switch_$dir"; + $this->$t_dir = $detect_switch->$dir(); + } + foreach($detect_switch->get_vdirs() as $vdir){ + $t_vdir = "_switch_$vdir"; + $this->$t_vdir = $detect_switch->$vdir(); + } + $this->_switch_event_host = $detect_switch->event_host; + $this->_switch_event_port = $detect_switch->event_port; + $this->_switch_event_password = $detect_switch->event_password; + + //copy from _POST + foreach($_POST as $key=>$value){ + if(substr($key,0,3) == "db_"){ + $o_key = "_$key"; + $this->$o_key = $value; + } + } + if($this->_db_create and strlen($this->_db_create_username) == 0) + { + $this->_db_create_username = $this->_db_username; + $this->_db_create_password = $this->_db_password; + } + if (strlen($this->_db_port) == 0) { $this->_db_port = "5432"; } + + // domain info + if(strlen($domain_uuid) == 0){ $domain_uuid = uuid(); } + $this->_domain_name = $domain_name; + $this->_domain_uuid = $domain_uuid; + + //collect misc info + $this->_domain_count = 1; //assumed to be one + } + } + } ?> \ No newline at end of file diff --git a/core/install/resources/classes/install_fusionpbx.php b/core/install/resources/classes/install_fusionpbx.php index abe9333ec2..65d9447a87 100644 --- a/core/install/resources/classes/install_fusionpbx.php +++ b/core/install/resources/classes/install_fusionpbx.php @@ -1,953 +1,953 @@ - - Copyright (C) 2010-2016 - All Rights Reserved. - - Contributor(s): - Mark J Crane - Matthew Vale -*/ -include "root.php"; - -//define the install class - class install_fusionpbx { - - protected $global_settings; - protected $config_php; - protected $menu_uuid = 'b4750c3f-2a86-b00d-b7d0-345c14eca286'; - protected $dbh; - - public $debug = false; - public $echo_progress = false; - - public $install_language = 'en-us'; - public $admin_username; - public $admin_password; - public $default_country = 'US'; - public $template_name = 'enhanced'; - - function __construct($global_settings) { - if(is_null($global_settings)){ - require_once "resources/classes/global_settings.php"; - $global_settings = new global_settings(); - }elseif(!is_a($global_settings, 'global_settings')){ - throw new Exception('The parameter $global_settings must be a global_settings object (or a subclass of)'); - } - $this->global_settings = $global_settings; - if (is_dir("/etc/fusionpbx")){ - $this->config_php = "/etc/fusionpbx/config.php"; - } elseif (is_dir("/usr/local/etc/fusionpbx")){ - $this->config_php = "/usr/local/etc/fusionpbx/config.php"; - } - elseif (is_dir($_SERVER["PROJECT_ROOT"]."/resources")) { - $this->config_php = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/config.php"; - } - else { - $this->config_php = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/config.php"; - } - $this->config_php = normalize_path_to_os($this->config_php); - } - - function write_debug($message) { - if($this->debug){ - echo "$message\n"; - } - } - - function write_progress($message) { - if($this->echo_progress){ - echo "$message\n"; - } - } - - function install_phase_1() { - ini_set('max_execution_time',3600); - $this->write_progress("Install phase 1 started for FusionPBX"); - $this->create_config_php(); - $this->write_progress("\tExecuting config.php"); - require $this->config_php; - global $db; - $db = $this->dbh; - $this->create_database(); - $this->create_domain(); - $this->create_superuser(); - $this->app_defaults(); - $this->write_progress("\tRunning requires"); - require "resources/require.php"; - $this->write_progress("Install phase 1 complete for FusionPBX"); - } - - function install_phase_2() { - ini_set('max_execution_time',3600); - $this->write_progress("Install phase 2 started for FusionPBX"); - //$this->app_defaults(); - $this->write_progress("Install phase 2 complete for FusionPBX"); - } - - protected function create_config_php() { - $this->write_progress("\tCreating " . $this->config_php); - $tmp_config = "global_settings->db_type()."'; //sqlite, mysql, pgsql, others with a manually created PDO connection\n"; - $tmp_config .= "\n"; - if ($this->global_settings->db_type() == "sqlite") { - $tmp_config .= " //sqlite: the db_name and db_path are automatically assigned however the values can be overidden by setting the values here.\n"; - $tmp_config .= " \$db_name = '".$this->global_settings->db_name()."'; //host name/ip address + '.db' is the default database filename\n"; - $tmp_config .= " \$db_path = '".$this->global_settings->db_path()."'; //the path is determined by a php variable\n"; - } - $tmp_config .= "\n"; - $tmp_config .= " //mysql: database connection information\n"; - if ($this->global_settings->db_type() == "mysql") { - $db_host = $this->global_settings->db_host(); - if ( $db_host == "localhost") { - //if localhost is used it defaults to a Unix Socket which doesn't seem to work. - //replace localhost with 127.0.0.1 so that it will connect using TCP - $db_host = "127.0.0.1"; - } - $tmp_config .= " \$db_host = '".$db_host."';\n"; - $tmp_config .= " \$db_port = '".$this->global_settings->db_port()."';\n"; - $tmp_config .= " \$db_name = '".$this->global_settings->db_name()."';\n"; - $tmp_config .= " \$db_username = '".$this->global_settings->db_username()."';\n"; - $tmp_config .= " \$db_password = '".$this->global_settings->db_password()."';\n"; - } - else { - $tmp_config .= " //\$db_host = '';\n"; - $tmp_config .= " //\$db_port = '';\n"; - $tmp_config .= " //\$db_name = '';\n"; - $tmp_config .= " //\$db_username = '';\n"; - $tmp_config .= " //\$db_password = '';\n"; - } - $tmp_config .= "\n"; - $tmp_config .= " //pgsql: database connection information\n"; - if ($this->global_settings->db_type() == "pgsql") { - $db_host = $this->global_settings->db_host(); - //Unix Socket - if localhost or 127.0.0.1 we want it to default to a Unix Socket. - //$comment_out = ''; - //if ( $db_host == "localhost" or $db_host == "127.0.0.1") { - // $comment_out = "//"; - //} - //$tmp_config .= " $comment_out\$db_host = '".$this->global_settings->db_host()."'; //set the host only if the database is not local\n"; - $tmp_config .= " \$db_host = '".$this->global_settings->db_host()."'; //set the host only if the database is not local\n"; - $tmp_config .= " \$db_port = '".$this->global_settings->db_port()."';\n"; - $tmp_config .= " \$db_name = '".$this->global_settings->db_name()."';\n"; - $tmp_config .= " \$db_username = '".$this->global_settings->db_username()."';\n"; - $tmp_config .= " \$db_password = '".$this->global_settings->db_password()."';\n"; - } - else { - $tmp_config .= " //\$db_host = '".$this->global_settings->db_host()."'; //set the host only if the database is not local\n"; - $tmp_config .= " //\$db_port = '".$this->global_settings->db_port()."';\n"; - $tmp_config .= " //\$db_name = '".$this->global_settings->db_name()."';\n"; - $tmp_config .= " //\$db_username = '".$this->global_settings->db_username()."';\n"; - $tmp_config .= " //\$db_password = '".$this->global_settings->db_password()."';\n"; - } - $tmp_config .= "\n"; - $tmp_config .= " //show errors\n"; - $tmp_config .= " ini_set('display_errors', '1');\n"; - $tmp_config .= " //error_reporting (E_ALL); // Report everything\n"; - $tmp_config .= " //error_reporting (E_ALL ^ E_NOTICE); // Report everything\n"; - $tmp_config .= " error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ); //hide notices and warnings"; - $tmp_config .= "\n"; - $tmp_config .= "?>"; - - if((file_exists($this->config_php) - and !is_writable($this->config_php)) - or !is_writable(dirname($this->config_php)) - ) { - throw new Exception("cannot write to '" . $this->config_php . "'" ); - } - $fout = fopen($this->config_php,"w"); - fwrite($fout, $tmp_config); - unset($tmp_config); - fclose($fout); - } - - protected function create_database() { - $this->write_progress("\tUsing database as type " . $this->global_settings->db_type()); - $function = "create_database_" . $this->global_settings->db_type(); - $this->$function(); - - //sqlite is natively supported under all known OS'es - if($this->global_settings->db_type() != 'sqlite'){ - if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){ - //non sqlite database support only uses ODBC under windows - $this->create_odbc_database_connection(); - }elseif($this->global_settings->db_type() != 'pgsql'){ - //switch supports postgresql natively - $this->create_odbc_database_connection(); - } - } - } - - protected function create_odbc_database_connection() { - //needed for non native database support - $database_uuid = uuid(); - $sql = "insert into v_databases "; - $sql .= "("; - $sql .= "database_uuid, "; - $sql .= "database_driver, "; - $sql .= "database_type, "; - $sql .= "database_host, "; - $sql .= "database_port, "; - $sql .= "database_name, "; - $sql .= "database_username, "; - $sql .= "database_password, "; - $sql .= "database_path, "; - $sql .= "database_description "; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'$database_uuid', "; - $sql .= "'odbc', "; - $sql .= "'".$this->global_settings->db_type()."', "; - $sql .= "'".$this->global_settings->db_host()."', "; - $sql .= "'".$this->global_settings->db_port()."', "; - $sql .= "'".$this->global_settings->db_name()."', "; - $sql .= "'".$this->global_settings->db_username()."', "; - $sql .= "'".$this->global_settings->db_password()."', "; - $sql .= "'".$this->global_settings->db_path()."', "; - $sql .= "'Created by installer' "; - $sql .= ")"; - if($this->dbh->exec(check_sql($sql)) === false){ - throw new Exception("Failed to create odbc_database entery: " . join(":", $this->dbh->errorInfo())); - } - unset($sql); - } - - protected function create_database_sqlite() { - //sqlite database will be created when the config.php is loaded and only if the database file does not exist - try { - $this->dbh = new PDO('sqlite:'.$this->global_settings->db_path().'/'.$this->global_settings->db_name()); //sqlite 3 - //$this->dbh = new PDO('sqlite::memory:'); //sqlite 3 - } - catch (PDOException $error) { - throw new Exception("Failed to create database: " . $error->getMessage()); - } - - //add additional functions to SQLite - bool PDO::sqliteCreateFunction ( string function_name, callback callback [, int num_args] ) - if (!function_exists('php_now')) { - function php_now() { - if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get")) { - @date_default_timezone_set(@date_default_timezone_get()); - } - return date("Y-m-d H:i:s"); - } - } - $this->dbh->sqliteCreateFunction('now', 'php_now', 0); - - //add the database structure - require_once "resources/classes/schema.php"; - $schema = new schema; - $schema->db = $this->dbh; - $schema->db_type = $this->global_settings->db_type(); - $schema->sql(); - $schema->exec(); - - //get the contents of the sql file - if (file_exists('/usr/share/examples/fusionpbx/resources/install/sql/sqlite.sql')){ - $filename = "/usr/share/examples/fusionpbx/resources/install/sql/sqlite.sql"; - } - else { - $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/sqlite.sql'; - } - $file_contents = file_get_contents($filename); - unset($filename); - - //replace \r\n with \n then explode on \n - $file_contents = str_replace("\r\n", "\n", $file_contents); - - //loop line by line through all the lines of sql code - $this->dbh->beginTransaction(); - $string_array = explode("\n", $file_contents); - $x = 0; - foreach($string_array as $sql) { - try { - $this->dbh->query($sql); - } - catch (PDOException $error) { - throw new Exception("error creating database: " . $error->getMessage() . "\n" . $sql ); - } - $x++; - } - unset ($file_contents, $sql); - $this->dbh->commit(); - - //set the file permissions - chmod($this->global_settings->db_path().'/'.$this->global_settings->db_name(), 0777); - } - - protected function create_database_pgsql() { - //create the database - if ($this->global_settings->db_create()) { - //attempt to create new Postgres role and database - $this->write_progress("\tCreating database"); - $db_create_username = $this->global_settings->db_create_username(); - $db_create_password = $this->global_settings->db_create_password(); - $db_host = $this->global_settings->db_host(); - $db_port = $this->global_settings->db_port(); - if(strlen($db_create_username) == 0){ - $db_create_username = $this->global_settings->db_username(); - $db_create_password = $this->global_settings->db_password(); - } - if (strlen($db_host) == 0) { - $db_host = 'localhost'; - } - - try { - $this->dbh = new PDO("pgsql:host=$db_host port=$db_port user=$db_create_username password=$db_create_password dbname=template1"); - } catch (PDOException $error) { - throw new Exception("error connecting to database in order to create: " . $error->getMessage()); - } - - //create the database, user, grant perms - if($this->dbh->exec("CREATE DATABASE {$this->global_settings->db_name()}") === false) { - throw new Exception("Failed to create database {$this->global_settings->db_name()}: " . join(":", $this->dbh->errorInfo())); - } - if($this->global_settings->db_username() != $db_create_username){ - if($this->dbh->exec("CREATE USER {$this->global_settings->db_username()} WITH PASSWORD '{$this->global_settings->db_password()}'") === false){ - // user may be already exists - // throw new Exception("Failed to create user {$this->global_settings->db_name()}: " . join(":", $this->dbh->errorInfo())); - } - if($this->dbh->exec("GRANT ALL ON DATABASE {$this->global_settings->db_name()} TO {$this->global_settings->db_username()}") === false){ - throw new Exception("Failed to create user {$this->global_settings->db_name()}: " . join(":", $this->dbh->errorInfo())); - } - } - - //close database connection_aborted - $this->dbh = null; - } - $this->write_progress("\tInstalling data to database"); - - //open database connection with $this->global_settings->db_name() - try { - if (strlen($this->global_settings->db_host()) > 0) { - $this->dbh = new PDO("pgsql:host={$this->global_settings->db_host()} port={$this->global_settings->db_port()} dbname={$this->global_settings->db_name()} user={$this->global_settings->db_username()} password={$this->global_settings->db_password()}"); - } else { - $this->dbh = new PDO("pgsql:host=localhost port={$this->global_settings->db_port()} user={$this->global_settings->db_username()} password={$this->global_settings->db_password()} dbname={$this->global_settings->db_name()}"); - } - } - catch (PDOException $error) { - throw new Exception("error connecting to database: " . $error->getMessage()); - } - - //add the database structure - require_once "resources/classes/schema.php"; - $schema = new schema; - $schema->db = $this->dbh; - $schema->db_type = $this->global_settings->db_type(); - $schema->sql(); - $schema->exec(); - - //get the contents of the sql file - if (file_exists('/usr/share/examples/fusionpbx/resources/install/sql/pgsql.sql')){ - $filename = "/usr/share/examples/fusionpbx/resources/install/sql/pgsql.sql"; - } - else { - $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/pgsql.sql'; - } - $file_contents = file_get_contents($filename); - - //replace \r\n with \n then explode on \n - $file_contents = str_replace("\r\n", "\n", $file_contents); - - //loop line by line through all the lines of sql code - $string_array = explode("\n", $file_contents); - $x = 0; - foreach($string_array as $sql) { - if (strlen($sql) > 3) { - try { - $this->dbh->query($sql); - } - catch (PDOException $error) { - throw new Exception("error creating database: " . $error->getMessage() . "\n" . $sql ); - } - } - $x++; - } - unset ($file_contents, $sql); - } - - protected function create_database_mysql() { - //database connection - $connect_string; - if (strlen($this->global_settings->db_host()) == 0 && strlen($this->global_settings->db_port()) == 0) { - //if both host and port are empty use the unix socket - $connect_string = "mysql:host={$this->global_settings->db_host()};unix_socket=/var/run/mysqld/mysqld.sock;"; - } - elseif (strlen($this->global_settings->db_port()) == 0) { - //leave out port if it is empty - $connect_string = "mysql:host={$this->global_settings->db_host()};"; - } - else { - $connect_string = "mysql:host={$this->global_settings->db_host()};port={$this->global_settings->db_port()};"; - } - - //if we need create new database - if ($this->global_settings->db_create()) { - //attempt to create new user and database - $this->write_progress("\tCreating database"); - $db_create_username = $this->global_settings->db_create_username(); - $db_create_password = $this->global_settings->db_create_password(); - - if(strlen($db_create_username) == 0){ - $db_create_username = $this->global_settings->db_username(); - $db_create_password = $this->global_settings->db_password(); - } - - //connect to MySQL - try { - $this->dbh = new PDO($connect_string, $db_create_username, $db_create_password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); - $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); - } - catch (PDOException $error) { - throw new Exception("error connecting to database for create: " . $error->getMessage() . "\n" . $sql ); - } - - //select the mysql database - try { - $this->dbh->query("USE mysql;"); - } - catch (PDOException $error) { - throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); - } - - //create user if we use separeate user to access and create - if($this->global_settings->db_username() != $db_create_username) { - //create user and set the permissions - try { - $tmp_sql = "CREATE USER '".$this->global_settings->db_username()."'@'%' IDENTIFIED BY '".$this->global_settings->db_password()."'; "; - $this->dbh->query($tmp_sql); - } - catch (PDOException $error) { - // ignore error here because user may already exists - // (e.g. reinstall can be done via remove db) - // throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); - } - - //set account to unlimited use - try { - if ($this->global_settings->db_host() == "localhost" || $this->global_settings->db_host() == "127.0.0.1") { - $tmp_sql = "GRANT USAGE ON * . * TO '".$this->global_settings->db_username()."'@'localhost' "; - $tmp_sql .= "IDENTIFIED BY '".$this->global_settings->db_password()."' "; - $tmp_sql .= "WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; "; - $this->dbh->query($tmp_sql); - - $tmp_sql = "GRANT USAGE ON * . * TO '".$this->global_settings->db_username()."'@'127.0.0.1' "; - $tmp_sql .= "IDENTIFIED BY '".$this->global_settings->db_password()."' "; - $tmp_sql .= "WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; "; - $this->dbh->query($tmp_sql); - } - else { - $tmp_sql = "GRANT USAGE ON * . * TO '".$this->global_settings->db_username()."'@'".$this->global_settings->db_host()."' "; - $tmp_sql .= "IDENTIFIED BY '".$this->global_settings->db_password()."' "; - $tmp_sql .= "WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; "; - $this->dbh->query($tmp_sql); - } - } - catch (PDOException $error) { - throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); - } - } - - //create the database and set the create user with permissions - try { - $tmp_sql = "CREATE DATABASE IF NOT EXISTS ".$this->global_settings->db_name()."; "; - $this->dbh->query($tmp_sql); - } - catch (PDOException $error) { - throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); - } - - //set user permissions - if($this->global_settings->db_username() != $db_create_username) { - try { - $this->dbh->query("GRANT ALL PRIVILEGES ON ".$this->global_settings->db_name().".* TO '".$this->global_settings->db_username()."'@'%'; "); - } - catch (PDOException $error) { - throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); - } - } - - //make the changes active - try { - $tmp_sql = "FLUSH PRIVILEGES; "; - $this->dbh->query($tmp_sql); - } - catch (PDOException $error) { - throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); - } - $this->dbh = null; - } - - $this->write_progress("\tInstalling data to database"); - - //connect to the database - try { - $this->dbh = new PDO($connect_string, $this->global_settings->db_username(), $this->global_settings->db_password(), array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); - $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); - } - catch (PDOException $error) { - throw new Exception("error connecting to database: " . $error->getMessage() . "\n" . $sql ); - } - - //select the database - try { - $this->dbh->query("USE ".$this->global_settings->db_name().";"); - } - catch (PDOException $error) { - throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); - } - - //add the database structure - require_once "resources/classes/schema.php"; - $schema = new schema; - $schema->db = $this->dbh; - $schema->db_type = $this->global_settings->db_type(); - $schema->sql(); - $schema->exec(); - - //add the defaults data into the database - //get the contents of the sql file - if (file_exists('/usr/share/examples/fusionpbx/resources/install/sql/mysql.sql')){ - $filename = "/usr/share/examples/fusionpbx/resources/install/sql/mysql.sql"; - } - else { - $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/mysql.sql'; - } - $file_contents = file_get_contents($filename); - - //replace \r\n with \n then explode on \n - $file_contents = str_replace("\r\n", "\n", $file_contents); - - //loop line by line through all the lines of sql code - $string_array = explode("\n", $file_contents); - $x = 0; - foreach($string_array as $sql) { - if (strlen($sql) > 3) { - try { - if ($this->debug) { - $this->write_debug( $sql."\n"); - } - $this->dbh->query($sql); - } - catch (PDOException $error) { - //echo "error on line $x: " . $error->getMessage() . " sql: $sql
"; - //die(); - } - } - $x++; - } - unset ($file_contents, $sql); - } - - protected function create_domain() { - $this->write_progress("\tChecking if domain exists '" . $this->global_settings->domain_name() . "'"); - $sql = "select * from v_domains "; - $sql .= "where domain_name = '".$this->global_settings->domain_name()."' "; - $sql .= "limit 1"; - $this->write_debug($sql); - $prep_statement = $this->dbh->prepare(check_sql($sql)); - if($prep_statement->execute() === false){ - throw new Exception("Failed to search for domain: " . join(":", $this->dbh->errorInfo())); - } - $result = $prep_statement->fetch(PDO::FETCH_NAMED); - unset($sql, $prep_statement); - if ($result) { - $this->global_settings->set_domain_uuid($result['domain_uuid']); - $this->write_progress("... domain exists as '" . $this->global_settings->domain_uuid() . "'"); - if($result['domain_enabled'] != 'true'){ - throw new Exception("Domain already exists but is disabled, this is unexpected"); - } - } else { - $this->write_progress("\t... creating domain"); - $sql = "insert into v_domains "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "domain_name, "; - $sql .= "domain_description "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$this->global_settings->domain_uuid()."', "; - $sql .= "'".$this->global_settings->domain_name()."', "; - $sql .= "'Default Domain' "; - $sql .= ");"; - - $this->write_debug($sql); - if($this->dbh->exec(check_sql($sql)) === false){ - throw new Exception("Failed to execute sql statement: " . join(":", $this->dbh->errorInfo())); - } - unset($sql); - - //domain settings - $x = 0; - $tmp[$x]['name'] = 'uuid'; - $tmp[$x]['value'] = $this->menu_uuid; - $tmp[$x]['category'] = 'domain'; - $tmp[$x]['subcategory'] = 'menu'; - $tmp[$x]['enabled'] = 'true'; - $x++; - $tmp[$x]['name'] = 'name'; - $tmp[$x]['category'] = 'domain'; - $tmp[$x]['subcategory'] = 'time_zone'; - $tmp[$x]['enabled'] = 'true'; - $x++; - $tmp[$x]['name'] = 'code'; - $tmp[$x]['value'] = 'en-us'; - $tmp[$x]['category'] = 'domain'; - $tmp[$x]['subcategory'] = 'language'; - $tmp[$x]['enabled'] = 'true'; - $x++; - $tmp[$x]['name'] = 'iso_code'; - $tmp[$x]['value'] = $this->default_country; - $tmp[$x]['category'] = 'domain'; - $tmp[$x]['subcategory'] = 'country'; - $tmp[$x]['enabled'] = 'true'; - $x++; - $tmp[$x]['name'] = 'name'; - $tmp[$x]['value'] = $this->template_name; - $tmp[$x]['category'] = 'domain'; - $tmp[$x]['subcategory'] = 'template'; - $tmp[$x]['enabled'] = 'true'; - $x++; - - //server settings - $tmp[$x]['name'] = 'dir'; - $tmp[$x]['value'] = $this->global_settings->switch_temp_dir(); - $tmp[$x]['category'] = 'server'; - $tmp[$x]['subcategory'] = 'temp'; - $tmp[$x]['enabled'] = 'true'; - $x++; - $x++; - $tmp[$x]['name'] = 'dir'; - $tmp[$x]['value'] = $this->global_settings->switch_backup_vdir(); - $tmp[$x]['category'] = 'server'; - $tmp[$x]['subcategory'] = 'backup'; - $tmp[$x]['enabled'] = 'true'; - $x++; - - $this->dbh->beginTransaction(); - foreach($tmp as $row) { - $sql = "insert into v_default_settings "; - $sql .= "("; - $sql .= "default_setting_uuid, "; - $sql .= "default_setting_name, "; - $sql .= "default_setting_value, "; - $sql .= "default_setting_category, "; - $sql .= "default_setting_subcategory, "; - $sql .= "default_setting_enabled "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".uuid()."', "; - $sql .= "'".$row['name']."', "; - $sql .= "'".$row['value']."', "; - $sql .= "'".$row['category']."', "; - $sql .= "'".$row['subcategory']."', "; - $sql .= "'".$row['enabled']."' "; - $sql .= ");"; - $this->write_debug($sql); - $this->dbh->exec(check_sql($sql)); - unset($sql); - } - $this->dbh->commit(); - unset($tmp); - - //get the list of installed apps from the core and mod directories - $config_list = glob($_SERVER["DOCUMENT_ROOT"] . PROJECT_PATH . "/*/*/app_config.php"); - $x=0; - foreach ($config_list as $config_path) { - include($config_path); - $x++; - } - } - } - - protected function create_superuser() { - $this->write_progress("\tChecking if superuser exists '" . $this->admin_username . "'"); - $sql = "select * from v_users "; - $sql .= "where domain_uuid = '".$this->global_settings->domain_uuid()."' "; - $sql .= "and username = '".$this->admin_username."' "; - $sql .= "limit 1 "; - $this->write_debug($sql); - $prep_statement = $this->dbh->prepare(check_sql($sql)); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_NAMED); - unset($sql, $prep_statement); - $salt = generate_password('20', '4'); - if ($result) { - $this->admin_uuid = $result['user_uuid']; - $this->write_progress("... superuser exists as '" . $this->admin_uuid . "', updating password"); - $sql = "update v_users "; - $sql .= "set password = '".md5($salt.$this->admin_password)."' "; - $sql .= "set salt = '$salt' "; - $sql .= "where USER_uuid = '".$this->admin_uuid."' "; - $this->write_debug($sql); - $this->dbh->exec(check_sql($sql)); - } else { - //message - $this->write_progress("\t... creating super user"); - //add a user and then add the user to the superadmin group - //prepare the values - $this->admin_uuid = uuid(); - $contact_uuid = uuid(); - //set a sessiong variable - $_SESSION["user_uuid"] = $user_uuid; - //salt used with the password to create a one way hash - //add the user account - $sql = "insert into v_users "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "user_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "username, "; - $sql .= "password, "; - $sql .= "salt, "; - $sql .= "add_date, "; - $sql .= "add_user, "; - $sql .= "user_enabled "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$this->global_settings->domain_uuid()."', "; - $sql .= "'".$this->admin_uuid."', "; - $sql .= "'$contact_uuid', "; - $sql .= "'".$this->admin_username."', "; - $sql .= "'".md5($salt.$this->admin_password)."', "; - $sql .= "'$salt', "; - $sql .= "now(), "; - $sql .= "'".$this->admin_username."', "; - $sql .= "'true' "; - $sql .= ");"; - $this->write_debug( $sql."\n"); - $this->dbh->exec(check_sql($sql)); - unset($sql); - } - $this->write_progress("\tChecking if superuser contact exists"); - $sql = "select count(*) from v_contacts "; - $sql .= "where domain_uuid = '".$this->global_settings->domain_uuid()."' "; - $sql .= "and contact_name_given = '".$this->admin_username."' "; - $sql .= "and contact_nickname = '".$this->admin_username."' "; - $sql .= "limit 1 "; - $this->write_debug($sql); - $prep_statement = $this->dbh->prepare(check_sql($sql)); - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - if ($row['count'] == 0) { - $sql = "insert into v_contacts "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "contact_uuid, "; - $sql .= "contact_type, "; - $sql .= "contact_name_given, "; - $sql .= "contact_nickname "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".$this->global_settings->domain_uuid()."', "; - $sql .= "'$contact_uuid', "; - $sql .= "'user', "; - $sql .= "'".$this->admin_username."', "; - $sql .= "'".$this->admin_username."' "; - $sql .= ")"; - $this->dbh->exec(check_sql($sql)); - unset($sql); - } - $this->write_progress("\tChecking if superuser is in the correct group"); - $sql = "select count(*) from v_group_users "; - $sql .= "where domain_uuid = '".$this->global_settings->domain_uuid()."' "; - $sql .= "and user_uuid = '".$this->admin_uuid."' "; - $sql .= "and group_name = 'superadmin' "; - $sql .= "limit 1 "; - $this->write_debug($sql); - $prep_statement = $this->dbh->prepare(check_sql($sql)); - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - if ($row['count'] == 0) { - //add the user to the superadmin group - $sql = "insert into v_group_users "; - $sql .= "("; - $sql .= "group_user_uuid, "; - $sql .= "domain_uuid, "; - $sql .= "user_uuid, "; - $sql .= "group_name "; - $sql .= ") "; - $sql .= "values "; - $sql .= "("; - $sql .= "'".uuid()."', "; - $sql .= "'".$this->global_settings->domain_uuid()."', "; - $sql .= "'".$this->admin_uuid."', "; - $sql .= "'superadmin' "; - $sql .= ");"; - $this->write_debug( $sql."\n"); - $this->dbh->exec(check_sql($sql)); - unset($sql); - } - } - - protected function app_defaults() { - - //write a progress message - $this->write_progress("\tRunning app_defaults"); - - //set needed session settings - $_SESSION["username"] = $this->admin_username; - $_SESSION["domain_uuid"] = $this->global_settings->domain_uuid(); - require $this->config_php; - require "resources/require.php"; - $_SESSION['event_socket_ip_address'] = $this->global_settings->event_host; - $_SESSION['event_socket_port'] = $this->global_settings->event_port; - $_SESSION['event_socket_password'] = $this->global_settings->event_password; - - //get the groups assigned to the user and then set the groups in $_SESSION["groups"] - $sql = "SELECT * FROM v_group_users "; - $sql .= "where domain_uuid=:domain_uuid "; - $sql .= "and user_uuid=:user_uuid "; - $prep_statement = $this->dbh->prepare(check_sql($sql)); - $prep_statement->bindParam(':domain_uuid', $this->global_settings->domain_uuid); - $prep_statement->bindParam(':user_uuid', $this->admin_uuid); - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - $_SESSION["groups"] = $result; - unset($sql, $row_count, $prep_statement); - - //get the permissions assigned to the groups that the user is a member of set the permissions in $_SESSION['permissions'] - $x = 0; - $sql = "select distinct(permission_name) from v_group_permissions "; - foreach($_SESSION["groups"] as $field) { - if (strlen($field['group_name']) > 0) { - if ($x == 0) { - $sql .= "where (domain_uuid = '".$this->global_settings->domain_uuid."' and group_name = '".$field['group_name']."') "; - } - else { - $sql .= "or (domain_uuid = '".$this->global_settings->domain_uuid."' and group_name = '".$field['group_name']."') "; - } - $x++; - } - } - $prep_statement_sub = $this->dbh->prepare($sql); - $prep_statement_sub->execute(); - $_SESSION['permissions'] = $prep_statement_sub->fetchAll(PDO::FETCH_NAMED); - unset($sql, $prep_statement_sub); - - //include the config.php - $db_type = $this->global_settings->db_type(); - $db_path = $this->global_settings->db_path(); - $db_host = $this->global_settings->db_host(); - $db_port = $this->global_settings->db_port(); - $db_name = $this->global_settings->db_name(); - $db_username = $this->global_settings->db_username(); - $db_password = $this->global_settings->db_password(); - - //add the database structure - require_once "resources/classes/schema.php"; - $schema = new schema; - echo $schema->schema(); - - //run all app_defaults.php files - $default_language = $this->install_language; - $domain = new domains; - $domain->upgrade(); - - //get the switch default settings - $sql = "select * from v_default_settings "; - $sql .= "where default_setting_category = 'switch' "; - $sql .= "and default_setting_enabled = 'true' "; - $prep_statement = $this->dbh->prepare($sql); - $prep_statement->execute(); - $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach($default_settings as $row) { - $name = $row['default_setting_name']; - $category = $row['default_setting_category']; - $subcategory = $row['default_setting_subcategory']; - if ($category == "switch") { - $_SESSION[$category][$subcategory]['uuid'] = $row['default_setting_uuid']; - $_SESSION[$category][$subcategory][$name] = $row['default_setting_value']; - } - } - unset ($prep_statement, $sql); - - //update config.lua - $obj = new scripts; - $obj->copy_files(); - $obj->write_config(); - - //synchronize the config with the saved settings - save_switch_xml(); - - //do not show the apply settings reminder on the login page - $_SESSION["reload_xml"] = false; - - //clear the menu - $_SESSION["menu"] = ""; - - } - - public function remove_config() { - if (file_exists('/bin/rm')) { - $this->write_debug('rm -f ' . $this->config_php); - exec ('rm -f ' . $this->config_php); - } - elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){ - $this->write_debug("del /S /F /Q '$dir'"); - exec("del /F /Q '" . $this->config_php . "'"); - } - else { - $this->write_debug("delete file: ".$file); - unlink($this->config_php); - } - clearstatcache(); - } - } - + + Copyright (C) 2010-2016 + All Rights Reserved. + + Contributor(s): + Mark J Crane + Matthew Vale +*/ +include "root.php"; + +//define the install class + class install_fusionpbx { + + protected $global_settings; + protected $config_php; + protected $menu_uuid = 'b4750c3f-2a86-b00d-b7d0-345c14eca286'; + protected $dbh; + + public $debug = false; + public $echo_progress = false; + + public $install_language = 'en-us'; + public $admin_username; + public $admin_password; + public $default_country = 'US'; + public $template_name = 'enhanced'; + + function __construct($global_settings) { + if(is_null($global_settings)){ + require_once "resources/classes/global_settings.php"; + $global_settings = new global_settings(); + }elseif(!is_a($global_settings, 'global_settings')){ + throw new Exception('The parameter $global_settings must be a global_settings object (or a subclass of)'); + } + $this->global_settings = $global_settings; + if (is_dir("/etc/fusionpbx")){ + $this->config_php = "/etc/fusionpbx/config.php"; + } elseif (is_dir("/usr/local/etc/fusionpbx")){ + $this->config_php = "/usr/local/etc/fusionpbx/config.php"; + } + elseif (is_dir($_SERVER["PROJECT_ROOT"]."/resources")) { + $this->config_php = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/config.php"; + } + else { + $this->config_php = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/config.php"; + } + $this->config_php = normalize_path_to_os($this->config_php); + } + + function write_debug($message) { + if($this->debug){ + echo "$message\n"; + } + } + + function write_progress($message) { + if($this->echo_progress){ + echo "$message\n"; + } + } + + function install_phase_1() { + ini_set('max_execution_time',3600); + $this->write_progress("Install phase 1 started for FusionPBX"); + $this->create_config_php(); + $this->write_progress("\tExecuting config.php"); + require $this->config_php; + global $db; + $db = $this->dbh; + $this->create_database(); + $this->create_domain(); + $this->create_superuser(); + $this->app_defaults(); + $this->write_progress("\tRunning requires"); + require "resources/require.php"; + $this->write_progress("Install phase 1 complete for FusionPBX"); + } + + function install_phase_2() { + ini_set('max_execution_time',3600); + $this->write_progress("Install phase 2 started for FusionPBX"); + //$this->app_defaults(); + $this->write_progress("Install phase 2 complete for FusionPBX"); + } + + protected function create_config_php() { + $this->write_progress("\tCreating " . $this->config_php); + $tmp_config = "global_settings->db_type()."'; //sqlite, mysql, pgsql, others with a manually created PDO connection\n"; + $tmp_config .= "\n"; + if ($this->global_settings->db_type() == "sqlite") { + $tmp_config .= " //sqlite: the db_name and db_path are automatically assigned however the values can be overidden by setting the values here.\n"; + $tmp_config .= " \$db_name = '".$this->global_settings->db_name()."'; //host name/ip address + '.db' is the default database filename\n"; + $tmp_config .= " \$db_path = '".$this->global_settings->db_path()."'; //the path is determined by a php variable\n"; + } + $tmp_config .= "\n"; + $tmp_config .= " //mysql: database connection information\n"; + if ($this->global_settings->db_type() == "mysql") { + $db_host = $this->global_settings->db_host(); + if ( $db_host == "localhost") { + //if localhost is used it defaults to a Unix Socket which doesn't seem to work. + //replace localhost with 127.0.0.1 so that it will connect using TCP + $db_host = "127.0.0.1"; + } + $tmp_config .= " \$db_host = '".$db_host."';\n"; + $tmp_config .= " \$db_port = '".$this->global_settings->db_port()."';\n"; + $tmp_config .= " \$db_name = '".$this->global_settings->db_name()."';\n"; + $tmp_config .= " \$db_username = '".$this->global_settings->db_username()."';\n"; + $tmp_config .= " \$db_password = '".$this->global_settings->db_password()."';\n"; + } + else { + $tmp_config .= " //\$db_host = '';\n"; + $tmp_config .= " //\$db_port = '';\n"; + $tmp_config .= " //\$db_name = '';\n"; + $tmp_config .= " //\$db_username = '';\n"; + $tmp_config .= " //\$db_password = '';\n"; + } + $tmp_config .= "\n"; + $tmp_config .= " //pgsql: database connection information\n"; + if ($this->global_settings->db_type() == "pgsql") { + $db_host = $this->global_settings->db_host(); + //Unix Socket - if localhost or 127.0.0.1 we want it to default to a Unix Socket. + //$comment_out = ''; + //if ( $db_host == "localhost" or $db_host == "127.0.0.1") { + // $comment_out = "//"; + //} + //$tmp_config .= " $comment_out\$db_host = '".$this->global_settings->db_host()."'; //set the host only if the database is not local\n"; + $tmp_config .= " \$db_host = '".$this->global_settings->db_host()."'; //set the host only if the database is not local\n"; + $tmp_config .= " \$db_port = '".$this->global_settings->db_port()."';\n"; + $tmp_config .= " \$db_name = '".$this->global_settings->db_name()."';\n"; + $tmp_config .= " \$db_username = '".$this->global_settings->db_username()."';\n"; + $tmp_config .= " \$db_password = '".$this->global_settings->db_password()."';\n"; + } + else { + $tmp_config .= " //\$db_host = '".$this->global_settings->db_host()."'; //set the host only if the database is not local\n"; + $tmp_config .= " //\$db_port = '".$this->global_settings->db_port()."';\n"; + $tmp_config .= " //\$db_name = '".$this->global_settings->db_name()."';\n"; + $tmp_config .= " //\$db_username = '".$this->global_settings->db_username()."';\n"; + $tmp_config .= " //\$db_password = '".$this->global_settings->db_password()."';\n"; + } + $tmp_config .= "\n"; + $tmp_config .= " //show errors\n"; + $tmp_config .= " ini_set('display_errors', '1');\n"; + $tmp_config .= " //error_reporting (E_ALL); // Report everything\n"; + $tmp_config .= " //error_reporting (E_ALL ^ E_NOTICE); // Report everything\n"; + $tmp_config .= " error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ); //hide notices and warnings"; + $tmp_config .= "\n"; + $tmp_config .= "?>"; + + if((file_exists($this->config_php) + and !is_writable($this->config_php)) + or !is_writable(dirname($this->config_php)) + ) { + throw new Exception("cannot write to '" . $this->config_php . "'" ); + } + $fout = fopen($this->config_php,"w"); + fwrite($fout, $tmp_config); + unset($tmp_config); + fclose($fout); + } + + protected function create_database() { + $this->write_progress("\tUsing database as type " . $this->global_settings->db_type()); + $function = "create_database_" . $this->global_settings->db_type(); + $this->$function(); + + //sqlite is natively supported under all known OS'es + if($this->global_settings->db_type() != 'sqlite'){ + if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){ + //non sqlite database support only uses ODBC under windows + $this->create_odbc_database_connection(); + }elseif($this->global_settings->db_type() != 'pgsql'){ + //switch supports postgresql natively + $this->create_odbc_database_connection(); + } + } + } + + protected function create_odbc_database_connection() { + //needed for non native database support + $database_uuid = uuid(); + $sql = "insert into v_databases "; + $sql .= "("; + $sql .= "database_uuid, "; + $sql .= "database_driver, "; + $sql .= "database_type, "; + $sql .= "database_host, "; + $sql .= "database_port, "; + $sql .= "database_name, "; + $sql .= "database_username, "; + $sql .= "database_password, "; + $sql .= "database_path, "; + $sql .= "database_description "; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'$database_uuid', "; + $sql .= "'odbc', "; + $sql .= "'".$this->global_settings->db_type()."', "; + $sql .= "'".$this->global_settings->db_host()."', "; + $sql .= "'".$this->global_settings->db_port()."', "; + $sql .= "'".$this->global_settings->db_name()."', "; + $sql .= "'".$this->global_settings->db_username()."', "; + $sql .= "'".$this->global_settings->db_password()."', "; + $sql .= "'".$this->global_settings->db_path()."', "; + $sql .= "'Created by installer' "; + $sql .= ")"; + if($this->dbh->exec(check_sql($sql)) === false){ + throw new Exception("Failed to create odbc_database entery: " . join(":", $this->dbh->errorInfo())); + } + unset($sql); + } + + protected function create_database_sqlite() { + //sqlite database will be created when the config.php is loaded and only if the database file does not exist + try { + $this->dbh = new PDO('sqlite:'.$this->global_settings->db_path().'/'.$this->global_settings->db_name()); //sqlite 3 + //$this->dbh = new PDO('sqlite::memory:'); //sqlite 3 + } + catch (PDOException $error) { + throw new Exception("Failed to create database: " . $error->getMessage()); + } + + //add additional functions to SQLite - bool PDO::sqliteCreateFunction ( string function_name, callback callback [, int num_args] ) + if (!function_exists('php_now')) { + function php_now() { + if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get")) { + @date_default_timezone_set(@date_default_timezone_get()); + } + return date("Y-m-d H:i:s"); + } + } + $this->dbh->sqliteCreateFunction('now', 'php_now', 0); + + //add the database structure + require_once "resources/classes/schema.php"; + $schema = new schema; + $schema->db = $this->dbh; + $schema->db_type = $this->global_settings->db_type(); + $schema->sql(); + $schema->exec(); + + //get the contents of the sql file + if (file_exists('/usr/share/examples/fusionpbx/resources/install/sql/sqlite.sql')){ + $filename = "/usr/share/examples/fusionpbx/resources/install/sql/sqlite.sql"; + } + else { + $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/sqlite.sql'; + } + $file_contents = file_get_contents($filename); + unset($filename); + + //replace \r\n with \n then explode on \n + $file_contents = str_replace("\r\n", "\n", $file_contents); + + //loop line by line through all the lines of sql code + $this->dbh->beginTransaction(); + $string_array = explode("\n", $file_contents); + $x = 0; + foreach($string_array as $sql) { + try { + $this->dbh->query($sql); + } + catch (PDOException $error) { + throw new Exception("error creating database: " . $error->getMessage() . "\n" . $sql ); + } + $x++; + } + unset ($file_contents, $sql); + $this->dbh->commit(); + + //set the file permissions + chmod($this->global_settings->db_path().'/'.$this->global_settings->db_name(), 0777); + } + + protected function create_database_pgsql() { + //create the database + if ($this->global_settings->db_create()) { + //attempt to create new Postgres role and database + $this->write_progress("\tCreating database"); + $db_create_username = $this->global_settings->db_create_username(); + $db_create_password = $this->global_settings->db_create_password(); + $db_host = $this->global_settings->db_host(); + $db_port = $this->global_settings->db_port(); + if(strlen($db_create_username) == 0){ + $db_create_username = $this->global_settings->db_username(); + $db_create_password = $this->global_settings->db_password(); + } + if (strlen($db_host) == 0) { + $db_host = 'localhost'; + } + + try { + $this->dbh = new PDO("pgsql:host=$db_host port=$db_port user=$db_create_username password=$db_create_password dbname=template1"); + } catch (PDOException $error) { + throw new Exception("error connecting to database in order to create: " . $error->getMessage()); + } + + //create the database, user, grant perms + if($this->dbh->exec("CREATE DATABASE {$this->global_settings->db_name()}") === false) { + throw new Exception("Failed to create database {$this->global_settings->db_name()}: " . join(":", $this->dbh->errorInfo())); + } + if($this->global_settings->db_username() != $db_create_username){ + if($this->dbh->exec("CREATE USER {$this->global_settings->db_username()} WITH PASSWORD '{$this->global_settings->db_password()}'") === false){ + // user may be already exists + // throw new Exception("Failed to create user {$this->global_settings->db_name()}: " . join(":", $this->dbh->errorInfo())); + } + if($this->dbh->exec("GRANT ALL ON DATABASE {$this->global_settings->db_name()} TO {$this->global_settings->db_username()}") === false){ + throw new Exception("Failed to create user {$this->global_settings->db_name()}: " . join(":", $this->dbh->errorInfo())); + } + } + + //close database connection_aborted + $this->dbh = null; + } + $this->write_progress("\tInstalling data to database"); + + //open database connection with $this->global_settings->db_name() + try { + if (strlen($this->global_settings->db_host()) > 0) { + $this->dbh = new PDO("pgsql:host={$this->global_settings->db_host()} port={$this->global_settings->db_port()} dbname={$this->global_settings->db_name()} user={$this->global_settings->db_username()} password={$this->global_settings->db_password()}"); + } else { + $this->dbh = new PDO("pgsql:host=localhost port={$this->global_settings->db_port()} user={$this->global_settings->db_username()} password={$this->global_settings->db_password()} dbname={$this->global_settings->db_name()}"); + } + } + catch (PDOException $error) { + throw new Exception("error connecting to database: " . $error->getMessage()); + } + + //add the database structure + require_once "resources/classes/schema.php"; + $schema = new schema; + $schema->db = $this->dbh; + $schema->db_type = $this->global_settings->db_type(); + $schema->sql(); + $schema->exec(); + + //get the contents of the sql file + if (file_exists('/usr/share/examples/fusionpbx/resources/install/sql/pgsql.sql')){ + $filename = "/usr/share/examples/fusionpbx/resources/install/sql/pgsql.sql"; + } + else { + $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/pgsql.sql'; + } + $file_contents = file_get_contents($filename); + + //replace \r\n with \n then explode on \n + $file_contents = str_replace("\r\n", "\n", $file_contents); + + //loop line by line through all the lines of sql code + $string_array = explode("\n", $file_contents); + $x = 0; + foreach($string_array as $sql) { + if (strlen($sql) > 3) { + try { + $this->dbh->query($sql); + } + catch (PDOException $error) { + throw new Exception("error creating database: " . $error->getMessage() . "\n" . $sql ); + } + } + $x++; + } + unset ($file_contents, $sql); + } + + protected function create_database_mysql() { + //database connection + $connect_string; + if (strlen($this->global_settings->db_host()) == 0 && strlen($this->global_settings->db_port()) == 0) { + //if both host and port are empty use the unix socket + $connect_string = "mysql:host={$this->global_settings->db_host()};unix_socket=/var/run/mysqld/mysqld.sock;"; + } + elseif (strlen($this->global_settings->db_port()) == 0) { + //leave out port if it is empty + $connect_string = "mysql:host={$this->global_settings->db_host()};"; + } + else { + $connect_string = "mysql:host={$this->global_settings->db_host()};port={$this->global_settings->db_port()};"; + } + + //if we need create new database + if ($this->global_settings->db_create()) { + //attempt to create new user and database + $this->write_progress("\tCreating database"); + $db_create_username = $this->global_settings->db_create_username(); + $db_create_password = $this->global_settings->db_create_password(); + + if(strlen($db_create_username) == 0){ + $db_create_username = $this->global_settings->db_username(); + $db_create_password = $this->global_settings->db_password(); + } + + //connect to MySQL + try { + $this->dbh = new PDO($connect_string, $db_create_username, $db_create_password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); + $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); + } + catch (PDOException $error) { + throw new Exception("error connecting to database for create: " . $error->getMessage() . "\n" . $sql ); + } + + //select the mysql database + try { + $this->dbh->query("USE mysql;"); + } + catch (PDOException $error) { + throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); + } + + //create user if we use separeate user to access and create + if($this->global_settings->db_username() != $db_create_username) { + //create user and set the permissions + try { + $tmp_sql = "CREATE USER '".$this->global_settings->db_username()."'@'%' IDENTIFIED BY '".$this->global_settings->db_password()."'; "; + $this->dbh->query($tmp_sql); + } + catch (PDOException $error) { + // ignore error here because user may already exists + // (e.g. reinstall can be done via remove db) + // throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); + } + + //set account to unlimited use + try { + if ($this->global_settings->db_host() == "localhost" || $this->global_settings->db_host() == "127.0.0.1") { + $tmp_sql = "GRANT USAGE ON * . * TO '".$this->global_settings->db_username()."'@'localhost' "; + $tmp_sql .= "IDENTIFIED BY '".$this->global_settings->db_password()."' "; + $tmp_sql .= "WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; "; + $this->dbh->query($tmp_sql); + + $tmp_sql = "GRANT USAGE ON * . * TO '".$this->global_settings->db_username()."'@'127.0.0.1' "; + $tmp_sql .= "IDENTIFIED BY '".$this->global_settings->db_password()."' "; + $tmp_sql .= "WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; "; + $this->dbh->query($tmp_sql); + } + else { + $tmp_sql = "GRANT USAGE ON * . * TO '".$this->global_settings->db_username()."'@'".$this->global_settings->db_host()."' "; + $tmp_sql .= "IDENTIFIED BY '".$this->global_settings->db_password()."' "; + $tmp_sql .= "WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; "; + $this->dbh->query($tmp_sql); + } + } + catch (PDOException $error) { + throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); + } + } + + //create the database and set the create user with permissions + try { + $tmp_sql = "CREATE DATABASE IF NOT EXISTS ".$this->global_settings->db_name()."; "; + $this->dbh->query($tmp_sql); + } + catch (PDOException $error) { + throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); + } + + //set user permissions + if($this->global_settings->db_username() != $db_create_username) { + try { + $this->dbh->query("GRANT ALL PRIVILEGES ON ".$this->global_settings->db_name().".* TO '".$this->global_settings->db_username()."'@'%'; "); + } + catch (PDOException $error) { + throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); + } + } + + //make the changes active + try { + $tmp_sql = "FLUSH PRIVILEGES; "; + $this->dbh->query($tmp_sql); + } + catch (PDOException $error) { + throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); + } + $this->dbh = null; + } + + $this->write_progress("\tInstalling data to database"); + + //connect to the database + try { + $this->dbh = new PDO($connect_string, $this->global_settings->db_username(), $this->global_settings->db_password(), array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); + $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); + } + catch (PDOException $error) { + throw new Exception("error connecting to database: " . $error->getMessage() . "\n" . $sql ); + } + + //select the database + try { + $this->dbh->query("USE ".$this->global_settings->db_name().";"); + } + catch (PDOException $error) { + throw new Exception("error in database: " . $error->getMessage() . "\n" . $sql ); + } + + //add the database structure + require_once "resources/classes/schema.php"; + $schema = new schema; + $schema->db = $this->dbh; + $schema->db_type = $this->global_settings->db_type(); + $schema->sql(); + $schema->exec(); + + //add the defaults data into the database + //get the contents of the sql file + if (file_exists('/usr/share/examples/fusionpbx/resources/install/sql/mysql.sql')){ + $filename = "/usr/share/examples/fusionpbx/resources/install/sql/mysql.sql"; + } + else { + $filename = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/resources/install/sql/mysql.sql'; + } + $file_contents = file_get_contents($filename); + + //replace \r\n with \n then explode on \n + $file_contents = str_replace("\r\n", "\n", $file_contents); + + //loop line by line through all the lines of sql code + $string_array = explode("\n", $file_contents); + $x = 0; + foreach($string_array as $sql) { + if (strlen($sql) > 3) { + try { + if ($this->debug) { + $this->write_debug( $sql."\n"); + } + $this->dbh->query($sql); + } + catch (PDOException $error) { + //echo "error on line $x: " . $error->getMessage() . " sql: $sql
"; + //die(); + } + } + $x++; + } + unset ($file_contents, $sql); + } + + protected function create_domain() { + $this->write_progress("\tChecking if domain exists '" . $this->global_settings->domain_name() . "'"); + $sql = "select * from v_domains "; + $sql .= "where domain_name = '".$this->global_settings->domain_name()."' "; + $sql .= "limit 1"; + $this->write_debug($sql); + $prep_statement = $this->dbh->prepare(check_sql($sql)); + if($prep_statement->execute() === false){ + throw new Exception("Failed to search for domain: " . join(":", $this->dbh->errorInfo())); + } + $result = $prep_statement->fetch(PDO::FETCH_NAMED); + unset($sql, $prep_statement); + if ($result) { + $this->global_settings->set_domain_uuid($result['domain_uuid']); + $this->write_progress("... domain exists as '" . $this->global_settings->domain_uuid() . "'"); + if($result['domain_enabled'] != 'true'){ + throw new Exception("Domain already exists but is disabled, this is unexpected"); + } + } else { + $this->write_progress("\t... creating domain"); + $sql = "insert into v_domains "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "domain_name, "; + $sql .= "domain_description "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$this->global_settings->domain_uuid()."', "; + $sql .= "'".$this->global_settings->domain_name()."', "; + $sql .= "'Default Domain' "; + $sql .= ");"; + + $this->write_debug($sql); + if($this->dbh->exec(check_sql($sql)) === false){ + throw new Exception("Failed to execute sql statement: " . join(":", $this->dbh->errorInfo())); + } + unset($sql); + + //domain settings + $x = 0; + $tmp[$x]['name'] = 'uuid'; + $tmp[$x]['value'] = $this->menu_uuid; + $tmp[$x]['category'] = 'domain'; + $tmp[$x]['subcategory'] = 'menu'; + $tmp[$x]['enabled'] = 'true'; + $x++; + $tmp[$x]['name'] = 'name'; + $tmp[$x]['category'] = 'domain'; + $tmp[$x]['subcategory'] = 'time_zone'; + $tmp[$x]['enabled'] = 'true'; + $x++; + $tmp[$x]['name'] = 'code'; + $tmp[$x]['value'] = 'en-us'; + $tmp[$x]['category'] = 'domain'; + $tmp[$x]['subcategory'] = 'language'; + $tmp[$x]['enabled'] = 'true'; + $x++; + $tmp[$x]['name'] = 'iso_code'; + $tmp[$x]['value'] = $this->default_country; + $tmp[$x]['category'] = 'domain'; + $tmp[$x]['subcategory'] = 'country'; + $tmp[$x]['enabled'] = 'true'; + $x++; + $tmp[$x]['name'] = 'name'; + $tmp[$x]['value'] = $this->template_name; + $tmp[$x]['category'] = 'domain'; + $tmp[$x]['subcategory'] = 'template'; + $tmp[$x]['enabled'] = 'true'; + $x++; + + //server settings + $tmp[$x]['name'] = 'dir'; + $tmp[$x]['value'] = $this->global_settings->switch_temp_dir(); + $tmp[$x]['category'] = 'server'; + $tmp[$x]['subcategory'] = 'temp'; + $tmp[$x]['enabled'] = 'true'; + $x++; + $x++; + $tmp[$x]['name'] = 'dir'; + $tmp[$x]['value'] = $this->global_settings->switch_backup_vdir(); + $tmp[$x]['category'] = 'server'; + $tmp[$x]['subcategory'] = 'backup'; + $tmp[$x]['enabled'] = 'true'; + $x++; + + $this->dbh->beginTransaction(); + foreach($tmp as $row) { + $sql = "insert into v_default_settings "; + $sql .= "("; + $sql .= "default_setting_uuid, "; + $sql .= "default_setting_name, "; + $sql .= "default_setting_value, "; + $sql .= "default_setting_category, "; + $sql .= "default_setting_subcategory, "; + $sql .= "default_setting_enabled "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".uuid()."', "; + $sql .= "'".$row['name']."', "; + $sql .= "'".$row['value']."', "; + $sql .= "'".$row['category']."', "; + $sql .= "'".$row['subcategory']."', "; + $sql .= "'".$row['enabled']."' "; + $sql .= ");"; + $this->write_debug($sql); + $this->dbh->exec(check_sql($sql)); + unset($sql); + } + $this->dbh->commit(); + unset($tmp); + + //get the list of installed apps from the core and mod directories + $config_list = glob($_SERVER["DOCUMENT_ROOT"] . PROJECT_PATH . "/*/*/app_config.php"); + $x=0; + foreach ($config_list as $config_path) { + include($config_path); + $x++; + } + } + } + + protected function create_superuser() { + $this->write_progress("\tChecking if superuser exists '" . $this->admin_username . "'"); + $sql = "select * from v_users "; + $sql .= "where domain_uuid = '".$this->global_settings->domain_uuid()."' "; + $sql .= "and username = '".$this->admin_username."' "; + $sql .= "limit 1 "; + $this->write_debug($sql); + $prep_statement = $this->dbh->prepare(check_sql($sql)); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_NAMED); + unset($sql, $prep_statement); + $salt = generate_password('20', '4'); + if ($result) { + $this->admin_uuid = $result['user_uuid']; + $this->write_progress("... superuser exists as '" . $this->admin_uuid . "', updating password"); + $sql = "update v_users "; + $sql .= "set password = '".md5($salt.$this->admin_password)."' "; + $sql .= "set salt = '$salt' "; + $sql .= "where USER_uuid = '".$this->admin_uuid."' "; + $this->write_debug($sql); + $this->dbh->exec(check_sql($sql)); + } else { + //message + $this->write_progress("\t... creating super user"); + //add a user and then add the user to the superadmin group + //prepare the values + $this->admin_uuid = uuid(); + $contact_uuid = uuid(); + //set a sessiong variable + $_SESSION["user_uuid"] = $user_uuid; + //salt used with the password to create a one way hash + //add the user account + $sql = "insert into v_users "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "user_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "username, "; + $sql .= "password, "; + $sql .= "salt, "; + $sql .= "add_date, "; + $sql .= "add_user, "; + $sql .= "user_enabled "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$this->global_settings->domain_uuid()."', "; + $sql .= "'".$this->admin_uuid."', "; + $sql .= "'$contact_uuid', "; + $sql .= "'".$this->admin_username."', "; + $sql .= "'".md5($salt.$this->admin_password)."', "; + $sql .= "'$salt', "; + $sql .= "now(), "; + $sql .= "'".$this->admin_username."', "; + $sql .= "'true' "; + $sql .= ");"; + $this->write_debug( $sql."\n"); + $this->dbh->exec(check_sql($sql)); + unset($sql); + } + $this->write_progress("\tChecking if superuser contact exists"); + $sql = "select count(*) from v_contacts "; + $sql .= "where domain_uuid = '".$this->global_settings->domain_uuid()."' "; + $sql .= "and contact_name_given = '".$this->admin_username."' "; + $sql .= "and contact_nickname = '".$this->admin_username."' "; + $sql .= "limit 1 "; + $this->write_debug($sql); + $prep_statement = $this->dbh->prepare(check_sql($sql)); + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + if ($row['count'] == 0) { + $sql = "insert into v_contacts "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "contact_uuid, "; + $sql .= "contact_type, "; + $sql .= "contact_name_given, "; + $sql .= "contact_nickname "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".$this->global_settings->domain_uuid()."', "; + $sql .= "'$contact_uuid', "; + $sql .= "'user', "; + $sql .= "'".$this->admin_username."', "; + $sql .= "'".$this->admin_username."' "; + $sql .= ")"; + $this->dbh->exec(check_sql($sql)); + unset($sql); + } + $this->write_progress("\tChecking if superuser is in the correct group"); + $sql = "select count(*) from v_group_users "; + $sql .= "where domain_uuid = '".$this->global_settings->domain_uuid()."' "; + $sql .= "and user_uuid = '".$this->admin_uuid."' "; + $sql .= "and group_name = 'superadmin' "; + $sql .= "limit 1 "; + $this->write_debug($sql); + $prep_statement = $this->dbh->prepare(check_sql($sql)); + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + if ($row['count'] == 0) { + //add the user to the superadmin group + $sql = "insert into v_group_users "; + $sql .= "("; + $sql .= "group_user_uuid, "; + $sql .= "domain_uuid, "; + $sql .= "user_uuid, "; + $sql .= "group_name "; + $sql .= ") "; + $sql .= "values "; + $sql .= "("; + $sql .= "'".uuid()."', "; + $sql .= "'".$this->global_settings->domain_uuid()."', "; + $sql .= "'".$this->admin_uuid."', "; + $sql .= "'superadmin' "; + $sql .= ");"; + $this->write_debug( $sql."\n"); + $this->dbh->exec(check_sql($sql)); + unset($sql); + } + } + + protected function app_defaults() { + + //write a progress message + $this->write_progress("\tRunning app_defaults"); + + //set needed session settings + $_SESSION["username"] = $this->admin_username; + $_SESSION["domain_uuid"] = $this->global_settings->domain_uuid(); + require $this->config_php; + require "resources/require.php"; + $_SESSION['event_socket_ip_address'] = $this->global_settings->event_host; + $_SESSION['event_socket_port'] = $this->global_settings->event_port; + $_SESSION['event_socket_password'] = $this->global_settings->event_password; + + //get the groups assigned to the user and then set the groups in $_SESSION["groups"] + $sql = "SELECT * FROM v_group_users "; + $sql .= "where domain_uuid=:domain_uuid "; + $sql .= "and user_uuid=:user_uuid "; + $prep_statement = $this->dbh->prepare(check_sql($sql)); + $prep_statement->bindParam(':domain_uuid', $this->global_settings->domain_uuid); + $prep_statement->bindParam(':user_uuid', $this->admin_uuid); + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + $_SESSION["groups"] = $result; + unset($sql, $row_count, $prep_statement); + + //get the permissions assigned to the groups that the user is a member of set the permissions in $_SESSION['permissions'] + $x = 0; + $sql = "select distinct(permission_name) from v_group_permissions "; + foreach($_SESSION["groups"] as $field) { + if (strlen($field['group_name']) > 0) { + if ($x == 0) { + $sql .= "where (domain_uuid = '".$this->global_settings->domain_uuid."' and group_name = '".$field['group_name']."') "; + } + else { + $sql .= "or (domain_uuid = '".$this->global_settings->domain_uuid."' and group_name = '".$field['group_name']."') "; + } + $x++; + } + } + $prep_statement_sub = $this->dbh->prepare($sql); + $prep_statement_sub->execute(); + $_SESSION['permissions'] = $prep_statement_sub->fetchAll(PDO::FETCH_NAMED); + unset($sql, $prep_statement_sub); + + //include the config.php + $db_type = $this->global_settings->db_type(); + $db_path = $this->global_settings->db_path(); + $db_host = $this->global_settings->db_host(); + $db_port = $this->global_settings->db_port(); + $db_name = $this->global_settings->db_name(); + $db_username = $this->global_settings->db_username(); + $db_password = $this->global_settings->db_password(); + + //add the database structure + require_once "resources/classes/schema.php"; + $schema = new schema; + echo $schema->schema(); + + //run all app_defaults.php files + $default_language = $this->install_language; + $domain = new domains; + $domain->upgrade(); + + //get the switch default settings + $sql = "select * from v_default_settings "; + $sql .= "where default_setting_category = 'switch' "; + $sql .= "and default_setting_enabled = 'true' "; + $prep_statement = $this->dbh->prepare($sql); + $prep_statement->execute(); + $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach($default_settings as $row) { + $name = $row['default_setting_name']; + $category = $row['default_setting_category']; + $subcategory = $row['default_setting_subcategory']; + if ($category == "switch") { + $_SESSION[$category][$subcategory]['uuid'] = $row['default_setting_uuid']; + $_SESSION[$category][$subcategory][$name] = $row['default_setting_value']; + } + } + unset ($prep_statement, $sql); + + //update config.lua + $obj = new scripts; + $obj->copy_files(); + $obj->write_config(); + + //synchronize the config with the saved settings + save_switch_xml(); + + //do not show the apply settings reminder on the login page + $_SESSION["reload_xml"] = false; + + //clear the menu + $_SESSION["menu"] = ""; + + } + + public function remove_config() { + if (file_exists('/bin/rm')) { + $this->write_debug('rm -f ' . $this->config_php); + exec ('rm -f ' . $this->config_php); + } + elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){ + $this->write_debug("del /S /F /Q '$dir'"); + exec("del /F /Q '" . $this->config_php . "'"); + } + else { + $this->write_debug("delete file: ".$file); + unlink($this->config_php); + } + clearstatcache(); + } + } + ?> \ No newline at end of file diff --git a/core/install/resources/classes/install_switch.php b/core/install/resources/classes/install_switch.php index 74f9e9c4c9..b1713bb2bc 100644 --- a/core/install/resources/classes/install_switch.php +++ b/core/install/resources/classes/install_switch.php @@ -1,146 +1,146 @@ - - Copyright (C) 2010-2015 - All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; - -//define the install class - class install_switch { - - protected $global_settings; - protected $dbh; - - public $debug = false; - public $echo_progress = false; - - function __construct($global_settings) { - if(is_null($global_settings)){ - require_once "core/install/resources/classes/global_settings.php"; - $global_settings = new global_settings(); - }elseif(!is_a($global_settings, 'global_settings')){ - throw new Exception('The parameter $global_settings must be a global_settings object (or a subclass of)'); - } - $this->global_settings = $global_settings; - } - - //utility Functions - function write_debug($message) { - if($this->debug){ - echo "$message\n"; - } - } - - function write_progress($message) { - if($this->echo_progress){ - echo "$message\n"; - } - } - - protected function backup_dir($dir, $backup_name){ - if (!is_readable($dir)) { - throw new Exception("backup_dir() source directory '".$dir."' does not exist."); - } - $dst_tar = join( DIRECTORY_SEPARATOR, array(sys_get_temp_dir(), "$backup_name.tar")); - //pharData is the correct way to do it, but it keeps creating incomplete archives - //$tar = new PharData($dst_tar); - //$tar->buildFromDirectory($dir); - $this->write_debug("backing up to $dst_tar"); - if (file_exists('/bin/tar')) { - exec('tar -cvf ' .$dst_tar. ' -C '.$dir .' .'); - }else{ - $this->write_debug('WARN: old config could not be compressed'); - $dst_dir = join( DIRECTORY_SEPARATOR, array(sys_get_temp_dir(), "$backup_name")); - recursive_copy($dir, $dst_dir); - } - } - - function install_phase_1() { - $this->write_progress("Install phase 1 started for switch"); - $this->copy_conf(); - $this->write_progress("Install phase 1 completed for switch"); - } - - function install_phase_2() { - $this->write_progress("Install phase 2 started for switch"); - $this->restart_switch(); - $this->write_progress("Install phase 2 completed for switch"); - } - - protected function copy_conf() { - //send a message - $this->write_progress("\tCopying Config"); - - //make a backup of the config - if (file_exists($this->global_settings->switch_conf_dir())) { - $this->backup_dir($this->global_settings->switch_conf_dir(), 'fusionpbx_switch_config'); - recursive_delete($this->global_settings->switch_conf_dir()); - } - - //make sure the conf directory exists - if (!is_dir($this->global_settings->switch_conf_dir())) { - if (!mkdir($this->global_settings->switch_conf_dir(), 0774, true)) { - throw new Exception("Failed to create the switch conf directory '".$this->global_settings->switch_conf_dir()."'. "); - } - } - - //copy resources/templates/conf to the freeswitch conf dir - if (file_exists('/usr/share/examples/fusionpbx/resources/templates/conf')){ - $src_dir = "/usr/share/examples/fusionpbx/resources/templates/conf"; - } - else { - $src_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/templates/conf"; - } - $dst_dir = $this->global_settings->switch_conf_dir(); - if (is_readable($dst_dir)) { - recursive_copy($src_dir, $dst_dir); - unset($src_dir, $dst_dir); - } - $fax_dir = join( DIRECTORY_SEPARATOR, array($this->global_settings->switch_storage_dir(), 'fax')); - if (!is_readable($fax_dir)) { mkdir($fax_dir,0777,true); } - $voicemail_dir = join( DIRECTORY_SEPARATOR, array($this->global_settings->switch_storage_dir(), 'voicemail')); - if (!is_readable($voicemail_dir)) { mkdir($voicemail_dir,0777,true); } - - //write the xml_cdr.conf.xml file - if (file_exists($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/app/xml_cdr")) { - xml_cdr_conf_xml(); - } - - //write the switch.conf.xml file - if (file_exists($this->global_settings->switch_conf_dir())) { - switch_conf_xml(); - } - } - - protected function restart_switch() { - $esl = new event_socket; - if(!$esl->connect($this->global_settings->switch_event_host(), $this->global_settings->switch_event_port(), $this->global_settings->switch_event_password())) { - throw new Exception("Failed to connect to switch"); - } - if (!$esl->request('api fsctl shutdown restart elegant')){ - throw new Exception("Failed to send switch restart"); - } - $esl->reset_fp(); - } - } + + Copyright (C) 2010-2015 + All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; + +//define the install class + class install_switch { + + protected $global_settings; + protected $dbh; + + public $debug = false; + public $echo_progress = false; + + function __construct($global_settings) { + if(is_null($global_settings)){ + require_once "core/install/resources/classes/global_settings.php"; + $global_settings = new global_settings(); + }elseif(!is_a($global_settings, 'global_settings')){ + throw new Exception('The parameter $global_settings must be a global_settings object (or a subclass of)'); + } + $this->global_settings = $global_settings; + } + + //utility Functions + function write_debug($message) { + if($this->debug){ + echo "$message\n"; + } + } + + function write_progress($message) { + if($this->echo_progress){ + echo "$message\n"; + } + } + + protected function backup_dir($dir, $backup_name){ + if (!is_readable($dir)) { + throw new Exception("backup_dir() source directory '".$dir."' does not exist."); + } + $dst_tar = join( DIRECTORY_SEPARATOR, array(sys_get_temp_dir(), "$backup_name.tar")); + //pharData is the correct way to do it, but it keeps creating incomplete archives + //$tar = new PharData($dst_tar); + //$tar->buildFromDirectory($dir); + $this->write_debug("backing up to $dst_tar"); + if (file_exists('/bin/tar')) { + exec('tar -cvf ' .$dst_tar. ' -C '.$dir .' .'); + }else{ + $this->write_debug('WARN: old config could not be compressed'); + $dst_dir = join( DIRECTORY_SEPARATOR, array(sys_get_temp_dir(), "$backup_name")); + recursive_copy($dir, $dst_dir); + } + } + + function install_phase_1() { + $this->write_progress("Install phase 1 started for switch"); + $this->copy_conf(); + $this->write_progress("Install phase 1 completed for switch"); + } + + function install_phase_2() { + $this->write_progress("Install phase 2 started for switch"); + $this->restart_switch(); + $this->write_progress("Install phase 2 completed for switch"); + } + + protected function copy_conf() { + //send a message + $this->write_progress("\tCopying Config"); + + //make a backup of the config + if (file_exists($this->global_settings->switch_conf_dir())) { + $this->backup_dir($this->global_settings->switch_conf_dir(), 'fusionpbx_switch_config'); + recursive_delete($this->global_settings->switch_conf_dir()); + } + + //make sure the conf directory exists + if (!is_dir($this->global_settings->switch_conf_dir())) { + if (!mkdir($this->global_settings->switch_conf_dir(), 0774, true)) { + throw new Exception("Failed to create the switch conf directory '".$this->global_settings->switch_conf_dir()."'. "); + } + } + + //copy resources/templates/conf to the freeswitch conf dir + if (file_exists('/usr/share/examples/fusionpbx/resources/templates/conf')){ + $src_dir = "/usr/share/examples/fusionpbx/resources/templates/conf"; + } + else { + $src_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/templates/conf"; + } + $dst_dir = $this->global_settings->switch_conf_dir(); + if (is_readable($dst_dir)) { + recursive_copy($src_dir, $dst_dir); + unset($src_dir, $dst_dir); + } + $fax_dir = join( DIRECTORY_SEPARATOR, array($this->global_settings->switch_storage_dir(), 'fax')); + if (!is_readable($fax_dir)) { mkdir($fax_dir,0777,true); } + $voicemail_dir = join( DIRECTORY_SEPARATOR, array($this->global_settings->switch_storage_dir(), 'voicemail')); + if (!is_readable($voicemail_dir)) { mkdir($voicemail_dir,0777,true); } + + //write the xml_cdr.conf.xml file + if (file_exists($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/app/xml_cdr")) { + xml_cdr_conf_xml(); + } + + //write the switch.conf.xml file + if (file_exists($this->global_settings->switch_conf_dir())) { + switch_conf_xml(); + } + } + + protected function restart_switch() { + $esl = new event_socket; + if(!$esl->connect($this->global_settings->switch_event_host(), $this->global_settings->switch_event_port(), $this->global_settings->switch_event_password())) { + throw new Exception("Failed to connect to switch"); + } + if (!$esl->request('api fsctl shutdown restart elegant')){ + throw new Exception("Failed to send switch restart"); + } + $esl->reset_fp(); + } + } ?> \ No newline at end of file diff --git a/core/install/resources/classes/iso_countries.php b/core/install/resources/classes/iso_countries.php index ea03a6b5c1..3149ef937c 100644 --- a/core/install/resources/classes/iso_countries.php +++ b/core/install/resources/classes/iso_countries.php @@ -1,252 +1,252 @@ - 'Afghanistan', - 'AX' => 'Aland Islands', - 'AL' => 'Albania', - 'DZ' => 'Algeria', - 'AS' => 'American Samoa', - 'AD' => 'Andorra', - 'AO' => 'Angola', - 'AI' => 'Anguilla', - 'AQ' => 'Antarctica', - 'AG' => 'Antigua And Barbuda', - 'AR' => 'Argentina', - 'AM' => 'Armenia', - 'AW' => 'Aruba', - 'AU' => 'Australia', - 'AT' => 'Austria', - 'AZ' => 'Azerbaijan', - 'BS' => 'Bahamas', - 'BH' => 'Bahrain', - 'BD' => 'Bangladesh', - 'BB' => 'Barbados', - 'BY' => 'Belarus', - 'BE' => 'Belgium', - 'BZ' => 'Belize', - 'BJ' => 'Benin', - 'BM' => 'Bermuda', - 'BT' => 'Bhutan', - 'BO' => 'Bolivia', - 'BA' => 'Bosnia And Herzegovina', - 'BW' => 'Botswana', - 'BV' => 'Bouvet Island', - 'BR' => 'Brazil', - 'IO' => 'British Indian Ocean Territory', - 'BN' => 'Brunei Darussalam', - 'BG' => 'Bulgaria', - 'BF' => 'Burkina Faso', - 'BI' => 'Burundi', - 'KH' => 'Cambodia', - 'CM' => 'Cameroon', - 'CA' => 'Canada', - 'CV' => 'Cape Verde', - 'KY' => 'Cayman Islands', - 'CF' => 'Central African Republic', - 'TD' => 'Chad', - 'CL' => 'Chile', - 'CN' => 'China', - 'CX' => 'Christmas Island', - 'CC' => 'Cocos (Keeling) Islands', - 'CO' => 'Colombia', - 'KM' => 'Comoros', - 'CG' => 'Congo', - 'CD' => 'Congo, Democratic Republic', - 'CK' => 'Cook Islands', - 'CR' => 'Costa Rica', - 'CI' => 'Cote D\'Ivoire', - 'HR' => 'Croatia', - 'CU' => 'Cuba', - 'CY' => 'Cyprus', - 'CZ' => 'Czech Republic', - 'DK' => 'Denmark', - 'DJ' => 'Djibouti', - 'DM' => 'Dominica', - 'DO' => 'Dominican Republic', - 'EC' => 'Ecuador', - 'EG' => 'Egypt', - 'SV' => 'El Salvador', - 'GQ' => 'Equatorial Guinea', - 'ER' => 'Eritrea', - 'EE' => 'Estonia', - 'ET' => 'Ethiopia', - 'FK' => 'Falkland Islands (Malvinas)', - 'FO' => 'Faroe Islands', - 'FJ' => 'Fiji', - 'FI' => 'Finland', - 'FR' => 'France', - 'GF' => 'French Guiana', - 'PF' => 'French Polynesia', - 'TF' => 'French Southern Territories', - 'GA' => 'Gabon', - 'GM' => 'Gambia', - 'GE' => 'Georgia', - 'DE' => 'Germany', - 'GH' => 'Ghana', - 'GI' => 'Gibraltar', - 'GR' => 'Greece', - 'GL' => 'Greenland', - 'GD' => 'Grenada', - 'GP' => 'Guadeloupe', - 'GU' => 'Guam', - 'GT' => 'Guatemala', - 'GG' => 'Guernsey', - 'GN' => 'Guinea', - 'GW' => 'Guinea-Bissau', - 'GY' => 'Guyana', - 'HT' => 'Haiti', - 'HM' => 'Heard Island & Mcdonald Islands', - 'VA' => 'Holy See (Vatican City State)', - 'HN' => 'Honduras', - 'HK' => 'Hong Kong', - 'HU' => 'Hungary', - 'IS' => 'Iceland', - 'IN' => 'India', - 'ID' => 'Indonesia', - 'IR' => 'Iran, Islamic Republic Of', - 'IQ' => 'Iraq', - 'IE' => 'Ireland', - 'IM' => 'Isle Of Man', - 'IL' => 'Israel', - 'IT' => 'Italy', - 'JM' => 'Jamaica', - 'JP' => 'Japan', - 'JE' => 'Jersey', - 'JO' => 'Jordan', - 'KZ' => 'Kazakhstan', - 'KE' => 'Kenya', - 'KI' => 'Kiribati', - 'KR' => 'Korea', - 'KW' => 'Kuwait', - 'KG' => 'Kyrgyzstan', - 'LA' => 'Lao People\'s Democratic Republic', - 'LV' => 'Latvia', - 'LB' => 'Lebanon', - 'LS' => 'Lesotho', - 'LR' => 'Liberia', - 'LY' => 'Libyan Arab Jamahiriya', - 'LI' => 'Liechtenstein', - 'LT' => 'Lithuania', - 'LU' => 'Luxembourg', - 'MO' => 'Macao', - 'MK' => 'Macedonia', - 'MG' => 'Madagascar', - 'MW' => 'Malawi', - 'MY' => 'Malaysia', - 'MV' => 'Maldives', - 'ML' => 'Mali', - 'MT' => 'Malta', - 'MH' => 'Marshall Islands', - 'MQ' => 'Martinique', - 'MR' => 'Mauritania', - 'MU' => 'Mauritius', - 'YT' => 'Mayotte', - 'MX' => 'Mexico', - 'FM' => 'Micronesia, Federated States Of', - 'MD' => 'Moldova', - 'MC' => 'Monaco', - 'MN' => 'Mongolia', - 'ME' => 'Montenegro', - 'MS' => 'Montserrat', - 'MA' => 'Morocco', - 'MZ' => 'Mozambique', - 'MM' => 'Myanmar', - 'NA' => 'Namibia', - 'NR' => 'Nauru', - 'NP' => 'Nepal', - 'NL' => 'Netherlands', - 'AN' => 'Netherlands Antilles', - 'NC' => 'New Caledonia', - 'NZ' => 'New Zealand', - 'NI' => 'Nicaragua', - 'NE' => 'Niger', - 'NG' => 'Nigeria', - 'NU' => 'Niue', - 'NF' => 'Norfolk Island', - 'MP' => 'Northern Mariana Islands', - 'NO' => 'Norway', - 'OM' => 'Oman', - 'PK' => 'Pakistan', - 'PW' => 'Palau', - 'PS' => 'Palestinian Territory, Occupied', - 'PA' => 'Panama', - 'PG' => 'Papua New Guinea', - 'PY' => 'Paraguay', - 'PE' => 'Peru', - 'PH' => 'Philippines', - 'PN' => 'Pitcairn', - 'PL' => 'Poland', - 'PT' => 'Portugal', - 'PR' => 'Puerto Rico', - 'QA' => 'Qatar', - 'RE' => 'Reunion', - 'RO' => 'Romania', - 'RU' => 'Russian Federation', - 'RW' => 'Rwanda', - 'BL' => 'Saint Barthelemy', - 'SH' => 'Saint Helena', - 'KN' => 'Saint Kitts And Nevis', - 'LC' => 'Saint Lucia', - 'MF' => 'Saint Martin', - 'PM' => 'Saint Pierre And Miquelon', - 'VC' => 'Saint Vincent And Grenadines', - 'WS' => 'Samoa', - 'SM' => 'San Marino', - 'ST' => 'Sao Tome And Principe', - 'SA' => 'Saudi Arabia', - 'SN' => 'Senegal', - 'RS' => 'Serbia', - 'SC' => 'Seychelles', - 'SL' => 'Sierra Leone', - 'SG' => 'Singapore', - 'SK' => 'Slovakia', - 'SI' => 'Slovenia', - 'SB' => 'Solomon Islands', - 'SO' => 'Somalia', - 'ZA' => 'South Africa', - 'GS' => 'South Georgia And Sandwich Isl.', - 'ES' => 'Spain', - 'LK' => 'Sri Lanka', - 'SD' => 'Sudan', - 'SR' => 'Suriname', - 'SJ' => 'Svalbard And Jan Mayen', - 'SZ' => 'Swaziland', - 'SE' => 'Sweden', - 'CH' => 'Switzerland', - 'SY' => 'Syrian Arab Republic', - 'TW' => 'Taiwan', - 'TJ' => 'Tajikistan', - 'TZ' => 'Tanzania', - 'TH' => 'Thailand', - 'TL' => 'Timor-Leste', - 'TG' => 'Togo', - 'TK' => 'Tokelau', - 'TO' => 'Tonga', - 'TT' => 'Trinidad And Tobago', - 'TN' => 'Tunisia', - 'TR' => 'Turkey', - 'TM' => 'Turkmenistan', - 'TC' => 'Turks And Caicos Islands', - 'TV' => 'Tuvalu', - 'UG' => 'Uganda', - 'UA' => 'Ukraine', - 'AE' => 'United Arab Emirates', - 'GB' => 'United Kingdom', - 'US' => 'United States', - 'UM' => 'United States Outlying Islands', - 'UY' => 'Uruguay', - 'UZ' => 'Uzbekistan', - 'VU' => 'Vanuatu', - 'VE' => 'Venezuela', - 'VN' => 'Viet Nam', - 'VG' => 'Virgin Islands, British', - 'VI' => 'Virgin Islands, U.S.', - 'WF' => 'Wallis And Futuna', - 'EH' => 'Western Sahara', - 'YE' => 'Yemen', - 'ZM' => 'Zambia', - 'ZW' => 'Zimbabwe', -); - + 'Afghanistan', + 'AX' => 'Aland Islands', + 'AL' => 'Albania', + 'DZ' => 'Algeria', + 'AS' => 'American Samoa', + 'AD' => 'Andorra', + 'AO' => 'Angola', + 'AI' => 'Anguilla', + 'AQ' => 'Antarctica', + 'AG' => 'Antigua And Barbuda', + 'AR' => 'Argentina', + 'AM' => 'Armenia', + 'AW' => 'Aruba', + 'AU' => 'Australia', + 'AT' => 'Austria', + 'AZ' => 'Azerbaijan', + 'BS' => 'Bahamas', + 'BH' => 'Bahrain', + 'BD' => 'Bangladesh', + 'BB' => 'Barbados', + 'BY' => 'Belarus', + 'BE' => 'Belgium', + 'BZ' => 'Belize', + 'BJ' => 'Benin', + 'BM' => 'Bermuda', + 'BT' => 'Bhutan', + 'BO' => 'Bolivia', + 'BA' => 'Bosnia And Herzegovina', + 'BW' => 'Botswana', + 'BV' => 'Bouvet Island', + 'BR' => 'Brazil', + 'IO' => 'British Indian Ocean Territory', + 'BN' => 'Brunei Darussalam', + 'BG' => 'Bulgaria', + 'BF' => 'Burkina Faso', + 'BI' => 'Burundi', + 'KH' => 'Cambodia', + 'CM' => 'Cameroon', + 'CA' => 'Canada', + 'CV' => 'Cape Verde', + 'KY' => 'Cayman Islands', + 'CF' => 'Central African Republic', + 'TD' => 'Chad', + 'CL' => 'Chile', + 'CN' => 'China', + 'CX' => 'Christmas Island', + 'CC' => 'Cocos (Keeling) Islands', + 'CO' => 'Colombia', + 'KM' => 'Comoros', + 'CG' => 'Congo', + 'CD' => 'Congo, Democratic Republic', + 'CK' => 'Cook Islands', + 'CR' => 'Costa Rica', + 'CI' => 'Cote D\'Ivoire', + 'HR' => 'Croatia', + 'CU' => 'Cuba', + 'CY' => 'Cyprus', + 'CZ' => 'Czech Republic', + 'DK' => 'Denmark', + 'DJ' => 'Djibouti', + 'DM' => 'Dominica', + 'DO' => 'Dominican Republic', + 'EC' => 'Ecuador', + 'EG' => 'Egypt', + 'SV' => 'El Salvador', + 'GQ' => 'Equatorial Guinea', + 'ER' => 'Eritrea', + 'EE' => 'Estonia', + 'ET' => 'Ethiopia', + 'FK' => 'Falkland Islands (Malvinas)', + 'FO' => 'Faroe Islands', + 'FJ' => 'Fiji', + 'FI' => 'Finland', + 'FR' => 'France', + 'GF' => 'French Guiana', + 'PF' => 'French Polynesia', + 'TF' => 'French Southern Territories', + 'GA' => 'Gabon', + 'GM' => 'Gambia', + 'GE' => 'Georgia', + 'DE' => 'Germany', + 'GH' => 'Ghana', + 'GI' => 'Gibraltar', + 'GR' => 'Greece', + 'GL' => 'Greenland', + 'GD' => 'Grenada', + 'GP' => 'Guadeloupe', + 'GU' => 'Guam', + 'GT' => 'Guatemala', + 'GG' => 'Guernsey', + 'GN' => 'Guinea', + 'GW' => 'Guinea-Bissau', + 'GY' => 'Guyana', + 'HT' => 'Haiti', + 'HM' => 'Heard Island & Mcdonald Islands', + 'VA' => 'Holy See (Vatican City State)', + 'HN' => 'Honduras', + 'HK' => 'Hong Kong', + 'HU' => 'Hungary', + 'IS' => 'Iceland', + 'IN' => 'India', + 'ID' => 'Indonesia', + 'IR' => 'Iran, Islamic Republic Of', + 'IQ' => 'Iraq', + 'IE' => 'Ireland', + 'IM' => 'Isle Of Man', + 'IL' => 'Israel', + 'IT' => 'Italy', + 'JM' => 'Jamaica', + 'JP' => 'Japan', + 'JE' => 'Jersey', + 'JO' => 'Jordan', + 'KZ' => 'Kazakhstan', + 'KE' => 'Kenya', + 'KI' => 'Kiribati', + 'KR' => 'Korea', + 'KW' => 'Kuwait', + 'KG' => 'Kyrgyzstan', + 'LA' => 'Lao People\'s Democratic Republic', + 'LV' => 'Latvia', + 'LB' => 'Lebanon', + 'LS' => 'Lesotho', + 'LR' => 'Liberia', + 'LY' => 'Libyan Arab Jamahiriya', + 'LI' => 'Liechtenstein', + 'LT' => 'Lithuania', + 'LU' => 'Luxembourg', + 'MO' => 'Macao', + 'MK' => 'Macedonia', + 'MG' => 'Madagascar', + 'MW' => 'Malawi', + 'MY' => 'Malaysia', + 'MV' => 'Maldives', + 'ML' => 'Mali', + 'MT' => 'Malta', + 'MH' => 'Marshall Islands', + 'MQ' => 'Martinique', + 'MR' => 'Mauritania', + 'MU' => 'Mauritius', + 'YT' => 'Mayotte', + 'MX' => 'Mexico', + 'FM' => 'Micronesia, Federated States Of', + 'MD' => 'Moldova', + 'MC' => 'Monaco', + 'MN' => 'Mongolia', + 'ME' => 'Montenegro', + 'MS' => 'Montserrat', + 'MA' => 'Morocco', + 'MZ' => 'Mozambique', + 'MM' => 'Myanmar', + 'NA' => 'Namibia', + 'NR' => 'Nauru', + 'NP' => 'Nepal', + 'NL' => 'Netherlands', + 'AN' => 'Netherlands Antilles', + 'NC' => 'New Caledonia', + 'NZ' => 'New Zealand', + 'NI' => 'Nicaragua', + 'NE' => 'Niger', + 'NG' => 'Nigeria', + 'NU' => 'Niue', + 'NF' => 'Norfolk Island', + 'MP' => 'Northern Mariana Islands', + 'NO' => 'Norway', + 'OM' => 'Oman', + 'PK' => 'Pakistan', + 'PW' => 'Palau', + 'PS' => 'Palestinian Territory, Occupied', + 'PA' => 'Panama', + 'PG' => 'Papua New Guinea', + 'PY' => 'Paraguay', + 'PE' => 'Peru', + 'PH' => 'Philippines', + 'PN' => 'Pitcairn', + 'PL' => 'Poland', + 'PT' => 'Portugal', + 'PR' => 'Puerto Rico', + 'QA' => 'Qatar', + 'RE' => 'Reunion', + 'RO' => 'Romania', + 'RU' => 'Russian Federation', + 'RW' => 'Rwanda', + 'BL' => 'Saint Barthelemy', + 'SH' => 'Saint Helena', + 'KN' => 'Saint Kitts And Nevis', + 'LC' => 'Saint Lucia', + 'MF' => 'Saint Martin', + 'PM' => 'Saint Pierre And Miquelon', + 'VC' => 'Saint Vincent And Grenadines', + 'WS' => 'Samoa', + 'SM' => 'San Marino', + 'ST' => 'Sao Tome And Principe', + 'SA' => 'Saudi Arabia', + 'SN' => 'Senegal', + 'RS' => 'Serbia', + 'SC' => 'Seychelles', + 'SL' => 'Sierra Leone', + 'SG' => 'Singapore', + 'SK' => 'Slovakia', + 'SI' => 'Slovenia', + 'SB' => 'Solomon Islands', + 'SO' => 'Somalia', + 'ZA' => 'South Africa', + 'GS' => 'South Georgia And Sandwich Isl.', + 'ES' => 'Spain', + 'LK' => 'Sri Lanka', + 'SD' => 'Sudan', + 'SR' => 'Suriname', + 'SJ' => 'Svalbard And Jan Mayen', + 'SZ' => 'Swaziland', + 'SE' => 'Sweden', + 'CH' => 'Switzerland', + 'SY' => 'Syrian Arab Republic', + 'TW' => 'Taiwan', + 'TJ' => 'Tajikistan', + 'TZ' => 'Tanzania', + 'TH' => 'Thailand', + 'TL' => 'Timor-Leste', + 'TG' => 'Togo', + 'TK' => 'Tokelau', + 'TO' => 'Tonga', + 'TT' => 'Trinidad And Tobago', + 'TN' => 'Tunisia', + 'TR' => 'Turkey', + 'TM' => 'Turkmenistan', + 'TC' => 'Turks And Caicos Islands', + 'TV' => 'Tuvalu', + 'UG' => 'Uganda', + 'UA' => 'Ukraine', + 'AE' => 'United Arab Emirates', + 'GB' => 'United Kingdom', + 'US' => 'United States', + 'UM' => 'United States Outlying Islands', + 'UY' => 'Uruguay', + 'UZ' => 'Uzbekistan', + 'VU' => 'Vanuatu', + 'VE' => 'Venezuela', + 'VN' => 'Viet Nam', + 'VG' => 'Virgin Islands, British', + 'VI' => 'Virgin Islands, U.S.', + 'WF' => 'Wallis And Futuna', + 'EH' => 'Western Sahara', + 'YE' => 'Yemen', + 'ZM' => 'Zambia', + 'ZW' => 'Zimbabwe', +); + ?> \ No newline at end of file diff --git a/core/install/resources/page_parts/install_config_database.php b/core/install/resources/page_parts/install_config_database.php index e6797197a7..685649e22a 100644 --- a/core/install/resources/page_parts/install_config_database.php +++ b/core/install/resources/page_parts/install_config_database.php @@ -1,276 +1,276 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - Matthew Vale -*/ - - echo "
\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if ($db_type == "sqlite") { - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - } - - if ($db_type == "mysql") { - - //set defaults - if (strlen($db_host) == 0) { $db_host = 'localhost'; } - if (strlen($db_port) == 0) { $db_port = '3306'; } - //if (strlen($db_name) == 0) { $db_name = 'fusionpbx'; } - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - } - - if ($db_type == "pgsql") { - if (strlen($db_host) == 0) { $db_host = 'localhost'; } - if (strlen($db_port) == 0) { $db_port = '5432'; } - if (strlen($db_name) == 0) { $db_name = 'fusionpbx'; } - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - } - - echo "
".$text['header-config_database']."\n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " Database Filename\n"; - echo "\n"; - echo "
\n"; - echo " Set the database filename. The file extension should be '.db'.\n"; - echo "\n"; - echo "
\n"; - echo " Database Directory\n"; - echo "\n"; - echo "
\n"; - echo " Set the path to the database directory.\n"; - echo "
\n"; - echo " Database Host\n"; - echo "\n"; - echo "
\n"; - echo " Enter the host address for the database server.\n"; - echo "\n"; - echo "
\n"; - echo " Database Port\n"; - echo "\n"; - echo "
\n"; - echo " Enter the port number. It is optional if the database is using the default port.\n"; - echo "\n"; - echo "
\n"; - echo " Database Name\n"; - echo "\n"; - echo "
\n"; - echo " Enter the name of the database.\n"; - echo "\n"; - echo "
\n"; - echo " Database Username\n"; - echo "\n"; - echo "
\n"; - echo " Enter the database username. \n"; - echo "\n"; - echo "
\n"; - echo " Database Password\n"; - echo "\n"; - echo "
\n"; - echo " Enter the database password.\n"; - echo "\n"; - echo "
\n"; - echo " Create Database Options\n"; - echo "\n"; - if($db_create=='1') { $checked = "checked='checked'"; } else { $checked = ''; } - echo " \n"; - echo "
\n"; - echo "Choose whether to create the database\n"; - echo "
\n"; - echo " Create Database Username\n"; - echo "\n"; - echo "
\n"; - echo " Optional, this username is used to create the database, a database user and set the permissions. \n"; - echo " By default this username is 'root' however it can be any account with permission to add a database, user, and grant permissions. \n"; - echo "
\n"; - echo " Create Database Password\n"; - echo "\n"; - echo "
\n"; - echo " Enter the create database password.\n"; - echo "\n"; - echo "
\n"; - echo " Database Host\n"; - echo "\n"; - echo "
\n"; - echo " Enter the host address for the database server.\n"; - echo "\n"; - echo "
\n"; - echo " Database Port\n"; - echo "\n"; - echo "
\n"; - echo " Enter the port number. It is optional if the database is using the default port.\n"; - echo "\n"; - echo "
\n"; - echo " Database Name\n"; - echo "\n"; - echo "
\n"; - echo " Enter the name of the database.\n"; - echo "\n"; - echo "
\n"; - echo " Database Username\n"; - echo "\n"; - echo "
\n"; - echo " Enter the database username.\n"; - echo "\n"; - echo "
\n"; - echo " Database Password\n"; - echo "\n"; - echo "
\n"; - echo " Enter the database password.\n"; - echo "\n"; - echo "
\n"; - echo " Create Database Options\n"; - echo "\n"; - if($db_create=='1') { $checked = "checked='checked'"; } else { $checked = ''; } - echo " \n"; - echo "
\n"; - echo " Create Database Username\n"; - echo "\n"; - echo "
\n"; - echo " Optional, this username is used to create the database, a database user and set the permissions. \n"; - echo " By default this username is 'pgsql' however it can be any account with permission to add a database, user, and grant permissions. \n"; - echo " Leave blank to use the details above. \n"; - echo "
\n"; - echo " Create Database Password\n"; - echo "\n"; - echo "
\n"; - echo " Enter the create database password.\n"; - echo "\n"; - echo "
"; - //echo "
\n"; - //echo " \n"; - //echo " \n"; - //echo "
\n"; - echo "
\n"; + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Matthew Vale +*/ + + echo "
\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if ($db_type == "sqlite") { + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + } + + if ($db_type == "mysql") { + + //set defaults + if (strlen($db_host) == 0) { $db_host = 'localhost'; } + if (strlen($db_port) == 0) { $db_port = '3306'; } + //if (strlen($db_name) == 0) { $db_name = 'fusionpbx'; } + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + } + + if ($db_type == "pgsql") { + if (strlen($db_host) == 0) { $db_host = 'localhost'; } + if (strlen($db_port) == 0) { $db_port = '5432'; } + if (strlen($db_name) == 0) { $db_name = 'fusionpbx'; } + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + } + + echo "
".$text['header-config_database']."\n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " Database Filename\n"; + echo "\n"; + echo "
\n"; + echo " Set the database filename. The file extension should be '.db'.\n"; + echo "\n"; + echo "
\n"; + echo " Database Directory\n"; + echo "\n"; + echo "
\n"; + echo " Set the path to the database directory.\n"; + echo "
\n"; + echo " Database Host\n"; + echo "\n"; + echo "
\n"; + echo " Enter the host address for the database server.\n"; + echo "\n"; + echo "
\n"; + echo " Database Port\n"; + echo "\n"; + echo "
\n"; + echo " Enter the port number. It is optional if the database is using the default port.\n"; + echo "\n"; + echo "
\n"; + echo " Database Name\n"; + echo "\n"; + echo "
\n"; + echo " Enter the name of the database.\n"; + echo "\n"; + echo "
\n"; + echo " Database Username\n"; + echo "\n"; + echo "
\n"; + echo " Enter the database username. \n"; + echo "\n"; + echo "
\n"; + echo " Database Password\n"; + echo "\n"; + echo "
\n"; + echo " Enter the database password.\n"; + echo "\n"; + echo "
\n"; + echo " Create Database Options\n"; + echo "\n"; + if($db_create=='1') { $checked = "checked='checked'"; } else { $checked = ''; } + echo " \n"; + echo "
\n"; + echo "Choose whether to create the database\n"; + echo "
\n"; + echo " Create Database Username\n"; + echo "\n"; + echo "
\n"; + echo " Optional, this username is used to create the database, a database user and set the permissions. \n"; + echo " By default this username is 'root' however it can be any account with permission to add a database, user, and grant permissions. \n"; + echo "
\n"; + echo " Create Database Password\n"; + echo "\n"; + echo "
\n"; + echo " Enter the create database password.\n"; + echo "\n"; + echo "
\n"; + echo " Database Host\n"; + echo "\n"; + echo "
\n"; + echo " Enter the host address for the database server.\n"; + echo "\n"; + echo "
\n"; + echo " Database Port\n"; + echo "\n"; + echo "
\n"; + echo " Enter the port number. It is optional if the database is using the default port.\n"; + echo "\n"; + echo "
\n"; + echo " Database Name\n"; + echo "\n"; + echo "
\n"; + echo " Enter the name of the database.\n"; + echo "\n"; + echo "
\n"; + echo " Database Username\n"; + echo "\n"; + echo "
\n"; + echo " Enter the database username.\n"; + echo "\n"; + echo "
\n"; + echo " Database Password\n"; + echo "\n"; + echo "
\n"; + echo " Enter the database password.\n"; + echo "\n"; + echo "
\n"; + echo " Create Database Options\n"; + echo "\n"; + if($db_create=='1') { $checked = "checked='checked'"; } else { $checked = ''; } + echo " \n"; + echo "
\n"; + echo " Create Database Username\n"; + echo "\n"; + echo "
\n"; + echo " Optional, this username is used to create the database, a database user and set the permissions. \n"; + echo " By default this username is 'pgsql' however it can be any account with permission to add a database, user, and grant permissions. \n"; + echo " Leave blank to use the details above. \n"; + echo "
\n"; + echo " Create Database Password\n"; + echo "\n"; + echo "
\n"; + echo " Enter the create database password.\n"; + echo "\n"; + echo "
"; + //echo "
\n"; + //echo " \n"; + //echo " \n"; + //echo "
\n"; + echo "
\n"; ?> \ No newline at end of file diff --git a/core/install/resources/page_parts/install_config_detail.php b/core/install/resources/page_parts/install_config_detail.php index ca50cb6b3a..9569038a8b 100644 --- a/core/install/resources/page_parts/install_config_detail.php +++ b/core/install/resources/page_parts/install_config_detail.php @@ -1,150 +1,150 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - Matthew Vale -*/ - - echo "
\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "
".$text['header-config_detail']."\n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " Username\n"; - echo "\n"; - echo "
\n"; - echo " Enter the username to use when logging in with the browser.
\n"; - echo "
\n"; - echo " Password\n"; - echo "\n"; - echo "
\n"; - echo " Enter the password to use when logging in with the browser.
\n"; - echo "
\n"; - echo " Country\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo " Select ISO country code used to initialize calling contry code variables.
\n"; - echo "
\n"; - echo " Theme: \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " Select a theme to set as the default.
\n"; - echo "
\n"; - echo " Domain name\n"; - echo "\n"; - echo "
\n"; - echo " Enter the default domain name. \n"; - echo "\n"; - echo "
\n"; - echo " Database Type\n"; - echo "\n"; - echo "
\n"; - echo " Select the database type.\n"; - echo "\n"; - echo "
"; - //echo "
\n"; - //echo " \n"; - //echo " \n"; - //echo "
\n"; - echo "
\n"; + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Matthew Vale +*/ + + echo "
\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "
".$text['header-config_detail']."\n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " Username\n"; + echo "\n"; + echo "
\n"; + echo " Enter the username to use when logging in with the browser.
\n"; + echo "
\n"; + echo " Password\n"; + echo "\n"; + echo "
\n"; + echo " Enter the password to use when logging in with the browser.
\n"; + echo "
\n"; + echo " Country\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo " Select ISO country code used to initialize calling contry code variables.
\n"; + echo "
\n"; + echo " Theme: \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " Select a theme to set as the default.
\n"; + echo "
\n"; + echo " Domain name\n"; + echo "\n"; + echo "
\n"; + echo " Enter the default domain name. \n"; + echo "\n"; + echo "
\n"; + echo " Database Type\n"; + echo "\n"; + echo "
\n"; + echo " Select the database type.\n"; + echo "\n"; + echo "
"; + //echo "
\n"; + //echo " \n"; + //echo " \n"; + //echo "
\n"; + echo "
\n"; ?> \ No newline at end of file diff --git a/core/install/resources/page_parts/install_event_socket.php b/core/install/resources/page_parts/install_event_socket.php index 0655dcf327..2927eaf217 100644 --- a/core/install/resources/page_parts/install_event_socket.php +++ b/core/install/resources/page_parts/install_event_socket.php @@ -1,137 +1,137 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2012 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Matthew Vale -*/ - //fetch the values - require_once "core/install/resources/classes/detect_switch.php"; - $switch_detect = new detect_switch($event_host, $event_port, $event_password); - //$switch_detect->event_port = 2021; - $detect_ok = true; - try { - $switch_detect->detect(); - } catch(Exception $e){ - //echo "

Failed to detect configuration detect_switch reported: " . $e->getMessage() ."

\n"; - //$detect_ok = false; - } - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo " \n"; - echo " \n"; - echo " "; - - echo "
".$text['header-event_socket']."

"; - //echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " ".$text['label-event_host']."\n"; - echo "\n"; - echo " event_host."\" />\n"; - echo "
\n"; - echo $text['description-event_host']."\n"; - echo "
\n"; - echo " ".$text['label-event_port']."\n"; - echo "\n"; - echo " event_port."\"/>\n"; - echo "
\n"; - echo $text['description-event_port']."\n"; - echo "
\n"; - echo " ".$text['label-event_password']."\n"; - echo "\n"; - echo " event_password."\"/>\n"; - echo "
\n"; - echo $text['description-event_password']."\n"; - echo "
\n"; - echo "
"; - echo "
"; - if($detect_ok){ - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - - $id = 1; - echo "\n"; - echo "\n"; - echo "\n"; - - foreach ($switch_detect->get_dirs() as $folder) - { - if($id % 2 == 0){ echo "\n"; } - echo "\n"; - echo "\n"; - if($id % 2 == 1){ echo "\n"; } - $id++; - } - if($id % 2 == 1){ echo "\n"; } - echo "\n"; - echo "\n"; - echo "\n"; - $id=0; - foreach ($switch_detect->get_vdirs() as $folder) { - if($id % 2 == 0){ echo "\n"; } - echo "\n"; - echo "\n"; - if($id % 2 == 1){ echo "\n"; } - $id++; - } - echo "
".$text['title-detected_configuration']."
\n"; - echo "Switch version\n"; - echo "\n"; - echo " ".$switch_detect->version()."\n"; - echo "
\n"; - echo $folder."\n"; - echo "\n"; - echo " ".$switch_detect->$folder()."\n"; - echo "

".$text['title-assumed_configuration']."
\n"; - echo $folder."\n"; - echo "\n"; - echo " ".$switch_detect->$folder()."\n"; - echo "
"; - } - + + Portions created by the Initial Developer are Copyright (C) 2008-2012 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Matthew Vale +*/ + //fetch the values + require_once "core/install/resources/classes/detect_switch.php"; + $switch_detect = new detect_switch($event_host, $event_port, $event_password); + //$switch_detect->event_port = 2021; + $detect_ok = true; + try { + $switch_detect->detect(); + } catch(Exception $e){ + //echo "

Failed to detect configuration detect_switch reported: " . $e->getMessage() ."

\n"; + //$detect_ok = false; + } + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo " \n"; + echo " \n"; + echo " "; + + echo "
".$text['header-event_socket']."

"; + //echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " ".$text['label-event_host']."\n"; + echo "\n"; + echo " event_host."\" />\n"; + echo "
\n"; + echo $text['description-event_host']."\n"; + echo "
\n"; + echo " ".$text['label-event_port']."\n"; + echo "\n"; + echo " event_port."\"/>\n"; + echo "
\n"; + echo $text['description-event_port']."\n"; + echo "
\n"; + echo " ".$text['label-event_password']."\n"; + echo "\n"; + echo " event_password."\"/>\n"; + echo "
\n"; + echo $text['description-event_password']."\n"; + echo "
\n"; + echo "
"; + echo "
"; + if($detect_ok){ + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + + $id = 1; + echo "\n"; + echo "\n"; + echo "\n"; + + foreach ($switch_detect->get_dirs() as $folder) + { + if($id % 2 == 0){ echo "\n"; } + echo "\n"; + echo "\n"; + if($id % 2 == 1){ echo "\n"; } + $id++; + } + if($id % 2 == 1){ echo "\n"; } + echo "\n"; + echo "\n"; + echo "\n"; + $id=0; + foreach ($switch_detect->get_vdirs() as $folder) { + if($id % 2 == 0){ echo "\n"; } + echo "\n"; + echo "\n"; + if($id % 2 == 1){ echo "\n"; } + $id++; + } + echo "
".$text['title-detected_configuration']."
\n"; + echo "Switch version\n"; + echo "\n"; + echo " ".$switch_detect->version()."\n"; + echo "
\n"; + echo $folder."\n"; + echo "\n"; + echo " ".$switch_detect->$folder()."\n"; + echo "

".$text['title-assumed_configuration']."
\n"; + echo $folder."\n"; + echo "\n"; + echo " ".$switch_detect->$folder()."\n"; + echo "
"; + } + ?> \ No newline at end of file diff --git a/core/install/resources/page_parts/install_select_language.php b/core/install/resources/page_parts/install_select_language.php index ba36b2761c..313823f88e 100644 --- a/core/install/resources/page_parts/install_select_language.php +++ b/core/install/resources/page_parts/install_select_language.php @@ -1,65 +1,65 @@ - - Portions created by the Initial Developer are Copyright (C) 2015-2016 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Matthew Vale -*/ - - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
".$text['header-select_language']."

"; - echo " \n"; - echo "
\n"; - echo " ".$text['label-select_language']."\n"; - echo " \n"; - echo " "; - foreach($_SESSION['app']['languages'] as $lang_code){ - echo " "; - echo " "; - echo " "; - echo " "; - echo " "; - } - echo "
\n"; - echo " "; - echo " \n"; - echo " $lang_code ".$text["language-$lang_code"]; - echo " \n"; - echo "  \n"; - echo "
"; - echo "
\n"; - echo " ".$text['description-select_language']."\n"; - echo "
"; - echo "

"; - + + Portions created by the Initial Developer are Copyright (C) 2015-2016 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Matthew Vale +*/ + + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
".$text['header-select_language']."

"; + echo " \n"; + echo "
\n"; + echo " ".$text['label-select_language']."\n"; + echo " \n"; + echo " "; + foreach($_SESSION['app']['languages'] as $lang_code){ + echo " "; + echo " "; + echo " "; + echo " "; + echo " "; + } + echo "
\n"; + echo " "; + echo " \n"; + echo " $lang_code ".$text["language-$lang_code"]; + echo " \n"; + echo "  \n"; + echo "
"; + echo "
\n"; + echo " ".$text['description-select_language']."\n"; + echo "
"; + echo "

"; + ?> \ No newline at end of file diff --git a/core/notifications/notification_edit.php b/core/notifications/notification_edit.php index 7000d577d6..5c6402c9df 100644 --- a/core/notifications/notification_edit.php +++ b/core/notifications/notification_edit.php @@ -1,461 +1,461 @@ - -Portions created by the Initial Developer are Copyright (C) 2008-2012 -the Initial Developer. All Rights Reserved. - -Contributor(s): -Mark J Crane -*/ - -require_once "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; -if (if_group('superadmin')) { - //access granted -} -else { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -// retrieve software uuid - $sql = "select software_uuid, software_url, software_version from v_software"; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $software_uuid = $row["software_uuid"]; - $software_url = $row["software_url"]; - $software_version = $row["software_version"]; - break; // limit to 1 row - } - } - unset($sql, $prep_statement); - - if (count($_REQUEST) > 0) { - - // prepare demographic information ********************************************** - - // fusionpbx version - $software_ver = $software_version; - - // php version - $php_ver = phpversion(); - - // webserver name & version - $web_server = $_SERVER['SERVER_SOFTWARE']; - - // switch version - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if ($fp) { - $switch_result = event_socket_request($fp, 'api version'); - } - $switch_ver = trim($switch_result); - - // database name & version - switch ($db_type) { - case "pgsql" : $db_ver_query = "select version() as db_ver;"; break; - case "mysql" : $db_ver_query = "select version() as db_ver;"; break; - case "sqlite" : $db_ver_query = "select sqlite_version() as db_ver;"; break; - } - $prep_statement = $db->prepare($db_ver_query); - if ($prep_statement) { - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $database_version = $row["db_ver"]; - break; // limit to 1 row - } - } - unset($db_ver_query, $prep_statement); - $db_ver = $database_version; - - // operating system name & version - $os_platform = PHP_OS; - $os_info_1 = php_uname("a"); - if ($os_platform == "Linux") { - $os_info_2 = shell_exec("cat /etc/*{release,version}"); - $os_info_2 .= shell_exec("lsb_release -d -s"); - } - else if (substr(strtoupper($os_platform), 0, 3) == "WIN") { - $os_info_2 = trim(shell_exec("ver")); - } - - // ************************************************************************** - - // check for demographic only submit - if (isset($_GET["demo"])) { - - // update remote server record with new values - $url = "https://".$software_url."/app/notifications/notifications_manage.php"; - $url .= "?demo"; - $url .= "&id=".$software_uuid; - $url .= "&software_ver=".urlencode($software_ver); - $url .= "&php_ver=".urlencode($php_ver); - $url .= "&web_server=".urlencode($web_server); - $url .= "&switch_ver=".urlencode($switch_ver); - $url .= "&db_type=".urlencode($db_type); - $url .= "&db_ver=".urlencode($db_ver); - $url .= "&os_platform=".urlencode($os_platform); - $url .= "&os_info_1=".urlencode($os_info_1); - $url .= "&os_info_2=".urlencode($os_info_2); - - if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { - $response = file_get_contents($url); - } - else if (function_exists('curl_version')) { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, $url); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - $response = curl_exec($curl); - curl_close($curl); - } - - // parse response - $response = json_decode($response, true); - - if ($response['result'] == 'submitted') { - // set message - $_SESSION["message"] = $text['message-demographics_submitted']; - } - - header("Location: notification_edit.php"); - exit; - - } - - // retrieve submitted values - $project_notifications = check_str($_POST["project_notifications"]); - $project_security = check_str($_POST["project_security"]); - $project_releases = check_str($_POST["project_releases"]); - $project_events = check_str($_POST["project_events"]); - $project_news = check_str($_POST["project_news"]); - $project_notification_method = check_str($_POST["project_notification_method"]); - $project_notification_recipient = check_str($_POST["project_notification_recipient"]); - - // get local project notification participation flag - $sql = "select project_notifications from v_notifications"; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $current_project_notifications = $row["project_notifications"]; - break; // limit to 1 row - } - } - unset($sql, $prep_statement); - - // check if remote record should be removed - if ($project_notifications == 'false') { - - if ($current_project_notifications == 'true') { - // remove remote server record - $url = "https://".$software_url."/app/notifications/notifications_manage.php?id=".$software_uuid."&action=delete"; - if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { - $response = file_get_contents($url); - } - else if (function_exists('curl_version')) { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, $url); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - $response = curl_exec($curl); - curl_close($curl); - } - - // parse response - $response = json_decode($response, true); - - if ($response['result'] == 'deleted') { - // set local project notification participation flag to false - $sql = "update v_notifications set project_notifications = 'false'"; - $db->exec(check_sql($sql)); - unset($sql); - } - } - // redirect - $_SESSION["message"] = $text['message-update']; - header("Location: notification_edit.php"); - exit; - } - - // check for invalid values - if ($project_notifications == 'true') { - if ( - ($project_notification_method == 'email' && !valid_email($project_notification_recipient)) || - ($project_notification_method == 'email' && $project_notification_recipient == '') - ) { - $_SESSION["postback"] = $_POST; - $_SESSION["message_mood"] = 'negative'; - $_SESSION["message"] = $text['message-invalid_recipient']; - header("Location: notification_edit.php"); - exit; - } - } - - // update remote server record with new values - $url = "https://".$software_url."/app/notifications/notifications_manage.php"; - $url .= "?id=".$software_uuid; - $url .= "&security=".$project_security; - $url .= "&releases=".$project_releases; - $url .= "&events=".$project_events; - $url .= "&news=".$project_news; - $url .= "&method=".$project_notification_method; - $url .= "&recipient=".urlencode($project_notification_recipient); - $url .= "&software_ver=".urlencode($software_ver); - $url .= "&php_ver=".urlencode($php_ver); - $url .= "&web_server=".urlencode($web_server); - $url .= "&switch_ver=".urlencode($switch_ver); - $url .= "&db_type=".urlencode($db_type); - $url .= "&db_ver=".urlencode($db_ver); - $url .= "&os_platform=".urlencode($os_platform); - $url .= "&os_info_1=".urlencode($os_info_1); - $url .= "&os_info_2=".urlencode($os_info_2); - - if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { - $response = file_get_contents($url); - } - else if (function_exists('curl_version')) { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, $url); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - $response = curl_exec($curl); - curl_close($curl); - } - - // parse response - $response = json_decode($response, true); - - if ($response['result'] == 'updated' || $response['result'] == 'inserted') { - // set local project notification participation flag to true - $sql = "update v_notifications set project_notifications = 'true'"; - $db->exec(check_sql($sql)); - unset($sql); - // set message - $_SESSION["message"] = $text['message-update']; - if ( - $project_security == 'false' && - $project_releases == 'false' && - $project_events == 'false' && - $project_news == 'false' - ) { - $_SESSION["message_mood"] = 'alert'; - $_SESSION["message"] = $_SESSION["message"]." - ".$text['message-no_channels']; - } - // redirect - header("Location: notification_edit.php"); - exit; - } - - } - -// check postback session - if (!isset($_SESSION["postback"])) { - - // check local project notification participation flag - $sql = "select project_notifications from v_notifications"; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); - foreach ($result as &$row) { - $setting["project_notifications"] = $row["project_notifications"]; - break; // limit to 1 row - } - } - unset($sql, $prep_statement); - - // if participation enabled - if ($setting["project_notifications"] == 'true') { - - // get current project notification preferences - $url = "https://".$software_url."/app/notifications/notifications_manage.php?id=".$software_uuid; - if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { - $response = file_get_contents($url); - } - else if (function_exists('curl_version')) { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, $url); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - $response = curl_exec($curl); - curl_close($curl); - } - - // parse response - $setting = json_decode($response, true); - $setting["project_notifications"] = 'true'; - } - - } - else { - - // load postback variables - $setting = fix_postback($_SESSION["postback"]); - unset($_SESSION["postback"]); - - } - -require_once "resources/header.php"; -$document['title'] = $text['title-notifications']; - -// show the content - echo "
\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo "
".$text['header-notifications']."

"; - echo " \n"; - echo "

"; - echo "
\n"; - echo " ".$text['description-notifications']."

\n"; - echo "
\n"; - echo $text['label-project_notifications']."\n"; - echo " \n"; - echo "
\n"; - echo $text['description-project_notifications']."\n"; - echo "
\n"; - - echo "
\n"; - echo "\n"; - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo " \n"; - /* - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - */ - - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - - echo "
\n"; - echo $text['label-project_security']."\n"; - echo " \n"; - echo "
\n"; - echo $text['description-project_security']."\n"; - echo "
\n"; - echo $text['label-project_releases']."\n"; - echo " \n"; - echo "
\n"; - echo $text['description-project_releases']."\n"; - echo "
\n"; - echo $text['label-project_events']."\n"; - echo " \n"; - echo "
\n"; - echo $text['description-project_events']."\n"; - echo "
\n"; - echo $text['label-project_news']."\n"; - echo " \n"; - echo "
\n"; - echo $text['description-project_news']."\n"; - echo "
\n"; - echo $text['label-project_notification_method']."\n"; - echo " \n"; - echo "
\n"; - echo $text['description-project_notification_method']."\n"; - echo "
\n"; - echo $text['label-project_notification_recipient']."\n"; - echo " \n"; - echo "
\n"; - echo $text['description-project_notification_recipient']."\n"; - echo "
\n"; - echo "
\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " ".$text['message-disclaimer']."\n"; - echo "

\n"; - echo " ".$text['message-demographics']." ".$text['message-demographics_click_here'].".\n"; - echo "
\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo " "; - - echo "
\n"; - echo "
"; - echo " \n"; - echo "
\n"; - - echo "
\n"; - -// include the footer - require_once "resources/footer.php"; + +Portions created by the Initial Developer are Copyright (C) 2008-2012 +the Initial Developer. All Rights Reserved. + +Contributor(s): +Mark J Crane +*/ + +require_once "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; +if (if_group('superadmin')) { + //access granted +} +else { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +// retrieve software uuid + $sql = "select software_uuid, software_url, software_version from v_software"; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $software_uuid = $row["software_uuid"]; + $software_url = $row["software_url"]; + $software_version = $row["software_version"]; + break; // limit to 1 row + } + } + unset($sql, $prep_statement); + + if (count($_REQUEST) > 0) { + + // prepare demographic information ********************************************** + + // fusionpbx version + $software_ver = $software_version; + + // php version + $php_ver = phpversion(); + + // webserver name & version + $web_server = $_SERVER['SERVER_SOFTWARE']; + + // switch version + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if ($fp) { + $switch_result = event_socket_request($fp, 'api version'); + } + $switch_ver = trim($switch_result); + + // database name & version + switch ($db_type) { + case "pgsql" : $db_ver_query = "select version() as db_ver;"; break; + case "mysql" : $db_ver_query = "select version() as db_ver;"; break; + case "sqlite" : $db_ver_query = "select sqlite_version() as db_ver;"; break; + } + $prep_statement = $db->prepare($db_ver_query); + if ($prep_statement) { + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $database_version = $row["db_ver"]; + break; // limit to 1 row + } + } + unset($db_ver_query, $prep_statement); + $db_ver = $database_version; + + // operating system name & version + $os_platform = PHP_OS; + $os_info_1 = php_uname("a"); + if ($os_platform == "Linux") { + $os_info_2 = shell_exec("cat /etc/*{release,version}"); + $os_info_2 .= shell_exec("lsb_release -d -s"); + } + else if (substr(strtoupper($os_platform), 0, 3) == "WIN") { + $os_info_2 = trim(shell_exec("ver")); + } + + // ************************************************************************** + + // check for demographic only submit + if (isset($_GET["demo"])) { + + // update remote server record with new values + $url = "https://".$software_url."/app/notifications/notifications_manage.php"; + $url .= "?demo"; + $url .= "&id=".$software_uuid; + $url .= "&software_ver=".urlencode($software_ver); + $url .= "&php_ver=".urlencode($php_ver); + $url .= "&web_server=".urlencode($web_server); + $url .= "&switch_ver=".urlencode($switch_ver); + $url .= "&db_type=".urlencode($db_type); + $url .= "&db_ver=".urlencode($db_ver); + $url .= "&os_platform=".urlencode($os_platform); + $url .= "&os_info_1=".urlencode($os_info_1); + $url .= "&os_info_2=".urlencode($os_info_2); + + if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { + $response = file_get_contents($url); + } + else if (function_exists('curl_version')) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + } + + // parse response + $response = json_decode($response, true); + + if ($response['result'] == 'submitted') { + // set message + $_SESSION["message"] = $text['message-demographics_submitted']; + } + + header("Location: notification_edit.php"); + exit; + + } + + // retrieve submitted values + $project_notifications = check_str($_POST["project_notifications"]); + $project_security = check_str($_POST["project_security"]); + $project_releases = check_str($_POST["project_releases"]); + $project_events = check_str($_POST["project_events"]); + $project_news = check_str($_POST["project_news"]); + $project_notification_method = check_str($_POST["project_notification_method"]); + $project_notification_recipient = check_str($_POST["project_notification_recipient"]); + + // get local project notification participation flag + $sql = "select project_notifications from v_notifications"; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $current_project_notifications = $row["project_notifications"]; + break; // limit to 1 row + } + } + unset($sql, $prep_statement); + + // check if remote record should be removed + if ($project_notifications == 'false') { + + if ($current_project_notifications == 'true') { + // remove remote server record + $url = "https://".$software_url."/app/notifications/notifications_manage.php?id=".$software_uuid."&action=delete"; + if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { + $response = file_get_contents($url); + } + else if (function_exists('curl_version')) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + } + + // parse response + $response = json_decode($response, true); + + if ($response['result'] == 'deleted') { + // set local project notification participation flag to false + $sql = "update v_notifications set project_notifications = 'false'"; + $db->exec(check_sql($sql)); + unset($sql); + } + } + // redirect + $_SESSION["message"] = $text['message-update']; + header("Location: notification_edit.php"); + exit; + } + + // check for invalid values + if ($project_notifications == 'true') { + if ( + ($project_notification_method == 'email' && !valid_email($project_notification_recipient)) || + ($project_notification_method == 'email' && $project_notification_recipient == '') + ) { + $_SESSION["postback"] = $_POST; + $_SESSION["message_mood"] = 'negative'; + $_SESSION["message"] = $text['message-invalid_recipient']; + header("Location: notification_edit.php"); + exit; + } + } + + // update remote server record with new values + $url = "https://".$software_url."/app/notifications/notifications_manage.php"; + $url .= "?id=".$software_uuid; + $url .= "&security=".$project_security; + $url .= "&releases=".$project_releases; + $url .= "&events=".$project_events; + $url .= "&news=".$project_news; + $url .= "&method=".$project_notification_method; + $url .= "&recipient=".urlencode($project_notification_recipient); + $url .= "&software_ver=".urlencode($software_ver); + $url .= "&php_ver=".urlencode($php_ver); + $url .= "&web_server=".urlencode($web_server); + $url .= "&switch_ver=".urlencode($switch_ver); + $url .= "&db_type=".urlencode($db_type); + $url .= "&db_ver=".urlencode($db_ver); + $url .= "&os_platform=".urlencode($os_platform); + $url .= "&os_info_1=".urlencode($os_info_1); + $url .= "&os_info_2=".urlencode($os_info_2); + + if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { + $response = file_get_contents($url); + } + else if (function_exists('curl_version')) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + } + + // parse response + $response = json_decode($response, true); + + if ($response['result'] == 'updated' || $response['result'] == 'inserted') { + // set local project notification participation flag to true + $sql = "update v_notifications set project_notifications = 'true'"; + $db->exec(check_sql($sql)); + unset($sql); + // set message + $_SESSION["message"] = $text['message-update']; + if ( + $project_security == 'false' && + $project_releases == 'false' && + $project_events == 'false' && + $project_news == 'false' + ) { + $_SESSION["message_mood"] = 'alert'; + $_SESSION["message"] = $_SESSION["message"]." - ".$text['message-no_channels']; + } + // redirect + header("Location: notification_edit.php"); + exit; + } + + } + +// check postback session + if (!isset($_SESSION["postback"])) { + + // check local project notification participation flag + $sql = "select project_notifications from v_notifications"; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); + foreach ($result as &$row) { + $setting["project_notifications"] = $row["project_notifications"]; + break; // limit to 1 row + } + } + unset($sql, $prep_statement); + + // if participation enabled + if ($setting["project_notifications"] == 'true') { + + // get current project notification preferences + $url = "https://".$software_url."/app/notifications/notifications_manage.php?id=".$software_uuid; + if (file_get_contents(__FILE__) && ini_get('allow_url_fopen')) { + $response = file_get_contents($url); + } + else if (function_exists('curl_version')) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + } + + // parse response + $setting = json_decode($response, true); + $setting["project_notifications"] = 'true'; + } + + } + else { + + // load postback variables + $setting = fix_postback($_SESSION["postback"]); + unset($_SESSION["postback"]); + + } + +require_once "resources/header.php"; +$document['title'] = $text['title-notifications']; + +// show the content + echo "
\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo "
".$text['header-notifications']."

"; + echo " \n"; + echo "

"; + echo "
\n"; + echo " ".$text['description-notifications']."

\n"; + echo "
\n"; + echo $text['label-project_notifications']."\n"; + echo " \n"; + echo "
\n"; + echo $text['description-project_notifications']."\n"; + echo "
\n"; + + echo "
\n"; + echo "\n"; + + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo " \n"; + /* + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + */ + + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + + echo "
\n"; + echo $text['label-project_security']."\n"; + echo " \n"; + echo "
\n"; + echo $text['description-project_security']."\n"; + echo "
\n"; + echo $text['label-project_releases']."\n"; + echo " \n"; + echo "
\n"; + echo $text['description-project_releases']."\n"; + echo "
\n"; + echo $text['label-project_events']."\n"; + echo " \n"; + echo "
\n"; + echo $text['description-project_events']."\n"; + echo "
\n"; + echo $text['label-project_news']."\n"; + echo " \n"; + echo "
\n"; + echo $text['description-project_news']."\n"; + echo "
\n"; + echo $text['label-project_notification_method']."\n"; + echo " \n"; + echo "
\n"; + echo $text['description-project_notification_method']."\n"; + echo "
\n"; + echo $text['label-project_notification_recipient']."\n"; + echo " \n"; + echo "
\n"; + echo $text['description-project_notification_recipient']."\n"; + echo "
\n"; + echo "
\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " ".$text['message-disclaimer']."\n"; + echo "

\n"; + echo " ".$text['message-demographics']." ".$text['message-demographics_click_here'].".\n"; + echo "
\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo " "; + + echo "
\n"; + echo "
"; + echo " \n"; + echo "
\n"; + + echo "
\n"; + +// include the footer + require_once "resources/footer.php"; ?> \ No newline at end of file diff --git a/core/upgrade/index.php b/core/upgrade/index.php index 1b69f98865..a479130969 100644 --- a/core/upgrade/index.php +++ b/core/upgrade/index.php @@ -1,249 +1,249 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2015 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -set_time_limit(600); //sec (10 min) - -include "root.php"; -require_once "resources/require.php"; -require_once "resources/check_auth.php"; - -//check the permission -if ( - !permission_exists('upgrade_source') && - !permission_exists('upgrade_schema') && - !permission_exists('upgrade_apps') && - !permission_exists('menu_restore') && - !permission_exists('group_edit') - ) { - echo "access denied"; - exit; -} - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -if (sizeof($_POST) > 0) { - - $do = $_POST['do']; - - // run source update - if ($do["source"] && permission_exists("upgrade_source") && !is_dir("/usr/share/examples/fusionpbx")) { - chdir($_SERVER["PROJECT_ROOT"]); - exec("git pull", $response_source_update); - $update_failed = true; - if (sizeof($response_source_update) > 0) { - $_SESSION["response_source_update"] = $response_source_update; - foreach ($response_source_update as $response_line) { - if (substr_count($response_line, "Updating ") > 0 || substr_count($response_line, "Already up-to-date.") > 0) { - $update_failed = false; - } - } - } - if ($update_failed) { - $_SESSION["message_delay"] = 3500; - $_SESSION["message_mood"] = 'negative'; - $response_message = $text['message-upgrade_source_failed']; - } - } - - // load an array of the database schema and compare it with the active database - if ($do["schema"] && permission_exists("upgrade_schema")) { - $response_message = $text['message-upgrade_schema']; - - $upgrade_data_types = check_str($do["data_types"]); - require_once "resources/classes/schema.php"; - $obj = new schema(); - $_SESSION["schema"]["response"] = $obj->schema("html"); - } - - // process the apps defaults - if ($do["apps"] && permission_exists("upgrade_apps")) { - $response_message = $text['message-upgrade_apps']; - - require_once "resources/classes/domains.php"; - $domain = new domains; - $domain->upgrade(); - } - - // restore defaults of the selected menu - if ($do["menu"] && permission_exists("menu_restore")) { - $sel_menu = explode('|', check_str($_POST["sel_menu"])); - $menu_uuid = $sel_menu[0]; - $menu_language = $sel_menu[1]; - $included = true; - require_once("core/menu/menu_restore_default.php"); - unset($sel_menu); - $response_message = $text['message-upgrade_menu']; - } - - // restore default permissions - if ($do["permissions"] && permission_exists("group_edit")) { - $included = true; - require_once("core/users/permissions_default.php"); - $response_message = "Permission Defaults Restored"; - } - - if (sizeof($_POST['do']) > 1) { - $response_message = $text['message-upgrade']; - } - - $_SESSION["message"] = $response_message; - header("Location: ".PROJECT_PATH."/core/upgrade/index.php"); - exit; - -} // end if - - -require_once "resources/header.php"; -$document['title'] = $text['title-upgrade']; - -echo "".$text['header-upgrade'].""; -echo "

"; -echo $text['description-upgrade']; -echo "

"; - -echo "
\n"; - -if (permission_exists("upgrade_source") && !is_dir("/usr/share/examples/fusionpbx") && is_writeable($_SERVER["PROJECT_ROOT"]."/.git")) { - echo "\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - echo "
\n"; - echo " ".$text['label-upgrade_source']; - echo " \n"; - echo " \n"; - echo "
\n"; -} - -if (permission_exists("upgrade_schema")) { - echo "\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - echo "
\n"; - echo " ".$text['label-upgrade_schema']; - echo " \n"; - echo " \n"; - echo "
\n"; - - echo "\n"; -} - -if (permission_exists("upgrade_apps")) { - echo "\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - echo "
\n"; - echo " ".$text['label-upgrade_apps']; - echo " \n"; - echo " \n"; - echo "
\n"; -} - -if (permission_exists("menu_restore")) { - echo "\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - echo "
\n"; - echo " ".$text['label-upgrade_menu']; - echo " \n"; - echo " \n"; - echo "
\n"; -} - -if (permission_exists("group_edit")) { - echo "\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - echo "
\n"; - echo " ".$text['label-upgrade_permissions']; - echo " \n"; - echo " \n"; - echo "
\n"; -} - -echo "
"; -echo "
"; -echo "

"; -echo "
\n"; - -// output result of source update -if (sizeof($_SESSION["response_source_update"]) > 0) { - echo "
"; - echo "".$text['header-source_update_results'].""; - echo "

"; - echo "
";
-	echo implode("\n", $_SESSION["response_source_update"]);
-	echo "
"; - echo "

"; - unset($_SESSION["response_source_update"]); -} - -// output result of upgrade schema -if ($_SESSION["schema"]["response"] != '') { - echo "
"; - echo "".$text['header-upgrade_schema_results'].""; - echo "

"; - echo $_SESSION["schema"]["response"]; - unset($_SESSION["schema"]["response"]); -} - -require_once "resources/footer.php"; + + Portions created by the Initial Developer are Copyright (C) 2008-2015 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +set_time_limit(600); //sec (10 min) + +include "root.php"; +require_once "resources/require.php"; +require_once "resources/check_auth.php"; + +//check the permission +if ( + !permission_exists('upgrade_source') && + !permission_exists('upgrade_schema') && + !permission_exists('upgrade_apps') && + !permission_exists('menu_restore') && + !permission_exists('group_edit') + ) { + echo "access denied"; + exit; +} + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +if (sizeof($_POST) > 0) { + + $do = $_POST['do']; + + // run source update + if ($do["source"] && permission_exists("upgrade_source") && !is_dir("/usr/share/examples/fusionpbx")) { + chdir($_SERVER["PROJECT_ROOT"]); + exec("git pull", $response_source_update); + $update_failed = true; + if (sizeof($response_source_update) > 0) { + $_SESSION["response_source_update"] = $response_source_update; + foreach ($response_source_update as $response_line) { + if (substr_count($response_line, "Updating ") > 0 || substr_count($response_line, "Already up-to-date.") > 0) { + $update_failed = false; + } + } + } + if ($update_failed) { + $_SESSION["message_delay"] = 3500; + $_SESSION["message_mood"] = 'negative'; + $response_message = $text['message-upgrade_source_failed']; + } + } + + // load an array of the database schema and compare it with the active database + if ($do["schema"] && permission_exists("upgrade_schema")) { + $response_message = $text['message-upgrade_schema']; + + $upgrade_data_types = check_str($do["data_types"]); + require_once "resources/classes/schema.php"; + $obj = new schema(); + $_SESSION["schema"]["response"] = $obj->schema("html"); + } + + // process the apps defaults + if ($do["apps"] && permission_exists("upgrade_apps")) { + $response_message = $text['message-upgrade_apps']; + + require_once "resources/classes/domains.php"; + $domain = new domains; + $domain->upgrade(); + } + + // restore defaults of the selected menu + if ($do["menu"] && permission_exists("menu_restore")) { + $sel_menu = explode('|', check_str($_POST["sel_menu"])); + $menu_uuid = $sel_menu[0]; + $menu_language = $sel_menu[1]; + $included = true; + require_once("core/menu/menu_restore_default.php"); + unset($sel_menu); + $response_message = $text['message-upgrade_menu']; + } + + // restore default permissions + if ($do["permissions"] && permission_exists("group_edit")) { + $included = true; + require_once("core/users/permissions_default.php"); + $response_message = "Permission Defaults Restored"; + } + + if (sizeof($_POST['do']) > 1) { + $response_message = $text['message-upgrade']; + } + + $_SESSION["message"] = $response_message; + header("Location: ".PROJECT_PATH."/core/upgrade/index.php"); + exit; + +} // end if + + +require_once "resources/header.php"; +$document['title'] = $text['title-upgrade']; + +echo "".$text['header-upgrade'].""; +echo "

"; +echo $text['description-upgrade']; +echo "

"; + +echo "
\n"; + +if (permission_exists("upgrade_source") && !is_dir("/usr/share/examples/fusionpbx") && is_writeable($_SERVER["PROJECT_ROOT"]."/.git")) { + echo "\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + echo "
\n"; + echo " ".$text['label-upgrade_source']; + echo " \n"; + echo " \n"; + echo "
\n"; +} + +if (permission_exists("upgrade_schema")) { + echo "\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + echo "
\n"; + echo " ".$text['label-upgrade_schema']; + echo " \n"; + echo " \n"; + echo "
\n"; + + echo "\n"; +} + +if (permission_exists("upgrade_apps")) { + echo "\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + echo "
\n"; + echo " ".$text['label-upgrade_apps']; + echo " \n"; + echo " \n"; + echo "
\n"; +} + +if (permission_exists("menu_restore")) { + echo "\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + echo "
\n"; + echo " ".$text['label-upgrade_menu']; + echo " \n"; + echo " \n"; + echo "
\n"; +} + +if (permission_exists("group_edit")) { + echo "\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + echo "
\n"; + echo " ".$text['label-upgrade_permissions']; + echo " \n"; + echo " \n"; + echo "
\n"; +} + +echo "
"; +echo "
"; +echo "

"; +echo "
\n"; + +// output result of source update +if (sizeof($_SESSION["response_source_update"]) > 0) { + echo "
"; + echo "".$text['header-source_update_results'].""; + echo "

"; + echo "
";
+	echo implode("\n", $_SESSION["response_source_update"]);
+	echo "
"; + echo "

"; + unset($_SESSION["response_source_update"]); +} + +// output result of upgrade schema +if ($_SESSION["schema"]["response"] != '') { + echo "
"; + echo "".$text['header-upgrade_schema_results'].""; + echo "

"; + echo $_SESSION["schema"]["response"]; + unset($_SESSION["schema"]["response"]); +} + +require_once "resources/footer.php"; ?> \ No newline at end of file diff --git a/core/user_settings/app_languages.php b/core/user_settings/app_languages.php index 7bbab6086e..c051c837d8 100644 --- a/core/user_settings/app_languages.php +++ b/core/user_settings/app_languages.php @@ -1,1260 +1,1260 @@ - \ No newline at end of file diff --git a/core/user_settings/app_menu.php b/core/user_settings/app_menu.php index c5bfe6b731..30e26b4c10 100644 --- a/core/user_settings/app_menu.php +++ b/core/user_settings/app_menu.php @@ -1,43 +1,43 @@ - \ No newline at end of file diff --git a/core/users/app_config.php b/core/users/app_config.php index f47beab300..f17e8fda35 100644 --- a/core/users/app_config.php +++ b/core/users/app_config.php @@ -1,421 +1,421 @@ - + diff --git a/core/users/app_languages.php b/core/users/app_languages.php index d611d07d5c..45dec66a6a 100644 --- a/core/users/app_languages.php +++ b/core/users/app_languages.php @@ -1,1073 +1,1073 @@ - \ No newline at end of file diff --git a/core/users/app_menu.php b/core/users/app_menu.php index 86c7086ba4..60d2327b2c 100644 --- a/core/users/app_menu.php +++ b/core/users/app_menu.php @@ -1,36 +1,36 @@ - \ No newline at end of file diff --git a/core/users/groupedit.php b/core/users/groupedit.php index ce78bb6a0e..71e4d30cbb 100644 --- a/core/users/groupedit.php +++ b/core/users/groupedit.php @@ -1,312 +1,312 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2014 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; -require_once "resources/require.php"; - -//check permissions - require_once "resources/check_auth.php"; - if (permission_exists('group_edit')) { - //access allowed - } - else { - echo "access denied"; - return; - } - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//process update - if (count($_POST) > 0) { - //set the variables - $group_uuid = check_str($_POST['group_uuid']); - $group_name = check_str($_POST['group_name']); - $group_name_previous = check_str($_POST['group_name_previous']); - $domain_uuid = check_str($_POST["domain_uuid"]); - $domain_uuid_previous = check_str($_POST["domain_uuid_previous"]); - $group_description = check_str($_POST["group_description"]); - - //check for global/domain duplicates - $sql = "select count(*) as num_rows from v_groups where "; - $sql .= "group_name = '".$group_name."' "; - $sql .= "and group_uuid <> '".$group_uuid."' "; - $sql .= "and domain_uuid ".(($domain_uuid != '') ? " = '".$domain_uuid."' " : " is null "); - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - $group_exists = ($row['num_rows'] > 0) ? true : false; - } - else { - $group_exists = false; - } - unset($sql, $prep_statement, $row); - - //update group - if (!$group_exists) { - $sql = "update v_groups "; - $sql .= "set "; - $sql .= "group_name = '".$group_name."', "; - $sql .= "domain_uuid = ".(($domain_uuid != '') ? "'".$domain_uuid."'" : "null").", "; - $sql .= "group_description = '".$group_description."' "; - $sql .= "where group_uuid = '".$group_uuid."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - echo "
".print_r($error, true)."
"; - exit; - } - - //group changed from global to domain-specific - if ($domain_uuid_previous == '' && $domain_uuid != '') { - //remove any users assigned to the group from the old domain - $sql = "delete from v_group_users where group_uuid = '".$group_uuid."' and domain_uuid <> '".$domain_uuid."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - //update permissions to use new domain uuid - $sql = "update v_group_permissions set domain_uuid = '".$domain_uuid."' where group_name = '".$group_name_previous."' and domain_uuid is null "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - //change group name - if ($group_name != $group_name_previous && $group_name != '') { - //change group name in group users - $sql = "update v_group_users set group_name = '".$group_name."' where group_uuid = '".$group_uuid."' and group_name = '".$group_name_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - //change group name in permissions - $sql = "update v_group_permissions set group_name = '".$group_name."' where domain_uuid = '".$domain_uuid."' and group_name = '".$group_name_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - } - } - - //group changed from one domain to another - else if ($domain_uuid_previous != '' && $domain_uuid != '' && $domain_uuid_previous != $domain_uuid) { - //remove any users assigned to the group from the old domain - $sql = "delete from v_group_users where group_uuid = '".$group_uuid."' and domain_uuid = '".$domain_uuid_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - //update permissions to use new domain uuid - $sql = "update v_group_permissions set domain_uuid = '".$domain_uuid."' where group_name = '".$group_name_previous."' and domain_uuid = '".$domain_uuid_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - //change group name - if ($group_name != $group_name_previous && $group_name != '') { - //change group name in group users - $sql = "update v_group_users set group_name = '".$group_name."' where group_uuid = '".$group_uuid."' and group_name = '".$group_name_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - //change group name in permissions - $sql = "update v_group_permissions set group_name = '".$group_name."' where domain_uuid = '".$domain_uuid."' and group_name = '".$group_name_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - } - } - - //group changed from domain-specific to global - else if ($domain_uuid_previous != '' && $domain_uuid == '') { - //change group name - if ($group_name != $group_name_previous && $group_name != '') { - //change group name in group users - $sql = "update v_group_users set group_name = '".$group_name."' where group_uuid = '".$group_uuid."' and group_name = '".$group_name_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - //change group name in permissions - $sql = "update v_group_permissions set group_name = '".$group_name."' where domain_uuid = '".$domain_uuid_previous."' and group_name = '".$group_name_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - } - //update permissions to not use a domain uuid - $sql = "update v_group_permissions set domain_uuid = null where group_name = '".$group_name."' and domain_uuid = '".$domain_uuid_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - } - - //domain didn't change, but name may still - else { - //change group name - if ($group_name != $group_name_previous && $group_name != '') { - //change group name in group users - $sql = "update v_group_users set group_name = '".$group_name."' where group_uuid = '".$group_uuid."' and group_name = '".$group_name_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - //change group name in permissions - $sql = "update v_group_permissions set group_name = '".$group_name."' where domain_uuid ".(($domain_uuid != '') ? " = '".$domain_uuid."' " : " is null ")." and group_name = '".$group_name_previous."' "; - if (!$db->exec(check_sql($sql))) { - $error = $db->errorInfo(); - //echo "
".print_r($error, true)."
"; exit; - } - } - } - - $_SESSION["message"] = $text['message-update']; - header("Location: groups.php"); - } - else { - $_SESSION['message_mood'] = 'negative'; - $_SESSION["message"] = $text['message-group_exists']; - header("Location: groupedit.php?id=".$group_uuid); - } - - //redirect the user - return; - } - -//pre-populate the form - $group_uuid = check_str($_REQUEST['id']); - if ($group_uuid != '') { - $sql = "select * from v_groups where "; - $sql .= "group_uuid = '".$group_uuid."' "; - $prep_statement = $db->prepare($sql); - if ($prep_statement) { - $prep_statement->execute(); - $row = $prep_statement->fetch(PDO::FETCH_ASSOC); - $group_name = $row['group_name']; - $domain_uuid = $row['domain_uuid']; - $group_description = $row['group_description']; - } - } - -//include the header - include "resources/header.php"; - $document['title'] = $text['title-group_edit']; - -//copy group javascript - echo "\n"; - -//show the content - echo "
\n"; - echo "\n"; - - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " ".$text['header-group_edit']."\n"; - echo "

\n"; - echo " ".$text['description-group_edit']."\n"; - echo "
\n"; - echo " "; - echo " "; - echo " \n"; - echo "
\n"; - echo "
"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - if (permission_exists('group_domain')) { - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - } - else { - echo ""; - } - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - - echo "
\n"; - echo $text['label-group_name']."\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo " ".$text['label-domain']."\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo "
\n"; - echo $text['description-domain_name']."\n"; - echo "
\n"; - echo $text['label-group_description']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo "
"; - echo " \n"; - echo "
\n"; - echo "

"; - echo "
"; - -//include the footer - include "resources/footer.php"; - + + Portions created by the Initial Developer are Copyright (C) 2008-2014 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; +require_once "resources/require.php"; + +//check permissions + require_once "resources/check_auth.php"; + if (permission_exists('group_edit')) { + //access allowed + } + else { + echo "access denied"; + return; + } + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//process update + if (count($_POST) > 0) { + //set the variables + $group_uuid = check_str($_POST['group_uuid']); + $group_name = check_str($_POST['group_name']); + $group_name_previous = check_str($_POST['group_name_previous']); + $domain_uuid = check_str($_POST["domain_uuid"]); + $domain_uuid_previous = check_str($_POST["domain_uuid_previous"]); + $group_description = check_str($_POST["group_description"]); + + //check for global/domain duplicates + $sql = "select count(*) as num_rows from v_groups where "; + $sql .= "group_name = '".$group_name."' "; + $sql .= "and group_uuid <> '".$group_uuid."' "; + $sql .= "and domain_uuid ".(($domain_uuid != '') ? " = '".$domain_uuid."' " : " is null "); + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + $group_exists = ($row['num_rows'] > 0) ? true : false; + } + else { + $group_exists = false; + } + unset($sql, $prep_statement, $row); + + //update group + if (!$group_exists) { + $sql = "update v_groups "; + $sql .= "set "; + $sql .= "group_name = '".$group_name."', "; + $sql .= "domain_uuid = ".(($domain_uuid != '') ? "'".$domain_uuid."'" : "null").", "; + $sql .= "group_description = '".$group_description."' "; + $sql .= "where group_uuid = '".$group_uuid."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + echo "
".print_r($error, true)."
"; + exit; + } + + //group changed from global to domain-specific + if ($domain_uuid_previous == '' && $domain_uuid != '') { + //remove any users assigned to the group from the old domain + $sql = "delete from v_group_users where group_uuid = '".$group_uuid."' and domain_uuid <> '".$domain_uuid."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + //update permissions to use new domain uuid + $sql = "update v_group_permissions set domain_uuid = '".$domain_uuid."' where group_name = '".$group_name_previous."' and domain_uuid is null "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + //change group name + if ($group_name != $group_name_previous && $group_name != '') { + //change group name in group users + $sql = "update v_group_users set group_name = '".$group_name."' where group_uuid = '".$group_uuid."' and group_name = '".$group_name_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + //change group name in permissions + $sql = "update v_group_permissions set group_name = '".$group_name."' where domain_uuid = '".$domain_uuid."' and group_name = '".$group_name_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + } + } + + //group changed from one domain to another + else if ($domain_uuid_previous != '' && $domain_uuid != '' && $domain_uuid_previous != $domain_uuid) { + //remove any users assigned to the group from the old domain + $sql = "delete from v_group_users where group_uuid = '".$group_uuid."' and domain_uuid = '".$domain_uuid_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + //update permissions to use new domain uuid + $sql = "update v_group_permissions set domain_uuid = '".$domain_uuid."' where group_name = '".$group_name_previous."' and domain_uuid = '".$domain_uuid_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + //change group name + if ($group_name != $group_name_previous && $group_name != '') { + //change group name in group users + $sql = "update v_group_users set group_name = '".$group_name."' where group_uuid = '".$group_uuid."' and group_name = '".$group_name_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + //change group name in permissions + $sql = "update v_group_permissions set group_name = '".$group_name."' where domain_uuid = '".$domain_uuid."' and group_name = '".$group_name_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + } + } + + //group changed from domain-specific to global + else if ($domain_uuid_previous != '' && $domain_uuid == '') { + //change group name + if ($group_name != $group_name_previous && $group_name != '') { + //change group name in group users + $sql = "update v_group_users set group_name = '".$group_name."' where group_uuid = '".$group_uuid."' and group_name = '".$group_name_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + //change group name in permissions + $sql = "update v_group_permissions set group_name = '".$group_name."' where domain_uuid = '".$domain_uuid_previous."' and group_name = '".$group_name_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + } + //update permissions to not use a domain uuid + $sql = "update v_group_permissions set domain_uuid = null where group_name = '".$group_name."' and domain_uuid = '".$domain_uuid_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + } + + //domain didn't change, but name may still + else { + //change group name + if ($group_name != $group_name_previous && $group_name != '') { + //change group name in group users + $sql = "update v_group_users set group_name = '".$group_name."' where group_uuid = '".$group_uuid."' and group_name = '".$group_name_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + //change group name in permissions + $sql = "update v_group_permissions set group_name = '".$group_name."' where domain_uuid ".(($domain_uuid != '') ? " = '".$domain_uuid."' " : " is null ")." and group_name = '".$group_name_previous."' "; + if (!$db->exec(check_sql($sql))) { + $error = $db->errorInfo(); + //echo "
".print_r($error, true)."
"; exit; + } + } + } + + $_SESSION["message"] = $text['message-update']; + header("Location: groups.php"); + } + else { + $_SESSION['message_mood'] = 'negative'; + $_SESSION["message"] = $text['message-group_exists']; + header("Location: groupedit.php?id=".$group_uuid); + } + + //redirect the user + return; + } + +//pre-populate the form + $group_uuid = check_str($_REQUEST['id']); + if ($group_uuid != '') { + $sql = "select * from v_groups where "; + $sql .= "group_uuid = '".$group_uuid."' "; + $prep_statement = $db->prepare($sql); + if ($prep_statement) { + $prep_statement->execute(); + $row = $prep_statement->fetch(PDO::FETCH_ASSOC); + $group_name = $row['group_name']; + $domain_uuid = $row['domain_uuid']; + $group_description = $row['group_description']; + } + } + +//include the header + include "resources/header.php"; + $document['title'] = $text['title-group_edit']; + +//copy group javascript + echo "\n"; + +//show the content + echo "
\n"; + echo "\n"; + + echo "\n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " ".$text['header-group_edit']."\n"; + echo "

\n"; + echo " ".$text['description-group_edit']."\n"; + echo "
\n"; + echo " "; + echo " "; + echo " \n"; + echo "
\n"; + echo "
"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + if (permission_exists('group_domain')) { + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + } + else { + echo ""; + } + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + + echo "
\n"; + echo $text['label-group_name']."\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo " ".$text['label-domain']."\n"; + echo "\n"; + echo " \n"; + echo " \n"; + echo "
\n"; + echo $text['description-domain_name']."\n"; + echo "
\n"; + echo $text['label-group_description']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo "
"; + echo " \n"; + echo "
\n"; + echo "

"; + echo "
"; + +//include the footer + include "resources/footer.php"; + ?> \ No newline at end of file diff --git a/resources/app_languages.php b/resources/app_languages.php index 1390cf9203..9874bb920a 100644 --- a/resources/app_languages.php +++ b/resources/app_languages.php @@ -1,748 +1,748 @@ - \ No newline at end of file diff --git a/resources/classes/cache.php b/resources/classes/cache.php index 55fc8e039b..de1e8e44d5 100644 --- a/resources/classes/cache.php +++ b/resources/classes/cache.php @@ -1,139 +1,139 @@ - $value) { - unset($this->$key); - } - } - - /** - * Add a specific item in the cache - * @var string $key the cache id - * @var string $value string to be cached - */ - public function set($key, $value) { - // connect to event socket - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if ($fp === false) { - return false; - } - - //send a custom event - - //run the memcache - $command = "memcache set ".$key." ".$value; - $result = event_socket_request($fp, 'api '.$command); - - //close event socket - fclose($fp); - - // return result - return $result; - } - - /** - * Get a specific item from the cache - * @var string $key cache id - */ - public function get($key) { - // connect to event socket - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if ($fp === false) { - return false; - } - - //send a custom event - - //run the memcache - $command = "memcache get ".$key; - $result = event_socket_request($fp, 'api '.$command); - - //close event socket - fclose($fp); - - // return result - return $result; - } - - /** - * Delete a specific item from the cache - * @var string $key cache id - */ - public function delete($key) { - // connect to event socket - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if ($fp === false) { - return false; - } - - //send a custom event - $event = "sendevent CUSTOM\n"; - $event .= "Event-Name: MEMCACHE\n"; - $event .= "Event-Subclass: delete\n"; - $event .= "API-Command: memcache\n"; - $event .= "API-Command-Argument: delete ".$key."\n"; - event_socket_request($fp, $event); - - //run the memcache - $command = "memcache delete ".$key; - $result = event_socket_request($fp, 'api '.$command); - - //close event socket - fclose($fp); - - // return result - return $result; - } - - /** - * Delete the entire cache - */ - public function flush() { - // connect to event socket - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if ($fp === false) { - return false; - } - - //send a custom event - $event = "sendevent CUSTOM\n"; - $event .= "Event-Name: MEMCACHE\n"; - $event .= "Event-Subclass: flush\n"; - $event .= "API-Command: memcache\n"; - $event .= "API-Command-Argument: flush\n"; - event_socket_request($fp, $event); - - //run the memcache - $command = "memcache flush"; - $result = event_socket_request($fp, 'api '.$command); - - //close event socket - fclose($fp); - - // return result - return $result; - } -} - + $value) { + unset($this->$key); + } + } + + /** + * Add a specific item in the cache + * @var string $key the cache id + * @var string $value string to be cached + */ + public function set($key, $value) { + // connect to event socket + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if ($fp === false) { + return false; + } + + //send a custom event + + //run the memcache + $command = "memcache set ".$key." ".$value; + $result = event_socket_request($fp, 'api '.$command); + + //close event socket + fclose($fp); + + // return result + return $result; + } + + /** + * Get a specific item from the cache + * @var string $key cache id + */ + public function get($key) { + // connect to event socket + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if ($fp === false) { + return false; + } + + //send a custom event + + //run the memcache + $command = "memcache get ".$key; + $result = event_socket_request($fp, 'api '.$command); + + //close event socket + fclose($fp); + + // return result + return $result; + } + + /** + * Delete a specific item from the cache + * @var string $key cache id + */ + public function delete($key) { + // connect to event socket + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if ($fp === false) { + return false; + } + + //send a custom event + $event = "sendevent CUSTOM\n"; + $event .= "Event-Name: MEMCACHE\n"; + $event .= "Event-Subclass: delete\n"; + $event .= "API-Command: memcache\n"; + $event .= "API-Command-Argument: delete ".$key."\n"; + event_socket_request($fp, $event); + + //run the memcache + $command = "memcache delete ".$key; + $result = event_socket_request($fp, 'api '.$command); + + //close event socket + fclose($fp); + + // return result + return $result; + } + + /** + * Delete the entire cache + */ + public function flush() { + // connect to event socket + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if ($fp === false) { + return false; + } + + //send a custom event + $event = "sendevent CUSTOM\n"; + $event .= "Event-Name: MEMCACHE\n"; + $event .= "Event-Subclass: flush\n"; + $event .= "API-Command: memcache\n"; + $event .= "API-Command-Argument: flush\n"; + event_socket_request($fp, $event); + + //run the memcache + $command = "memcache flush"; + $result = event_socket_request($fp, 'api '.$command); + + //close event socket + fclose($fp); + + // return result + return $result; + } +} + ?> \ No newline at end of file diff --git a/resources/classes/config.php b/resources/classes/config.php index cc675d6933..a69f66de99 100644 --- a/resources/classes/config.php +++ b/resources/classes/config.php @@ -1,127 +1,127 @@ - $value) { - unset($this->$key); - } - } - - /** - * Determine whether the config.php exists - * @var string $db_type - type of database - * @var string $db_name - name of the database - * @var string $db_username - username to access the database - * @var string $db_password - password to access the database - * @var string $db_host - hostname of the database server - * @var string $db_path - path of the database file - * @var string $db_port - network port to connect to the database - */ - public function get() { - $this->find(); - if ($this->exists()) { - require $this->config_path; - $this->db_type = $db_type; - $this->db_name = $db_name; - $this->db_username = $db_username; - $this->db_password = $db_password; - $this->db_host = $db_host; - $this->db_path = $db_path; - $this->db_port = $db_port; - } - } - - /** - * Find the path to the config.php - * @var string $config_path - full path to the config.php file - */ - public function find() { - //get the PROJECT PATH - include "root.php"; - // find the file - if (file_exists($_SERVER["PROJECT_ROOT"]."/resources/config.php")) { - $this->config_path = $_SERVER["PROJECT_ROOT"]."/resources/config.php"; - } elseif (file_exists("/etc/fusionpbx/config.php")) { - $this->config_path = "/etc/fusionpbx/config.php"; - } elseif (file_exists("/usr/local/etc/fusionpbx/config.php")) { - $this->config_path = "/usr/local/etc/fusionpbx/config.php"; - } - else { - $this->config_path = ''; - } - //return the path - return $this->config_path; - } - - /** - * Determine whether the config.php exists - */ - public function exists() { - $this->find(); - if (strlen($this->config_path) > 0) { - return true; - } - else { - return false; - } - } -} -/* -$config = new config; -$config_exists = $config->exists(); -$config_path = $config->find(); -$config->get(); -$db_type = $config->db_type; -$db_name = $config->db_name; -$db_username = $config->db_username; -$db_password = $config->db_password; -$db_host = $config->db_host; -$db_path = $config->db_path; -$db_port = $config->db_port; -echo "config_path: ".$config_path."\n"; -if ($config_exists) { - echo "config_exists: true\n"; -} else { - echo "config_exists: false\n"; -} -echo "db_type: ".$db_type."\n"; -echo "db_name: ".$db_name."\n"; -echo "db_username: ".$db_username."\n"; -echo "db_password: ".$db_password."\n"; -echo "db_host: ".$db_host."\n"; -echo "db_path: ".$db_path."\n"; -echo "db_port: ".$db_port."\n"; -*/ - + $value) { + unset($this->$key); + } + } + + /** + * Determine whether the config.php exists + * @var string $db_type - type of database + * @var string $db_name - name of the database + * @var string $db_username - username to access the database + * @var string $db_password - password to access the database + * @var string $db_host - hostname of the database server + * @var string $db_path - path of the database file + * @var string $db_port - network port to connect to the database + */ + public function get() { + $this->find(); + if ($this->exists()) { + require $this->config_path; + $this->db_type = $db_type; + $this->db_name = $db_name; + $this->db_username = $db_username; + $this->db_password = $db_password; + $this->db_host = $db_host; + $this->db_path = $db_path; + $this->db_port = $db_port; + } + } + + /** + * Find the path to the config.php + * @var string $config_path - full path to the config.php file + */ + public function find() { + //get the PROJECT PATH + include "root.php"; + // find the file + if (file_exists($_SERVER["PROJECT_ROOT"]."/resources/config.php")) { + $this->config_path = $_SERVER["PROJECT_ROOT"]."/resources/config.php"; + } elseif (file_exists("/etc/fusionpbx/config.php")) { + $this->config_path = "/etc/fusionpbx/config.php"; + } elseif (file_exists("/usr/local/etc/fusionpbx/config.php")) { + $this->config_path = "/usr/local/etc/fusionpbx/config.php"; + } + else { + $this->config_path = ''; + } + //return the path + return $this->config_path; + } + + /** + * Determine whether the config.php exists + */ + public function exists() { + $this->find(); + if (strlen($this->config_path) > 0) { + return true; + } + else { + return false; + } + } +} +/* +$config = new config; +$config_exists = $config->exists(); +$config_path = $config->find(); +$config->get(); +$db_type = $config->db_type; +$db_name = $config->db_name; +$db_username = $config->db_username; +$db_password = $config->db_password; +$db_host = $config->db_host; +$db_path = $config->db_path; +$db_port = $config->db_port; +echo "config_path: ".$config_path."\n"; +if ($config_exists) { + echo "config_exists: true\n"; +} else { + echo "config_exists: false\n"; +} +echo "db_type: ".$db_type."\n"; +echo "db_name: ".$db_name."\n"; +echo "db_username: ".$db_username."\n"; +echo "db_password: ".$db_password."\n"; +echo "db_host: ".$db_host."\n"; +echo "db_path: ".$db_path."\n"; +echo "db_port: ".$db_port."\n"; +*/ + ?> \ No newline at end of file diff --git a/resources/classes/destinations.php b/resources/classes/destinations.php index 88c70cb76e..7b20b1e69d 100644 --- a/resources/classes/destinations.php +++ b/resources/classes/destinations.php @@ -1,280 +1,280 @@ - &$app) { - if (isset($app['destinations'])) foreach ($app['destinations'] as &$row) { - $this->destinations[] = $row; - } - } - - //put the array in order - foreach ($this->destinations as $row) { - $option_groups[] = $row['label']; - } - array_multisort($option_groups, SORT_ASC, $this->destinations); - - //add the sql and data to the array - $x = 0; - foreach ($this->destinations as $row) { - if ($row['type'] = 'sql') { - if (isset($row['sql'])) { - if (is_array($row['sql'])) { - $sql = trim($row['sql'][$db_type])." "; - } - else { - $sql = trim($row['sql'])." "; - } - } - else { - $field_count = count($row['field']); - $fields = ''; - $c = 1; - foreach ($row['field'] as $key => $value) { - if ($field_count != $c) { $delimiter = ','; } else { $delimiter = ''; } - $fields .= $value." as ".$key.$delimiter." "; - $c++; - } - $sql = "select ".$fields; - $sql .= " from v_".$row['name']." "; - } - if (isset($row['where'])) { - $sql .= trim($row['where'])." "; - } - $sql .= "order by ".trim($row['order_by']); - $sql = str_replace("\${domain_uuid}", $_SESSION['domain_uuid'], $sql); - $sql = trim($sql); - $statement = $db->prepare($sql); - $statement->execute(); - $result = $statement->fetchAll(PDO::FETCH_NAMED); - unset($statement); - - $this->destinations[$x]['result']['sql'] = $sql; - $this->destinations[$x]['result']['data'] = $result; - } - $x++; - } - $this->destinations[$x]['type'] = 'array'; - $this->destinations[$x]['label'] = 'other'; - $this->destinations[$x]['name'] = 'dialplan'; - $this->destinations[$x]['field']['name'] = "name"; - $this->destinations[$x]['field']['destination'] = "destination"; - $this->destinations[$x]['select_value']['dialplan'] = "transfer:\${destination}"; - $this->destinations[$x]['select_value']['ivr'] = "menu-exec-app:transfer \${destination}"; - $this->destinations[$x]['select_label'] = "\${name}"; - $y = 0; - $this->destinations[$x]['result']['data'][$y]['label'] = 'check_voicemail'; - $this->destinations[$x]['result']['data'][$y]['name'] = '*98'; - $this->destinations[$x]['result']['data'][$y]['destination'] = '*98 XML ${context}'; - $y++; - $this->destinations[$x]['result']['data'][$y]['label'] = 'company_directory'; - $this->destinations[$x]['result']['data'][$y]['name'] = '*411'; - $this->destinations[$x]['result']['data'][$y]['destination'] = '*411 XML ${context}'; - $y++; - $this->destinations[$x]['result']['data'][$y]['label'] = 'hangup'; - $this->destinations[$x]['result']['data'][$y]['name'] = 'hangup'; - $this->destinations[$x]['result']['data'][$y]['application'] = 'hangup'; - $this->destinations[$x]['result']['data'][$y]['destination'] = ''; - $y++; - $this->destinations[$x]['result']['data'][$y]['label'] = 'record'; - $this->destinations[$x]['result']['data'][$y]['name'] = '*732'; - $this->destinations[$x]['result']['data'][$y]['destination'] = '*732 XML ${context}'; - $y++; - } - - /** - * Called when there are no references to a particular object - * unset the variables used in the class - */ - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - /** - * Get the destination menu - * @var string $destination_type can be ivr, dialplan, call_center_contact or bridge - * @var string $destination_name - current name - * @var string $destination_value - current value - */ - public function select($destination_type, $destination_name, $destination_value) { - - //remove special characters from the name - $destination_id = str_replace("]", "", $destination_name); - $destination_id = str_replace("[", "_", $destination_id); - - //add additional - if (if_group("superadmin")) { - $response = "\n"; - $response .= "\n"; - } - - //set default to false - $select_found = false; - - $response .= " \n"; - if (if_group("superadmin")) { - $response .= ""; - } - - //return the formatted destinations - return $response; - } -} -/* -$obj = new destinations; -//$destinations = $obj->destinations; -echo $obj->select('ivr', 'example1', 'menu-exec-app:transfer 32 XML voip.fusionpbx.com'); -echo $obj->select('ivr', 'example2', ''); -echo $obj->select('ivr', 'example3', ''); -echo $obj->select('ivr', 'example4', ''); -echo $obj->select('ivr', 'example5', ''); -echo $obj->select('ivr', 'example6', ''); -*/ - -?> + &$app) { + if (isset($app['destinations'])) foreach ($app['destinations'] as &$row) { + $this->destinations[] = $row; + } + } + + //put the array in order + foreach ($this->destinations as $row) { + $option_groups[] = $row['label']; + } + array_multisort($option_groups, SORT_ASC, $this->destinations); + + //add the sql and data to the array + $x = 0; + foreach ($this->destinations as $row) { + if ($row['type'] = 'sql') { + if (isset($row['sql'])) { + if (is_array($row['sql'])) { + $sql = trim($row['sql'][$db_type])." "; + } + else { + $sql = trim($row['sql'])." "; + } + } + else { + $field_count = count($row['field']); + $fields = ''; + $c = 1; + foreach ($row['field'] as $key => $value) { + if ($field_count != $c) { $delimiter = ','; } else { $delimiter = ''; } + $fields .= $value." as ".$key.$delimiter." "; + $c++; + } + $sql = "select ".$fields; + $sql .= " from v_".$row['name']." "; + } + if (isset($row['where'])) { + $sql .= trim($row['where'])." "; + } + $sql .= "order by ".trim($row['order_by']); + $sql = str_replace("\${domain_uuid}", $_SESSION['domain_uuid'], $sql); + $sql = trim($sql); + $statement = $db->prepare($sql); + $statement->execute(); + $result = $statement->fetchAll(PDO::FETCH_NAMED); + unset($statement); + + $this->destinations[$x]['result']['sql'] = $sql; + $this->destinations[$x]['result']['data'] = $result; + } + $x++; + } + $this->destinations[$x]['type'] = 'array'; + $this->destinations[$x]['label'] = 'other'; + $this->destinations[$x]['name'] = 'dialplan'; + $this->destinations[$x]['field']['name'] = "name"; + $this->destinations[$x]['field']['destination'] = "destination"; + $this->destinations[$x]['select_value']['dialplan'] = "transfer:\${destination}"; + $this->destinations[$x]['select_value']['ivr'] = "menu-exec-app:transfer \${destination}"; + $this->destinations[$x]['select_label'] = "\${name}"; + $y = 0; + $this->destinations[$x]['result']['data'][$y]['label'] = 'check_voicemail'; + $this->destinations[$x]['result']['data'][$y]['name'] = '*98'; + $this->destinations[$x]['result']['data'][$y]['destination'] = '*98 XML ${context}'; + $y++; + $this->destinations[$x]['result']['data'][$y]['label'] = 'company_directory'; + $this->destinations[$x]['result']['data'][$y]['name'] = '*411'; + $this->destinations[$x]['result']['data'][$y]['destination'] = '*411 XML ${context}'; + $y++; + $this->destinations[$x]['result']['data'][$y]['label'] = 'hangup'; + $this->destinations[$x]['result']['data'][$y]['name'] = 'hangup'; + $this->destinations[$x]['result']['data'][$y]['application'] = 'hangup'; + $this->destinations[$x]['result']['data'][$y]['destination'] = ''; + $y++; + $this->destinations[$x]['result']['data'][$y]['label'] = 'record'; + $this->destinations[$x]['result']['data'][$y]['name'] = '*732'; + $this->destinations[$x]['result']['data'][$y]['destination'] = '*732 XML ${context}'; + $y++; + } + + /** + * Called when there are no references to a particular object + * unset the variables used in the class + */ + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + /** + * Get the destination menu + * @var string $destination_type can be ivr, dialplan, call_center_contact or bridge + * @var string $destination_name - current name + * @var string $destination_value - current value + */ + public function select($destination_type, $destination_name, $destination_value) { + + //remove special characters from the name + $destination_id = str_replace("]", "", $destination_name); + $destination_id = str_replace("[", "_", $destination_id); + + //add additional + if (if_group("superadmin")) { + $response = "\n"; + $response .= "\n"; + } + + //set default to false + $select_found = false; + + $response .= " \n"; + if (if_group("superadmin")) { + $response .= ""; + } + + //return the formatted destinations + return $response; + } +} +/* +$obj = new destinations; +//$destinations = $obj->destinations; +echo $obj->select('ivr', 'example1', 'menu-exec-app:transfer 32 XML voip.fusionpbx.com'); +echo $obj->select('ivr', 'example2', ''); +echo $obj->select('ivr', 'example3', ''); +echo $obj->select('ivr', 'example4', ''); +echo $obj->select('ivr', 'example5', ''); +echo $obj->select('ivr', 'example6', ''); +*/ + +?> diff --git a/resources/classes/event_socket.php b/resources/classes/event_socket.php index 13ad5048ad..101bc5b738 100644 --- a/resources/classes/event_socket.php +++ b/resources/classes/event_socket.php @@ -1,195 +1,195 @@ -content = ''; - $this->eol = "\n"; - } - - public function append($str) { - $this->content .= $str; - } - - public function read_line() { - $ar = explode($this->eol, $this->content, 2); - if (count($ar) != 2) { - return false; - } - $this->content = $ar[1]; - return $ar[0]; - } - - public function read_n($n) { - if (strlen($this->content) < $n) { - return false; - } - $s = substr($this->content, 0, $n); - $this->content = substr($this->content, $n); - return $s; - } - - public function read_all($n) { - $tmp = $this->content; - $this->content = ''; - return $tmp; - } -} -//$b = new buffer; -//$b->append("hello\nworld\n"); -//print($b->read_line()); -//print($b->read_line()); - -class event_socket { - private $buffer; - private $fp; - - public function __construct($fp = false) { - $this->buffer = new buffer; - $this->fp = $fp; - } - - public function __destructor() { - $this->close(); - } - - public function read_event() { - if (!$this->fp) { - return false; - } - - $b = $this->buffer; - $content_length = 0; - $content = Array(); - - while (true) { - while(($line = $b->read_line()) !== false ) { - if ($line == '') { - break 2; - } - $kv = explode(':', $line, 2); - $content[trim($kv[0])] = trim($kv[1]); - } - usleep(100); - - if (feof($this->fp)) { - break; - } - - $buffer = fgets($this->fp, 1024); - $b->append($buffer); - } - - if (array_key_exists('Content-Length', $content)) { - $str = $b->read_n($content['Content-Length']); - if ($str === false) { - while (!feof($this->fp)) { - $buffer = fgets($this->fp, 1024); - $b->append($buffer); - $str = $b->read_n($content['Content-Length']); - if ($str !== false) { - break; - } - } - } - if ($str !== false) { - $content['$'] = $str; - } - } - - return $content; - } - - public function connect($host, $port, $password) { - $fp = fsockopen($host, $port, $errno, $errdesc, 3); - - if (!$fp) { - return false; - } - - socket_set_blocking($fp, false); - $this->fp = $fp; - - // 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; - } - } - - // 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; - } - } - - return false; - } - - public function request($cmd) { - if (!$this->fp) { - return false; - } - - $cmd_array = explode("\n", $cmd); - foreach ($cmd_array as &$value) { - fputs($this->fp, $value."\n"); - } - fputs($this->fp, "\n"); //second line feed to end the headers - - $event = $this->read_event(); - - if (array_key_exists('$', $event)) { - return $event['$']; - } - return $event; - } - - public function reset_fp($fp = false){ - $tmp = $this->fp; - $this->fp = $fp; - return $tmp; - } - - public function close() { - if ($this->fp) { - fclose($fp->fp); - $this->fp = false; - } - } -} - -/* -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'); -// print($esl->request('api sofia status')); - -// $fp = event_socket_create('127.0.0.1', 8021, 'ClueCon'); -// print(event_socket_request($fp, 'api sofia status')); +content = ''; + $this->eol = "\n"; + } + + public function append($str) { + $this->content .= $str; + } + + public function read_line() { + $ar = explode($this->eol, $this->content, 2); + if (count($ar) != 2) { + return false; + } + $this->content = $ar[1]; + return $ar[0]; + } + + public function read_n($n) { + if (strlen($this->content) < $n) { + return false; + } + $s = substr($this->content, 0, $n); + $this->content = substr($this->content, $n); + return $s; + } + + public function read_all($n) { + $tmp = $this->content; + $this->content = ''; + return $tmp; + } +} +//$b = new buffer; +//$b->append("hello\nworld\n"); +//print($b->read_line()); +//print($b->read_line()); + +class event_socket { + private $buffer; + private $fp; + + public function __construct($fp = false) { + $this->buffer = new buffer; + $this->fp = $fp; + } + + public function __destructor() { + $this->close(); + } + + public function read_event() { + if (!$this->fp) { + return false; + } + + $b = $this->buffer; + $content_length = 0; + $content = Array(); + + while (true) { + while(($line = $b->read_line()) !== false ) { + if ($line == '') { + break 2; + } + $kv = explode(':', $line, 2); + $content[trim($kv[0])] = trim($kv[1]); + } + usleep(100); + + if (feof($this->fp)) { + break; + } + + $buffer = fgets($this->fp, 1024); + $b->append($buffer); + } + + if (array_key_exists('Content-Length', $content)) { + $str = $b->read_n($content['Content-Length']); + if ($str === false) { + while (!feof($this->fp)) { + $buffer = fgets($this->fp, 1024); + $b->append($buffer); + $str = $b->read_n($content['Content-Length']); + if ($str !== false) { + break; + } + } + } + if ($str !== false) { + $content['$'] = $str; + } + } + + return $content; + } + + public function connect($host, $port, $password) { + $fp = fsockopen($host, $port, $errno, $errdesc, 3); + + if (!$fp) { + return false; + } + + socket_set_blocking($fp, false); + $this->fp = $fp; + + // 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; + } + } + + // 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; + } + } + + return false; + } + + public function request($cmd) { + if (!$this->fp) { + return false; + } + + $cmd_array = explode("\n", $cmd); + foreach ($cmd_array as &$value) { + fputs($this->fp, $value."\n"); + } + fputs($this->fp, "\n"); //second line feed to end the headers + + $event = $this->read_event(); + + if (array_key_exists('$', $event)) { + return $event['$']; + } + return $event; + } + + public function reset_fp($fp = false){ + $tmp = $this->fp; + $this->fp = $fp; + return $tmp; + } + + public function close() { + if ($this->fp) { + fclose($fp->fp); + $this->fp = false; + } + } +} + +/* +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'); +// 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/groups.php b/resources/classes/groups.php index aeb719e64e..caa09ba60f 100644 --- a/resources/classes/groups.php +++ b/resources/classes/groups.php @@ -1,191 +1,191 @@ - - Portions created by the Initial Developer are Copyright (C) 2016 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - - -/** - * groups class provides methods for add, delete groups, and add default groups - * - * @method string add - * @method boolean delete - * @method boolean defaults - */ -if (!class_exists('groups')) { - class groups { - - public $db; - - /** - * Called when the object is created - */ - public function __construct() { - //connect to the database if not connected - if (!$this->db) { - require_once "resources/classes/database.php"; - $database = new database; - $database->connect(); - $this->db = $database->db; - } - } - - /** - * Called when there are no references to a particular object - * unset the variables used in the class - */ - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - /** - * add a group - */ - public function add() { - $id = uuid(); - //return $id; - return false; - } - - /** - * delete a group - */ - public function delete($id) { - return false; - } - - /** - * add defaults groups - */ - public function defaults() { - - //if the are no groups add the default groups - $sql = "SELECT * FROM v_groups "; - $sql .= "WHERE domain_uuid is null "; - $result = $this->db->query($sql)->fetch(); - $prep_statement = $this->db->prepare(check_sql($sql)); - if ($prep_statement) { - $prep_statement->execute(); - $result = $prep_statement->fetchAll(PDO::FETCH_ASSOC); - if (count($result) == 0) { - $x = 0; - $tmp[$x]['group_name'] = 'superadmin'; - $tmp[$x]['group_description'] = 'Super Administrator Group'; - $tmp[$x]['group_protected'] = 'false'; - $x++; - $tmp[$x]['group_name'] = 'admin'; - $tmp[$x]['group_description'] = 'Administrator Group'; - $tmp[$x]['group_protected'] = 'false'; - $x++; - $tmp[$x]['group_name'] = 'user'; - $tmp[$x]['group_description'] = 'User Group'; - $tmp[$x]['group_protected'] = 'false'; - $x++; - $tmp[$x]['group_name'] = 'public'; - $tmp[$x]['group_description'] = 'Public Group'; - $tmp[$x]['group_protected'] = 'false'; - $x++; - $tmp[$x]['group_name'] = 'agent'; - $tmp[$x]['group_description'] = 'Call Center Agent Group'; - $tmp[$x]['group_protected'] = 'false'; - $this->db->beginTransaction(); - foreach($tmp as $row) { - if (strlen($row['group_name']) > 0) { - $sql = "insert into v_groups "; - $sql .= "("; - $sql .= "domain_uuid, "; - $sql .= "group_uuid, "; - $sql .= "group_name, "; - $sql .= "group_description, "; - $sql .= "group_protected "; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "null, "; - $sql .= "'".uuid()."', "; - $sql .= "'".$row['group_name']."', "; - $sql .= "'".$row['group_description']."', "; - $sql .= "'".$row['group_protected']."' "; - $sql .= ")"; - $this->db->exec($sql); - unset($sql); - } - } - $this->db->commit(); - } - unset($prep_statement, $result); - } - - //if there are no permissions listed in v_group_permissions then set the default permissions - $sql = "select count(*) as count from v_group_permissions "; - $sql .= "where domain_uuid is null "; - $prep_statement = $this->db->prepare($sql); - $prep_statement->execute(); - $result = $prep_statement->fetch(PDO::FETCH_ASSOC); - unset ($prep_statement); - if ($result['count'] == 0) { - //build the apps array - $config_list = glob($_SERVER["DOCUMENT_ROOT"] . PROJECT_PATH . "/*/*/app_config.php"); - $x = 0; - foreach ($config_list as &$config_path) { - include($config_path); - $x++; - } - //no permissions found add the defaults - $this->db->beginTransaction(); - foreach($apps as $app) { - foreach ($app['permissions'] as $row) { - foreach ($row['groups'] as $group) { - //add the record - $sql = "insert into v_group_permissions "; - $sql .= "("; - $sql .= "group_permission_uuid, "; - $sql .= "domain_uuid, "; - $sql .= "permission_name, "; - $sql .= "group_name "; - $sql .= ")"; - $sql .= "values "; - $sql .= "("; - $sql .= "'".uuid()."', "; - $sql .= "null, "; - $sql .= "'".$row['name']."', "; - $sql .= "'".$group."' "; - $sql .= ")"; - $this->db->exec($sql); - unset($sql); - } - } - } - $this->db->commit(); - } - } - } //end scripts class -} -/* -//example use - $group = new groups; - $group->defaults(); -*/ + + Portions created by the Initial Developer are Copyright (C) 2016 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + + +/** + * groups class provides methods for add, delete groups, and add default groups + * + * @method string add + * @method boolean delete + * @method boolean defaults + */ +if (!class_exists('groups')) { + class groups { + + public $db; + + /** + * Called when the object is created + */ + public function __construct() { + //connect to the database if not connected + if (!$this->db) { + require_once "resources/classes/database.php"; + $database = new database; + $database->connect(); + $this->db = $database->db; + } + } + + /** + * Called when there are no references to a particular object + * unset the variables used in the class + */ + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + /** + * add a group + */ + public function add() { + $id = uuid(); + //return $id; + return false; + } + + /** + * delete a group + */ + public function delete($id) { + return false; + } + + /** + * add defaults groups + */ + public function defaults() { + + //if the are no groups add the default groups + $sql = "SELECT * FROM v_groups "; + $sql .= "WHERE domain_uuid is null "; + $result = $this->db->query($sql)->fetch(); + $prep_statement = $this->db->prepare(check_sql($sql)); + if ($prep_statement) { + $prep_statement->execute(); + $result = $prep_statement->fetchAll(PDO::FETCH_ASSOC); + if (count($result) == 0) { + $x = 0; + $tmp[$x]['group_name'] = 'superadmin'; + $tmp[$x]['group_description'] = 'Super Administrator Group'; + $tmp[$x]['group_protected'] = 'false'; + $x++; + $tmp[$x]['group_name'] = 'admin'; + $tmp[$x]['group_description'] = 'Administrator Group'; + $tmp[$x]['group_protected'] = 'false'; + $x++; + $tmp[$x]['group_name'] = 'user'; + $tmp[$x]['group_description'] = 'User Group'; + $tmp[$x]['group_protected'] = 'false'; + $x++; + $tmp[$x]['group_name'] = 'public'; + $tmp[$x]['group_description'] = 'Public Group'; + $tmp[$x]['group_protected'] = 'false'; + $x++; + $tmp[$x]['group_name'] = 'agent'; + $tmp[$x]['group_description'] = 'Call Center Agent Group'; + $tmp[$x]['group_protected'] = 'false'; + $this->db->beginTransaction(); + foreach($tmp as $row) { + if (strlen($row['group_name']) > 0) { + $sql = "insert into v_groups "; + $sql .= "("; + $sql .= "domain_uuid, "; + $sql .= "group_uuid, "; + $sql .= "group_name, "; + $sql .= "group_description, "; + $sql .= "group_protected "; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "null, "; + $sql .= "'".uuid()."', "; + $sql .= "'".$row['group_name']."', "; + $sql .= "'".$row['group_description']."', "; + $sql .= "'".$row['group_protected']."' "; + $sql .= ")"; + $this->db->exec($sql); + unset($sql); + } + } + $this->db->commit(); + } + unset($prep_statement, $result); + } + + //if there are no permissions listed in v_group_permissions then set the default permissions + $sql = "select count(*) as count from v_group_permissions "; + $sql .= "where domain_uuid is null "; + $prep_statement = $this->db->prepare($sql); + $prep_statement->execute(); + $result = $prep_statement->fetch(PDO::FETCH_ASSOC); + unset ($prep_statement); + if ($result['count'] == 0) { + //build the apps array + $config_list = glob($_SERVER["DOCUMENT_ROOT"] . PROJECT_PATH . "/*/*/app_config.php"); + $x = 0; + foreach ($config_list as &$config_path) { + include($config_path); + $x++; + } + //no permissions found add the defaults + $this->db->beginTransaction(); + foreach($apps as $app) { + foreach ($app['permissions'] as $row) { + foreach ($row['groups'] as $group) { + //add the record + $sql = "insert into v_group_permissions "; + $sql .= "("; + $sql .= "group_permission_uuid, "; + $sql .= "domain_uuid, "; + $sql .= "permission_name, "; + $sql .= "group_name "; + $sql .= ")"; + $sql .= "values "; + $sql .= "("; + $sql .= "'".uuid()."', "; + $sql .= "null, "; + $sql .= "'".$row['name']."', "; + $sql .= "'".$group."' "; + $sql .= ")"; + $this->db->exec($sql); + unset($sql); + } + } + } + $this->db->commit(); + } + } + } //end scripts class +} +/* +//example use + $group = new groups; + $group->defaults(); +*/ ?> \ No newline at end of file diff --git a/resources/classes/permissions.php b/resources/classes/permissions.php index c1ea8ee84a..2e426ac14a 100644 --- a/resources/classes/permissions.php +++ b/resources/classes/permissions.php @@ -1,105 +1,105 @@ - - Copyright (C) 2015 All Rights Reserved. - -*/ - -/** - * permission class - * - * @method string add - * @method string delete - * @method string exists - */ - if (!class_exists('permissions')) { - class permissions { - - /** - * Add a permission - * @var string $permission - */ - public function add($permission, $type = '') { - if (!$this->exists($permission)) { - //set the ordinal number - $i = count($_SESSION["permissions"])+1; - - //set the permission - $_SESSION["permissions"][$i]["permission_name"] = $permission; - $_SESSION["permissions"][$i]["permission_type"] = "temp"; - } - } - - /** - * Remove the permission - * @var string $permission - */ - public function delete($permission, $type = '') { - if ($this->exists($permission)) { - foreach($_SESSION["permissions"] as $key => $row) { - if ($row['permission_name'] == $permission) { - if ($row['permission_name'] == $permission) { - if ($type == 'temp') { - if ($row['permission_type'] == "temp") { - unset($_SESSION["permissions"][$key]); - } - } - else { - unset($_SESSION["permissions"][$key]); - } - } - break; - } - } - } - } - - /** - * Check to see if the permission exists - * @var string $permission - */ - function exists($permission) { - //set default false - $result = false; - //search for the permission - if (count($_SESSION["permissions"]) > 0) { - foreach($_SESSION["permissions"] as $row) { - if ($row['permission_name'] == $permission) { - $result = true; - break; - } - } - } - //return the result - return $result; - } - } - } - - //examples - /* - //add the permission - $p = new permissions; - $p->add($permission); - //delete the permission - $p = new permissions; - $p->delete($permission); - */ - + + Copyright (C) 2015 All Rights Reserved. + +*/ + +/** + * permission class + * + * @method string add + * @method string delete + * @method string exists + */ + if (!class_exists('permissions')) { + class permissions { + + /** + * Add a permission + * @var string $permission + */ + public function add($permission, $type = '') { + if (!$this->exists($permission)) { + //set the ordinal number + $i = count($_SESSION["permissions"])+1; + + //set the permission + $_SESSION["permissions"][$i]["permission_name"] = $permission; + $_SESSION["permissions"][$i]["permission_type"] = "temp"; + } + } + + /** + * Remove the permission + * @var string $permission + */ + public function delete($permission, $type = '') { + if ($this->exists($permission)) { + foreach($_SESSION["permissions"] as $key => $row) { + if ($row['permission_name'] == $permission) { + if ($row['permission_name'] == $permission) { + if ($type == 'temp') { + if ($row['permission_type'] == "temp") { + unset($_SESSION["permissions"][$key]); + } + } + else { + unset($_SESSION["permissions"][$key]); + } + } + break; + } + } + } + } + + /** + * Check to see if the permission exists + * @var string $permission + */ + function exists($permission) { + //set default false + $result = false; + //search for the permission + if (count($_SESSION["permissions"]) > 0) { + foreach($_SESSION["permissions"] as $row) { + if ($row['permission_name'] == $permission) { + $result = true; + break; + } + } + } + //return the result + return $result; + } + } + } + + //examples + /* + //add the permission + $p = new permissions; + $p->add($permission); + //delete the permission + $p = new permissions; + $p->delete($permission); + */ + ?> \ No newline at end of file diff --git a/resources/classes/switch_settings.php b/resources/classes/switch_settings.php index c0bd743708..070744b2e6 100644 --- a/resources/classes/switch_settings.php +++ b/resources/classes/switch_settings.php @@ -1,286 +1,286 @@ -db) { - require_once "resources/classes/database.php"; - $database = new database; - $database->connect(); - $this->db = $database->db; - } - } - - /** - * Called when there are no references to a particular object - * unset the variables used in the class - */ - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - /** - * settings Set switch directories in default settings - */ - public function settings() { - - //define the variables - if (!isset($this->event_socket_ip_address)) { - if (strlen($_SESSION['event_socket_ip_address']) > 0) { - $this->event_socket_ip_address = $_SESSION['event_socket_ip_address']; - } - else { - $this->event_socket_ip_address = '127.0.0.1'; - } - } - if (!isset($this->event_socket_port)) { - if (strlen($_SESSION['event_socket_ip_address']) > 0) { - $this->event_socket_port = $_SESSION['event_socket_port']; - } - else { - $this->event_socket_port = '8021'; - } - } - if (!isset($this->event_socket_password)) { - if (strlen($_SESSION['event_socket_ip_address']) > 0) { - $this->event_socket_password = $_SESSION['event_socket_password']; - } - else { - $this->event_socket_password = 'ClueCon'; - } - } - - { //connect to event socket - $esl = new event_socket; - $esl->connect($this->event_socket_ip_address, $this->event_socket_port, $this->event_socket_password); - - //run the api command - $result = $esl->request('api global_getvar'); - } //close event socket - - - //set the result as a named array - $vars = array(); - foreach (explode("\n", $result) as $row) { - $a = explode("=", $row); - if (substr($a[0], -4) == "_dir") { - $vars[$a[0]] = $a[1]; - } - } - - //set the bin directory - if ($vars['base_dir'] == "/usr/local/freeswitch") { - $bin = "/usr/local/freeswitch/bin"; - } else { - $bin = ""; - } - - //create the default settings array - $x=0; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'bin'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $bin; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'base'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['base_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'call_center'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['conf_dir'].'/autoload_configs'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'conf'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['conf_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'db'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['db_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'dialplan'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['conf_dir'].'/dialplan'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'extensions'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['conf_dir'].'/directory'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'grammar'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['grammar_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'log'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['log_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'mod'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['mod_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'phrases'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['conf_dir'].'/lang'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'recordings'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['recordings_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'scripts'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['script_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'sip_profiles'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['conf_dir'].'/sip_profiles'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'sounds'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['sounds_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'storage'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['storage_dir']; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - $array[$x]['default_setting_category'] = 'switch'; - $array[$x]['default_setting_subcategory'] = 'voicemail'; - $array[$x]['default_setting_name'] = 'dir'; - $array[$x]['default_setting_value'] = $vars['storage_dir'].'/voicemail'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = ''; - $x++; - - //get an array of the default settings - $sql = "select * from v_default_settings "; - $sql .= "where default_setting_category = 'switch' "; - $prep_statement = $this->db->prepare($sql); - $prep_statement->execute(); - $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - - //find the missing default settings - $x = 0; - foreach ($array as $setting) { - $found = false; - $missing[$x] = $setting; - foreach ($default_settings as $row) { - if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { - $found = true; - //remove items from the array that were found - unset($missing[$x]); - } - } - $x++; - } - - //add the missing default settings - if (is_array($missing)) { - $sql = "insert into v_default_settings ("; - $sql .= "default_setting_uuid, "; - $sql .= "default_setting_category, "; - $sql .= "default_setting_subcategory, "; - $sql .= "default_setting_name, "; - $sql .= "default_setting_value, "; - $sql .= "default_setting_enabled, "; - $sql .= "default_setting_description "; - $sql .= ") values \n"; - $i = 1; - foreach ($missing as $row) { - $sql .= "("; - $sql .= "'".uuid()."', "; - $sql .= "'".check_str($row['default_setting_category'])."', "; - $sql .= "'".check_str($row['default_setting_subcategory'])."', "; - $sql .= "'".check_str($row['default_setting_name'])."', "; - $sql .= "'".check_str($row['default_setting_value'])."', "; - $sql .= "'".check_str($row['default_setting_enabled'])."', "; - $sql .= "'".check_str($row['default_setting_description'])."' "; - $sql .= ")"; - if (sizeof($missing) != $i) { - $sql .= ",\n"; - } - $i++; - } - $this->db->exec(check_sql($sql)); - unset($missing); - } - - //set the default settings - foreach ($array as $row) { - if (!isset($_SESSION['switch'][$row['default_setting_subcategory']])) { - if ($row['default_setting_enabled'] != "false") { - $_SESSION['switch'][$row['default_setting_subcategory']] = $row['default_setting_value']; - } - } - } - - //unset the array variable - unset($array); - } - } -} - -?> +db) { + require_once "resources/classes/database.php"; + $database = new database; + $database->connect(); + $this->db = $database->db; + } + } + + /** + * Called when there are no references to a particular object + * unset the variables used in the class + */ + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + /** + * settings Set switch directories in default settings + */ + public function settings() { + + //define the variables + if (!isset($this->event_socket_ip_address)) { + if (strlen($_SESSION['event_socket_ip_address']) > 0) { + $this->event_socket_ip_address = $_SESSION['event_socket_ip_address']; + } + else { + $this->event_socket_ip_address = '127.0.0.1'; + } + } + if (!isset($this->event_socket_port)) { + if (strlen($_SESSION['event_socket_ip_address']) > 0) { + $this->event_socket_port = $_SESSION['event_socket_port']; + } + else { + $this->event_socket_port = '8021'; + } + } + if (!isset($this->event_socket_password)) { + if (strlen($_SESSION['event_socket_ip_address']) > 0) { + $this->event_socket_password = $_SESSION['event_socket_password']; + } + else { + $this->event_socket_password = 'ClueCon'; + } + } + + { //connect to event socket + $esl = new event_socket; + $esl->connect($this->event_socket_ip_address, $this->event_socket_port, $this->event_socket_password); + + //run the api command + $result = $esl->request('api global_getvar'); + } //close event socket + + + //set the result as a named array + $vars = array(); + foreach (explode("\n", $result) as $row) { + $a = explode("=", $row); + if (substr($a[0], -4) == "_dir") { + $vars[$a[0]] = $a[1]; + } + } + + //set the bin directory + if ($vars['base_dir'] == "/usr/local/freeswitch") { + $bin = "/usr/local/freeswitch/bin"; + } else { + $bin = ""; + } + + //create the default settings array + $x=0; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'bin'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $bin; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'base'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['base_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'call_center'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['conf_dir'].'/autoload_configs'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'conf'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['conf_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'db'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['db_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'dialplan'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['conf_dir'].'/dialplan'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'extensions'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['conf_dir'].'/directory'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'grammar'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['grammar_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'log'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['log_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'mod'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['mod_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'phrases'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['conf_dir'].'/lang'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'recordings'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['recordings_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'scripts'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['script_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'sip_profiles'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['conf_dir'].'/sip_profiles'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'sounds'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['sounds_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'storage'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['storage_dir']; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + $array[$x]['default_setting_category'] = 'switch'; + $array[$x]['default_setting_subcategory'] = 'voicemail'; + $array[$x]['default_setting_name'] = 'dir'; + $array[$x]['default_setting_value'] = $vars['storage_dir'].'/voicemail'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = ''; + $x++; + + //get an array of the default settings + $sql = "select * from v_default_settings "; + $sql .= "where default_setting_category = 'switch' "; + $prep_statement = $this->db->prepare($sql); + $prep_statement->execute(); + $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + + //find the missing default settings + $x = 0; + foreach ($array as $setting) { + $found = false; + $missing[$x] = $setting; + foreach ($default_settings as $row) { + if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { + $found = true; + //remove items from the array that were found + unset($missing[$x]); + } + } + $x++; + } + + //add the missing default settings + if (is_array($missing)) { + $sql = "insert into v_default_settings ("; + $sql .= "default_setting_uuid, "; + $sql .= "default_setting_category, "; + $sql .= "default_setting_subcategory, "; + $sql .= "default_setting_name, "; + $sql .= "default_setting_value, "; + $sql .= "default_setting_enabled, "; + $sql .= "default_setting_description "; + $sql .= ") values \n"; + $i = 1; + foreach ($missing as $row) { + $sql .= "("; + $sql .= "'".uuid()."', "; + $sql .= "'".check_str($row['default_setting_category'])."', "; + $sql .= "'".check_str($row['default_setting_subcategory'])."', "; + $sql .= "'".check_str($row['default_setting_name'])."', "; + $sql .= "'".check_str($row['default_setting_value'])."', "; + $sql .= "'".check_str($row['default_setting_enabled'])."', "; + $sql .= "'".check_str($row['default_setting_description'])."' "; + $sql .= ")"; + if (sizeof($missing) != $i) { + $sql .= ",\n"; + } + $i++; + } + $this->db->exec(check_sql($sql)); + unset($missing); + } + + //set the default settings + foreach ($array as $row) { + if (!isset($_SESSION['switch'][$row['default_setting_subcategory']])) { + if ($row['default_setting_enabled'] != "false") { + $_SESSION['switch'][$row['default_setting_subcategory']] = $row['default_setting_value']; + } + } + } + + //unset the array variable + unset($array); + } + } +} + +?> diff --git a/resources/classes/template.php b/resources/classes/template.php index 5595cf3861..ef310b4699 100644 --- a/resources/classes/template.php +++ b/resources/classes/template.php @@ -1,101 +1,101 @@ - - Copyright (C) 2013 - All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ -include "root.php"; - -//define the template class - if (!class_exists('template')) { - class template { - - public $engine; - public $template_dir; - public $cache_dir; - private $object; - private $var_array; - - public function __construct(){ - } - - public function init() { - if ($this->engine === 'smarty') { - require_once "resources/templates/engine/smarty/Smarty.class.php"; - $this->object = new Smarty(); - $this->object->setTemplateDir($this->template_dir); - $this->object->setCompileDir($this->cache_dir); - $this->object->setCacheDir($this->cache_dir); - } - if ($this->engine === 'raintpl') { - require_once "resources/templates/engine/raintpl/rain.tpl.class.php"; - $this->object = new RainTPL(); - RainTPL::configure('tpl_dir', realpath($this->template_dir)."/"); - RainTPL::configure('cache_dir', realpath($this->cache_dir)."/"); - } - if ($this->engine === 'twig') { - require_once "resources/templates/engine/Twig/Autoloader.php"; - Twig_Autoloader::register(); - $loader = new Twig_Loader_Filesystem($this->template_dir); - $this->object = new Twig_Environment($loader); - $lexer = new Twig_Lexer($this->object, array( - 'tag_comment' => array('{*', '*}'), - 'tag_block' => array('{', '}'), - 'tag_variable' => array('{$', '}'), - )); - $this->object->setLexer($lexer); - } - } - - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - public function assign($key, $value) { - if ($this->engine === 'smarty') { - $this->object->assign($key, $value); - } - if ($this->engine === 'raintpl') { - $this->object->assign($key, $value); - } - if ($this->engine === 'twig') { - $this->var_array[$key] = $value; - } - } - - public function render($name) { - if ($this->engine === 'smarty') { - return $this->object->fetch($name); - } - if ($this->engine === 'raintpl') { - return $this->object-> draw($name, 'return_string=true'); - } - if ($this->engine === 'twig') { - return $this->object->render($name,$this->var_array); - } - } - } - } - -?> + + Copyright (C) 2013 + All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ +include "root.php"; + +//define the template class + if (!class_exists('template')) { + class template { + + public $engine; + public $template_dir; + public $cache_dir; + private $object; + private $var_array; + + public function __construct(){ + } + + public function init() { + if ($this->engine === 'smarty') { + require_once "resources/templates/engine/smarty/Smarty.class.php"; + $this->object = new Smarty(); + $this->object->setTemplateDir($this->template_dir); + $this->object->setCompileDir($this->cache_dir); + $this->object->setCacheDir($this->cache_dir); + } + if ($this->engine === 'raintpl') { + require_once "resources/templates/engine/raintpl/rain.tpl.class.php"; + $this->object = new RainTPL(); + RainTPL::configure('tpl_dir', realpath($this->template_dir)."/"); + RainTPL::configure('cache_dir', realpath($this->cache_dir)."/"); + } + if ($this->engine === 'twig') { + require_once "resources/templates/engine/Twig/Autoloader.php"; + Twig_Autoloader::register(); + $loader = new Twig_Loader_Filesystem($this->template_dir); + $this->object = new Twig_Environment($loader); + $lexer = new Twig_Lexer($this->object, array( + 'tag_comment' => array('{*', '*}'), + 'tag_block' => array('{', '}'), + 'tag_variable' => array('{$', '}'), + )); + $this->object->setLexer($lexer); + } + } + + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + public function assign($key, $value) { + if ($this->engine === 'smarty') { + $this->object->assign($key, $value); + } + if ($this->engine === 'raintpl') { + $this->object->assign($key, $value); + } + if ($this->engine === 'twig') { + $this->var_array[$key] = $value; + } + } + + public function render($name) { + if ($this->engine === 'smarty') { + return $this->object->fetch($name); + } + if ($this->engine === 'raintpl') { + return $this->object-> draw($name, 'return_string=true'); + } + if ($this->engine === 'twig') { + return $this->object->render($name,$this->var_array); + } + } + } + } + +?> diff --git a/resources/classes/text.php b/resources/classes/text.php index 1a88bf67a7..a2f7e0a653 100644 --- a/resources/classes/text.php +++ b/resources/classes/text.php @@ -1,83 +1,83 @@ - $value) { - unset($this->$key); - } - } - - /** - * Get a specific item from the cache - * @var string $language_code examples: en-us, es-cl, fr-fr, pt-pt - * @var string $app_path examples: app/exec or core/domains - */ - public function get($language_code = null, $app_path = null, $exclude_global = false) { - //get the global app_languages.php - if (!$exclude_global){ - include $_SERVER["PROJECT_ROOT"]."/resources/app_languages.php"; - } - - //get the app_languages.php - if ($app_path != null) { - $lang_path = $_SERVER["PROJECT_ROOT"]."/".$app_path."/app_languages.php"; - } - else { - $lang_path = getcwd().'/app_languages.php'; - } - if(file_exists($lang_path)){ - require $lang_path; - } - - //get the available languages - krsort($text); - foreach ($text as $lang_label => $lang_codes) { - foreach ($lang_codes as $lang_code => $lang_text) { - if ($lang_text != '') { - $app_languages[] = $lang_code; - } - } - } - $_SESSION['app']['languages'] = array_unique($app_languages); - - //check the session language - if (isset($_SESSION['domain']) and $language_code == null){ - $language_code = $_SESSION['domain']['language']['code']; - } elseif ($language_code == null){ - $language_code = 'en-us'; - } - - //reduce to specific language - if ($language_code != 'all') { - foreach ($text as $key => $value) { - if (strlen($value[$language_code]) > 0) { - $text[$key] = $value[$language_code]; - } else { - //fallback to en-us - $text[$key] = $value['en-us']; - } - } - } - - //return the array of translations - return $text; - } -} - + $value) { + unset($this->$key); + } + } + + /** + * Get a specific item from the cache + * @var string $language_code examples: en-us, es-cl, fr-fr, pt-pt + * @var string $app_path examples: app/exec or core/domains + */ + public function get($language_code = null, $app_path = null, $exclude_global = false) { + //get the global app_languages.php + if (!$exclude_global){ + include $_SERVER["PROJECT_ROOT"]."/resources/app_languages.php"; + } + + //get the app_languages.php + if ($app_path != null) { + $lang_path = $_SERVER["PROJECT_ROOT"]."/".$app_path."/app_languages.php"; + } + else { + $lang_path = getcwd().'/app_languages.php'; + } + if(file_exists($lang_path)){ + require $lang_path; + } + + //get the available languages + krsort($text); + foreach ($text as $lang_label => $lang_codes) { + foreach ($lang_codes as $lang_code => $lang_text) { + if ($lang_text != '') { + $app_languages[] = $lang_code; + } + } + } + $_SESSION['app']['languages'] = array_unique($app_languages); + + //check the session language + if (isset($_SESSION['domain']) and $language_code == null){ + $language_code = $_SESSION['domain']['language']['code']; + } elseif ($language_code == null){ + $language_code = 'en-us'; + } + + //reduce to specific language + if ($language_code != 'all') { + foreach ($text as $key => $value) { + if (strlen($value[$language_code]) > 0) { + $text[$key] = $value[$language_code]; + } else { + //fallback to en-us + $text[$key] = $value['en-us']; + } + } + } + + //return the array of translations + return $text; + } +} + ?> \ No newline at end of file diff --git a/resources/classes/users.php b/resources/classes/users.php index da4ec3d1bc..02de1ada72 100644 --- a/resources/classes/users.php +++ b/resources/classes/users.php @@ -1,77 +1,77 @@ - - Portions created by the Initial Developer are Copyright (C) 2016 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - - -/** - * users class provides methods for adding and removing users - * - * @method string add - * @method boolean delete - */ -if (!class_exists('users')) { - class users { - - /** - * Called when the object is created - */ - public function __construct() { - //place holder - } - - /** - * Called when there are no references to a particular object - * unset the variables used in the class - */ - public function __destruct() { - foreach ($this as $key => $value) { - unset($this->$key); - } - } - - /** - * add a user - */ - public function add($username, $password) { - $id = uuid(); - //return $id; - return false; - } - - /** - * delete a user - */ - public function delete($id) { - return false; - } - - } //end scripts class -} -/* -//example use - $user = new users; - $user->add($username, $password); -*/ + + Portions created by the Initial Developer are Copyright (C) 2016 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + + +/** + * users class provides methods for adding and removing users + * + * @method string add + * @method boolean delete + */ +if (!class_exists('users')) { + class users { + + /** + * Called when the object is created + */ + public function __construct() { + //place holder + } + + /** + * Called when there are no references to a particular object + * unset the variables used in the class + */ + public function __destruct() { + foreach ($this as $key => $value) { + unset($this->$key); + } + } + + /** + * add a user + */ + public function add($username, $password) { + $id = uuid(); + //return $id; + return false; + } + + /** + * delete a user + */ + public function delete($id) { + return false; + } + + } //end scripts class +} +/* +//example use + $user = new users; + $user->add($username, $password); +*/ ?> \ No newline at end of file diff --git a/resources/countries.php b/resources/countries.php index 88f144c60a..3908e52abf 100644 --- a/resources/countries.php +++ b/resources/countries.php @@ -1,916 +1,916 @@ - \ No newline at end of file diff --git a/resources/fpdi/filters/FilterASCIIHexDecode.php b/resources/fpdi/filters/FilterASCIIHexDecode.php index 90df053c19..4040302d32 100644 --- a/resources/fpdi/filters/FilterASCIIHexDecode.php +++ b/resources/fpdi/filters/FilterASCIIHexDecode.php @@ -1,52 +1,52 @@ -')); - if ((strlen($data) % 2) == 1) { - $data .= '0'; - } - - return pack('H*', $data); - } - - /** - * Converts a string into ASCII hexadecimal representation. - * - * @param string $data The input string - * @param boolean $leaveEOD - * @return string - */ - public function encode($data, $leaveEOD = false) - { - return current(unpack('H*', $data)) . ($leaveEOD ? '' : '>'); - } +')); + if ((strlen($data) % 2) == 1) { + $data .= '0'; + } + + return pack('H*', $data); + } + + /** + * Converts a string into ASCII hexadecimal representation. + * + * @param string $data The input string + * @param boolean $leaveEOD + * @return string + */ + public function encode($data, $leaveEOD = false) + { + return current(unpack('H*', $data)) . ($leaveEOD ? '' : '>'); + } } \ No newline at end of file diff --git a/resources/fpdi/fpdi.php b/resources/fpdi/fpdi.php index 96341b00f4..3a84631e57 100644 --- a/resources/fpdi/fpdi.php +++ b/resources/fpdi/fpdi.php @@ -1,695 +1,695 @@ -currentFilename = $filename; - - if (!isset($this->parsers[$filename])) { - $this->parsers[$filename] = $this->_getPdfParser($filename); - $this->setPdfVersion( - max($this->getPdfVersion(), $this->parsers[$filename]->getPdfVersion()) - ); - } - - $this->currentParser =& $this->parsers[$filename]; - - return $this->parsers[$filename]->getPageCount(); - } - - /** - * Returns a PDF parser object - * - * @param string $filename - * @return fpdi_pdf_parser - */ - protected function _getPdfParser($filename) - { - require_once('fpdi_pdf_parser.php'); - return new fpdi_pdf_parser($filename); - } - - /** - * Get the current PDF version. - * - * @return string - */ - public function getPdfVersion() - { - return $this->PDFVersion; - } - - /** - * Set the PDF version. - * - * @param string $version - */ - public function setPdfVersion($version = '1.3') - { - $this->PDFVersion = sprintf('%.1F', $version); - } - - /** - * Import a page. - * - * The second parameter defines the bounding box that should be used to transform the page into a - * form XObject. - * - * Following values are available: MediaBox, CropBox, BleedBox, TrimBox, ArtBox. - * If a box is not especially defined its default box will be used: - * - *
    - *
  • CropBox: Default -> MediaBox
  • - *
  • BleedBox: Default -> CropBox
  • - *
  • TrimBox: Default -> CropBox
  • - *
  • ArtBox: Default -> CropBox
  • - *
- * - * It is possible to get the used page box by the {@link getLastUsedPageBox()} method. - * - * @param int $pageNo The page number - * @param string $boxName The boundary box to use when transforming the page into a form XObject - * @param boolean $groupXObject Define the form XObject as a group XObject to support transparency (if used) - * @return int An id of the imported page/template to use with e.g. fpdf_tpl::useTemplate() - * @throws LogicException|InvalidArgumentException - * @see getLastUsedPageBox() - */ - public function importPage($pageNo, $boxName = 'CropBox', $groupXObject = true) - { - if ($this->_inTpl) { - throw new LogicException('Please import the desired pages before creating a new template.'); - } - - $fn = $this->currentFilename; - $boxName = '/' . ltrim($boxName, '/'); - - // check if page already imported - $pageKey = $fn . '-' . ((int)$pageNo) . $boxName; - if (isset($this->_importedPages[$pageKey])) { - return $this->_importedPages[$pageKey]; - } - - $parser = $this->parsers[$fn]; - $parser->setPageNo($pageNo); - - if (!in_array($boxName, $parser->availableBoxes)) { - throw new InvalidArgumentException(sprintf('Unknown box: %s', $boxName)); - } - - $pageBoxes = $parser->getPageBoxes($pageNo, $this->k); - - /** - * MediaBox - * CropBox: Default -> MediaBox - * BleedBox: Default -> CropBox - * TrimBox: Default -> CropBox - * ArtBox: Default -> CropBox - */ - if (!isset($pageBoxes[$boxName]) && ($boxName == '/BleedBox' || $boxName == '/TrimBox' || $boxName == '/ArtBox')) - $boxName = '/CropBox'; - if (!isset($pageBoxes[$boxName]) && $boxName == '/CropBox') - $boxName = '/MediaBox'; - - if (!isset($pageBoxes[$boxName])) - return false; - - $this->lastUsedPageBox = $boxName; - - $box = $pageBoxes[$boxName]; - - $this->tpl++; - $this->_tpls[$this->tpl] = array(); - $tpl =& $this->_tpls[$this->tpl]; - $tpl['parser'] = $parser; - $tpl['resources'] = $parser->getPageResources(); - $tpl['buffer'] = $parser->getContent(); - $tpl['box'] = $box; - $tpl['groupXObject'] = $groupXObject; - if ($groupXObject) { - $this->setPdfVersion(max($this->getPdfVersion(), 1.4)); - } - - // To build an array that can be used by PDF_TPL::useTemplate() - $this->_tpls[$this->tpl] = array_merge($this->_tpls[$this->tpl], $box); - - // An imported page will start at 0,0 all the time. Translation will be set in _putformxobjects() - $tpl['x'] = 0; - $tpl['y'] = 0; - - // handle rotated pages - $rotation = $parser->getPageRotation($pageNo); - $tpl['_rotationAngle'] = 0; - if (isset($rotation[1]) && ($angle = $rotation[1] % 360) != 0) { - $steps = $angle / 90; - - $_w = $tpl['w']; - $_h = $tpl['h']; - $tpl['w'] = $steps % 2 == 0 ? $_w : $_h; - $tpl['h'] = $steps % 2 == 0 ? $_h : $_w; - - if ($angle < 0) - $angle += 360; - - $tpl['_rotationAngle'] = $angle * -1; - } - - $this->_importedPages[$pageKey] = $this->tpl; - - return $this->tpl; - } - - /** - * Returns the last used page boundary box. - * - * @return string The used boundary box: MediaBox, CropBox, BleedBox, TrimBox or ArtBox - */ - public function getLastUsedPageBox() - { - return $this->lastUsedPageBox; - } - - /** - * Use a template or imported page in current page or other template. - * - * You can use a template in a page or in another template. - * You can give the used template a new size. All parameters are optional. - * The width or height is calculated automatically if one is given. If no - * parameter is given the origin size as defined in beginTemplate() or of - * the imported page is used. - * - * The calculated or used width and height are returned as an array. - * - * @param int $tplIdx A valid template-id - * @param int $x The x-position - * @param int $y The y-position - * @param int $w The new width of the template - * @param int $h The new height of the template - * @param boolean $adjustPageSize If set to true the current page will be resized to fit the dimensions - * of the template - * - * @return array The height and width of the template (array('w' => ..., 'h' => ...)) - * @throws LogicException|InvalidArgumentException - */ - public function useTemplate($tplIdx, $x = null, $y = null, $w = 0, $h = 0, $adjustPageSize = false) - { - if ($adjustPageSize == true && is_null($x) && is_null($y)) { - $size = $this->getTemplateSize($tplIdx, $w, $h); - $orientation = $size['w'] > $size['h'] ? 'L' : 'P'; - $size = array($size['w'], $size['h']); - - if (is_subclass_of($this, 'TCPDF')) { - $this->setPageFormat($size, $orientation); - } else { - $size = $this->_getpagesize($size); - - if($orientation != $this->CurOrientation || - $size[0] != $this->CurPageSize[0] || - $size[1] != $this->CurPageSize[1] - ) { - // New size or orientation - if ($orientation=='P') { - $this->w = $size[0]; - $this->h = $size[1]; - } else { - $this->w = $size[1]; - $this->h = $size[0]; - } - $this->wPt = $this->w * $this->k; - $this->hPt = $this->h * $this->k; - $this->PageBreakTrigger = $this->h - $this->bMargin; - $this->CurOrientation = $orientation; - $this->CurPageSize = $size; - $this->PageSizes[$this->page] = array($this->wPt, $this->hPt); - } - } - } - - $this->_out('q 0 J 1 w 0 j 0 G 0 g'); // reset standard values - $size = parent::useTemplate($tplIdx, $x, $y, $w, $h); - $this->_out('Q'); - - return $size; - } - - /** - * Copy all imported objects to the resulting document. - */ - protected function _putimportedobjects() - { - foreach($this->parsers AS $filename => $p) { - $this->currentParser =& $p; - if (!isset($this->_objStack[$filename]) || !is_array($this->_objStack[$filename])) { - continue; - } - while(($n = key($this->_objStack[$filename])) !== null) { - try { - $nObj = $this->currentParser->resolveObject($this->_objStack[$filename][$n][1]); - } catch (Exception $e) { - $nObj = array(pdf_parser::TYPE_OBJECT, pdf_parser::TYPE_NULL); - } - - $this->_newobj($this->_objStack[$filename][$n][0]); - - if ($nObj[0] == pdf_parser::TYPE_STREAM) { - $this->_writeValue($nObj); - } else { - $this->_writeValue($nObj[1]); - } - - $this->_out("\nendobj"); - $this->_objStack[$filename][$n] = null; // free memory - unset($this->_objStack[$filename][$n]); - reset($this->_objStack[$filename]); - } - } - } - - /** - * Writes the form XObjects to the PDF document. - */ - protected function _putformxobjects() - { - $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; - reset($this->_tpls); - foreach($this->_tpls AS $tplIdx => $tpl) { - $this->_newobj(); - $currentN = $this->n; // TCPDF/Protection: rem current "n" - - $this->_tpls[$tplIdx]['n'] = $this->n; - $this->_out('<<' . $filter . '/Type /XObject'); - $this->_out('/Subtype /Form'); - $this->_out('/FormType 1'); - - $this->_out(sprintf('/BBox [%.2F %.2F %.2F %.2F]', - (isset($tpl['box']['llx']) ? $tpl['box']['llx'] : $tpl['x']) * $this->k, - (isset($tpl['box']['lly']) ? $tpl['box']['lly'] : -$tpl['y']) * $this->k, - (isset($tpl['box']['urx']) ? $tpl['box']['urx'] : $tpl['w'] + $tpl['x']) * $this->k, - (isset($tpl['box']['ury']) ? $tpl['box']['ury'] : $tpl['h'] - $tpl['y']) * $this->k - )); - - $c = 1; - $s = 0; - $tx = 0; - $ty = 0; - - if (isset($tpl['box'])) { - $tx = -$tpl['box']['llx']; - $ty = -$tpl['box']['lly']; - - if ($tpl['_rotationAngle'] <> 0) { - $angle = $tpl['_rotationAngle'] * M_PI/180; - $c = cos($angle); - $s = sin($angle); - - switch($tpl['_rotationAngle']) { - case -90: - $tx = -$tpl['box']['lly']; - $ty = $tpl['box']['urx']; - break; - case -180: - $tx = $tpl['box']['urx']; - $ty = $tpl['box']['ury']; - break; - case -270: - $tx = $tpl['box']['ury']; - $ty = -$tpl['box']['llx']; - break; - } - } - } else if ($tpl['x'] != 0 || $tpl['y'] != 0) { - $tx = -$tpl['x'] * 2; - $ty = $tpl['y'] * 2; - } - - $tx *= $this->k; - $ty *= $this->k; - - if ($c != 1 || $s != 0 || $tx != 0 || $ty != 0) { - $this->_out(sprintf('/Matrix [%.5F %.5F %.5F %.5F %.5F %.5F]', - $c, $s, -$s, $c, $tx, $ty - )); - } - - $this->_out('/Resources '); - - if (isset($tpl['resources'])) { - $this->currentParser = $tpl['parser']; - $this->_writeValue($tpl['resources']); // "n" will be changed - } else { - - $this->_out('<_res['tpl'][$tplIdx])) { - $res = $this->_res['tpl'][$tplIdx]; - - if (isset($res['fonts']) && count($res['fonts'])) { - $this->_out('/Font <<'); - foreach ($res['fonts'] as $font) - $this->_out('/F' . $font['i'] . ' ' . $font['n'] . ' 0 R'); - $this->_out('>>'); - } - if (isset($res['images']) && count($res['images']) || - isset($res['tpls']) && count($res['tpls'])) - { - $this->_out('/XObject <<'); - if (isset($res['images'])) { - foreach ($res['images'] as $image) - $this->_out('/I' . $image['i'] . ' ' . $image['n'] . ' 0 R'); - } - if (isset($res['tpls'])) { - foreach ($res['tpls'] as $i => $_tpl) - $this->_out($this->tplPrefix . $i . ' ' . $_tpl['n'] . ' 0 R'); - } - $this->_out('>>'); - } - $this->_out('>>'); - } - } - - if (isset($tpl['groupXObject']) && $tpl['groupXObject']) { - $this->_out('/Group <>'); - } - - $newN = $this->n; // TCPDF: rem new "n" - $this->n = $currentN; // TCPDF: reset to current "n" - - $buffer = ($this->compress) ? gzcompress($tpl['buffer']) : $tpl['buffer']; - - if (is_subclass_of($this, 'TCPDF')) { - $buffer = $this->_getrawstream($buffer); - $this->_out('/Length ' . strlen($buffer) . ' >>'); - $this->_out("stream\n" . $buffer . "\nendstream"); - } else { - $this->_out('/Length ' . strlen($buffer) . ' >>'); - $this->_putstream($buffer); - } - $this->_out('endobj'); - $this->n = $newN; // TCPDF: reset to new "n" - } - - $this->_putimportedobjects(); - } - - /** - * Creates and optionally write the object definition to the document. - * - * Rewritten to handle existing own defined objects - * - * @param bool $objId - * @param bool $onlyNewObj - * @return bool|int - */ - public function _newobj($objId = false, $onlyNewObj = false) - { - if (!$objId) { - $objId = ++$this->n; - } - - //Begin a new object - if (!$onlyNewObj) { - $this->offsets[$objId] = is_subclass_of($this, 'TCPDF') ? $this->bufferlen : strlen($this->buffer); - $this->_out($objId . ' 0 obj'); - $this->_currentObjId = $objId; // for later use with encryption - } - - return $objId; - } - - /** - * Writes a PDF value to the resulting document. - * - * Needed to rebuild the source document - * - * @param mixed $value A PDF-Value. Structure of values see cases in this method - */ - protected function _writeValue(&$value) - { - if (is_subclass_of($this, 'TCPDF')) { - parent::_prepareValue($value); - } - - switch ($value[0]) { - - case pdf_parser::TYPE_TOKEN: - $this->_straightOut($value[1] . ' '); - break; - case pdf_parser::TYPE_NUMERIC: - case pdf_parser::TYPE_REAL: - if (is_float($value[1]) && $value[1] != 0) { - $this->_straightOut(rtrim(rtrim(sprintf('%F', $value[1]), '0'), '.') . ' '); - } else { - $this->_straightOut($value[1] . ' '); - } - break; - - case pdf_parser::TYPE_ARRAY: - - // An array. Output the proper - // structure and move on. - - $this->_straightOut('['); - for ($i = 0; $i < count($value[1]); $i++) { - $this->_writeValue($value[1][$i]); - } - - $this->_out(']'); - break; - - case pdf_parser::TYPE_DICTIONARY: - - // A dictionary. - $this->_straightOut('<<'); - - reset ($value[1]); - - while (list($k, $v) = each($value[1])) { - $this->_straightOut($k . ' '); - $this->_writeValue($v); - } - - $this->_straightOut('>>'); - break; - - case pdf_parser::TYPE_OBJREF: - - // An indirect object reference - // Fill the object stack if needed - $cpfn =& $this->currentParser->filename; - if (!isset($this->_doneObjStack[$cpfn][$value[1]])) { - $this->_newobj(false, true); - $this->_objStack[$cpfn][$value[1]] = array($this->n, $value); - $this->_doneObjStack[$cpfn][$value[1]] = array($this->n, $value); - } - $objId = $this->_doneObjStack[$cpfn][$value[1]][0]; - - $this->_out($objId . ' 0 R'); - break; - - case pdf_parser::TYPE_STRING: - - // A string. - $this->_straightOut('(' . $value[1] . ')'); - - break; - - case pdf_parser::TYPE_STREAM: - - // A stream. First, output the - // stream dictionary, then the - // stream data itself. - $this->_writeValue($value[1]); - $this->_out('stream'); - $this->_out($value[2][1]); - $this->_straightOut("endstream"); - break; - - case pdf_parser::TYPE_HEX: - $this->_straightOut('<' . $value[1] . '>'); - break; - - case pdf_parser::TYPE_BOOLEAN: - $this->_straightOut($value[1] ? 'true ' : 'false '); - break; - - case pdf_parser::TYPE_NULL: - // The null object. - - $this->_straightOut('null '); - break; - } - } - - - /** - * Modified _out() method so not each call will add a newline to the output. - */ - protected function _straightOut($s) - { - if (!is_subclass_of($this, 'TCPDF')) { - if ($this->state == 2) { - $this->pages[$this->page] .= $s; - } else { - $this->buffer .= $s; - } - - } else { - if ($this->state == 2) { - if ($this->inxobj) { - // we are inside an XObject template - $this->xobjects[$this->xobjid]['outdata'] .= $s; - } else if ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) { - // puts data before page footer - $pagebuff = $this->getPageBuffer($this->page); - $page = substr($pagebuff, 0, -$this->footerlen[$this->page]); - $footer = substr($pagebuff, -$this->footerlen[$this->page]); - $this->setPageBuffer($this->page, $page . $s . $footer); - // update footer position - $this->footerpos[$this->page] += strlen($s); - } else { - // set page data - $this->setPageBuffer($this->page, $s, true); - } - } else if ($this->state > 0) { - // set general data - $this->setBuffer($s); - } - } - } - - /** - * Ends the document - * - * Overwritten to close opened parsers - */ - public function _enddoc() - { - parent::_enddoc(); - $this->_closeParsers(); - } - - /** - * Close all files opened by parsers. - * - * @return boolean - */ - protected function _closeParsers() - { - if ($this->state > 2) { - $this->cleanUp(); - return true; - } - - return false; - } - - /** - * Removes cycled references and closes the file handles of the parser objects. - */ - public function cleanUp() - { - while (($parser = array_pop($this->parsers)) !== null) { - /** - * @var fpdi_pdf_parser $parser - */ - $parser->closeFile(); - } - } +currentFilename = $filename; + + if (!isset($this->parsers[$filename])) { + $this->parsers[$filename] = $this->_getPdfParser($filename); + $this->setPdfVersion( + max($this->getPdfVersion(), $this->parsers[$filename]->getPdfVersion()) + ); + } + + $this->currentParser =& $this->parsers[$filename]; + + return $this->parsers[$filename]->getPageCount(); + } + + /** + * Returns a PDF parser object + * + * @param string $filename + * @return fpdi_pdf_parser + */ + protected function _getPdfParser($filename) + { + require_once('fpdi_pdf_parser.php'); + return new fpdi_pdf_parser($filename); + } + + /** + * Get the current PDF version. + * + * @return string + */ + public function getPdfVersion() + { + return $this->PDFVersion; + } + + /** + * Set the PDF version. + * + * @param string $version + */ + public function setPdfVersion($version = '1.3') + { + $this->PDFVersion = sprintf('%.1F', $version); + } + + /** + * Import a page. + * + * The second parameter defines the bounding box that should be used to transform the page into a + * form XObject. + * + * Following values are available: MediaBox, CropBox, BleedBox, TrimBox, ArtBox. + * If a box is not especially defined its default box will be used: + * + *
    + *
  • CropBox: Default -> MediaBox
  • + *
  • BleedBox: Default -> CropBox
  • + *
  • TrimBox: Default -> CropBox
  • + *
  • ArtBox: Default -> CropBox
  • + *
+ * + * It is possible to get the used page box by the {@link getLastUsedPageBox()} method. + * + * @param int $pageNo The page number + * @param string $boxName The boundary box to use when transforming the page into a form XObject + * @param boolean $groupXObject Define the form XObject as a group XObject to support transparency (if used) + * @return int An id of the imported page/template to use with e.g. fpdf_tpl::useTemplate() + * @throws LogicException|InvalidArgumentException + * @see getLastUsedPageBox() + */ + public function importPage($pageNo, $boxName = 'CropBox', $groupXObject = true) + { + if ($this->_inTpl) { + throw new LogicException('Please import the desired pages before creating a new template.'); + } + + $fn = $this->currentFilename; + $boxName = '/' . ltrim($boxName, '/'); + + // check if page already imported + $pageKey = $fn . '-' . ((int)$pageNo) . $boxName; + if (isset($this->_importedPages[$pageKey])) { + return $this->_importedPages[$pageKey]; + } + + $parser = $this->parsers[$fn]; + $parser->setPageNo($pageNo); + + if (!in_array($boxName, $parser->availableBoxes)) { + throw new InvalidArgumentException(sprintf('Unknown box: %s', $boxName)); + } + + $pageBoxes = $parser->getPageBoxes($pageNo, $this->k); + + /** + * MediaBox + * CropBox: Default -> MediaBox + * BleedBox: Default -> CropBox + * TrimBox: Default -> CropBox + * ArtBox: Default -> CropBox + */ + if (!isset($pageBoxes[$boxName]) && ($boxName == '/BleedBox' || $boxName == '/TrimBox' || $boxName == '/ArtBox')) + $boxName = '/CropBox'; + if (!isset($pageBoxes[$boxName]) && $boxName == '/CropBox') + $boxName = '/MediaBox'; + + if (!isset($pageBoxes[$boxName])) + return false; + + $this->lastUsedPageBox = $boxName; + + $box = $pageBoxes[$boxName]; + + $this->tpl++; + $this->_tpls[$this->tpl] = array(); + $tpl =& $this->_tpls[$this->tpl]; + $tpl['parser'] = $parser; + $tpl['resources'] = $parser->getPageResources(); + $tpl['buffer'] = $parser->getContent(); + $tpl['box'] = $box; + $tpl['groupXObject'] = $groupXObject; + if ($groupXObject) { + $this->setPdfVersion(max($this->getPdfVersion(), 1.4)); + } + + // To build an array that can be used by PDF_TPL::useTemplate() + $this->_tpls[$this->tpl] = array_merge($this->_tpls[$this->tpl], $box); + + // An imported page will start at 0,0 all the time. Translation will be set in _putformxobjects() + $tpl['x'] = 0; + $tpl['y'] = 0; + + // handle rotated pages + $rotation = $parser->getPageRotation($pageNo); + $tpl['_rotationAngle'] = 0; + if (isset($rotation[1]) && ($angle = $rotation[1] % 360) != 0) { + $steps = $angle / 90; + + $_w = $tpl['w']; + $_h = $tpl['h']; + $tpl['w'] = $steps % 2 == 0 ? $_w : $_h; + $tpl['h'] = $steps % 2 == 0 ? $_h : $_w; + + if ($angle < 0) + $angle += 360; + + $tpl['_rotationAngle'] = $angle * -1; + } + + $this->_importedPages[$pageKey] = $this->tpl; + + return $this->tpl; + } + + /** + * Returns the last used page boundary box. + * + * @return string The used boundary box: MediaBox, CropBox, BleedBox, TrimBox or ArtBox + */ + public function getLastUsedPageBox() + { + return $this->lastUsedPageBox; + } + + /** + * Use a template or imported page in current page or other template. + * + * You can use a template in a page or in another template. + * You can give the used template a new size. All parameters are optional. + * The width or height is calculated automatically if one is given. If no + * parameter is given the origin size as defined in beginTemplate() or of + * the imported page is used. + * + * The calculated or used width and height are returned as an array. + * + * @param int $tplIdx A valid template-id + * @param int $x The x-position + * @param int $y The y-position + * @param int $w The new width of the template + * @param int $h The new height of the template + * @param boolean $adjustPageSize If set to true the current page will be resized to fit the dimensions + * of the template + * + * @return array The height and width of the template (array('w' => ..., 'h' => ...)) + * @throws LogicException|InvalidArgumentException + */ + public function useTemplate($tplIdx, $x = null, $y = null, $w = 0, $h = 0, $adjustPageSize = false) + { + if ($adjustPageSize == true && is_null($x) && is_null($y)) { + $size = $this->getTemplateSize($tplIdx, $w, $h); + $orientation = $size['w'] > $size['h'] ? 'L' : 'P'; + $size = array($size['w'], $size['h']); + + if (is_subclass_of($this, 'TCPDF')) { + $this->setPageFormat($size, $orientation); + } else { + $size = $this->_getpagesize($size); + + if($orientation != $this->CurOrientation || + $size[0] != $this->CurPageSize[0] || + $size[1] != $this->CurPageSize[1] + ) { + // New size or orientation + if ($orientation=='P') { + $this->w = $size[0]; + $this->h = $size[1]; + } else { + $this->w = $size[1]; + $this->h = $size[0]; + } + $this->wPt = $this->w * $this->k; + $this->hPt = $this->h * $this->k; + $this->PageBreakTrigger = $this->h - $this->bMargin; + $this->CurOrientation = $orientation; + $this->CurPageSize = $size; + $this->PageSizes[$this->page] = array($this->wPt, $this->hPt); + } + } + } + + $this->_out('q 0 J 1 w 0 j 0 G 0 g'); // reset standard values + $size = parent::useTemplate($tplIdx, $x, $y, $w, $h); + $this->_out('Q'); + + return $size; + } + + /** + * Copy all imported objects to the resulting document. + */ + protected function _putimportedobjects() + { + foreach($this->parsers AS $filename => $p) { + $this->currentParser =& $p; + if (!isset($this->_objStack[$filename]) || !is_array($this->_objStack[$filename])) { + continue; + } + while(($n = key($this->_objStack[$filename])) !== null) { + try { + $nObj = $this->currentParser->resolveObject($this->_objStack[$filename][$n][1]); + } catch (Exception $e) { + $nObj = array(pdf_parser::TYPE_OBJECT, pdf_parser::TYPE_NULL); + } + + $this->_newobj($this->_objStack[$filename][$n][0]); + + if ($nObj[0] == pdf_parser::TYPE_STREAM) { + $this->_writeValue($nObj); + } else { + $this->_writeValue($nObj[1]); + } + + $this->_out("\nendobj"); + $this->_objStack[$filename][$n] = null; // free memory + unset($this->_objStack[$filename][$n]); + reset($this->_objStack[$filename]); + } + } + } + + /** + * Writes the form XObjects to the PDF document. + */ + protected function _putformxobjects() + { + $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; + reset($this->_tpls); + foreach($this->_tpls AS $tplIdx => $tpl) { + $this->_newobj(); + $currentN = $this->n; // TCPDF/Protection: rem current "n" + + $this->_tpls[$tplIdx]['n'] = $this->n; + $this->_out('<<' . $filter . '/Type /XObject'); + $this->_out('/Subtype /Form'); + $this->_out('/FormType 1'); + + $this->_out(sprintf('/BBox [%.2F %.2F %.2F %.2F]', + (isset($tpl['box']['llx']) ? $tpl['box']['llx'] : $tpl['x']) * $this->k, + (isset($tpl['box']['lly']) ? $tpl['box']['lly'] : -$tpl['y']) * $this->k, + (isset($tpl['box']['urx']) ? $tpl['box']['urx'] : $tpl['w'] + $tpl['x']) * $this->k, + (isset($tpl['box']['ury']) ? $tpl['box']['ury'] : $tpl['h'] - $tpl['y']) * $this->k + )); + + $c = 1; + $s = 0; + $tx = 0; + $ty = 0; + + if (isset($tpl['box'])) { + $tx = -$tpl['box']['llx']; + $ty = -$tpl['box']['lly']; + + if ($tpl['_rotationAngle'] <> 0) { + $angle = $tpl['_rotationAngle'] * M_PI/180; + $c = cos($angle); + $s = sin($angle); + + switch($tpl['_rotationAngle']) { + case -90: + $tx = -$tpl['box']['lly']; + $ty = $tpl['box']['urx']; + break; + case -180: + $tx = $tpl['box']['urx']; + $ty = $tpl['box']['ury']; + break; + case -270: + $tx = $tpl['box']['ury']; + $ty = -$tpl['box']['llx']; + break; + } + } + } else if ($tpl['x'] != 0 || $tpl['y'] != 0) { + $tx = -$tpl['x'] * 2; + $ty = $tpl['y'] * 2; + } + + $tx *= $this->k; + $ty *= $this->k; + + if ($c != 1 || $s != 0 || $tx != 0 || $ty != 0) { + $this->_out(sprintf('/Matrix [%.5F %.5F %.5F %.5F %.5F %.5F]', + $c, $s, -$s, $c, $tx, $ty + )); + } + + $this->_out('/Resources '); + + if (isset($tpl['resources'])) { + $this->currentParser = $tpl['parser']; + $this->_writeValue($tpl['resources']); // "n" will be changed + } else { + + $this->_out('<_res['tpl'][$tplIdx])) { + $res = $this->_res['tpl'][$tplIdx]; + + if (isset($res['fonts']) && count($res['fonts'])) { + $this->_out('/Font <<'); + foreach ($res['fonts'] as $font) + $this->_out('/F' . $font['i'] . ' ' . $font['n'] . ' 0 R'); + $this->_out('>>'); + } + if (isset($res['images']) && count($res['images']) || + isset($res['tpls']) && count($res['tpls'])) + { + $this->_out('/XObject <<'); + if (isset($res['images'])) { + foreach ($res['images'] as $image) + $this->_out('/I' . $image['i'] . ' ' . $image['n'] . ' 0 R'); + } + if (isset($res['tpls'])) { + foreach ($res['tpls'] as $i => $_tpl) + $this->_out($this->tplPrefix . $i . ' ' . $_tpl['n'] . ' 0 R'); + } + $this->_out('>>'); + } + $this->_out('>>'); + } + } + + if (isset($tpl['groupXObject']) && $tpl['groupXObject']) { + $this->_out('/Group <>'); + } + + $newN = $this->n; // TCPDF: rem new "n" + $this->n = $currentN; // TCPDF: reset to current "n" + + $buffer = ($this->compress) ? gzcompress($tpl['buffer']) : $tpl['buffer']; + + if (is_subclass_of($this, 'TCPDF')) { + $buffer = $this->_getrawstream($buffer); + $this->_out('/Length ' . strlen($buffer) . ' >>'); + $this->_out("stream\n" . $buffer . "\nendstream"); + } else { + $this->_out('/Length ' . strlen($buffer) . ' >>'); + $this->_putstream($buffer); + } + $this->_out('endobj'); + $this->n = $newN; // TCPDF: reset to new "n" + } + + $this->_putimportedobjects(); + } + + /** + * Creates and optionally write the object definition to the document. + * + * Rewritten to handle existing own defined objects + * + * @param bool $objId + * @param bool $onlyNewObj + * @return bool|int + */ + public function _newobj($objId = false, $onlyNewObj = false) + { + if (!$objId) { + $objId = ++$this->n; + } + + //Begin a new object + if (!$onlyNewObj) { + $this->offsets[$objId] = is_subclass_of($this, 'TCPDF') ? $this->bufferlen : strlen($this->buffer); + $this->_out($objId . ' 0 obj'); + $this->_currentObjId = $objId; // for later use with encryption + } + + return $objId; + } + + /** + * Writes a PDF value to the resulting document. + * + * Needed to rebuild the source document + * + * @param mixed $value A PDF-Value. Structure of values see cases in this method + */ + protected function _writeValue(&$value) + { + if (is_subclass_of($this, 'TCPDF')) { + parent::_prepareValue($value); + } + + switch ($value[0]) { + + case pdf_parser::TYPE_TOKEN: + $this->_straightOut($value[1] . ' '); + break; + case pdf_parser::TYPE_NUMERIC: + case pdf_parser::TYPE_REAL: + if (is_float($value[1]) && $value[1] != 0) { + $this->_straightOut(rtrim(rtrim(sprintf('%F', $value[1]), '0'), '.') . ' '); + } else { + $this->_straightOut($value[1] . ' '); + } + break; + + case pdf_parser::TYPE_ARRAY: + + // An array. Output the proper + // structure and move on. + + $this->_straightOut('['); + for ($i = 0; $i < count($value[1]); $i++) { + $this->_writeValue($value[1][$i]); + } + + $this->_out(']'); + break; + + case pdf_parser::TYPE_DICTIONARY: + + // A dictionary. + $this->_straightOut('<<'); + + reset ($value[1]); + + while (list($k, $v) = each($value[1])) { + $this->_straightOut($k . ' '); + $this->_writeValue($v); + } + + $this->_straightOut('>>'); + break; + + case pdf_parser::TYPE_OBJREF: + + // An indirect object reference + // Fill the object stack if needed + $cpfn =& $this->currentParser->filename; + if (!isset($this->_doneObjStack[$cpfn][$value[1]])) { + $this->_newobj(false, true); + $this->_objStack[$cpfn][$value[1]] = array($this->n, $value); + $this->_doneObjStack[$cpfn][$value[1]] = array($this->n, $value); + } + $objId = $this->_doneObjStack[$cpfn][$value[1]][0]; + + $this->_out($objId . ' 0 R'); + break; + + case pdf_parser::TYPE_STRING: + + // A string. + $this->_straightOut('(' . $value[1] . ')'); + + break; + + case pdf_parser::TYPE_STREAM: + + // A stream. First, output the + // stream dictionary, then the + // stream data itself. + $this->_writeValue($value[1]); + $this->_out('stream'); + $this->_out($value[2][1]); + $this->_straightOut("endstream"); + break; + + case pdf_parser::TYPE_HEX: + $this->_straightOut('<' . $value[1] . '>'); + break; + + case pdf_parser::TYPE_BOOLEAN: + $this->_straightOut($value[1] ? 'true ' : 'false '); + break; + + case pdf_parser::TYPE_NULL: + // The null object. + + $this->_straightOut('null '); + break; + } + } + + + /** + * Modified _out() method so not each call will add a newline to the output. + */ + protected function _straightOut($s) + { + if (!is_subclass_of($this, 'TCPDF')) { + if ($this->state == 2) { + $this->pages[$this->page] .= $s; + } else { + $this->buffer .= $s; + } + + } else { + if ($this->state == 2) { + if ($this->inxobj) { + // we are inside an XObject template + $this->xobjects[$this->xobjid]['outdata'] .= $s; + } else if ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) { + // puts data before page footer + $pagebuff = $this->getPageBuffer($this->page); + $page = substr($pagebuff, 0, -$this->footerlen[$this->page]); + $footer = substr($pagebuff, -$this->footerlen[$this->page]); + $this->setPageBuffer($this->page, $page . $s . $footer); + // update footer position + $this->footerpos[$this->page] += strlen($s); + } else { + // set page data + $this->setPageBuffer($this->page, $s, true); + } + } else if ($this->state > 0) { + // set general data + $this->setBuffer($s); + } + } + } + + /** + * Ends the document + * + * Overwritten to close opened parsers + */ + public function _enddoc() + { + parent::_enddoc(); + $this->_closeParsers(); + } + + /** + * Close all files opened by parsers. + * + * @return boolean + */ + protected function _closeParsers() + { + if ($this->state > 2) { + $this->cleanUp(); + return true; + } + + return false; + } + + /** + * Removes cycled references and closes the file handles of the parser objects. + */ + public function cleanUp() + { + while (($parser = array_pop($this->parsers)) !== null) { + /** + * @var fpdi_pdf_parser $parser + */ + $parser->closeFile(); + } + } } \ No newline at end of file diff --git a/resources/fpdi/fpdi_pdf_parser.php b/resources/fpdi/fpdi_pdf_parser.php index 1fa5d0174d..deeaf6c16f 100644 --- a/resources/fpdi/fpdi_pdf_parser.php +++ b/resources/fpdi/fpdi_pdf_parser.php @@ -1,354 +1,354 @@ -resolveObject($this->_root[1][1]['/Pages']); - - // Read pages - $this->_readPages($pages, $this->_pages); - - // count pages; - $this->_pageCount = count($this->_pages); - } - - /** - * Get page count from source file. - * - * @return int - */ - public function getPageCount() - { - return $this->_pageCount; - } - - /** - * Set the page number. - * - * @param int $pageNo Page number to use - * @throws InvalidArgumentException - */ - public function setPageNo($pageNo) - { - $pageNo = ((int) $pageNo) - 1; - - if ($pageNo < 0 || $pageNo >= $this->getPageCount()) { - throw new InvalidArgumentException('Invalid page number!'); - } - - $this->pageNo = $pageNo; - } - - /** - * Get page-resources from current page - * - * @return array|boolean - */ - public function getPageResources() - { - return $this->_getPageResources($this->_pages[$this->pageNo]); - } - - /** - * Get page-resources from a /Page dictionary. - * - * @param array $obj Array of pdf-data - * @return array|boolean - */ - protected function _getPageResources($obj) - { - $obj = $this->resolveObject($obj); - - // If the current object has a resources - // dictionary associated with it, we use - // it. Otherwise, we move back to its - // parent object. - if (isset($obj[1][1]['/Resources'])) { - $res = $this->resolveObject($obj[1][1]['/Resources']); - if ($res[0] == pdf_parser::TYPE_OBJECT) - return $res[1]; - return $res; - } - - if (!isset($obj[1][1]['/Parent'])) { - return false; - } - - $res = $this->_getPageResources($obj[1][1]['/Parent']); - if ($res[0] == pdf_parser::TYPE_OBJECT) - return $res[1]; - return $res; - } - - /** - * Get content of current page. - * - * If /Contents is an array, the streams are concatenated - * - * @return string - */ - public function getContent() - { - $buffer = ''; - - if (isset($this->_pages[$this->pageNo][1][1]['/Contents'])) { - $contents = $this->_getPageContent($this->_pages[$this->pageNo][1][1]['/Contents']); - foreach ($contents AS $tmpContent) { - $buffer .= $this->_unFilterStream($tmpContent) . ' '; - } - } - - return $buffer; - } - - /** - * Resolve all content objects. - * - * @param array $contentRef - * @return array - */ - protected function _getPageContent($contentRef) - { - $contents = array(); - - if ($contentRef[0] == pdf_parser::TYPE_OBJREF) { - $content = $this->resolveObject($contentRef); - if ($content[1][0] == pdf_parser::TYPE_ARRAY) { - $contents = $this->_getPageContent($content[1]); - } else { - $contents[] = $content; - } - } else if ($contentRef[0] == pdf_parser::TYPE_ARRAY) { - foreach ($contentRef[1] AS $tmp_content_ref) { - $contents = array_merge($contents, $this->_getPageContent($tmp_content_ref)); - } - } - - return $contents; - } - - /** - * Get a boundary box from a page - * - * Array format is same as used by FPDF_TPL. - * - * @param array $page a /Page dictionary - * @param string $boxIndex Type of box {see {@link $availableBoxes}) - * @param float Scale factor from user space units to points - * - * @return array|boolean - */ - protected function _getPageBox($page, $boxIndex, $k) - { - $page = $this->resolveObject($page); - $box = null; - if (isset($page[1][1][$boxIndex])) { - $box = $page[1][1][$boxIndex]; - } - - if (!is_null($box) && $box[0] == pdf_parser::TYPE_OBJREF) { - $tmp_box = $this->resolveObject($box); - $box = $tmp_box[1]; - } - - if (!is_null($box) && $box[0] == pdf_parser::TYPE_ARRAY) { - $b = $box[1]; - return array( - 'x' => $b[0][1] / $k, - 'y' => $b[1][1] / $k, - 'w' => abs($b[0][1] - $b[2][1]) / $k, - 'h' => abs($b[1][1] - $b[3][1]) / $k, - 'llx' => min($b[0][1], $b[2][1]) / $k, - 'lly' => min($b[1][1], $b[3][1]) / $k, - 'urx' => max($b[0][1], $b[2][1]) / $k, - 'ury' => max($b[1][1], $b[3][1]) / $k, - ); - } else if (!isset($page[1][1]['/Parent'])) { - return false; - } else { - return $this->_getPageBox($this->resolveObject($page[1][1]['/Parent']), $boxIndex, $k); - } - } - - /** - * Get all page boundary boxes by page number - * - * @param int $pageNo The page number - * @param float $k Scale factor from user space units to points - * @return array - * @throws InvalidArgumentException - */ - public function getPageBoxes($pageNo, $k) - { - if (!isset($this->_pages[$pageNo - 1])) { - throw new InvalidArgumentException('Page ' . $pageNo . ' does not exists.'); - } - - return $this->_getPageBoxes($this->_pages[$pageNo - 1], $k); - } - - /** - * Get all boxes from /Page dictionary - * - * @param array $page A /Page dictionary - * @param float $k Scale factor from user space units to points - * @return array - */ - protected function _getPageBoxes($page, $k) - { - $boxes = array(); - - foreach($this->availableBoxes AS $box) { - if ($_box = $this->_getPageBox($page, $box, $k)) { - $boxes[$box] = $_box; - } - } - - return $boxes; - } - - /** - * Get the page rotation by page number - * - * @param integer $pageNo - * @throws InvalidArgumentException - * @return array - */ - public function getPageRotation($pageNo) - { - if (!isset($this->_pages[$pageNo - 1])) { - throw new InvalidArgumentException('Page ' . $pageNo . ' does not exists.'); - } - - return $this->_getPageRotation($this->_pages[$pageNo - 1]); - } - - /** - * Get the rotation value of a page - * - * @param array $obj A /Page dictionary - * @return array|bool - */ - protected function _getPageRotation($obj) - { - $obj = $this->resolveObject($obj); - if (isset($obj[1][1]['/Rotate'])) { - $res = $this->resolveObject($obj[1][1]['/Rotate']); - if ($res[0] == pdf_parser::TYPE_OBJECT) - return $res[1]; - return $res; - } - - if (!isset($obj[1][1]['/Parent'])) { - return false; - } - - $res = $this->_getPageRotation($obj[1][1]['/Parent']); - if ($res[0] == pdf_parser::TYPE_OBJECT) - return $res[1]; - - return $res; - } - - /** - * Read all pages - * - * @param array $pages /Pages dictionary - * @param array $result The result array - * @throws Exception - */ - protected function _readPages(&$pages, &$result) - { - // Get the kids dictionary - $_kids = $this->resolveObject($pages[1][1]['/Kids']); - - if (!is_array($_kids)) { - throw new Exception('Cannot find /Kids in current /Page-Dictionary'); - } - - if ($_kids[0] === self::TYPE_OBJECT) { - $_kids = $_kids[1]; - } - - $kids = $_kids[1]; - - foreach ($kids as $v) { - $pg = $this->resolveObject($v); - if ($pg[1][1]['/Type'][1] === '/Pages') { - // If one of the kids is an embedded - // /Pages array, resolve it as well. - $this->_readPages($pg, $result); - } else { - $result[] = $pg; - } - } - } +resolveObject($this->_root[1][1]['/Pages']); + + // Read pages + $this->_readPages($pages, $this->_pages); + + // count pages; + $this->_pageCount = count($this->_pages); + } + + /** + * Get page count from source file. + * + * @return int + */ + public function getPageCount() + { + return $this->_pageCount; + } + + /** + * Set the page number. + * + * @param int $pageNo Page number to use + * @throws InvalidArgumentException + */ + public function setPageNo($pageNo) + { + $pageNo = ((int) $pageNo) - 1; + + if ($pageNo < 0 || $pageNo >= $this->getPageCount()) { + throw new InvalidArgumentException('Invalid page number!'); + } + + $this->pageNo = $pageNo; + } + + /** + * Get page-resources from current page + * + * @return array|boolean + */ + public function getPageResources() + { + return $this->_getPageResources($this->_pages[$this->pageNo]); + } + + /** + * Get page-resources from a /Page dictionary. + * + * @param array $obj Array of pdf-data + * @return array|boolean + */ + protected function _getPageResources($obj) + { + $obj = $this->resolveObject($obj); + + // If the current object has a resources + // dictionary associated with it, we use + // it. Otherwise, we move back to its + // parent object. + if (isset($obj[1][1]['/Resources'])) { + $res = $this->resolveObject($obj[1][1]['/Resources']); + if ($res[0] == pdf_parser::TYPE_OBJECT) + return $res[1]; + return $res; + } + + if (!isset($obj[1][1]['/Parent'])) { + return false; + } + + $res = $this->_getPageResources($obj[1][1]['/Parent']); + if ($res[0] == pdf_parser::TYPE_OBJECT) + return $res[1]; + return $res; + } + + /** + * Get content of current page. + * + * If /Contents is an array, the streams are concatenated + * + * @return string + */ + public function getContent() + { + $buffer = ''; + + if (isset($this->_pages[$this->pageNo][1][1]['/Contents'])) { + $contents = $this->_getPageContent($this->_pages[$this->pageNo][1][1]['/Contents']); + foreach ($contents AS $tmpContent) { + $buffer .= $this->_unFilterStream($tmpContent) . ' '; + } + } + + return $buffer; + } + + /** + * Resolve all content objects. + * + * @param array $contentRef + * @return array + */ + protected function _getPageContent($contentRef) + { + $contents = array(); + + if ($contentRef[0] == pdf_parser::TYPE_OBJREF) { + $content = $this->resolveObject($contentRef); + if ($content[1][0] == pdf_parser::TYPE_ARRAY) { + $contents = $this->_getPageContent($content[1]); + } else { + $contents[] = $content; + } + } else if ($contentRef[0] == pdf_parser::TYPE_ARRAY) { + foreach ($contentRef[1] AS $tmp_content_ref) { + $contents = array_merge($contents, $this->_getPageContent($tmp_content_ref)); + } + } + + return $contents; + } + + /** + * Get a boundary box from a page + * + * Array format is same as used by FPDF_TPL. + * + * @param array $page a /Page dictionary + * @param string $boxIndex Type of box {see {@link $availableBoxes}) + * @param float Scale factor from user space units to points + * + * @return array|boolean + */ + protected function _getPageBox($page, $boxIndex, $k) + { + $page = $this->resolveObject($page); + $box = null; + if (isset($page[1][1][$boxIndex])) { + $box = $page[1][1][$boxIndex]; + } + + if (!is_null($box) && $box[0] == pdf_parser::TYPE_OBJREF) { + $tmp_box = $this->resolveObject($box); + $box = $tmp_box[1]; + } + + if (!is_null($box) && $box[0] == pdf_parser::TYPE_ARRAY) { + $b = $box[1]; + return array( + 'x' => $b[0][1] / $k, + 'y' => $b[1][1] / $k, + 'w' => abs($b[0][1] - $b[2][1]) / $k, + 'h' => abs($b[1][1] - $b[3][1]) / $k, + 'llx' => min($b[0][1], $b[2][1]) / $k, + 'lly' => min($b[1][1], $b[3][1]) / $k, + 'urx' => max($b[0][1], $b[2][1]) / $k, + 'ury' => max($b[1][1], $b[3][1]) / $k, + ); + } else if (!isset($page[1][1]['/Parent'])) { + return false; + } else { + return $this->_getPageBox($this->resolveObject($page[1][1]['/Parent']), $boxIndex, $k); + } + } + + /** + * Get all page boundary boxes by page number + * + * @param int $pageNo The page number + * @param float $k Scale factor from user space units to points + * @return array + * @throws InvalidArgumentException + */ + public function getPageBoxes($pageNo, $k) + { + if (!isset($this->_pages[$pageNo - 1])) { + throw new InvalidArgumentException('Page ' . $pageNo . ' does not exists.'); + } + + return $this->_getPageBoxes($this->_pages[$pageNo - 1], $k); + } + + /** + * Get all boxes from /Page dictionary + * + * @param array $page A /Page dictionary + * @param float $k Scale factor from user space units to points + * @return array + */ + protected function _getPageBoxes($page, $k) + { + $boxes = array(); + + foreach($this->availableBoxes AS $box) { + if ($_box = $this->_getPageBox($page, $box, $k)) { + $boxes[$box] = $_box; + } + } + + return $boxes; + } + + /** + * Get the page rotation by page number + * + * @param integer $pageNo + * @throws InvalidArgumentException + * @return array + */ + public function getPageRotation($pageNo) + { + if (!isset($this->_pages[$pageNo - 1])) { + throw new InvalidArgumentException('Page ' . $pageNo . ' does not exists.'); + } + + return $this->_getPageRotation($this->_pages[$pageNo - 1]); + } + + /** + * Get the rotation value of a page + * + * @param array $obj A /Page dictionary + * @return array|bool + */ + protected function _getPageRotation($obj) + { + $obj = $this->resolveObject($obj); + if (isset($obj[1][1]['/Rotate'])) { + $res = $this->resolveObject($obj[1][1]['/Rotate']); + if ($res[0] == pdf_parser::TYPE_OBJECT) + return $res[1]; + return $res; + } + + if (!isset($obj[1][1]['/Parent'])) { + return false; + } + + $res = $this->_getPageRotation($obj[1][1]['/Parent']); + if ($res[0] == pdf_parser::TYPE_OBJECT) + return $res[1]; + + return $res; + } + + /** + * Read all pages + * + * @param array $pages /Pages dictionary + * @param array $result The result array + * @throws Exception + */ + protected function _readPages(&$pages, &$result) + { + // Get the kids dictionary + $_kids = $this->resolveObject($pages[1][1]['/Kids']); + + if (!is_array($_kids)) { + throw new Exception('Cannot find /Kids in current /Page-Dictionary'); + } + + if ($_kids[0] === self::TYPE_OBJECT) { + $_kids = $_kids[1]; + } + + $kids = $_kids[1]; + + foreach ($kids as $v) { + $pg = $this->resolveObject($v); + if ($pg[1][1]['/Type'][1] === '/Pages') { + // If one of the kids is an embedded + // /Pages array, resolve it as well. + $this->_readPages($pg, $result); + } else { + $result[] = $pg; + } + } + } } \ No newline at end of file diff --git a/resources/fpdi/pdf_context.php b/resources/fpdi/pdf_context.php index f962e242bf..88f3aedeff 100644 --- a/resources/fpdi/pdf_context.php +++ b/resources/fpdi/pdf_context.php @@ -1,153 +1,153 @@ -file =& $f; - if (is_string($this->file)) - $this->_mode = 1; - - $this->reset(); - } - - /** - * Get the position in the file stream - * - * @return int - */ - public function getPos() - { - if ($this->_mode == 0) { - return ftell($this->file); - } else { - return 0; - } - } - - /** - * Reset the position in the file stream. - * - * Optionally move the file pointer to a new location and reset the buffered data. - * - * @param null $pos - * @param int $l - */ - public function reset($pos = null, $l = 100) - { - if ($this->_mode == 0) { - if (!is_null($pos)) { - fseek ($this->file, $pos); - } - - $this->buffer = $l > 0 ? fread($this->file, $l) : ''; - $this->length = strlen($this->buffer); - if ($this->length < $l) - $this->increaseLength($l - $this->length); - } else { - $this->buffer = $this->file; - $this->length = strlen($this->buffer); - } - $this->offset = 0; - $this->stack = array(); - } - - /** - * Make sure that there is at least one character beyond the current offset in the buffer. - * - * To prevent the tokenizer from attempting to access data that does not exist. - * - * @return bool - */ - public function ensureContent() - { - if ($this->offset >= $this->length - 1) { - return $this->increaseLength(); - } else { - return true; - } - } - - /** - * Forcefully read more data into the buffer - * - * @param int $l - * @return bool - */ - public function increaseLength($l = 100) - { - if ($this->_mode == 0 && feof($this->file)) { - return false; - } else if ($this->_mode == 0) { - $totalLength = $this->length + $l; - do { - $toRead = $totalLength - $this->length; - if ($toRead < 1) - break; - - $this->buffer .= fread($this->file, $toRead); - } while ((($this->length = strlen($this->buffer)) != $totalLength) && !feof($this->file)); - - return true; - } else { - return false; - } - } +file =& $f; + if (is_string($this->file)) + $this->_mode = 1; + + $this->reset(); + } + + /** + * Get the position in the file stream + * + * @return int + */ + public function getPos() + { + if ($this->_mode == 0) { + return ftell($this->file); + } else { + return 0; + } + } + + /** + * Reset the position in the file stream. + * + * Optionally move the file pointer to a new location and reset the buffered data. + * + * @param null $pos + * @param int $l + */ + public function reset($pos = null, $l = 100) + { + if ($this->_mode == 0) { + if (!is_null($pos)) { + fseek ($this->file, $pos); + } + + $this->buffer = $l > 0 ? fread($this->file, $l) : ''; + $this->length = strlen($this->buffer); + if ($this->length < $l) + $this->increaseLength($l - $this->length); + } else { + $this->buffer = $this->file; + $this->length = strlen($this->buffer); + } + $this->offset = 0; + $this->stack = array(); + } + + /** + * Make sure that there is at least one character beyond the current offset in the buffer. + * + * To prevent the tokenizer from attempting to access data that does not exist. + * + * @return bool + */ + public function ensureContent() + { + if ($this->offset >= $this->length - 1) { + return $this->increaseLength(); + } else { + return true; + } + } + + /** + * Forcefully read more data into the buffer + * + * @param int $l + * @return bool + */ + public function increaseLength($l = 100) + { + if ($this->_mode == 0 && feof($this->file)) { + return false; + } else if ($this->_mode == 0) { + $totalLength = $this->length + $l; + do { + $toRead = $totalLength - $this->length; + if ($toRead < 1) + break; + + $this->buffer .= fread($this->file, $toRead); + } while ((($this->length = strlen($this->buffer)) != $totalLength) && !feof($this->file)); + + return true; + } else { + return false; + } + } } \ No newline at end of file diff --git a/resources/fpdi/pdf_parser.php b/resources/fpdi/pdf_parser.php index a8170ddd7b..a1c82dec23 100644 --- a/resources/fpdi/pdf_parser.php +++ b/resources/fpdi/pdf_parser.php @@ -1,913 +1,913 @@ -filename = $filename; - - $this->_f = @fopen($this->filename, 'rb'); - - if (!$this->_f) { - throw new InvalidArgumentException(sprintf('Cannot open %s !', $filename)); - } - - $this->getPdfVersion(); - - require_once('pdf_context.php'); - $this->_c = new pdf_context($this->_f); - - // Read xref-Data - $this->_xref = array(); - $this->_readXref($this->_xref, $this->_findXref()); - - // Check for Encryption - $this->getEncryption(); - - // Read root - $this->_readRoot(); - } - - /** - * Destructor - */ - public function __destruct() - { - $this->closeFile(); - } - - /** - * Close the opened file - */ - public function closeFile() - { - if (isset($this->_f) && is_resource($this->_f)) { - fclose($this->_f); - unset($this->_f); - } - } - - /** - * Check Trailer for Encryption - * - * @throws Exception - */ - public function getEncryption() - { - if (isset($this->_xref['trailer'][1]['/Encrypt'])) { - throw new Exception('File is encrypted!'); - } - } - - /** - * Get PDF-Version - * - * @return string - */ - public function getPdfVersion() - { - if ($this->_pdfVersion === null) { - fseek($this->_f, 0); - preg_match('/\d\.\d/', fread($this->_f, 16), $m); - if (isset($m[0])) - $this->_pdfVersion = $m[0]; - } - - return $this->_pdfVersion; - } - - /** - * Read the /Root dictionary - */ - protected function _readRoot() - { - if ($this->_xref['trailer'][1]['/Root'][0] != self::TYPE_OBJREF) { - throw new Exception('Wrong Type of Root-Element! Must be an indirect reference'); - } - - $this->_root = $this->resolveObject($this->_xref['trailer'][1]['/Root']); - } - - /** - * Find the xref table - * - * @return integer - * @throws Exception - */ - protected function _findXref() - { - $toRead = self::$searchForStartxrefLength; - - $stat = fseek($this->_f, -$toRead, SEEK_END); - if ($stat === -1) { - fseek($this->_f, 0); - } - - $data = fread($this->_f, $toRead); - - $keywordPos = strpos(strrev($data), strrev('startxref')); - if (false === $keywordPos) { - $keywordPos = strpos(strrev($data), strrev('startref')); - } - - if (false === $keywordPos) { - throw new Exception('Unable to find "startxref" keyword.'); - } - - $pos = strlen($data) - $keywordPos; - $data = substr($data, $pos); - - if (!preg_match('/\s*(\d+).*$/s', $data, $matches)) { - throw new Exception('Unable to find pointer to xref table.'); - } - - return (int) $matches[1]; - } - - /** - * Read the xref table - * - * @param array $result Array of xref table entries - * @param integer $offset of xref table - * @return boolean - * @throws Exception - */ - protected function _readXref(&$result, $offset) - { - $tempPos = $offset - min(20, $offset); - fseek($this->_f, $tempPos); // set some bytes backwards to fetch corrupted docs - - $data = fread($this->_f, 100); - - $xrefPos = strrpos($data, 'xref'); - - if ($xrefPos === false) { - $this->_c->reset($offset); - $xrefStreamObjDec = $this->_readValue($this->_c); - - if (is_array($xrefStreamObjDec) && isset($xrefStreamObjDec[0]) && $xrefStreamObjDec[0] == self::TYPE_OBJDEC) { - throw new Exception( - sprintf( - 'This document (%s) probably uses a compression technique which is not supported by the ' . - 'free parser shipped with FPDI. (See https://www.setasign.com/fpdi-pdf-parser for more details)', - $this->filename - ) - ); - } else { - throw new Exception('Unable to find xref table.'); - } - } - - if (!isset($result['xrefLocation'])) { - $result['xrefLocation'] = $tempPos + $xrefPos; - $result['maxObject'] = 0; - } - - $cycles = -1; - $bytesPerCycle = 100; - - fseek($this->_f, $tempPos = $tempPos + $xrefPos + 4); // set the handle directly after the "xref"-keyword - $data = fread($this->_f, $bytesPerCycle); - - while (($trailerPos = strpos($data, 'trailer', max($bytesPerCycle * $cycles++, 0))) === false && !feof($this->_f)) { - $data .= fread($this->_f, $bytesPerCycle); - } - - if ($trailerPos === false) { - throw new Exception('Trailer keyword not found after xref table'); - } - - $data = ltrim(substr($data, 0, $trailerPos)); - - // get Line-Ending - preg_match_all("/(\r\n|\n|\r)/", substr($data, 0, 100), $m); // check the first 100 bytes for line breaks - - $differentLineEndings = count(array_unique($m[0])); - if ($differentLineEndings > 1) { - $lines = preg_split("/(\r\n|\n|\r)/", $data, -1, PREG_SPLIT_NO_EMPTY); - } else { - $lines = explode($m[0][0], $data); - } - - $data = $differentLineEndings = $m = null; - unset($data, $differentLineEndings, $m); - - $linesCount = count($lines); - - $start = 1; - - for ($i = 0; $i < $linesCount; $i++) { - $line = trim($lines[$i]); - if ($line) { - $pieces = explode(' ', $line); - $c = count($pieces); - switch($c) { - case 2: - $start = (int)$pieces[0]; - $end = $start + (int)$pieces[1]; - if ($end > $result['maxObject']) - $result['maxObject'] = $end; - break; - case 3: - if (!isset($result['xref'][$start])) - $result['xref'][$start] = array(); - - if (!array_key_exists($gen = (int) $pieces[1], $result['xref'][$start])) { - $result['xref'][$start][$gen] = $pieces[2] == 'n' ? (int) $pieces[0] : null; - } - $start++; - break; - default: - throw new Exception('Unexpected data in xref table'); - } - } - } - - $lines = $pieces = $line = $start = $end = $gen = null; - unset($lines, $pieces, $line, $start, $end, $gen); - - $this->_c->reset($tempPos + $trailerPos + 7); - $trailer = $this->_readValue($this->_c); - - if (!isset($result['trailer'])) { - $result['trailer'] = $trailer; - } - - if (isset($trailer[1]['/Prev'])) { - $this->_readXref($result, $trailer[1]['/Prev'][1]); - } - - $trailer = null; - unset($trailer); - - return true; - } - - /** - * Reads a PDF value - * - * @param pdf_context $c - * @param string $token A token - * @return mixed - */ - protected function _readValue(&$c, $token = null) - { - if (is_null($token)) { - $token = $this->_readToken($c); - } - - if ($token === false) { - return false; - } - - switch ($token) { - case '<': - // This is a hex string. - // Read the value, then the terminator - - $pos = $c->offset; - - while(1) { - - $match = strpos ($c->buffer, '>', $pos); - - // If you can't find it, try - // reading more data from the stream - - if ($match === false) { - if (!$c->increaseLength()) { - return false; - } else { - continue; - } - } - - $result = substr ($c->buffer, $c->offset, $match - $c->offset); - $c->offset = $match + 1; - - return array (self::TYPE_HEX, $result); - } - break; - - case '<<': - // This is a dictionary. - - $result = array(); - - // Recurse into this function until we reach - // the end of the dictionary. - while (($key = $this->_readToken($c)) !== '>>') { - if ($key === false) { - return false; - } - - if (($value = $this->_readValue($c)) === false) { - return false; - } - - // Catch missing value - if ($value[0] == self::TYPE_TOKEN && $value[1] == '>>') { - $result[$key] = array(self::TYPE_NULL); - break; - } - - $result[$key] = $value; - } - - return array (self::TYPE_DICTIONARY, $result); - - case '[': - // This is an array. - - $result = array(); - - // Recurse into this function until we reach - // the end of the array. - while (($token = $this->_readToken($c)) !== ']') { - if ($token === false) { - return false; - } - - if (($value = $this->_readValue($c, $token)) === false) { - return false; - } - - $result[] = $value; - } - - return array (self::TYPE_ARRAY, $result); - - case '(': - // This is a string - $pos = $c->offset; - - $openBrackets = 1; - do { - for (; $openBrackets != 0 && $pos < $c->length; $pos++) { - switch (ord($c->buffer[$pos])) { - case 0x28: // '(' - $openBrackets++; - break; - case 0x29: // ')' - $openBrackets--; - break; - case 0x5C: // backslash - $pos++; - } - } - } while($openBrackets != 0 && $c->increaseLength()); - - $result = substr($c->buffer, $c->offset, $pos - $c->offset - 1); - $c->offset = $pos; - - return array (self::TYPE_STRING, $result); - - case 'stream': - $tempPos = $c->getPos() - strlen($c->buffer); - $tempOffset = $c->offset; - - $c->reset($startPos = $tempPos + $tempOffset); - - $e = 0; // ensure line breaks in front of the stream - if ($c->buffer[0] == chr(10) || $c->buffer[0] == chr(13)) - $e++; - if ($c->buffer[1] == chr(10) && $c->buffer[0] != chr(10)) - $e++; - - if ($this->_currentObj[1][1]['/Length'][0] == self::TYPE_OBJREF) { - $tmpLength = $this->resolveObject($this->_currentObj[1][1]['/Length']); - $length = $tmpLength[1][1]; - } else { - $length = $this->_currentObj[1][1]['/Length'][1]; - } - - if ($length > 0) { - $c->reset($startPos + $e, $length); - $v = $c->buffer; - } else { - $v = ''; - } - - $c->reset($startPos + $e + $length); - $endstream = $this->_readToken($c); - - if ($endstream != 'endstream') { - $c->reset($startPos + $e + $length + 9); // 9 = strlen("endstream") - // We don't throw an error here because the next - // round trip will start at a new offset - } - - return array(self::TYPE_STREAM, $v); - - default : - if (is_numeric($token)) { - // A numeric token. Make sure that - // it is not part of something else. - if (($tok2 = $this->_readToken($c)) !== false) { - if (is_numeric($tok2)) { - - // Two numeric tokens in a row. - // In this case, we're probably in - // front of either an object reference - // or an object specification. - // Determine the case and return the data - if (($tok3 = $this->_readToken($c)) !== false) { - switch ($tok3) { - case 'obj': - return array(self::TYPE_OBJDEC, (int)$token, (int)$tok2); - case 'R': - return array(self::TYPE_OBJREF, (int)$token, (int)$tok2); - } - // If we get to this point, that numeric value up - // there was just a numeric value. Push the extra - // tokens back into the stack and return the value. - array_push($c->stack, $tok3); - } - } - - array_push($c->stack, $tok2); - } - - if ($token === (string)((int)$token)) - return array(self::TYPE_NUMERIC, (int)$token); - else - return array(self::TYPE_REAL, (float)$token); - } else if ($token == 'true' || $token == 'false') { - return array(self::TYPE_BOOLEAN, $token == 'true'); - } else if ($token == 'null') { - return array(self::TYPE_NULL); - } else { - // Just a token. Return it. - return array(self::TYPE_TOKEN, $token); - } - } - } - - /** - * Resolve an object - * - * @param array $objSpec The object-data - * @return array|boolean - * @throws Exception - */ - public function resolveObject($objSpec) - { - $c = $this->_c; - - // Exit if we get invalid data - if (!is_array($objSpec)) { - return false; - } - - if ($objSpec[0] == self::TYPE_OBJREF) { - - // This is a reference, resolve it - if (isset($this->_xref['xref'][$objSpec[1]][$objSpec[2]])) { - - // Save current file position - // This is needed if you want to resolve - // references while you're reading another object - // (e.g.: if you need to determine the length - // of a stream) - - $oldPos = $c->getPos(); - - // Reposition the file pointer and - // load the object header. - - $c->reset($this->_xref['xref'][$objSpec[1]][$objSpec[2]]); - - $header = $this->_readValue($c); - - if ($header[0] != self::TYPE_OBJDEC || $header[1] != $objSpec[1] || $header[2] != $objSpec[2]) { - $toSearchFor = $objSpec[1] . ' ' . $objSpec[2] . ' obj'; - if (preg_match('/' . $toSearchFor . '/', $c->buffer)) { - $c->offset = strpos($c->buffer, $toSearchFor) + strlen($toSearchFor); - // reset stack - $c->stack = array(); - } else { - throw new Exception( - sprintf("Unable to find object (%s, %s) at expected location.", $objSpec[1], $objSpec[2]) - ); - } - } - - // If we're being asked to store all the information - // about the object, we add the object ID and generation - // number for later use - $result = array ( - self::TYPE_OBJECT, - 'obj' => $objSpec[1], - 'gen' => $objSpec[2] - ); - - $this->_currentObj =& $result; - - // Now simply read the object data until - // we encounter an end-of-object marker - while (true) { - $value = $this->_readValue($c); - if ($value === false || count($result) > 4) { - // in this case the parser couldn't find an "endobj" so we break here - break; - } - - if ($value[0] == self::TYPE_TOKEN && $value[1] === 'endobj') { - break; - } - - $result[] = $value; - } - - $c->reset($oldPos); - - if (isset($result[2][0]) && $result[2][0] == self::TYPE_STREAM) { - $result[0] = self::TYPE_STREAM; - } - - } else { - throw new Exception( - sprintf("Unable to find object (%s, %s) at expected location.", $objSpec[1], $objSpec[2]) - ); - } - - return $result; - } else { - return $objSpec; - } - } - - /** - * Reads a token from the context - * - * @param pdf_context $c - * @return mixed - */ - protected function _readToken($c) - { - // If there is a token available - // on the stack, pop it out and - // return it. - - if (count($c->stack)) { - return array_pop($c->stack); - } - - // Strip away any whitespace - - do { - if (!$c->ensureContent()) { - return false; - } - $c->offset += strspn($c->buffer, "\x20\x0A\x0C\x0D\x09\x00", $c->offset); - } while ($c->offset >= $c->length - 1); - - // Get the first character in the stream - - $char = $c->buffer[$c->offset++]; - - switch ($char) { - - case '[': - case ']': - case '(': - case ')': - - // This is either an array or literal string - // delimiter, Return it - - return $char; - - case '<': - case '>': - - // This could either be a hex string or - // dictionary delimiter. Determine the - // appropriate case and return the token - - if ($c->buffer[$c->offset] == $char) { - if (!$c->ensureContent()) { - return false; - } - $c->offset++; - return $char . $char; - } else { - return $char; - } - - case '%': - - // This is a comment - jump over it! - - $pos = $c->offset; - while(1) { - $match = preg_match("/(\r\n|\r|\n)/", $c->buffer, $m, PREG_OFFSET_CAPTURE, $pos); - if ($match === 0) { - if (!$c->increaseLength()) { - return false; - } else { - continue; - } - } - - $c->offset = $m[0][1] + strlen($m[0][0]); - - return $this->_readToken($c); - } - - default: - - // This is "another" type of token (probably - // a dictionary entry or a numeric value) - // Find the end and return it. - - if (!$c->ensureContent()) { - return false; - } - - while(1) { - - // Determine the length of the token - - $pos = strcspn($c->buffer, "\x20%[]<>()/\x0A\x0C\x0D\x09\x00", $c->offset); - - if ($c->offset + $pos <= $c->length - 1) { - break; - } else { - // If the script reaches this point, - // the token may span beyond the end - // of the current buffer. Therefore, - // we increase the size of the buffer - // and try again--just to be safe. - - $c->increaseLength(); - } - } - - $result = substr($c->buffer, $c->offset - 1, $pos + 1); - - $c->offset += $pos; - - return $result; - } - } - - /** - * Un-filter a stream object - * - * @param array $obj - * @return string - * @throws Exception - */ - protected function _unFilterStream($obj) - { - $filters = array(); - - if (isset($obj[1][1]['/Filter'])) { - $filter = $obj[1][1]['/Filter']; - - if ($filter[0] == pdf_parser::TYPE_OBJREF) { - $tmpFilter = $this->resolveObject($filter); - $filter = $tmpFilter[1]; - } - - if ($filter[0] == pdf_parser::TYPE_TOKEN) { - $filters[] = $filter; - } else if ($filter[0] == pdf_parser::TYPE_ARRAY) { - $filters = $filter[1]; - } - } - - $stream = $obj[2][1]; - - foreach ($filters AS $filter) { - switch ($filter[1]) { - case '/FlateDecode': - case '/Fl': - if (function_exists('gzuncompress')) { - $oStream = $stream; - $stream = (strlen($stream) > 0) ? @gzuncompress($stream) : ''; - } else { - throw new Exception( - sprintf('To handle %s filter, please compile php with zlib support.', $filter[1]) - ); - } - - if ($stream === false) { - $tries = 0; - while ($tries < 8 && ($stream === false || strlen($stream) < strlen($oStream))) { - $oStream = substr($oStream, 1); - $stream = @gzinflate($oStream); - $tries++; - } - - if ($stream === false) { - throw new Exception('Error while decompressing stream.'); - } - } - break; - case '/LZWDecode': - require_once('filters/FilterLZW.php'); - $decoder = new FilterLZW(); - $stream = $decoder->decode($stream); - break; - case '/ASCII85Decode': - require_once('filters/FilterASCII85.php'); - $decoder = new FilterASCII85(); - $stream = $decoder->decode($stream); - break; - case '/ASCIIHexDecode': - require_once('filters/FilterASCIIHexDecode.php'); - $decoder = new FilterASCIIHexDecode(); - $stream = $decoder->decode($stream); - break; - case null: - break; - default: - throw new Exception(sprintf('Unsupported Filter: %s', $filter[1])); - } - } - - return $stream; - } +filename = $filename; + + $this->_f = @fopen($this->filename, 'rb'); + + if (!$this->_f) { + throw new InvalidArgumentException(sprintf('Cannot open %s !', $filename)); + } + + $this->getPdfVersion(); + + require_once('pdf_context.php'); + $this->_c = new pdf_context($this->_f); + + // Read xref-Data + $this->_xref = array(); + $this->_readXref($this->_xref, $this->_findXref()); + + // Check for Encryption + $this->getEncryption(); + + // Read root + $this->_readRoot(); + } + + /** + * Destructor + */ + public function __destruct() + { + $this->closeFile(); + } + + /** + * Close the opened file + */ + public function closeFile() + { + if (isset($this->_f) && is_resource($this->_f)) { + fclose($this->_f); + unset($this->_f); + } + } + + /** + * Check Trailer for Encryption + * + * @throws Exception + */ + public function getEncryption() + { + if (isset($this->_xref['trailer'][1]['/Encrypt'])) { + throw new Exception('File is encrypted!'); + } + } + + /** + * Get PDF-Version + * + * @return string + */ + public function getPdfVersion() + { + if ($this->_pdfVersion === null) { + fseek($this->_f, 0); + preg_match('/\d\.\d/', fread($this->_f, 16), $m); + if (isset($m[0])) + $this->_pdfVersion = $m[0]; + } + + return $this->_pdfVersion; + } + + /** + * Read the /Root dictionary + */ + protected function _readRoot() + { + if ($this->_xref['trailer'][1]['/Root'][0] != self::TYPE_OBJREF) { + throw new Exception('Wrong Type of Root-Element! Must be an indirect reference'); + } + + $this->_root = $this->resolveObject($this->_xref['trailer'][1]['/Root']); + } + + /** + * Find the xref table + * + * @return integer + * @throws Exception + */ + protected function _findXref() + { + $toRead = self::$searchForStartxrefLength; + + $stat = fseek($this->_f, -$toRead, SEEK_END); + if ($stat === -1) { + fseek($this->_f, 0); + } + + $data = fread($this->_f, $toRead); + + $keywordPos = strpos(strrev($data), strrev('startxref')); + if (false === $keywordPos) { + $keywordPos = strpos(strrev($data), strrev('startref')); + } + + if (false === $keywordPos) { + throw new Exception('Unable to find "startxref" keyword.'); + } + + $pos = strlen($data) - $keywordPos; + $data = substr($data, $pos); + + if (!preg_match('/\s*(\d+).*$/s', $data, $matches)) { + throw new Exception('Unable to find pointer to xref table.'); + } + + return (int) $matches[1]; + } + + /** + * Read the xref table + * + * @param array $result Array of xref table entries + * @param integer $offset of xref table + * @return boolean + * @throws Exception + */ + protected function _readXref(&$result, $offset) + { + $tempPos = $offset - min(20, $offset); + fseek($this->_f, $tempPos); // set some bytes backwards to fetch corrupted docs + + $data = fread($this->_f, 100); + + $xrefPos = strrpos($data, 'xref'); + + if ($xrefPos === false) { + $this->_c->reset($offset); + $xrefStreamObjDec = $this->_readValue($this->_c); + + if (is_array($xrefStreamObjDec) && isset($xrefStreamObjDec[0]) && $xrefStreamObjDec[0] == self::TYPE_OBJDEC) { + throw new Exception( + sprintf( + 'This document (%s) probably uses a compression technique which is not supported by the ' . + 'free parser shipped with FPDI. (See https://www.setasign.com/fpdi-pdf-parser for more details)', + $this->filename + ) + ); + } else { + throw new Exception('Unable to find xref table.'); + } + } + + if (!isset($result['xrefLocation'])) { + $result['xrefLocation'] = $tempPos + $xrefPos; + $result['maxObject'] = 0; + } + + $cycles = -1; + $bytesPerCycle = 100; + + fseek($this->_f, $tempPos = $tempPos + $xrefPos + 4); // set the handle directly after the "xref"-keyword + $data = fread($this->_f, $bytesPerCycle); + + while (($trailerPos = strpos($data, 'trailer', max($bytesPerCycle * $cycles++, 0))) === false && !feof($this->_f)) { + $data .= fread($this->_f, $bytesPerCycle); + } + + if ($trailerPos === false) { + throw new Exception('Trailer keyword not found after xref table'); + } + + $data = ltrim(substr($data, 0, $trailerPos)); + + // get Line-Ending + preg_match_all("/(\r\n|\n|\r)/", substr($data, 0, 100), $m); // check the first 100 bytes for line breaks + + $differentLineEndings = count(array_unique($m[0])); + if ($differentLineEndings > 1) { + $lines = preg_split("/(\r\n|\n|\r)/", $data, -1, PREG_SPLIT_NO_EMPTY); + } else { + $lines = explode($m[0][0], $data); + } + + $data = $differentLineEndings = $m = null; + unset($data, $differentLineEndings, $m); + + $linesCount = count($lines); + + $start = 1; + + for ($i = 0; $i < $linesCount; $i++) { + $line = trim($lines[$i]); + if ($line) { + $pieces = explode(' ', $line); + $c = count($pieces); + switch($c) { + case 2: + $start = (int)$pieces[0]; + $end = $start + (int)$pieces[1]; + if ($end > $result['maxObject']) + $result['maxObject'] = $end; + break; + case 3: + if (!isset($result['xref'][$start])) + $result['xref'][$start] = array(); + + if (!array_key_exists($gen = (int) $pieces[1], $result['xref'][$start])) { + $result['xref'][$start][$gen] = $pieces[2] == 'n' ? (int) $pieces[0] : null; + } + $start++; + break; + default: + throw new Exception('Unexpected data in xref table'); + } + } + } + + $lines = $pieces = $line = $start = $end = $gen = null; + unset($lines, $pieces, $line, $start, $end, $gen); + + $this->_c->reset($tempPos + $trailerPos + 7); + $trailer = $this->_readValue($this->_c); + + if (!isset($result['trailer'])) { + $result['trailer'] = $trailer; + } + + if (isset($trailer[1]['/Prev'])) { + $this->_readXref($result, $trailer[1]['/Prev'][1]); + } + + $trailer = null; + unset($trailer); + + return true; + } + + /** + * Reads a PDF value + * + * @param pdf_context $c + * @param string $token A token + * @return mixed + */ + protected function _readValue(&$c, $token = null) + { + if (is_null($token)) { + $token = $this->_readToken($c); + } + + if ($token === false) { + return false; + } + + switch ($token) { + case '<': + // This is a hex string. + // Read the value, then the terminator + + $pos = $c->offset; + + while(1) { + + $match = strpos ($c->buffer, '>', $pos); + + // If you can't find it, try + // reading more data from the stream + + if ($match === false) { + if (!$c->increaseLength()) { + return false; + } else { + continue; + } + } + + $result = substr ($c->buffer, $c->offset, $match - $c->offset); + $c->offset = $match + 1; + + return array (self::TYPE_HEX, $result); + } + break; + + case '<<': + // This is a dictionary. + + $result = array(); + + // Recurse into this function until we reach + // the end of the dictionary. + while (($key = $this->_readToken($c)) !== '>>') { + if ($key === false) { + return false; + } + + if (($value = $this->_readValue($c)) === false) { + return false; + } + + // Catch missing value + if ($value[0] == self::TYPE_TOKEN && $value[1] == '>>') { + $result[$key] = array(self::TYPE_NULL); + break; + } + + $result[$key] = $value; + } + + return array (self::TYPE_DICTIONARY, $result); + + case '[': + // This is an array. + + $result = array(); + + // Recurse into this function until we reach + // the end of the array. + while (($token = $this->_readToken($c)) !== ']') { + if ($token === false) { + return false; + } + + if (($value = $this->_readValue($c, $token)) === false) { + return false; + } + + $result[] = $value; + } + + return array (self::TYPE_ARRAY, $result); + + case '(': + // This is a string + $pos = $c->offset; + + $openBrackets = 1; + do { + for (; $openBrackets != 0 && $pos < $c->length; $pos++) { + switch (ord($c->buffer[$pos])) { + case 0x28: // '(' + $openBrackets++; + break; + case 0x29: // ')' + $openBrackets--; + break; + case 0x5C: // backslash + $pos++; + } + } + } while($openBrackets != 0 && $c->increaseLength()); + + $result = substr($c->buffer, $c->offset, $pos - $c->offset - 1); + $c->offset = $pos; + + return array (self::TYPE_STRING, $result); + + case 'stream': + $tempPos = $c->getPos() - strlen($c->buffer); + $tempOffset = $c->offset; + + $c->reset($startPos = $tempPos + $tempOffset); + + $e = 0; // ensure line breaks in front of the stream + if ($c->buffer[0] == chr(10) || $c->buffer[0] == chr(13)) + $e++; + if ($c->buffer[1] == chr(10) && $c->buffer[0] != chr(10)) + $e++; + + if ($this->_currentObj[1][1]['/Length'][0] == self::TYPE_OBJREF) { + $tmpLength = $this->resolveObject($this->_currentObj[1][1]['/Length']); + $length = $tmpLength[1][1]; + } else { + $length = $this->_currentObj[1][1]['/Length'][1]; + } + + if ($length > 0) { + $c->reset($startPos + $e, $length); + $v = $c->buffer; + } else { + $v = ''; + } + + $c->reset($startPos + $e + $length); + $endstream = $this->_readToken($c); + + if ($endstream != 'endstream') { + $c->reset($startPos + $e + $length + 9); // 9 = strlen("endstream") + // We don't throw an error here because the next + // round trip will start at a new offset + } + + return array(self::TYPE_STREAM, $v); + + default : + if (is_numeric($token)) { + // A numeric token. Make sure that + // it is not part of something else. + if (($tok2 = $this->_readToken($c)) !== false) { + if (is_numeric($tok2)) { + + // Two numeric tokens in a row. + // In this case, we're probably in + // front of either an object reference + // or an object specification. + // Determine the case and return the data + if (($tok3 = $this->_readToken($c)) !== false) { + switch ($tok3) { + case 'obj': + return array(self::TYPE_OBJDEC, (int)$token, (int)$tok2); + case 'R': + return array(self::TYPE_OBJREF, (int)$token, (int)$tok2); + } + // If we get to this point, that numeric value up + // there was just a numeric value. Push the extra + // tokens back into the stack and return the value. + array_push($c->stack, $tok3); + } + } + + array_push($c->stack, $tok2); + } + + if ($token === (string)((int)$token)) + return array(self::TYPE_NUMERIC, (int)$token); + else + return array(self::TYPE_REAL, (float)$token); + } else if ($token == 'true' || $token == 'false') { + return array(self::TYPE_BOOLEAN, $token == 'true'); + } else if ($token == 'null') { + return array(self::TYPE_NULL); + } else { + // Just a token. Return it. + return array(self::TYPE_TOKEN, $token); + } + } + } + + /** + * Resolve an object + * + * @param array $objSpec The object-data + * @return array|boolean + * @throws Exception + */ + public function resolveObject($objSpec) + { + $c = $this->_c; + + // Exit if we get invalid data + if (!is_array($objSpec)) { + return false; + } + + if ($objSpec[0] == self::TYPE_OBJREF) { + + // This is a reference, resolve it + if (isset($this->_xref['xref'][$objSpec[1]][$objSpec[2]])) { + + // Save current file position + // This is needed if you want to resolve + // references while you're reading another object + // (e.g.: if you need to determine the length + // of a stream) + + $oldPos = $c->getPos(); + + // Reposition the file pointer and + // load the object header. + + $c->reset($this->_xref['xref'][$objSpec[1]][$objSpec[2]]); + + $header = $this->_readValue($c); + + if ($header[0] != self::TYPE_OBJDEC || $header[1] != $objSpec[1] || $header[2] != $objSpec[2]) { + $toSearchFor = $objSpec[1] . ' ' . $objSpec[2] . ' obj'; + if (preg_match('/' . $toSearchFor . '/', $c->buffer)) { + $c->offset = strpos($c->buffer, $toSearchFor) + strlen($toSearchFor); + // reset stack + $c->stack = array(); + } else { + throw new Exception( + sprintf("Unable to find object (%s, %s) at expected location.", $objSpec[1], $objSpec[2]) + ); + } + } + + // If we're being asked to store all the information + // about the object, we add the object ID and generation + // number for later use + $result = array ( + self::TYPE_OBJECT, + 'obj' => $objSpec[1], + 'gen' => $objSpec[2] + ); + + $this->_currentObj =& $result; + + // Now simply read the object data until + // we encounter an end-of-object marker + while (true) { + $value = $this->_readValue($c); + if ($value === false || count($result) > 4) { + // in this case the parser couldn't find an "endobj" so we break here + break; + } + + if ($value[0] == self::TYPE_TOKEN && $value[1] === 'endobj') { + break; + } + + $result[] = $value; + } + + $c->reset($oldPos); + + if (isset($result[2][0]) && $result[2][0] == self::TYPE_STREAM) { + $result[0] = self::TYPE_STREAM; + } + + } else { + throw new Exception( + sprintf("Unable to find object (%s, %s) at expected location.", $objSpec[1], $objSpec[2]) + ); + } + + return $result; + } else { + return $objSpec; + } + } + + /** + * Reads a token from the context + * + * @param pdf_context $c + * @return mixed + */ + protected function _readToken($c) + { + // If there is a token available + // on the stack, pop it out and + // return it. + + if (count($c->stack)) { + return array_pop($c->stack); + } + + // Strip away any whitespace + + do { + if (!$c->ensureContent()) { + return false; + } + $c->offset += strspn($c->buffer, "\x20\x0A\x0C\x0D\x09\x00", $c->offset); + } while ($c->offset >= $c->length - 1); + + // Get the first character in the stream + + $char = $c->buffer[$c->offset++]; + + switch ($char) { + + case '[': + case ']': + case '(': + case ')': + + // This is either an array or literal string + // delimiter, Return it + + return $char; + + case '<': + case '>': + + // This could either be a hex string or + // dictionary delimiter. Determine the + // appropriate case and return the token + + if ($c->buffer[$c->offset] == $char) { + if (!$c->ensureContent()) { + return false; + } + $c->offset++; + return $char . $char; + } else { + return $char; + } + + case '%': + + // This is a comment - jump over it! + + $pos = $c->offset; + while(1) { + $match = preg_match("/(\r\n|\r|\n)/", $c->buffer, $m, PREG_OFFSET_CAPTURE, $pos); + if ($match === 0) { + if (!$c->increaseLength()) { + return false; + } else { + continue; + } + } + + $c->offset = $m[0][1] + strlen($m[0][0]); + + return $this->_readToken($c); + } + + default: + + // This is "another" type of token (probably + // a dictionary entry or a numeric value) + // Find the end and return it. + + if (!$c->ensureContent()) { + return false; + } + + while(1) { + + // Determine the length of the token + + $pos = strcspn($c->buffer, "\x20%[]<>()/\x0A\x0C\x0D\x09\x00", $c->offset); + + if ($c->offset + $pos <= $c->length - 1) { + break; + } else { + // If the script reaches this point, + // the token may span beyond the end + // of the current buffer. Therefore, + // we increase the size of the buffer + // and try again--just to be safe. + + $c->increaseLength(); + } + } + + $result = substr($c->buffer, $c->offset - 1, $pos + 1); + + $c->offset += $pos; + + return $result; + } + } + + /** + * Un-filter a stream object + * + * @param array $obj + * @return string + * @throws Exception + */ + protected function _unFilterStream($obj) + { + $filters = array(); + + if (isset($obj[1][1]['/Filter'])) { + $filter = $obj[1][1]['/Filter']; + + if ($filter[0] == pdf_parser::TYPE_OBJREF) { + $tmpFilter = $this->resolveObject($filter); + $filter = $tmpFilter[1]; + } + + if ($filter[0] == pdf_parser::TYPE_TOKEN) { + $filters[] = $filter; + } else if ($filter[0] == pdf_parser::TYPE_ARRAY) { + $filters = $filter[1]; + } + } + + $stream = $obj[2][1]; + + foreach ($filters AS $filter) { + switch ($filter[1]) { + case '/FlateDecode': + case '/Fl': + if (function_exists('gzuncompress')) { + $oStream = $stream; + $stream = (strlen($stream) > 0) ? @gzuncompress($stream) : ''; + } else { + throw new Exception( + sprintf('To handle %s filter, please compile php with zlib support.', $filter[1]) + ); + } + + if ($stream === false) { + $tries = 0; + while ($tries < 8 && ($stream === false || strlen($stream) < strlen($oStream))) { + $oStream = substr($oStream, 1); + $stream = @gzinflate($oStream); + $tries++; + } + + if ($stream === false) { + throw new Exception('Error while decompressing stream.'); + } + } + break; + case '/LZWDecode': + require_once('filters/FilterLZW.php'); + $decoder = new FilterLZW(); + $stream = $decoder->decode($stream); + break; + case '/ASCII85Decode': + require_once('filters/FilterASCII85.php'); + $decoder = new FilterASCII85(); + $stream = $decoder->decode($stream); + break; + case '/ASCIIHexDecode': + require_once('filters/FilterASCIIHexDecode.php'); + $decoder = new FilterASCIIHexDecode(); + $stream = $decoder->decode($stream); + break; + case null: + break; + default: + throw new Exception(sprintf('Unsupported Filter: %s', $filter[1])); + } + } + + return $stream; + } } \ No newline at end of file diff --git a/resources/templates/engine/smarty/sysplugins/smarty_internal_parsetree.php b/resources/templates/engine/smarty/sysplugins/smarty_internal_parsetree.php index 03518657ec..10920b908f 100644 --- a/resources/templates/engine/smarty/sysplugins/smarty_internal_parsetree.php +++ b/resources/templates/engine/smarty/sysplugins/smarty_internal_parsetree.php @@ -1,393 +1,393 @@ -parser = $parser; - $this->data = $data; - $this->saved_block_nesting = $parser->block_nesting_level; - } - - /** - * Return buffer content - * - * @return string content - */ - public function to_smarty_php() - { - return $this->data; - } - - /** - * Return complied code that loads the evaluated outout of buffer content into a temporary variable - * - * @return string template code - */ - public function assign_to_var() - { - $var = sprintf('$_tmp%d', ++Smarty_Internal_Templateparser::$prefix_number); - $this->parser->compiler->prefix_code[] = sprintf('%s', $this->data, $var); - - return $var; - } - -} - -/** - * Code fragment inside a tag. - * - * @package Smarty - * @subpackage Compiler - * @ignore - */ -class _smarty_code extends _smarty_parsetree -{ - /** - * Create parse tree buffer for code fragment - * - * @param object $parser parser object - * @param string $data content - */ - public function __construct($parser, $data) - { - $this->parser = $parser; - $this->data = $data; - } - - /** - * Return buffer content in parentheses - * - * @return string content - */ - public function to_smarty_php() - { - return sprintf("(%s)", $this->data); - } - -} - -/** - * Double quoted string inside a tag. - * - * @package Smarty - * @subpackage Compiler - * @ignore - */ -class _smarty_doublequoted extends _smarty_parsetree -{ - /** - * Create parse tree buffer for double quoted string subtrees - * - * @param object $parser parser object - * @param _smarty_parsetree $subtree parsetree buffer - */ - public function __construct($parser, _smarty_parsetree $subtree) - { - $this->parser = $parser; - $this->subtrees[] = $subtree; - if ($subtree instanceof _smarty_tag) { - $this->parser->block_nesting_level = count($this->parser->compiler->_tag_stack); - } - } - - /** - * Append buffer to subtree - * - * @param _smarty_parsetree $subtree parsetree buffer - */ - public function append_subtree(_smarty_parsetree $subtree) - { - $last_subtree = count($this->subtrees) - 1; - if ($last_subtree >= 0 && $this->subtrees[$last_subtree] instanceof _smarty_tag && $this->subtrees[$last_subtree]->saved_block_nesting < $this->parser->block_nesting_level) { - if ($subtree instanceof _smarty_code) { - $this->subtrees[$last_subtree]->data .= 'data . ';?>'; - } elseif ($subtree instanceof _smarty_dq_content) { - $this->subtrees[$last_subtree]->data .= 'data . '";?>'; - } else { - $this->subtrees[$last_subtree]->data .= $subtree->data; - } - } else { - $this->subtrees[] = $subtree; - } - if ($subtree instanceof _smarty_tag) { - $this->parser->block_nesting_level = count($this->parser->compiler->_tag_stack); - } - } - - /** - * Merge subtree buffer content together - * - * @return string compiled template code - */ - public function to_smarty_php() - { - $code = ''; - foreach ($this->subtrees as $subtree) { - if ($code !== "") { - $code .= "."; - } - if ($subtree instanceof _smarty_tag) { - $more_php = $subtree->assign_to_var(); - } else { - $more_php = $subtree->to_smarty_php(); - } - - $code .= $more_php; - - if (!$subtree instanceof _smarty_dq_content) { - $this->parser->compiler->has_variable_string = true; - } - } - - return $code; - } - -} - -/** - * Raw chars as part of a double quoted string. - * - * @package Smarty - * @subpackage Compiler - * @ignore - */ -class _smarty_dq_content extends _smarty_parsetree -{ - /** - * Create parse tree buffer with string content - * - * @param object $parser parser object - * @param string $data string section - */ - public function __construct($parser, $data) - { - $this->parser = $parser; - $this->data = $data; - } - - /** - * Return content as double quoted string - * - * @return string doubled quoted string - */ - public function to_smarty_php() - { - return '"' . $this->data . '"'; - } - -} - -/** - * Template element - * - * @package Smarty - * @subpackage Compiler - * @ignore - */ -class _smarty_template_buffer extends _smarty_parsetree -{ - /** - * Array of template elements - * - * @var array - */ - public $subtrees = Array(); - - /** - * Create root of parse tree for template elements - * - * @param object $parser parse object - */ - public function __construct($parser) - { - $this->parser = $parser; - } - - /** - * Append buffer to subtree - * - * @param _smarty_parsetree $subtree - */ - public function append_subtree(_smarty_parsetree $subtree) - { - $this->subtrees[] = $subtree; - } - - /** - * Sanitize and merge subtree buffers together - * - * @return string template code content - */ - public function to_smarty_php() - { - $code = ''; - for ($key = 0, $cnt = count($this->subtrees); $key < $cnt; $key++) { - if ($key + 2 < $cnt) { - if ($this->subtrees[$key] instanceof _smarty_linebreak && $this->subtrees[$key + 1] instanceof _smarty_tag && $this->subtrees[$key + 1]->data == '' && $this->subtrees[$key + 2] instanceof _smarty_linebreak) { - $key = $key + 1; - continue; - } - if (substr($this->subtrees[$key]->data, -1) == '<' && $this->subtrees[$key + 1]->data == '' && substr($this->subtrees[$key + 2]->data, -1) == '?') { - $key = $key + 2; - continue; - } - } - if (substr($code, -1) == '<') { - $subtree = $this->subtrees[$key]->to_smarty_php(); - if (substr($subtree, 0, 1) == '?') { - $code = substr($code, 0, strlen($code) - 1) . '<?' . substr($subtree, 1); - } elseif ($this->parser->asp_tags && substr($subtree, 0, 1) == '%') { - $code = substr($code, 0, strlen($code) - 1) . '<%' . substr($subtree, 1); - } else { - $code .= $subtree; - } - continue; - } - if ($this->parser->asp_tags && substr($code, -1) == '%') { - $subtree = $this->subtrees[$key]->to_smarty_php(); - if (substr($subtree, 0, 1) == '>') { - $code = substr($code, 0, strlen($code) - 1) . '%>' . substr($subtree, 1); - } else { - $code .= $subtree; - } - continue; - } - if (substr($code, -1) == '?') { - $subtree = $this->subtrees[$key]->to_smarty_php(); - if (substr($subtree, 0, 1) == '>') { - $code = substr($code, 0, strlen($code) - 1) . '?>' . substr($subtree, 1); - } else { - $code .= $subtree; - } - continue; - } - $code .= $this->subtrees[$key]->to_smarty_php(); - } - - return $code; - } - -} - -/** - * template text - * - * @package Smarty - * @subpackage Compiler - * @ignore - */ -class _smarty_text extends _smarty_parsetree -{ - /** - * Create template text buffer - * - * @param object $parser parser object - * @param string $data text - */ - public function __construct($parser, $data) - { - $this->parser = $parser; - $this->data = $data; - } - - /** - * Return buffer content - * - * @return strint text - */ - public function to_smarty_php() - { - return $this->data; - } - -} - -/** - * template linebreaks - * - * @package Smarty - * @subpackage Compiler - * @ignore - */ -class _smarty_linebreak extends _smarty_parsetree -{ - /** - * Create buffer with linebreak content - * - * @param object $parser parser object - * @param string $data linebreak string - */ - public function __construct($parser, $data) - { - $this->parser = $parser; - $this->data = $data; - } - - /** - * Return linebrak - * - * @return string linebreak - */ - public function to_smarty_php() - { - return $this->data; - } - -} +parser = $parser; + $this->data = $data; + $this->saved_block_nesting = $parser->block_nesting_level; + } + + /** + * Return buffer content + * + * @return string content + */ + public function to_smarty_php() + { + return $this->data; + } + + /** + * Return complied code that loads the evaluated outout of buffer content into a temporary variable + * + * @return string template code + */ + public function assign_to_var() + { + $var = sprintf('$_tmp%d', ++Smarty_Internal_Templateparser::$prefix_number); + $this->parser->compiler->prefix_code[] = sprintf('%s', $this->data, $var); + + return $var; + } + +} + +/** + * Code fragment inside a tag. + * + * @package Smarty + * @subpackage Compiler + * @ignore + */ +class _smarty_code extends _smarty_parsetree +{ + /** + * Create parse tree buffer for code fragment + * + * @param object $parser parser object + * @param string $data content + */ + public function __construct($parser, $data) + { + $this->parser = $parser; + $this->data = $data; + } + + /** + * Return buffer content in parentheses + * + * @return string content + */ + public function to_smarty_php() + { + return sprintf("(%s)", $this->data); + } + +} + +/** + * Double quoted string inside a tag. + * + * @package Smarty + * @subpackage Compiler + * @ignore + */ +class _smarty_doublequoted extends _smarty_parsetree +{ + /** + * Create parse tree buffer for double quoted string subtrees + * + * @param object $parser parser object + * @param _smarty_parsetree $subtree parsetree buffer + */ + public function __construct($parser, _smarty_parsetree $subtree) + { + $this->parser = $parser; + $this->subtrees[] = $subtree; + if ($subtree instanceof _smarty_tag) { + $this->parser->block_nesting_level = count($this->parser->compiler->_tag_stack); + } + } + + /** + * Append buffer to subtree + * + * @param _smarty_parsetree $subtree parsetree buffer + */ + public function append_subtree(_smarty_parsetree $subtree) + { + $last_subtree = count($this->subtrees) - 1; + if ($last_subtree >= 0 && $this->subtrees[$last_subtree] instanceof _smarty_tag && $this->subtrees[$last_subtree]->saved_block_nesting < $this->parser->block_nesting_level) { + if ($subtree instanceof _smarty_code) { + $this->subtrees[$last_subtree]->data .= 'data . ';?>'; + } elseif ($subtree instanceof _smarty_dq_content) { + $this->subtrees[$last_subtree]->data .= 'data . '";?>'; + } else { + $this->subtrees[$last_subtree]->data .= $subtree->data; + } + } else { + $this->subtrees[] = $subtree; + } + if ($subtree instanceof _smarty_tag) { + $this->parser->block_nesting_level = count($this->parser->compiler->_tag_stack); + } + } + + /** + * Merge subtree buffer content together + * + * @return string compiled template code + */ + public function to_smarty_php() + { + $code = ''; + foreach ($this->subtrees as $subtree) { + if ($code !== "") { + $code .= "."; + } + if ($subtree instanceof _smarty_tag) { + $more_php = $subtree->assign_to_var(); + } else { + $more_php = $subtree->to_smarty_php(); + } + + $code .= $more_php; + + if (!$subtree instanceof _smarty_dq_content) { + $this->parser->compiler->has_variable_string = true; + } + } + + return $code; + } + +} + +/** + * Raw chars as part of a double quoted string. + * + * @package Smarty + * @subpackage Compiler + * @ignore + */ +class _smarty_dq_content extends _smarty_parsetree +{ + /** + * Create parse tree buffer with string content + * + * @param object $parser parser object + * @param string $data string section + */ + public function __construct($parser, $data) + { + $this->parser = $parser; + $this->data = $data; + } + + /** + * Return content as double quoted string + * + * @return string doubled quoted string + */ + public function to_smarty_php() + { + return '"' . $this->data . '"'; + } + +} + +/** + * Template element + * + * @package Smarty + * @subpackage Compiler + * @ignore + */ +class _smarty_template_buffer extends _smarty_parsetree +{ + /** + * Array of template elements + * + * @var array + */ + public $subtrees = Array(); + + /** + * Create root of parse tree for template elements + * + * @param object $parser parse object + */ + public function __construct($parser) + { + $this->parser = $parser; + } + + /** + * Append buffer to subtree + * + * @param _smarty_parsetree $subtree + */ + public function append_subtree(_smarty_parsetree $subtree) + { + $this->subtrees[] = $subtree; + } + + /** + * Sanitize and merge subtree buffers together + * + * @return string template code content + */ + public function to_smarty_php() + { + $code = ''; + for ($key = 0, $cnt = count($this->subtrees); $key < $cnt; $key++) { + if ($key + 2 < $cnt) { + if ($this->subtrees[$key] instanceof _smarty_linebreak && $this->subtrees[$key + 1] instanceof _smarty_tag && $this->subtrees[$key + 1]->data == '' && $this->subtrees[$key + 2] instanceof _smarty_linebreak) { + $key = $key + 1; + continue; + } + if (substr($this->subtrees[$key]->data, -1) == '<' && $this->subtrees[$key + 1]->data == '' && substr($this->subtrees[$key + 2]->data, -1) == '?') { + $key = $key + 2; + continue; + } + } + if (substr($code, -1) == '<') { + $subtree = $this->subtrees[$key]->to_smarty_php(); + if (substr($subtree, 0, 1) == '?') { + $code = substr($code, 0, strlen($code) - 1) . '<?' . substr($subtree, 1); + } elseif ($this->parser->asp_tags && substr($subtree, 0, 1) == '%') { + $code = substr($code, 0, strlen($code) - 1) . '<%' . substr($subtree, 1); + } else { + $code .= $subtree; + } + continue; + } + if ($this->parser->asp_tags && substr($code, -1) == '%') { + $subtree = $this->subtrees[$key]->to_smarty_php(); + if (substr($subtree, 0, 1) == '>') { + $code = substr($code, 0, strlen($code) - 1) . '%>' . substr($subtree, 1); + } else { + $code .= $subtree; + } + continue; + } + if (substr($code, -1) == '?') { + $subtree = $this->subtrees[$key]->to_smarty_php(); + if (substr($subtree, 0, 1) == '>') { + $code = substr($code, 0, strlen($code) - 1) . '?>' . substr($subtree, 1); + } else { + $code .= $subtree; + } + continue; + } + $code .= $this->subtrees[$key]->to_smarty_php(); + } + + return $code; + } + +} + +/** + * template text + * + * @package Smarty + * @subpackage Compiler + * @ignore + */ +class _smarty_text extends _smarty_parsetree +{ + /** + * Create template text buffer + * + * @param object $parser parser object + * @param string $data text + */ + public function __construct($parser, $data) + { + $this->parser = $parser; + $this->data = $data; + } + + /** + * Return buffer content + * + * @return strint text + */ + public function to_smarty_php() + { + return $this->data; + } + +} + +/** + * template linebreaks + * + * @package Smarty + * @subpackage Compiler + * @ignore + */ +class _smarty_linebreak extends _smarty_parsetree +{ + /** + * Create buffer with linebreak content + * + * @param object $parser parser object + * @param string $data linebreak string + */ + public function __construct($parser, $data) + { + $this->parser = $parser; + $this->data = $data; + } + + /** + * Return linebrak + * + * @return string linebreak + */ + public function to_smarty_php() + { + return $this->data; + } + +} diff --git a/resources/templates/engine/smarty/sysplugins/smarty_internal_templatebase.php b/resources/templates/engine/smarty/sysplugins/smarty_internal_templatebase.php index 8ce6d5ecaa..5ebb6a49fe 100644 --- a/resources/templates/engine/smarty/sysplugins/smarty_internal_templatebase.php +++ b/resources/templates/engine/smarty/sysplugins/smarty_internal_templatebase.php @@ -1,822 +1,822 @@ -template_class) { - $template = $this; - } - if (!empty($cache_id) && is_object($cache_id)) { - $parent = $cache_id; - $cache_id = null; - } - if ($parent === null && ($this instanceof Smarty || is_string($template))) { - $parent = $this; - } - // create template object if necessary - $_template = ($template instanceof $this->template_class) - ? $template - : $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false); - // if called by Smarty object make sure we use current caching status - if ($this instanceof Smarty) { - $_template->caching = $this->caching; - } - // merge all variable scopes into template - if ($merge_tpl_vars) { - // save local variables - $save_tpl_vars = $_template->tpl_vars; - $save_config_vars = $_template->config_vars; - $ptr_array = array($_template); - $ptr = $_template; - while (isset($ptr->parent)) { - $ptr_array[] = $ptr = $ptr->parent; - } - $ptr_array = array_reverse($ptr_array); - $parent_ptr = reset($ptr_array); - $tpl_vars = $parent_ptr->tpl_vars; - $config_vars = $parent_ptr->config_vars; - while ($parent_ptr = next($ptr_array)) { - if (!empty($parent_ptr->tpl_vars)) { - $tpl_vars = array_merge($tpl_vars, $parent_ptr->tpl_vars); - } - if (!empty($parent_ptr->config_vars)) { - $config_vars = array_merge($config_vars, $parent_ptr->config_vars); - } - } - if (!empty(Smarty::$global_tpl_vars)) { - $tpl_vars = array_merge(Smarty::$global_tpl_vars, $tpl_vars); - } - $_template->tpl_vars = $tpl_vars; - $_template->config_vars = $config_vars; - } - // dummy local smarty variable - if (!isset($_template->tpl_vars['smarty'])) { - $_template->tpl_vars['smarty'] = new Smarty_Variable; - } - if (isset($this->smarty->error_reporting)) { - $_smarty_old_error_level = error_reporting($this->smarty->error_reporting); - } - // check URL debugging control - if (!$this->smarty->debugging && $this->smarty->debugging_ctrl == 'URL') { - if (isset($_SERVER['QUERY_STRING'])) { - $_query_string = $_SERVER['QUERY_STRING']; - } else { - $_query_string = ''; - } - if (false !== strpos($_query_string, $this->smarty->smarty_debug_id)) { - if (false !== strpos($_query_string, $this->smarty->smarty_debug_id . '=on')) { - // enable debugging for this browser session - setcookie('SMARTY_DEBUG', true); - $this->smarty->debugging = true; - } elseif (false !== strpos($_query_string, $this->smarty->smarty_debug_id . '=off')) { - // disable debugging for this browser session - setcookie('SMARTY_DEBUG', false); - $this->smarty->debugging = false; - } else { - // enable debugging for this page - $this->smarty->debugging = true; - } - } else { - if (isset($_COOKIE['SMARTY_DEBUG'])) { - $this->smarty->debugging = true; - } - } - } - // must reset merge template date - $_template->smarty->merged_templates_func = array(); - // get rendered template - // disable caching for evaluated code - if ($_template->source->recompiled) { - $_template->caching = false; - } - // checks if template exists - if (!$_template->source->exists) { - if ($_template->parent instanceof Smarty_Internal_Template) { - $parent_resource = " in '{$_template->parent->template_resource}'"; - } else { - $parent_resource = ''; - } - throw new SmartyException("Unable to load template {$_template->source->type} '{$_template->source->name}'{$parent_resource}"); - } - // read from cache or render - if (!($_template->caching == Smarty::CACHING_LIFETIME_CURRENT || $_template->caching == Smarty::CACHING_LIFETIME_SAVED) || !$_template->cached->valid) { - // render template (not loaded and not in cache) - if (!$_template->source->uncompiled) { - $_smarty_tpl = $_template; - if ($_template->source->recompiled) { - $code = $_template->compiler->compileTemplate($_template); - if ($this->smarty->debugging) { - Smarty_Internal_Debug::start_render($_template); - } - try { - ob_start(); - eval("?>" . $code); - unset($code); - } catch (Exception $e) { - ob_get_clean(); - throw $e; - } - } else { - if (!$_template->compiled->exists || ($_template->smarty->force_compile && !$_template->compiled->isCompiled)) { - $_template->compileTemplateSource(); - $code = file_get_contents($_template->compiled->filepath); - eval("?>" . $code); - unset($code); - $_template->compiled->loaded = true; - $_template->compiled->isCompiled = true; - } - if ($this->smarty->debugging) { - Smarty_Internal_Debug::start_render($_template); - } - if (!$_template->compiled->loaded) { - include($_template->compiled->filepath); - if ($_template->mustCompile) { - // recompile and load again - $_template->compileTemplateSource(); - $code = file_get_contents($_template->compiled->filepath); - eval("?>" . $code); - unset($code); - $_template->compiled->isCompiled = true; - } - $_template->compiled->loaded = true; - } else { - $_template->decodeProperties($_template->compiled->_properties, false); - } - try { - ob_start(); - if (empty($_template->properties['unifunc']) || !is_callable($_template->properties['unifunc'])) { - throw new SmartyException("Invalid compiled template for '{$_template->template_resource}'"); - } - array_unshift($_template->_capture_stack,array()); - // - // render compiled template - // - $_template->properties['unifunc']($_template); - // any unclosed {capture} tags ? - if (isset($_template->_capture_stack[0][0])) { - $_template->capture_error(); - } - array_shift($_template->_capture_stack); - } catch (Exception $e) { - ob_get_clean(); - throw $e; - } - } - } else { - if ($_template->source->uncompiled) { - if ($this->smarty->debugging) { - Smarty_Internal_Debug::start_render($_template); - } - try { - ob_start(); - $_template->source->renderUncompiled($_template); - } catch (Exception $e) { - ob_get_clean(); - throw $e; - } - } else { - throw new SmartyException("Resource '$_template->source->type' must have 'renderUncompiled' method"); - } - } - $_output = ob_get_clean(); - if (!$_template->source->recompiled && empty($_template->properties['file_dependency'][$_template->source->uid])) { - $_template->properties['file_dependency'][$_template->source->uid] = array($_template->source->filepath, $_template->source->timestamp, $_template->source->type); - } - if ($_template->parent instanceof Smarty_Internal_Template) { - $_template->parent->properties['file_dependency'] = array_merge($_template->parent->properties['file_dependency'], $_template->properties['file_dependency']); - foreach ($_template->required_plugins as $code => $tmp1) { - foreach ($tmp1 as $name => $tmp) { - foreach ($tmp as $type => $data) { - $_template->parent->required_plugins[$code][$name][$type] = $data; - } - } - } - } - if ($this->smarty->debugging) { - Smarty_Internal_Debug::end_render($_template); - } - // write to cache when nessecary - if (!$_template->source->recompiled && ($_template->caching == Smarty::CACHING_LIFETIME_SAVED || $_template->caching == Smarty::CACHING_LIFETIME_CURRENT)) { - if ($this->smarty->debugging) { - Smarty_Internal_Debug::start_cache($_template); - } - $_template->properties['has_nocache_code'] = false; - // get text between non-cached items - $cache_split = preg_split("!/\*%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*\/(.+?)/\*/%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!s", $_output); - // get non-cached items - preg_match_all("!/\*%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*\/(.+?)/\*/%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!s", $_output, $cache_parts); - $output = ''; - // loop over items, stitch back together - foreach ($cache_split as $curr_idx => $curr_split) { - // escape PHP tags in template content - $output .= preg_replace('/(<%|%>|<\?php|<\?|\?>)/', "\n", $curr_split); - if (isset($cache_parts[0][$curr_idx])) { - $_template->properties['has_nocache_code'] = true; - // remove nocache tags from cache output - $output .= preg_replace("!/\*/?%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!", '', $cache_parts[0][$curr_idx]); - } - } - if (!$no_output_filter && !$_template->has_nocache_code && (isset($this->smarty->autoload_filters['output']) || isset($this->smarty->registered_filters['output']))) { - $output = Smarty_Internal_Filter_Handler::runFilter('output', $output, $_template); - } - // rendering (must be done before writing cache file because of {function} nocache handling) - $_smarty_tpl = $_template; - try { - ob_start(); - eval("?>" . $output); - $_output = ob_get_clean(); - } catch (Exception $e) { - ob_get_clean(); - throw $e; - } - // write cache file content - $_template->writeCachedContent($output); - if ($this->smarty->debugging) { - Smarty_Internal_Debug::end_cache($_template); - } - } else { - // var_dump('renderTemplate', $_template->has_nocache_code, $_template->template_resource, $_template->properties['nocache_hash'], $_template->parent->properties['nocache_hash'], $_output); - if (!empty($_template->properties['nocache_hash']) && !empty($_template->parent->properties['nocache_hash'])) { - // replace nocache_hash - $_output = str_replace("{$_template->properties['nocache_hash']}", $_template->parent->properties['nocache_hash'], $_output); - $_template->parent->has_nocache_code = $_template->parent->has_nocache_code || $_template->has_nocache_code; - } - } - } else { - if ($this->smarty->debugging) { - Smarty_Internal_Debug::start_cache($_template); - } - try { - ob_start(); - array_unshift($_template->_capture_stack,array()); - // - // render cached template - // - $_template->properties['unifunc']($_template); - // any unclosed {capture} tags ? - if (isset($_template->_capture_stack[0][0])) { - $_template->capture_error(); - } - array_shift($_template->_capture_stack); - $_output = ob_get_clean(); - } catch (Exception $e) { - ob_get_clean(); - throw $e; - } - if ($this->smarty->debugging) { - Smarty_Internal_Debug::end_cache($_template); - } - } - if ((!$this->caching || $_template->has_nocache_code || $_template->source->recompiled) && !$no_output_filter && (isset($this->smarty->autoload_filters['output']) || isset($this->smarty->registered_filters['output']))) { - $_output = Smarty_Internal_Filter_Handler::runFilter('output', $_output, $_template); - } - if (isset($this->error_reporting)) { - error_reporting($_smarty_old_error_level); - } - // display or fetch - if ($display) { - if ($this->caching && $this->cache_modified_check) { - $_isCached = $_template->isCached() && !$_template->has_nocache_code; - $_last_modified_date = @substr($_SERVER['HTTP_IF_MODIFIED_SINCE'], 0, strpos($_SERVER['HTTP_IF_MODIFIED_SINCE'], 'GMT') + 3); - if ($_isCached && $_template->cached->timestamp <= strtotime($_last_modified_date)) { - switch (PHP_SAPI) { - case 'cgi': // php-cgi < 5.3 - case 'cgi-fcgi': // php-cgi >= 5.3 - case 'fpm-fcgi': // php-fpm >= 5.3.3 - header('Status: 304 Not Modified'); - break; - - case 'cli': - if (/* ^phpunit */!empty($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'])/* phpunit$ */) { - $_SERVER['SMARTY_PHPUNIT_HEADERS'][] = '304 Not Modified'; - } - break; - - default: - header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified'); - break; - } - } else { - switch (PHP_SAPI) { - case 'cli': - if (/* ^phpunit */!empty($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'])/* phpunit$ */) { - $_SERVER['SMARTY_PHPUNIT_HEADERS'][] = 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->cached->timestamp) . ' GMT'; - } - break; - - default: - header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->cached->timestamp) . ' GMT'); - break; - } - echo $_output; - } - } else { - echo $_output; - } - // debug output - if ($this->smarty->debugging) { - Smarty_Internal_Debug::display_debug($this); - } - if ($merge_tpl_vars) { - // restore local variables - $_template->tpl_vars = $save_tpl_vars; - $_template->config_vars = $save_config_vars; - } - - return; - } else { - if ($merge_tpl_vars) { - // restore local variables - $_template->tpl_vars = $save_tpl_vars; - $_template->config_vars = $save_config_vars; - } - // return fetched content - return $_output; - } - } - - /** - * displays a Smarty template - * - * @param string $template the resource handle of the template file or template object - * @param mixed $cache_id cache id to be used with this template - * @param mixed $compile_id compile id to be used with this template - * @param object $parent next higher level of Smarty variables - */ - public function display($template = null, $cache_id = null, $compile_id = null, $parent = null) - { - // display template - $this->fetch($template, $cache_id, $compile_id, $parent, true); - } - - /** - * test if cache is valid - * - * @param string|object $template the resource handle of the template file or template object - * @param mixed $cache_id cache id to be used with this template - * @param mixed $compile_id compile id to be used with this template - * @param object $parent next higher level of Smarty variables - * @return boolean cache status - */ - public function isCached($template = null, $cache_id = null, $compile_id = null, $parent = null) - { - if ($template === null && $this instanceof $this->template_class) { - return $this->cached->valid; - } - if (!($template instanceof $this->template_class)) { - if ($parent === null) { - $parent = $this; - } - $template = $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false); - } - // return cache status of template - return $template->cached->valid; - } - - /** - * creates a data object - * - * @param object $parent next higher level of Smarty variables - * @returns Smarty_Data data object - */ - public function createData($parent = null) - { - return new Smarty_Data($parent, $this); - } - - /** - * Registers plugin to be used in templates - * - * @param string $type plugin type - * @param string $tag name of template tag - * @param callback $callback PHP callback to register - * @param boolean $cacheable if true (default) this fuction is cachable - * @param array $cache_attr caching attributes if any - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - * @throws SmartyException when the plugin tag is invalid - */ - public function registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = null) - { - if (isset($this->smarty->registered_plugins[$type][$tag])) { - throw new SmartyException("Plugin tag \"{$tag}\" already registered"); - } elseif (!is_callable($callback)) { - throw new SmartyException("Plugin \"{$tag}\" not callable"); - } else { - $this->smarty->registered_plugins[$type][$tag] = array($callback, (bool) $cacheable, (array) $cache_attr); - } - - return $this; - } - - /** - * Unregister Plugin - * - * @param string $type of plugin - * @param string $tag name of plugin - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function unregisterPlugin($type, $tag) - { - if (isset($this->smarty->registered_plugins[$type][$tag])) { - unset($this->smarty->registered_plugins[$type][$tag]); - } - - return $this; - } - - /** - * Registers a resource to fetch a template - * - * @param string $type name of resource type - * @param Smarty_Resource|array $callback or instance of Smarty_Resource, or array of callbacks to handle resource (deprecated) - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function registerResource($type, $callback) - { - $this->smarty->registered_resources[$type] = $callback instanceof Smarty_Resource ? $callback : array($callback, false); - - return $this; - } - - /** - * Unregisters a resource - * - * @param string $type name of resource type - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function unregisterResource($type) - { - if (isset($this->smarty->registered_resources[$type])) { - unset($this->smarty->registered_resources[$type]); - } - - return $this; - } - - /** - * Registers a cache resource to cache a template's output - * - * @param string $type name of cache resource type - * @param Smarty_CacheResource $callback instance of Smarty_CacheResource to handle output caching - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function registerCacheResource($type, Smarty_CacheResource $callback) - { - $this->smarty->registered_cache_resources[$type] = $callback; - - return $this; - } - - /** - * Unregisters a cache resource - * - * @param string $type name of cache resource type - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function unregisterCacheResource($type) - { - if (isset($this->smarty->registered_cache_resources[$type])) { - unset($this->smarty->registered_cache_resources[$type]); - } - - return $this; - } - - /** - * Registers object to be used in templates - * - * @param string $object name of template object - * @param object $object_impl the referenced PHP object to register - * @param array $allowed list of allowed methods (empty = all) - * @param boolean $smarty_args smarty argument format, else traditional - * @param array $block_methods list of block-methods - * @param array $block_functs list of methods that are block format - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - * @throws SmartyException if any of the methods in $allowed or $block_methods are invalid - */ - public function registerObject($object_name, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array()) - { - // test if allowed methodes callable - if (!empty($allowed)) { - foreach ((array) $allowed as $method) { - if (!is_callable(array($object_impl, $method)) && !property_exists($object_impl, $method)) { - throw new SmartyException("Undefined method or property '$method' in registered object"); - } - } - } - // test if block methodes callable - if (!empty($block_methods)) { - foreach ((array) $block_methods as $method) { - if (!is_callable(array($object_impl, $method))) { - throw new SmartyException("Undefined method '$method' in registered object"); - } - } - } - // register the object - $this->smarty->registered_objects[$object_name] = - array($object_impl, (array) $allowed, (boolean) $smarty_args, (array) $block_methods); - - return $this; - } - - /** - * return a reference to a registered object - * - * @param string $name object name - * @return object - * @throws SmartyException if no such object is found - */ - public function getRegisteredObject($name) - { - if (!isset($this->smarty->registered_objects[$name])) { - throw new SmartyException("'$name' is not a registered object"); - } - if (!is_object($this->smarty->registered_objects[$name][0])) { - throw new SmartyException("registered '$name' is not an object"); - } - - return $this->smarty->registered_objects[$name][0]; - } - - /** - * unregister an object - * - * @param string $name object name - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function unregisterObject($name) - { - if (isset($this->smarty->registered_objects[$name])) { - unset($this->smarty->registered_objects[$name]); - } - - return $this; - } - - /** - * Registers static classes to be used in templates - * - * @param string $class name of template class - * @param string $class_impl the referenced PHP class to register - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - * @throws SmartyException if $class_impl does not refer to an existing class - */ - public function registerClass($class_name, $class_impl) - { - // test if exists - if (!class_exists($class_impl)) { - throw new SmartyException("Undefined class '$class_impl' in register template class"); - } - // register the class - $this->smarty->registered_classes[$class_name] = $class_impl; - - return $this; - } - - /** - * Registers a default plugin handler - * - * @param callable $callback class/method name - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - * @throws SmartyException if $callback is not callable - */ - public function registerDefaultPluginHandler($callback) - { - if (is_callable($callback)) { - $this->smarty->default_plugin_handler_func = $callback; - } else { - throw new SmartyException("Default plugin handler '$callback' not callable"); - } - - return $this; - } - - /** - * Registers a default template handler - * - * @param callable $callback class/method name - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - * @throws SmartyException if $callback is not callable - */ - public function registerDefaultTemplateHandler($callback) - { - if (is_callable($callback)) { - $this->smarty->default_template_handler_func = $callback; - } else { - throw new SmartyException("Default template handler '$callback' not callable"); - } - - return $this; - } - - /** - * Registers a default template handler - * - * @param callable $callback class/method name - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - * @throws SmartyException if $callback is not callable - */ - public function registerDefaultConfigHandler($callback) - { - if (is_callable($callback)) { - $this->smarty->default_config_handler_func = $callback; - } else { - throw new SmartyException("Default config handler '$callback' not callable"); - } - - return $this; - } - - /** - * Registers a filter function - * - * @param string $type filter type - * @param callback $callback - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function registerFilter($type, $callback) - { - $this->smarty->registered_filters[$type][$this->_get_filter_name($callback)] = $callback; - - return $this; - } - - /** - * Unregisters a filter function - * - * @param string $type filter type - * @param callback $callback - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function unregisterFilter($type, $callback) - { - $name = $this->_get_filter_name($callback); - if (isset($this->smarty->registered_filters[$type][$name])) { - unset($this->smarty->registered_filters[$type][$name]); - } - - return $this; - } - - /** - * Return internal filter name - * - * @param callback $function_name - * @return string internal filter name - */ - public function _get_filter_name($function_name) - { - if (is_array($function_name)) { - $_class_name = (is_object($function_name[0]) ? - get_class($function_name[0]) : $function_name[0]); - - return $_class_name . '_' . $function_name[1]; - } else { - return $function_name; - } - } - - /** - * load a filter of specified type and name - * - * @param string $type filter type - * @param string $name filter name - * @throws SmartyException if filter could not be loaded - */ - public function loadFilter($type, $name) - { - $_plugin = "smarty_{$type}filter_{$name}"; - $_filter_name = $_plugin; - if ($this->smarty->loadPlugin($_plugin)) { - if (class_exists($_plugin, false)) { - $_plugin = array($_plugin, 'execute'); - } - if (is_callable($_plugin)) { - $this->smarty->registered_filters[$type][$_filter_name] = $_plugin; - - return true; - } - } - throw new SmartyException("{$type}filter \"{$name}\" not callable"); - } - - /** - * unload a filter of specified type and name - * - * @param string $type filter type - * @param string $name filter name - * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining - */ - public function unloadFilter($type, $name) - { - $_filter_name = "smarty_{$type}filter_{$name}"; - if (isset($this->smarty->registered_filters[$type][$_filter_name])) { - unset ($this->smarty->registered_filters[$type][$_filter_name]); - } - - return $this; - } - - /** - * preg_replace callback to convert camelcase getter/setter to underscore property names - * - * @param string $match match string - * @return string replacemant - */ - private function replaceCamelcase($match) - { - return "_" . strtolower($match[1]); - } - - /** - * Handle unknown class methods - * - * @param string $name unknown method-name - * @param array $args argument array - */ - public function __call($name, $args) - { - static $_prefixes = array('set' => true, 'get' => true); - static $_resolved_property_name = array(); - static $_resolved_property_source = array(); - - // method of Smarty object? - if (method_exists($this->smarty, $name)) { - return call_user_func_array(array($this->smarty, $name), $args); - } - // see if this is a set/get for a property - $first3 = strtolower(substr($name, 0, 3)); - if (isset($_prefixes[$first3]) && isset($name[3]) && $name[3] !== '_') { - if (isset($_resolved_property_name[$name])) { - $property_name = $_resolved_property_name[$name]; - } else { - // try to keep case correct for future PHP 6.0 case-sensitive class methods - // lcfirst() not available < PHP 5.3.0, so improvise - $property_name = strtolower(substr($name, 3, 1)) . substr($name, 4); - // convert camel case to underscored name - $property_name = preg_replace_callback('/([A-Z])/', array($this,'replaceCamelcase'), $property_name); - $_resolved_property_name[$name] = $property_name; - } - if (isset($_resolved_property_source[$property_name])) { - $_is_this = $_resolved_property_source[$property_name]; - } else { - $_is_this = null; - if (property_exists($this, $property_name)) { - $_is_this = true; - } elseif (property_exists($this->smarty, $property_name)) { - $_is_this = false; - } - $_resolved_property_source[$property_name] = $_is_this; - } - if ($_is_this) { - if ($first3 == 'get') - return $this->$property_name; - else - return $this->$property_name = $args[0]; - } elseif ($_is_this === false) { - if ($first3 == 'get') - return $this->smarty->$property_name; - else - return $this->smarty->$property_name = $args[0]; - } else { - throw new SmartyException("property '$property_name' does not exist."); - - return false; - } - } - if ($name == 'Smarty') { - throw new SmartyException("PHP5 requires you to call __construct() instead of Smarty()"); - } - // must be unknown - throw new SmartyException("Call of unknown method '$name'."); - } - -} +template_class) { + $template = $this; + } + if (!empty($cache_id) && is_object($cache_id)) { + $parent = $cache_id; + $cache_id = null; + } + if ($parent === null && ($this instanceof Smarty || is_string($template))) { + $parent = $this; + } + // create template object if necessary + $_template = ($template instanceof $this->template_class) + ? $template + : $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false); + // if called by Smarty object make sure we use current caching status + if ($this instanceof Smarty) { + $_template->caching = $this->caching; + } + // merge all variable scopes into template + if ($merge_tpl_vars) { + // save local variables + $save_tpl_vars = $_template->tpl_vars; + $save_config_vars = $_template->config_vars; + $ptr_array = array($_template); + $ptr = $_template; + while (isset($ptr->parent)) { + $ptr_array[] = $ptr = $ptr->parent; + } + $ptr_array = array_reverse($ptr_array); + $parent_ptr = reset($ptr_array); + $tpl_vars = $parent_ptr->tpl_vars; + $config_vars = $parent_ptr->config_vars; + while ($parent_ptr = next($ptr_array)) { + if (!empty($parent_ptr->tpl_vars)) { + $tpl_vars = array_merge($tpl_vars, $parent_ptr->tpl_vars); + } + if (!empty($parent_ptr->config_vars)) { + $config_vars = array_merge($config_vars, $parent_ptr->config_vars); + } + } + if (!empty(Smarty::$global_tpl_vars)) { + $tpl_vars = array_merge(Smarty::$global_tpl_vars, $tpl_vars); + } + $_template->tpl_vars = $tpl_vars; + $_template->config_vars = $config_vars; + } + // dummy local smarty variable + if (!isset($_template->tpl_vars['smarty'])) { + $_template->tpl_vars['smarty'] = new Smarty_Variable; + } + if (isset($this->smarty->error_reporting)) { + $_smarty_old_error_level = error_reporting($this->smarty->error_reporting); + } + // check URL debugging control + if (!$this->smarty->debugging && $this->smarty->debugging_ctrl == 'URL') { + if (isset($_SERVER['QUERY_STRING'])) { + $_query_string = $_SERVER['QUERY_STRING']; + } else { + $_query_string = ''; + } + if (false !== strpos($_query_string, $this->smarty->smarty_debug_id)) { + if (false !== strpos($_query_string, $this->smarty->smarty_debug_id . '=on')) { + // enable debugging for this browser session + setcookie('SMARTY_DEBUG', true); + $this->smarty->debugging = true; + } elseif (false !== strpos($_query_string, $this->smarty->smarty_debug_id . '=off')) { + // disable debugging for this browser session + setcookie('SMARTY_DEBUG', false); + $this->smarty->debugging = false; + } else { + // enable debugging for this page + $this->smarty->debugging = true; + } + } else { + if (isset($_COOKIE['SMARTY_DEBUG'])) { + $this->smarty->debugging = true; + } + } + } + // must reset merge template date + $_template->smarty->merged_templates_func = array(); + // get rendered template + // disable caching for evaluated code + if ($_template->source->recompiled) { + $_template->caching = false; + } + // checks if template exists + if (!$_template->source->exists) { + if ($_template->parent instanceof Smarty_Internal_Template) { + $parent_resource = " in '{$_template->parent->template_resource}'"; + } else { + $parent_resource = ''; + } + throw new SmartyException("Unable to load template {$_template->source->type} '{$_template->source->name}'{$parent_resource}"); + } + // read from cache or render + if (!($_template->caching == Smarty::CACHING_LIFETIME_CURRENT || $_template->caching == Smarty::CACHING_LIFETIME_SAVED) || !$_template->cached->valid) { + // render template (not loaded and not in cache) + if (!$_template->source->uncompiled) { + $_smarty_tpl = $_template; + if ($_template->source->recompiled) { + $code = $_template->compiler->compileTemplate($_template); + if ($this->smarty->debugging) { + Smarty_Internal_Debug::start_render($_template); + } + try { + ob_start(); + eval("?>" . $code); + unset($code); + } catch (Exception $e) { + ob_get_clean(); + throw $e; + } + } else { + if (!$_template->compiled->exists || ($_template->smarty->force_compile && !$_template->compiled->isCompiled)) { + $_template->compileTemplateSource(); + $code = file_get_contents($_template->compiled->filepath); + eval("?>" . $code); + unset($code); + $_template->compiled->loaded = true; + $_template->compiled->isCompiled = true; + } + if ($this->smarty->debugging) { + Smarty_Internal_Debug::start_render($_template); + } + if (!$_template->compiled->loaded) { + include($_template->compiled->filepath); + if ($_template->mustCompile) { + // recompile and load again + $_template->compileTemplateSource(); + $code = file_get_contents($_template->compiled->filepath); + eval("?>" . $code); + unset($code); + $_template->compiled->isCompiled = true; + } + $_template->compiled->loaded = true; + } else { + $_template->decodeProperties($_template->compiled->_properties, false); + } + try { + ob_start(); + if (empty($_template->properties['unifunc']) || !is_callable($_template->properties['unifunc'])) { + throw new SmartyException("Invalid compiled template for '{$_template->template_resource}'"); + } + array_unshift($_template->_capture_stack,array()); + // + // render compiled template + // + $_template->properties['unifunc']($_template); + // any unclosed {capture} tags ? + if (isset($_template->_capture_stack[0][0])) { + $_template->capture_error(); + } + array_shift($_template->_capture_stack); + } catch (Exception $e) { + ob_get_clean(); + throw $e; + } + } + } else { + if ($_template->source->uncompiled) { + if ($this->smarty->debugging) { + Smarty_Internal_Debug::start_render($_template); + } + try { + ob_start(); + $_template->source->renderUncompiled($_template); + } catch (Exception $e) { + ob_get_clean(); + throw $e; + } + } else { + throw new SmartyException("Resource '$_template->source->type' must have 'renderUncompiled' method"); + } + } + $_output = ob_get_clean(); + if (!$_template->source->recompiled && empty($_template->properties['file_dependency'][$_template->source->uid])) { + $_template->properties['file_dependency'][$_template->source->uid] = array($_template->source->filepath, $_template->source->timestamp, $_template->source->type); + } + if ($_template->parent instanceof Smarty_Internal_Template) { + $_template->parent->properties['file_dependency'] = array_merge($_template->parent->properties['file_dependency'], $_template->properties['file_dependency']); + foreach ($_template->required_plugins as $code => $tmp1) { + foreach ($tmp1 as $name => $tmp) { + foreach ($tmp as $type => $data) { + $_template->parent->required_plugins[$code][$name][$type] = $data; + } + } + } + } + if ($this->smarty->debugging) { + Smarty_Internal_Debug::end_render($_template); + } + // write to cache when nessecary + if (!$_template->source->recompiled && ($_template->caching == Smarty::CACHING_LIFETIME_SAVED || $_template->caching == Smarty::CACHING_LIFETIME_CURRENT)) { + if ($this->smarty->debugging) { + Smarty_Internal_Debug::start_cache($_template); + } + $_template->properties['has_nocache_code'] = false; + // get text between non-cached items + $cache_split = preg_split("!/\*%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*\/(.+?)/\*/%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!s", $_output); + // get non-cached items + preg_match_all("!/\*%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*\/(.+?)/\*/%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!s", $_output, $cache_parts); + $output = ''; + // loop over items, stitch back together + foreach ($cache_split as $curr_idx => $curr_split) { + // escape PHP tags in template content + $output .= preg_replace('/(<%|%>|<\?php|<\?|\?>)/', "\n", $curr_split); + if (isset($cache_parts[0][$curr_idx])) { + $_template->properties['has_nocache_code'] = true; + // remove nocache tags from cache output + $output .= preg_replace("!/\*/?%%SmartyNocache:{$_template->properties['nocache_hash']}%%\*/!", '', $cache_parts[0][$curr_idx]); + } + } + if (!$no_output_filter && !$_template->has_nocache_code && (isset($this->smarty->autoload_filters['output']) || isset($this->smarty->registered_filters['output']))) { + $output = Smarty_Internal_Filter_Handler::runFilter('output', $output, $_template); + } + // rendering (must be done before writing cache file because of {function} nocache handling) + $_smarty_tpl = $_template; + try { + ob_start(); + eval("?>" . $output); + $_output = ob_get_clean(); + } catch (Exception $e) { + ob_get_clean(); + throw $e; + } + // write cache file content + $_template->writeCachedContent($output); + if ($this->smarty->debugging) { + Smarty_Internal_Debug::end_cache($_template); + } + } else { + // var_dump('renderTemplate', $_template->has_nocache_code, $_template->template_resource, $_template->properties['nocache_hash'], $_template->parent->properties['nocache_hash'], $_output); + if (!empty($_template->properties['nocache_hash']) && !empty($_template->parent->properties['nocache_hash'])) { + // replace nocache_hash + $_output = str_replace("{$_template->properties['nocache_hash']}", $_template->parent->properties['nocache_hash'], $_output); + $_template->parent->has_nocache_code = $_template->parent->has_nocache_code || $_template->has_nocache_code; + } + } + } else { + if ($this->smarty->debugging) { + Smarty_Internal_Debug::start_cache($_template); + } + try { + ob_start(); + array_unshift($_template->_capture_stack,array()); + // + // render cached template + // + $_template->properties['unifunc']($_template); + // any unclosed {capture} tags ? + if (isset($_template->_capture_stack[0][0])) { + $_template->capture_error(); + } + array_shift($_template->_capture_stack); + $_output = ob_get_clean(); + } catch (Exception $e) { + ob_get_clean(); + throw $e; + } + if ($this->smarty->debugging) { + Smarty_Internal_Debug::end_cache($_template); + } + } + if ((!$this->caching || $_template->has_nocache_code || $_template->source->recompiled) && !$no_output_filter && (isset($this->smarty->autoload_filters['output']) || isset($this->smarty->registered_filters['output']))) { + $_output = Smarty_Internal_Filter_Handler::runFilter('output', $_output, $_template); + } + if (isset($this->error_reporting)) { + error_reporting($_smarty_old_error_level); + } + // display or fetch + if ($display) { + if ($this->caching && $this->cache_modified_check) { + $_isCached = $_template->isCached() && !$_template->has_nocache_code; + $_last_modified_date = @substr($_SERVER['HTTP_IF_MODIFIED_SINCE'], 0, strpos($_SERVER['HTTP_IF_MODIFIED_SINCE'], 'GMT') + 3); + if ($_isCached && $_template->cached->timestamp <= strtotime($_last_modified_date)) { + switch (PHP_SAPI) { + case 'cgi': // php-cgi < 5.3 + case 'cgi-fcgi': // php-cgi >= 5.3 + case 'fpm-fcgi': // php-fpm >= 5.3.3 + header('Status: 304 Not Modified'); + break; + + case 'cli': + if (/* ^phpunit */!empty($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'])/* phpunit$ */) { + $_SERVER['SMARTY_PHPUNIT_HEADERS'][] = '304 Not Modified'; + } + break; + + default: + header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified'); + break; + } + } else { + switch (PHP_SAPI) { + case 'cli': + if (/* ^phpunit */!empty($_SERVER['SMARTY_PHPUNIT_DISABLE_HEADERS'])/* phpunit$ */) { + $_SERVER['SMARTY_PHPUNIT_HEADERS'][] = 'Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->cached->timestamp) . ' GMT'; + } + break; + + default: + header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->cached->timestamp) . ' GMT'); + break; + } + echo $_output; + } + } else { + echo $_output; + } + // debug output + if ($this->smarty->debugging) { + Smarty_Internal_Debug::display_debug($this); + } + if ($merge_tpl_vars) { + // restore local variables + $_template->tpl_vars = $save_tpl_vars; + $_template->config_vars = $save_config_vars; + } + + return; + } else { + if ($merge_tpl_vars) { + // restore local variables + $_template->tpl_vars = $save_tpl_vars; + $_template->config_vars = $save_config_vars; + } + // return fetched content + return $_output; + } + } + + /** + * displays a Smarty template + * + * @param string $template the resource handle of the template file or template object + * @param mixed $cache_id cache id to be used with this template + * @param mixed $compile_id compile id to be used with this template + * @param object $parent next higher level of Smarty variables + */ + public function display($template = null, $cache_id = null, $compile_id = null, $parent = null) + { + // display template + $this->fetch($template, $cache_id, $compile_id, $parent, true); + } + + /** + * test if cache is valid + * + * @param string|object $template the resource handle of the template file or template object + * @param mixed $cache_id cache id to be used with this template + * @param mixed $compile_id compile id to be used with this template + * @param object $parent next higher level of Smarty variables + * @return boolean cache status + */ + public function isCached($template = null, $cache_id = null, $compile_id = null, $parent = null) + { + if ($template === null && $this instanceof $this->template_class) { + return $this->cached->valid; + } + if (!($template instanceof $this->template_class)) { + if ($parent === null) { + $parent = $this; + } + $template = $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false); + } + // return cache status of template + return $template->cached->valid; + } + + /** + * creates a data object + * + * @param object $parent next higher level of Smarty variables + * @returns Smarty_Data data object + */ + public function createData($parent = null) + { + return new Smarty_Data($parent, $this); + } + + /** + * Registers plugin to be used in templates + * + * @param string $type plugin type + * @param string $tag name of template tag + * @param callback $callback PHP callback to register + * @param boolean $cacheable if true (default) this fuction is cachable + * @param array $cache_attr caching attributes if any + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + * @throws SmartyException when the plugin tag is invalid + */ + public function registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = null) + { + if (isset($this->smarty->registered_plugins[$type][$tag])) { + throw new SmartyException("Plugin tag \"{$tag}\" already registered"); + } elseif (!is_callable($callback)) { + throw new SmartyException("Plugin \"{$tag}\" not callable"); + } else { + $this->smarty->registered_plugins[$type][$tag] = array($callback, (bool) $cacheable, (array) $cache_attr); + } + + return $this; + } + + /** + * Unregister Plugin + * + * @param string $type of plugin + * @param string $tag name of plugin + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function unregisterPlugin($type, $tag) + { + if (isset($this->smarty->registered_plugins[$type][$tag])) { + unset($this->smarty->registered_plugins[$type][$tag]); + } + + return $this; + } + + /** + * Registers a resource to fetch a template + * + * @param string $type name of resource type + * @param Smarty_Resource|array $callback or instance of Smarty_Resource, or array of callbacks to handle resource (deprecated) + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function registerResource($type, $callback) + { + $this->smarty->registered_resources[$type] = $callback instanceof Smarty_Resource ? $callback : array($callback, false); + + return $this; + } + + /** + * Unregisters a resource + * + * @param string $type name of resource type + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function unregisterResource($type) + { + if (isset($this->smarty->registered_resources[$type])) { + unset($this->smarty->registered_resources[$type]); + } + + return $this; + } + + /** + * Registers a cache resource to cache a template's output + * + * @param string $type name of cache resource type + * @param Smarty_CacheResource $callback instance of Smarty_CacheResource to handle output caching + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function registerCacheResource($type, Smarty_CacheResource $callback) + { + $this->smarty->registered_cache_resources[$type] = $callback; + + return $this; + } + + /** + * Unregisters a cache resource + * + * @param string $type name of cache resource type + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function unregisterCacheResource($type) + { + if (isset($this->smarty->registered_cache_resources[$type])) { + unset($this->smarty->registered_cache_resources[$type]); + } + + return $this; + } + + /** + * Registers object to be used in templates + * + * @param string $object name of template object + * @param object $object_impl the referenced PHP object to register + * @param array $allowed list of allowed methods (empty = all) + * @param boolean $smarty_args smarty argument format, else traditional + * @param array $block_methods list of block-methods + * @param array $block_functs list of methods that are block format + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + * @throws SmartyException if any of the methods in $allowed or $block_methods are invalid + */ + public function registerObject($object_name, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array()) + { + // test if allowed methodes callable + if (!empty($allowed)) { + foreach ((array) $allowed as $method) { + if (!is_callable(array($object_impl, $method)) && !property_exists($object_impl, $method)) { + throw new SmartyException("Undefined method or property '$method' in registered object"); + } + } + } + // test if block methodes callable + if (!empty($block_methods)) { + foreach ((array) $block_methods as $method) { + if (!is_callable(array($object_impl, $method))) { + throw new SmartyException("Undefined method '$method' in registered object"); + } + } + } + // register the object + $this->smarty->registered_objects[$object_name] = + array($object_impl, (array) $allowed, (boolean) $smarty_args, (array) $block_methods); + + return $this; + } + + /** + * return a reference to a registered object + * + * @param string $name object name + * @return object + * @throws SmartyException if no such object is found + */ + public function getRegisteredObject($name) + { + if (!isset($this->smarty->registered_objects[$name])) { + throw new SmartyException("'$name' is not a registered object"); + } + if (!is_object($this->smarty->registered_objects[$name][0])) { + throw new SmartyException("registered '$name' is not an object"); + } + + return $this->smarty->registered_objects[$name][0]; + } + + /** + * unregister an object + * + * @param string $name object name + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function unregisterObject($name) + { + if (isset($this->smarty->registered_objects[$name])) { + unset($this->smarty->registered_objects[$name]); + } + + return $this; + } + + /** + * Registers static classes to be used in templates + * + * @param string $class name of template class + * @param string $class_impl the referenced PHP class to register + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + * @throws SmartyException if $class_impl does not refer to an existing class + */ + public function registerClass($class_name, $class_impl) + { + // test if exists + if (!class_exists($class_impl)) { + throw new SmartyException("Undefined class '$class_impl' in register template class"); + } + // register the class + $this->smarty->registered_classes[$class_name] = $class_impl; + + return $this; + } + + /** + * Registers a default plugin handler + * + * @param callable $callback class/method name + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + * @throws SmartyException if $callback is not callable + */ + public function registerDefaultPluginHandler($callback) + { + if (is_callable($callback)) { + $this->smarty->default_plugin_handler_func = $callback; + } else { + throw new SmartyException("Default plugin handler '$callback' not callable"); + } + + return $this; + } + + /** + * Registers a default template handler + * + * @param callable $callback class/method name + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + * @throws SmartyException if $callback is not callable + */ + public function registerDefaultTemplateHandler($callback) + { + if (is_callable($callback)) { + $this->smarty->default_template_handler_func = $callback; + } else { + throw new SmartyException("Default template handler '$callback' not callable"); + } + + return $this; + } + + /** + * Registers a default template handler + * + * @param callable $callback class/method name + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + * @throws SmartyException if $callback is not callable + */ + public function registerDefaultConfigHandler($callback) + { + if (is_callable($callback)) { + $this->smarty->default_config_handler_func = $callback; + } else { + throw new SmartyException("Default config handler '$callback' not callable"); + } + + return $this; + } + + /** + * Registers a filter function + * + * @param string $type filter type + * @param callback $callback + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function registerFilter($type, $callback) + { + $this->smarty->registered_filters[$type][$this->_get_filter_name($callback)] = $callback; + + return $this; + } + + /** + * Unregisters a filter function + * + * @param string $type filter type + * @param callback $callback + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function unregisterFilter($type, $callback) + { + $name = $this->_get_filter_name($callback); + if (isset($this->smarty->registered_filters[$type][$name])) { + unset($this->smarty->registered_filters[$type][$name]); + } + + return $this; + } + + /** + * Return internal filter name + * + * @param callback $function_name + * @return string internal filter name + */ + public function _get_filter_name($function_name) + { + if (is_array($function_name)) { + $_class_name = (is_object($function_name[0]) ? + get_class($function_name[0]) : $function_name[0]); + + return $_class_name . '_' . $function_name[1]; + } else { + return $function_name; + } + } + + /** + * load a filter of specified type and name + * + * @param string $type filter type + * @param string $name filter name + * @throws SmartyException if filter could not be loaded + */ + public function loadFilter($type, $name) + { + $_plugin = "smarty_{$type}filter_{$name}"; + $_filter_name = $_plugin; + if ($this->smarty->loadPlugin($_plugin)) { + if (class_exists($_plugin, false)) { + $_plugin = array($_plugin, 'execute'); + } + if (is_callable($_plugin)) { + $this->smarty->registered_filters[$type][$_filter_name] = $_plugin; + + return true; + } + } + throw new SmartyException("{$type}filter \"{$name}\" not callable"); + } + + /** + * unload a filter of specified type and name + * + * @param string $type filter type + * @param string $name filter name + * @return Smarty_Internal_Templatebase current Smarty_Internal_Templatebase (or Smarty or Smarty_Internal_Template) instance for chaining + */ + public function unloadFilter($type, $name) + { + $_filter_name = "smarty_{$type}filter_{$name}"; + if (isset($this->smarty->registered_filters[$type][$_filter_name])) { + unset ($this->smarty->registered_filters[$type][$_filter_name]); + } + + return $this; + } + + /** + * preg_replace callback to convert camelcase getter/setter to underscore property names + * + * @param string $match match string + * @return string replacemant + */ + private function replaceCamelcase($match) + { + return "_" . strtolower($match[1]); + } + + /** + * Handle unknown class methods + * + * @param string $name unknown method-name + * @param array $args argument array + */ + public function __call($name, $args) + { + static $_prefixes = array('set' => true, 'get' => true); + static $_resolved_property_name = array(); + static $_resolved_property_source = array(); + + // method of Smarty object? + if (method_exists($this->smarty, $name)) { + return call_user_func_array(array($this->smarty, $name), $args); + } + // see if this is a set/get for a property + $first3 = strtolower(substr($name, 0, 3)); + if (isset($_prefixes[$first3]) && isset($name[3]) && $name[3] !== '_') { + if (isset($_resolved_property_name[$name])) { + $property_name = $_resolved_property_name[$name]; + } else { + // try to keep case correct for future PHP 6.0 case-sensitive class methods + // lcfirst() not available < PHP 5.3.0, so improvise + $property_name = strtolower(substr($name, 3, 1)) . substr($name, 4); + // convert camel case to underscored name + $property_name = preg_replace_callback('/([A-Z])/', array($this,'replaceCamelcase'), $property_name); + $_resolved_property_name[$name] = $property_name; + } + if (isset($_resolved_property_source[$property_name])) { + $_is_this = $_resolved_property_source[$property_name]; + } else { + $_is_this = null; + if (property_exists($this, $property_name)) { + $_is_this = true; + } elseif (property_exists($this->smarty, $property_name)) { + $_is_this = false; + } + $_resolved_property_source[$property_name] = $_is_this; + } + if ($_is_this) { + if ($first3 == 'get') + return $this->$property_name; + else + return $this->$property_name = $args[0]; + } elseif ($_is_this === false) { + if ($first3 == 'get') + return $this->smarty->$property_name; + else + return $this->smarty->$property_name = $args[0]; + } else { + throw new SmartyException("property '$property_name' does not exist."); + + return false; + } + } + if ($name == 'Smarty') { + throw new SmartyException("PHP5 requires you to call __construct() instead of Smarty()"); + } + // must be unknown + throw new SmartyException("Call of unknown method '$name'."); + } + +} diff --git a/resources/templates/engine/smarty/sysplugins/smarty_internal_templatecompilerbase.php b/resources/templates/engine/smarty/sysplugins/smarty_internal_templatecompilerbase.php index d7268fbf7d..7236be8bd6 100644 --- a/resources/templates/engine/smarty/sysplugins/smarty_internal_templatecompilerbase.php +++ b/resources/templates/engine/smarty/sysplugins/smarty_internal_templatecompilerbase.php @@ -1,809 +1,809 @@ -nocache_hash = str_replace('.', '-', uniqid(rand(), true)); - } - - /** - * Method to compile a Smarty template - * - * @param Smarty_Internal_Template $template template object to compile - * @param bool $nocache true is shall be compiled in nocache mode - * @return bool true if compiling succeeded, false if it failed - */ - public function compileTemplate(Smarty_Internal_Template $template, $nocache = false) - { - if (empty($template->properties['nocache_hash'])) { - $template->properties['nocache_hash'] = $this->nocache_hash; - } else { - $this->nocache_hash = $template->properties['nocache_hash']; - } - // flag for nochache sections - $this->nocache = $nocache; - $this->tag_nocache = false; - // save template object in compiler class - $this->template = $template; - // reset has nocache code flag - $this->template->has_nocache_code = false; - $save_source = $this->template->source; - // template header code - $template_header = ''; - if (!$this->suppressHeader) { - $template_header .= "template->source->filepath . "\" */ ?>\n"; - } - - if (empty($this->template->source->components)) { - $this->sources = array($template->source); - } else { - // we have array of inheritance templates by extends: resource - $this->sources = array_reverse($template->source->components); - } - $loop = 0; - // the $this->sources array can get additional elements while compiling by the {extends} tag - while ($this->template->source = array_shift($this->sources)) { - $this->smarty->_current_file = $this->template->source->filepath; - if ($this->smarty->debugging) { - Smarty_Internal_Debug::start_compile($this->template); - } - $no_sources = count($this->sources); - if ($loop || $no_sources) { - $this->template->properties['file_dependency'][$this->template->source->uid] = array($this->template->source->filepath, $this->template->source->timestamp, $this->template->source->type); - } - $loop++; - if ($no_sources) { - $this->inheritance_child = true; - } else { - $this->inheritance_child = false; - } - do { - $_compiled_code = ''; - // flag for aborting current and start recompile - $this->abort_and_recompile = false; - // get template source - $_content = $this->template->source->content; - if ($_content != '') { - // run prefilter if required - if ((isset($this->smarty->autoload_filters['pre']) || isset($this->smarty->registered_filters['pre'])) && !$this->suppressFilter) { - $_content = Smarty_Internal_Filter_Handler::runFilter('pre', $_content, $template); - } - // call compiler - $_compiled_code = $this->doCompile($_content); - } - } while ($this->abort_and_recompile); - if ($this->smarty->debugging) { - Smarty_Internal_Debug::end_compile($this->template); - } - } - // restore source - $this->template->source = $save_source; - unset($save_source); - $this->smarty->_current_file = $this->template->source->filepath; - // free memory - unset($this->parser->root_buffer, $this->parser->current_buffer, $this->parser, $this->lex, $this->template); - self::$_tag_objects = array(); - // return compiled code to template object - $merged_code = ''; - if (!$this->suppressMergedTemplates && !empty($this->merged_templates)) { - foreach ($this->merged_templates as $code) { - $merged_code .= $code; - } - } - // run postfilter if required on compiled template code - if ((isset($this->smarty->autoload_filters['post']) || isset($this->smarty->registered_filters['post'])) && !$this->suppressFilter && $_compiled_code != '') { - $_compiled_code = Smarty_Internal_Filter_Handler::runFilter('post', $_compiled_code, $template); - } - if ($this->suppressTemplatePropertyHeader) { - $code = $_compiled_code . $merged_code; - } else { - $code = $template_header . $template->createTemplateCodeFrame($_compiled_code) . $merged_code; - } - // unset content because template inheritance could have replace source with parent code - unset ($template->source->content); - - return $code; - } - - /** - * Compile Tag - * - * This is a call back from the lexer/parser - * It executes the required compile plugin for the Smarty tag - * - * @param string $tag tag name - * @param array $args array with tag attributes - * @param array $parameter array with compilation parameter - * @return string compiled code - */ - public function compileTag($tag, $args, $parameter = array()) - { - // $args contains the attributes parsed and compiled by the lexer/parser - // assume that tag does compile into code, but creates no HTML output - $this->has_code = true; - $this->has_output = false; - // log tag/attributes - if (isset($this->smarty->get_used_tags) && $this->smarty->get_used_tags) { - $this->template->used_tags[] = array($tag, $args); - } - // check nocache option flag - if (in_array("'nocache'", $args) || in_array(array('nocache' => 'true'), $args) - || in_array(array('nocache' => '"true"'), $args) || in_array(array('nocache' => "'true'"), $args) - ) { - $this->tag_nocache = true; - } - // compile the smarty tag (required compile classes to compile the tag are autoloaded) - if (($_output = $this->callTagCompiler($tag, $args, $parameter)) === false) { - if (isset($this->smarty->template_functions[$tag])) { - // template defined by {template} tag - $args['_attr']['name'] = "'" . $tag . "'"; - $_output = $this->callTagCompiler('call', $args, $parameter); - } - } - if ($_output !== false) { - if ($_output !== true) { - // did we get compiled code - if ($this->has_code) { - // Does it create output? - if ($this->has_output) { - $_output .= "\n"; - } - // return compiled code - return $_output; - } - } - // tag did not produce compiled code - return null; - } else { - // map_named attributes - if (isset($args['_attr'])) { - foreach ($args['_attr'] as $key => $attribute) { - if (is_array($attribute)) { - $args = array_merge($args, $attribute); - } - } - } - // not an internal compiler tag - if (strlen($tag) < 6 || substr($tag, -5) != 'close') { - // check if tag is a registered object - if (isset($this->smarty->registered_objects[$tag]) && isset($parameter['object_methode'])) { - $methode = $parameter['object_methode']; - if (!in_array($methode, $this->smarty->registered_objects[$tag][3]) && - (empty($this->smarty->registered_objects[$tag][1]) || in_array($methode, $this->smarty->registered_objects[$tag][1])) - ) { - return $this->callTagCompiler('private_object_function', $args, $parameter, $tag, $methode); - } elseif (in_array($methode, $this->smarty->registered_objects[$tag][3])) { - return $this->callTagCompiler('private_object_block_function', $args, $parameter, $tag, $methode); - } else { - return $this->trigger_template_error('unallowed methode "' . $methode . '" in registered object "' . $tag . '"', $this->lex->taglineno); - } - } - // check if tag is registered - foreach (array(Smarty::PLUGIN_COMPILER, Smarty::PLUGIN_FUNCTION, Smarty::PLUGIN_BLOCK) as $plugin_type) { - if (isset($this->smarty->registered_plugins[$plugin_type][$tag])) { - // if compiler function plugin call it now - if ($plugin_type == Smarty::PLUGIN_COMPILER) { - $new_args = array(); - foreach ($args as $key => $mixed) { - if (is_array($mixed)) { - $new_args = array_merge($new_args, $mixed); - } else { - $new_args[$key] = $mixed; - } - } - if (!$this->smarty->registered_plugins[$plugin_type][$tag][1]) { - $this->tag_nocache = true; - } - $function = $this->smarty->registered_plugins[$plugin_type][$tag][0]; - if (!is_array($function)) { - return $function($new_args, $this); - } elseif (is_object($function[0])) { - return $this->smarty->registered_plugins[$plugin_type][$tag][0][0]->$function[1]($new_args, $this); - } else { - return call_user_func_array($function, array($new_args, $this)); - } - } - // compile registered function or block function - if ($plugin_type == Smarty::PLUGIN_FUNCTION || $plugin_type == Smarty::PLUGIN_BLOCK) { - return $this->callTagCompiler('private_registered_' . $plugin_type, $args, $parameter, $tag); - } - } - } - // check plugins from plugins folder - foreach ($this->smarty->plugin_search_order as $plugin_type) { - if ($plugin_type == Smarty::PLUGIN_COMPILER && $this->smarty->loadPlugin('smarty_compiler_' . $tag) && (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this))) { - $plugin = 'smarty_compiler_' . $tag; - if (is_callable($plugin)) { - // convert arguments format for old compiler plugins - $new_args = array(); - foreach ($args as $key => $mixed) { - if (is_array($mixed)) { - $new_args = array_merge($new_args, $mixed); - } else { - $new_args[$key] = $mixed; - } - } - - return $plugin($new_args, $this->smarty); - } - if (class_exists($plugin, false)) { - $plugin_object = new $plugin; - if (method_exists($plugin_object, 'compile')) { - return $plugin_object->compile($args, $this); - } - } - throw new SmartyException("Plugin \"{$tag}\" not callable"); - } else { - if ($function = $this->getPlugin($tag, $plugin_type)) { - if (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this)) { - return $this->callTagCompiler('private_' . $plugin_type . '_plugin', $args, $parameter, $tag, $function); - } - } - } - } - if (is_callable($this->smarty->default_plugin_handler_func)) { - $found = false; - // look for already resolved tags - foreach ($this->smarty->plugin_search_order as $plugin_type) { - if (isset($this->default_handler_plugins[$plugin_type][$tag])) { - $found = true; - break; - } - } - if (!$found) { - // call default handler - foreach ($this->smarty->plugin_search_order as $plugin_type) { - if ($this->getPluginFromDefaultHandler($tag, $plugin_type)) { - $found = true; - break; - } - } - } - if ($found) { - // if compiler function plugin call it now - if ($plugin_type == Smarty::PLUGIN_COMPILER) { - $new_args = array(); - foreach ($args as $mixed) { - $new_args = array_merge($new_args, $mixed); - } - $function = $this->default_handler_plugins[$plugin_type][$tag][0]; - if (!is_array($function)) { - return $function($new_args, $this); - } elseif (is_object($function[0])) { - return $this->default_handler_plugins[$plugin_type][$tag][0][0]->$function[1]($new_args, $this); - } else { - return call_user_func_array($function, array($new_args, $this)); - } - } else { - return $this->callTagCompiler('private_registered_' . $plugin_type, $args, $parameter, $tag); - } - } - } - } else { - // compile closing tag of block function - $base_tag = substr($tag, 0, -5); - // check if closing tag is a registered object - if (isset($this->smarty->registered_objects[$base_tag]) && isset($parameter['object_methode'])) { - $methode = $parameter['object_methode']; - if (in_array($methode, $this->smarty->registered_objects[$base_tag][3])) { - return $this->callTagCompiler('private_object_block_function', $args, $parameter, $tag, $methode); - } else { - return $this->trigger_template_error('unallowed closing tag methode "' . $methode . '" in registered object "' . $base_tag . '"', $this->lex->taglineno); - } - } - // registered block tag ? - if (isset($this->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$base_tag]) || isset($this->default_handler_plugins[Smarty::PLUGIN_BLOCK][$base_tag])) { - return $this->callTagCompiler('private_registered_block', $args, $parameter, $tag); - } - // block plugin? - if ($function = $this->getPlugin($base_tag, Smarty::PLUGIN_BLOCK)) { - return $this->callTagCompiler('private_block_plugin', $args, $parameter, $tag, $function); - } - // registered compiler plugin ? - if (isset($this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag])) { - // if compiler function plugin call it now - $args = array(); - if (!$this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][1]) { - $this->tag_nocache = true; - } - $function = $this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][0]; - if (!is_array($function)) { - return $function($args, $this); - } elseif (is_object($function[0])) { - return $this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][0][0]->$function[1]($args, $this); - } else { - return call_user_func_array($function, array($args, $this)); - } - } - if ($this->smarty->loadPlugin('smarty_compiler_' . $tag)) { - $plugin = 'smarty_compiler_' . $tag; - if (is_callable($plugin)) { - return $plugin($args, $this->smarty); - } - if (class_exists($plugin, false)) { - $plugin_object = new $plugin; - if (method_exists($plugin_object, 'compile')) { - return $plugin_object->compile($args, $this); - } - } - throw new SmartyException("Plugin \"{$tag}\" not callable"); - } - } - $this->trigger_template_error("unknown tag \"" . $tag . "\"", $this->lex->taglineno); - } - } - - /** - * lazy loads internal compile plugin for tag and calls the compile methode - * - * compile objects cached for reuse. - * class name format: Smarty_Internal_Compile_TagName - * plugin filename format: Smarty_Internal_Tagname.php - * - * @param string $tag tag name - * @param array $args list of tag attributes - * @param mixed $param1 optional parameter - * @param mixed $param2 optional parameter - * @param mixed $param3 optional parameter - * @return string compiled code - */ - public function callTagCompiler($tag, $args, $param1 = null, $param2 = null, $param3 = null) - { - // re-use object if already exists - if (isset(self::$_tag_objects[$tag])) { - // compile this tag - return self::$_tag_objects[$tag]->compile($args, $this, $param1, $param2, $param3); - } - // lazy load internal compiler plugin - $class_name = 'Smarty_Internal_Compile_' . $tag; - if ($this->smarty->loadPlugin($class_name)) { - // check if tag allowed by security - if (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this)) { - // use plugin if found - self::$_tag_objects[$tag] = new $class_name; - // compile this tag - return self::$_tag_objects[$tag]->compile($args, $this, $param1, $param2, $param3); - } - } - // no internal compile plugin for this tag - return false; - } - - /** - * Check for plugins and return function name - * - * @param string $pugin_name name of plugin or function - * @param string $plugin_type type of plugin - * @return string call name of function - */ - public function getPlugin($plugin_name, $plugin_type) - { - $function = null; - if ($this->template->caching && ($this->nocache || $this->tag_nocache)) { - if (isset($this->template->required_plugins['nocache'][$plugin_name][$plugin_type])) { - $function = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function']; - } elseif (isset($this->template->required_plugins['compiled'][$plugin_name][$plugin_type])) { - $this->template->required_plugins['nocache'][$plugin_name][$plugin_type] = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]; - $function = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function']; - } - } else { - if (isset($this->template->required_plugins['compiled'][$plugin_name][$plugin_type])) { - $function = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function']; - } elseif (isset($this->template->required_plugins['nocache'][$plugin_name][$plugin_type])) { - $this->template->required_plugins['compiled'][$plugin_name][$plugin_type] = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]; - $function = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function']; - } - } - if (isset($function)) { - if ($plugin_type == 'modifier') { - $this->modifier_plugins[$plugin_name] = true; - } - - return $function; - } - // loop through plugin dirs and find the plugin - $function = 'smarty_' . $plugin_type . '_' . $plugin_name; - $file = $this->smarty->loadPlugin($function, false); - - if (is_string($file)) { - if ($this->template->caching && ($this->nocache || $this->tag_nocache)) { - $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['file'] = $file; - $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function'] = $function; - } else { - $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['file'] = $file; - $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function'] = $function; - } - if ($plugin_type == 'modifier') { - $this->modifier_plugins[$plugin_name] = true; - } - - return $function; - } - if (is_callable($function)) { - // plugin function is defined in the script - return $function; - } - - return false; - } - - /** - * Check for plugins by default plugin handler - * - * @param string $tag name of tag - * @param string $plugin_type type of plugin - * @return boolean true if found - */ - public function getPluginFromDefaultHandler($tag, $plugin_type) - { - $callback = null; - $script = null; - $cacheable = true; - $result = call_user_func_array( - $this->smarty->default_plugin_handler_func, array($tag, $plugin_type, $this->template, &$callback, &$script, &$cacheable) - ); - if ($result) { - $this->tag_nocache = $this->tag_nocache || !$cacheable; - if ($script !== null) { - if (is_file($script)) { - if ($this->template->caching && ($this->nocache || $this->tag_nocache)) { - $this->template->required_plugins['nocache'][$tag][$plugin_type]['file'] = $script; - $this->template->required_plugins['nocache'][$tag][$plugin_type]['function'] = $callback; - } else { - $this->template->required_plugins['compiled'][$tag][$plugin_type]['file'] = $script; - $this->template->required_plugins['compiled'][$tag][$plugin_type]['function'] = $callback; - } - include_once $script; - } else { - $this->trigger_template_error("Default plugin handler: Returned script file \"{$script}\" for \"{$tag}\" not found"); - } - } - if (!is_string($callback) && !(is_array($callback) && is_string($callback[0]) && is_string($callback[1]))) { - $this->trigger_template_error("Default plugin handler: Returned callback for \"{$tag}\" must be a static function name or array of class and function name"); - } - if (is_callable($callback)) { - $this->default_handler_plugins[$plugin_type][$tag] = array($callback, true, array()); - - return true; - } else { - $this->trigger_template_error("Default plugin handler: Returned callback for \"{$tag}\" not callable"); - } - } - - return false; - } - - /** - * Inject inline code for nocache template sections - * - * This method gets the content of each template element from the parser. - * If the content is compiled code and it should be not cached the code is injected - * into the rendered output. - * - * @param string $content content of template element - * @param boolean $is_code true if content is compiled code - * @return string content - */ - public function processNocacheCode($content, $is_code) - { - // If the template is not evaluated and we have a nocache section and or a nocache tag - if ($is_code && !empty($content)) { - // generate replacement code - if ((!($this->template->source->recompiled) || $this->forceNocache) && $this->template->caching && !$this->suppressNocacheProcessing && - ($this->nocache || $this->tag_nocache) - ) { - $this->template->has_nocache_code = true; - $_output = addcslashes($content, '\'\\'); - $_output = str_replace("^#^", "'", $_output); - $_output = "nocache_hash}%%*/" . $_output . "/*/%%SmartyNocache:{$this->nocache_hash}%%*/';?>\n"; - // make sure we include modifier plugins for nocache code - foreach ($this->modifier_plugins as $plugin_name => $dummy) { - if (isset($this->template->required_plugins['compiled'][$plugin_name]['modifier'])) { - $this->template->required_plugins['nocache'][$plugin_name]['modifier'] = $this->template->required_plugins['compiled'][$plugin_name]['modifier']; - } - } - } else { - $_output = $content; - } - } else { - $_output = $content; - } - $this->modifier_plugins = array(); - $this->suppressNocacheProcessing = false; - $this->tag_nocache = false; - - return $_output; - } - - /** - * push current file and line offset on stack for tracing {block} source lines - * - * @param string $file new filename - * @param string $uid uid of file - * @param string $debug false debug end_compile shall not be called - * @param int $line line offset to source - */ - public function pushTrace($file, $uid, $line, $debug = true) - { - if ($this->smarty->debugging && $debug) { - Smarty_Internal_Debug::end_compile($this->template); - } - array_push($this->trace_stack, array($this->smarty->_current_file, $this->trace_filepath, $this->trace_uid, $this->trace_line_offset)); - $this->trace_filepath = $this->smarty->_current_file = $file; - $this->trace_uid = $uid; - $this->trace_line_offset = $line ; - if ($this->smarty->debugging) { - Smarty_Internal_Debug::start_compile($this->template); - } - } - - /** - * restore file and line offset - * - */ - public function popTrace() - { - if ($this->smarty->debugging) { - Smarty_Internal_Debug::end_compile($this->template); - } - $r = array_pop($this->trace_stack); - $this->smarty->_current_file = $r[0]; - $this->trace_filepath = $r[1]; - $this->trace_uid = $r[2]; - $this->trace_line_offset = $r[3]; - if ($this->smarty->debugging) { - Smarty_Internal_Debug::start_compile($this->template); - } - } - - /** - * display compiler error messages without dying - * - * If parameter $args is empty it is a parser detected syntax error. - * In this case the parser is called to obtain information about expected tokens. - * - * If parameter $args contains a string this is used as error message - * - * @param string $args individual error message or null - * @param string $line line-number - * @throws SmartyCompilerException when an unexpected token is found - */ - public function trigger_template_error($args = null, $line = null) - { - // get template source line which has error - if (!isset($line)) { - $line = $this->lex->line; - } -// $line += $this->trace_line_offset; - $match = preg_split("/\n/", $this->lex->data); - $error_text = 'Syntax error in template "' . (empty($this->trace_filepath) ? $this->template->source->filepath : $this->trace_filepath) . '" on line ' . ($line + $this->trace_line_offset) . ' "' . trim(preg_replace('![\t\r\n]+!', ' ', $match[$line - 1])) . '" '; - if (isset($args)) { - // individual error message - $error_text .= $args; - } else { - // expected token from parser - $error_text .= ' - Unexpected "' . $this->lex->value . '"'; - if (count($this->parser->yy_get_expected_tokens($this->parser->yymajor)) <= 4) { - foreach ($this->parser->yy_get_expected_tokens($this->parser->yymajor) as $token) { - $exp_token = $this->parser->yyTokenName[$token]; - if (isset($this->lex->smarty_token_names[$exp_token])) { - // token type from lexer - $expect[] = '"' . $this->lex->smarty_token_names[$exp_token] . '"'; - } else { - // otherwise internal token name - $expect[] = $this->parser->yyTokenName[$token]; - } - } - $error_text .= ', expected one of: ' . implode(' , ', $expect); - } - } - $e = new SmartyCompilerException($error_text); - $e->line = $line; - $e->source = trim(preg_replace('![\t\r\n]+!', ' ', $match[$line - 1])); - $e->desc = $args; - $e->template = $this->template->source->filepath; - throw $e; - } - -} +nocache_hash = str_replace('.', '-', uniqid(rand(), true)); + } + + /** + * Method to compile a Smarty template + * + * @param Smarty_Internal_Template $template template object to compile + * @param bool $nocache true is shall be compiled in nocache mode + * @return bool true if compiling succeeded, false if it failed + */ + public function compileTemplate(Smarty_Internal_Template $template, $nocache = false) + { + if (empty($template->properties['nocache_hash'])) { + $template->properties['nocache_hash'] = $this->nocache_hash; + } else { + $this->nocache_hash = $template->properties['nocache_hash']; + } + // flag for nochache sections + $this->nocache = $nocache; + $this->tag_nocache = false; + // save template object in compiler class + $this->template = $template; + // reset has nocache code flag + $this->template->has_nocache_code = false; + $save_source = $this->template->source; + // template header code + $template_header = ''; + if (!$this->suppressHeader) { + $template_header .= "template->source->filepath . "\" */ ?>\n"; + } + + if (empty($this->template->source->components)) { + $this->sources = array($template->source); + } else { + // we have array of inheritance templates by extends: resource + $this->sources = array_reverse($template->source->components); + } + $loop = 0; + // the $this->sources array can get additional elements while compiling by the {extends} tag + while ($this->template->source = array_shift($this->sources)) { + $this->smarty->_current_file = $this->template->source->filepath; + if ($this->smarty->debugging) { + Smarty_Internal_Debug::start_compile($this->template); + } + $no_sources = count($this->sources); + if ($loop || $no_sources) { + $this->template->properties['file_dependency'][$this->template->source->uid] = array($this->template->source->filepath, $this->template->source->timestamp, $this->template->source->type); + } + $loop++; + if ($no_sources) { + $this->inheritance_child = true; + } else { + $this->inheritance_child = false; + } + do { + $_compiled_code = ''; + // flag for aborting current and start recompile + $this->abort_and_recompile = false; + // get template source + $_content = $this->template->source->content; + if ($_content != '') { + // run prefilter if required + if ((isset($this->smarty->autoload_filters['pre']) || isset($this->smarty->registered_filters['pre'])) && !$this->suppressFilter) { + $_content = Smarty_Internal_Filter_Handler::runFilter('pre', $_content, $template); + } + // call compiler + $_compiled_code = $this->doCompile($_content); + } + } while ($this->abort_and_recompile); + if ($this->smarty->debugging) { + Smarty_Internal_Debug::end_compile($this->template); + } + } + // restore source + $this->template->source = $save_source; + unset($save_source); + $this->smarty->_current_file = $this->template->source->filepath; + // free memory + unset($this->parser->root_buffer, $this->parser->current_buffer, $this->parser, $this->lex, $this->template); + self::$_tag_objects = array(); + // return compiled code to template object + $merged_code = ''; + if (!$this->suppressMergedTemplates && !empty($this->merged_templates)) { + foreach ($this->merged_templates as $code) { + $merged_code .= $code; + } + } + // run postfilter if required on compiled template code + if ((isset($this->smarty->autoload_filters['post']) || isset($this->smarty->registered_filters['post'])) && !$this->suppressFilter && $_compiled_code != '') { + $_compiled_code = Smarty_Internal_Filter_Handler::runFilter('post', $_compiled_code, $template); + } + if ($this->suppressTemplatePropertyHeader) { + $code = $_compiled_code . $merged_code; + } else { + $code = $template_header . $template->createTemplateCodeFrame($_compiled_code) . $merged_code; + } + // unset content because template inheritance could have replace source with parent code + unset ($template->source->content); + + return $code; + } + + /** + * Compile Tag + * + * This is a call back from the lexer/parser + * It executes the required compile plugin for the Smarty tag + * + * @param string $tag tag name + * @param array $args array with tag attributes + * @param array $parameter array with compilation parameter + * @return string compiled code + */ + public function compileTag($tag, $args, $parameter = array()) + { + // $args contains the attributes parsed and compiled by the lexer/parser + // assume that tag does compile into code, but creates no HTML output + $this->has_code = true; + $this->has_output = false; + // log tag/attributes + if (isset($this->smarty->get_used_tags) && $this->smarty->get_used_tags) { + $this->template->used_tags[] = array($tag, $args); + } + // check nocache option flag + if (in_array("'nocache'", $args) || in_array(array('nocache' => 'true'), $args) + || in_array(array('nocache' => '"true"'), $args) || in_array(array('nocache' => "'true'"), $args) + ) { + $this->tag_nocache = true; + } + // compile the smarty tag (required compile classes to compile the tag are autoloaded) + if (($_output = $this->callTagCompiler($tag, $args, $parameter)) === false) { + if (isset($this->smarty->template_functions[$tag])) { + // template defined by {template} tag + $args['_attr']['name'] = "'" . $tag . "'"; + $_output = $this->callTagCompiler('call', $args, $parameter); + } + } + if ($_output !== false) { + if ($_output !== true) { + // did we get compiled code + if ($this->has_code) { + // Does it create output? + if ($this->has_output) { + $_output .= "\n"; + } + // return compiled code + return $_output; + } + } + // tag did not produce compiled code + return null; + } else { + // map_named attributes + if (isset($args['_attr'])) { + foreach ($args['_attr'] as $key => $attribute) { + if (is_array($attribute)) { + $args = array_merge($args, $attribute); + } + } + } + // not an internal compiler tag + if (strlen($tag) < 6 || substr($tag, -5) != 'close') { + // check if tag is a registered object + if (isset($this->smarty->registered_objects[$tag]) && isset($parameter['object_methode'])) { + $methode = $parameter['object_methode']; + if (!in_array($methode, $this->smarty->registered_objects[$tag][3]) && + (empty($this->smarty->registered_objects[$tag][1]) || in_array($methode, $this->smarty->registered_objects[$tag][1])) + ) { + return $this->callTagCompiler('private_object_function', $args, $parameter, $tag, $methode); + } elseif (in_array($methode, $this->smarty->registered_objects[$tag][3])) { + return $this->callTagCompiler('private_object_block_function', $args, $parameter, $tag, $methode); + } else { + return $this->trigger_template_error('unallowed methode "' . $methode . '" in registered object "' . $tag . '"', $this->lex->taglineno); + } + } + // check if tag is registered + foreach (array(Smarty::PLUGIN_COMPILER, Smarty::PLUGIN_FUNCTION, Smarty::PLUGIN_BLOCK) as $plugin_type) { + if (isset($this->smarty->registered_plugins[$plugin_type][$tag])) { + // if compiler function plugin call it now + if ($plugin_type == Smarty::PLUGIN_COMPILER) { + $new_args = array(); + foreach ($args as $key => $mixed) { + if (is_array($mixed)) { + $new_args = array_merge($new_args, $mixed); + } else { + $new_args[$key] = $mixed; + } + } + if (!$this->smarty->registered_plugins[$plugin_type][$tag][1]) { + $this->tag_nocache = true; + } + $function = $this->smarty->registered_plugins[$plugin_type][$tag][0]; + if (!is_array($function)) { + return $function($new_args, $this); + } elseif (is_object($function[0])) { + return $this->smarty->registered_plugins[$plugin_type][$tag][0][0]->$function[1]($new_args, $this); + } else { + return call_user_func_array($function, array($new_args, $this)); + } + } + // compile registered function or block function + if ($plugin_type == Smarty::PLUGIN_FUNCTION || $plugin_type == Smarty::PLUGIN_BLOCK) { + return $this->callTagCompiler('private_registered_' . $plugin_type, $args, $parameter, $tag); + } + } + } + // check plugins from plugins folder + foreach ($this->smarty->plugin_search_order as $plugin_type) { + if ($plugin_type == Smarty::PLUGIN_COMPILER && $this->smarty->loadPlugin('smarty_compiler_' . $tag) && (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this))) { + $plugin = 'smarty_compiler_' . $tag; + if (is_callable($plugin)) { + // convert arguments format for old compiler plugins + $new_args = array(); + foreach ($args as $key => $mixed) { + if (is_array($mixed)) { + $new_args = array_merge($new_args, $mixed); + } else { + $new_args[$key] = $mixed; + } + } + + return $plugin($new_args, $this->smarty); + } + if (class_exists($plugin, false)) { + $plugin_object = new $plugin; + if (method_exists($plugin_object, 'compile')) { + return $plugin_object->compile($args, $this); + } + } + throw new SmartyException("Plugin \"{$tag}\" not callable"); + } else { + if ($function = $this->getPlugin($tag, $plugin_type)) { + if (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this)) { + return $this->callTagCompiler('private_' . $plugin_type . '_plugin', $args, $parameter, $tag, $function); + } + } + } + } + if (is_callable($this->smarty->default_plugin_handler_func)) { + $found = false; + // look for already resolved tags + foreach ($this->smarty->plugin_search_order as $plugin_type) { + if (isset($this->default_handler_plugins[$plugin_type][$tag])) { + $found = true; + break; + } + } + if (!$found) { + // call default handler + foreach ($this->smarty->plugin_search_order as $plugin_type) { + if ($this->getPluginFromDefaultHandler($tag, $plugin_type)) { + $found = true; + break; + } + } + } + if ($found) { + // if compiler function plugin call it now + if ($plugin_type == Smarty::PLUGIN_COMPILER) { + $new_args = array(); + foreach ($args as $mixed) { + $new_args = array_merge($new_args, $mixed); + } + $function = $this->default_handler_plugins[$plugin_type][$tag][0]; + if (!is_array($function)) { + return $function($new_args, $this); + } elseif (is_object($function[0])) { + return $this->default_handler_plugins[$plugin_type][$tag][0][0]->$function[1]($new_args, $this); + } else { + return call_user_func_array($function, array($new_args, $this)); + } + } else { + return $this->callTagCompiler('private_registered_' . $plugin_type, $args, $parameter, $tag); + } + } + } + } else { + // compile closing tag of block function + $base_tag = substr($tag, 0, -5); + // check if closing tag is a registered object + if (isset($this->smarty->registered_objects[$base_tag]) && isset($parameter['object_methode'])) { + $methode = $parameter['object_methode']; + if (in_array($methode, $this->smarty->registered_objects[$base_tag][3])) { + return $this->callTagCompiler('private_object_block_function', $args, $parameter, $tag, $methode); + } else { + return $this->trigger_template_error('unallowed closing tag methode "' . $methode . '" in registered object "' . $base_tag . '"', $this->lex->taglineno); + } + } + // registered block tag ? + if (isset($this->smarty->registered_plugins[Smarty::PLUGIN_BLOCK][$base_tag]) || isset($this->default_handler_plugins[Smarty::PLUGIN_BLOCK][$base_tag])) { + return $this->callTagCompiler('private_registered_block', $args, $parameter, $tag); + } + // block plugin? + if ($function = $this->getPlugin($base_tag, Smarty::PLUGIN_BLOCK)) { + return $this->callTagCompiler('private_block_plugin', $args, $parameter, $tag, $function); + } + // registered compiler plugin ? + if (isset($this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag])) { + // if compiler function plugin call it now + $args = array(); + if (!$this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][1]) { + $this->tag_nocache = true; + } + $function = $this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][0]; + if (!is_array($function)) { + return $function($args, $this); + } elseif (is_object($function[0])) { + return $this->smarty->registered_plugins[Smarty::PLUGIN_COMPILER][$tag][0][0]->$function[1]($args, $this); + } else { + return call_user_func_array($function, array($args, $this)); + } + } + if ($this->smarty->loadPlugin('smarty_compiler_' . $tag)) { + $plugin = 'smarty_compiler_' . $tag; + if (is_callable($plugin)) { + return $plugin($args, $this->smarty); + } + if (class_exists($plugin, false)) { + $plugin_object = new $plugin; + if (method_exists($plugin_object, 'compile')) { + return $plugin_object->compile($args, $this); + } + } + throw new SmartyException("Plugin \"{$tag}\" not callable"); + } + } + $this->trigger_template_error("unknown tag \"" . $tag . "\"", $this->lex->taglineno); + } + } + + /** + * lazy loads internal compile plugin for tag and calls the compile methode + * + * compile objects cached for reuse. + * class name format: Smarty_Internal_Compile_TagName + * plugin filename format: Smarty_Internal_Tagname.php + * + * @param string $tag tag name + * @param array $args list of tag attributes + * @param mixed $param1 optional parameter + * @param mixed $param2 optional parameter + * @param mixed $param3 optional parameter + * @return string compiled code + */ + public function callTagCompiler($tag, $args, $param1 = null, $param2 = null, $param3 = null) + { + // re-use object if already exists + if (isset(self::$_tag_objects[$tag])) { + // compile this tag + return self::$_tag_objects[$tag]->compile($args, $this, $param1, $param2, $param3); + } + // lazy load internal compiler plugin + $class_name = 'Smarty_Internal_Compile_' . $tag; + if ($this->smarty->loadPlugin($class_name)) { + // check if tag allowed by security + if (!isset($this->smarty->security_policy) || $this->smarty->security_policy->isTrustedTag($tag, $this)) { + // use plugin if found + self::$_tag_objects[$tag] = new $class_name; + // compile this tag + return self::$_tag_objects[$tag]->compile($args, $this, $param1, $param2, $param3); + } + } + // no internal compile plugin for this tag + return false; + } + + /** + * Check for plugins and return function name + * + * @param string $pugin_name name of plugin or function + * @param string $plugin_type type of plugin + * @return string call name of function + */ + public function getPlugin($plugin_name, $plugin_type) + { + $function = null; + if ($this->template->caching && ($this->nocache || $this->tag_nocache)) { + if (isset($this->template->required_plugins['nocache'][$plugin_name][$plugin_type])) { + $function = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function']; + } elseif (isset($this->template->required_plugins['compiled'][$plugin_name][$plugin_type])) { + $this->template->required_plugins['nocache'][$plugin_name][$plugin_type] = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]; + $function = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function']; + } + } else { + if (isset($this->template->required_plugins['compiled'][$plugin_name][$plugin_type])) { + $function = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function']; + } elseif (isset($this->template->required_plugins['nocache'][$plugin_name][$plugin_type])) { + $this->template->required_plugins['compiled'][$plugin_name][$plugin_type] = $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]; + $function = $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function']; + } + } + if (isset($function)) { + if ($plugin_type == 'modifier') { + $this->modifier_plugins[$plugin_name] = true; + } + + return $function; + } + // loop through plugin dirs and find the plugin + $function = 'smarty_' . $plugin_type . '_' . $plugin_name; + $file = $this->smarty->loadPlugin($function, false); + + if (is_string($file)) { + if ($this->template->caching && ($this->nocache || $this->tag_nocache)) { + $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['file'] = $file; + $this->template->required_plugins['nocache'][$plugin_name][$plugin_type]['function'] = $function; + } else { + $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['file'] = $file; + $this->template->required_plugins['compiled'][$plugin_name][$plugin_type]['function'] = $function; + } + if ($plugin_type == 'modifier') { + $this->modifier_plugins[$plugin_name] = true; + } + + return $function; + } + if (is_callable($function)) { + // plugin function is defined in the script + return $function; + } + + return false; + } + + /** + * Check for plugins by default plugin handler + * + * @param string $tag name of tag + * @param string $plugin_type type of plugin + * @return boolean true if found + */ + public function getPluginFromDefaultHandler($tag, $plugin_type) + { + $callback = null; + $script = null; + $cacheable = true; + $result = call_user_func_array( + $this->smarty->default_plugin_handler_func, array($tag, $plugin_type, $this->template, &$callback, &$script, &$cacheable) + ); + if ($result) { + $this->tag_nocache = $this->tag_nocache || !$cacheable; + if ($script !== null) { + if (is_file($script)) { + if ($this->template->caching && ($this->nocache || $this->tag_nocache)) { + $this->template->required_plugins['nocache'][$tag][$plugin_type]['file'] = $script; + $this->template->required_plugins['nocache'][$tag][$plugin_type]['function'] = $callback; + } else { + $this->template->required_plugins['compiled'][$tag][$plugin_type]['file'] = $script; + $this->template->required_plugins['compiled'][$tag][$plugin_type]['function'] = $callback; + } + include_once $script; + } else { + $this->trigger_template_error("Default plugin handler: Returned script file \"{$script}\" for \"{$tag}\" not found"); + } + } + if (!is_string($callback) && !(is_array($callback) && is_string($callback[0]) && is_string($callback[1]))) { + $this->trigger_template_error("Default plugin handler: Returned callback for \"{$tag}\" must be a static function name or array of class and function name"); + } + if (is_callable($callback)) { + $this->default_handler_plugins[$plugin_type][$tag] = array($callback, true, array()); + + return true; + } else { + $this->trigger_template_error("Default plugin handler: Returned callback for \"{$tag}\" not callable"); + } + } + + return false; + } + + /** + * Inject inline code for nocache template sections + * + * This method gets the content of each template element from the parser. + * If the content is compiled code and it should be not cached the code is injected + * into the rendered output. + * + * @param string $content content of template element + * @param boolean $is_code true if content is compiled code + * @return string content + */ + public function processNocacheCode($content, $is_code) + { + // If the template is not evaluated and we have a nocache section and or a nocache tag + if ($is_code && !empty($content)) { + // generate replacement code + if ((!($this->template->source->recompiled) || $this->forceNocache) && $this->template->caching && !$this->suppressNocacheProcessing && + ($this->nocache || $this->tag_nocache) + ) { + $this->template->has_nocache_code = true; + $_output = addcslashes($content, '\'\\'); + $_output = str_replace("^#^", "'", $_output); + $_output = "nocache_hash}%%*/" . $_output . "/*/%%SmartyNocache:{$this->nocache_hash}%%*/';?>\n"; + // make sure we include modifier plugins for nocache code + foreach ($this->modifier_plugins as $plugin_name => $dummy) { + if (isset($this->template->required_plugins['compiled'][$plugin_name]['modifier'])) { + $this->template->required_plugins['nocache'][$plugin_name]['modifier'] = $this->template->required_plugins['compiled'][$plugin_name]['modifier']; + } + } + } else { + $_output = $content; + } + } else { + $_output = $content; + } + $this->modifier_plugins = array(); + $this->suppressNocacheProcessing = false; + $this->tag_nocache = false; + + return $_output; + } + + /** + * push current file and line offset on stack for tracing {block} source lines + * + * @param string $file new filename + * @param string $uid uid of file + * @param string $debug false debug end_compile shall not be called + * @param int $line line offset to source + */ + public function pushTrace($file, $uid, $line, $debug = true) + { + if ($this->smarty->debugging && $debug) { + Smarty_Internal_Debug::end_compile($this->template); + } + array_push($this->trace_stack, array($this->smarty->_current_file, $this->trace_filepath, $this->trace_uid, $this->trace_line_offset)); + $this->trace_filepath = $this->smarty->_current_file = $file; + $this->trace_uid = $uid; + $this->trace_line_offset = $line ; + if ($this->smarty->debugging) { + Smarty_Internal_Debug::start_compile($this->template); + } + } + + /** + * restore file and line offset + * + */ + public function popTrace() + { + if ($this->smarty->debugging) { + Smarty_Internal_Debug::end_compile($this->template); + } + $r = array_pop($this->trace_stack); + $this->smarty->_current_file = $r[0]; + $this->trace_filepath = $r[1]; + $this->trace_uid = $r[2]; + $this->trace_line_offset = $r[3]; + if ($this->smarty->debugging) { + Smarty_Internal_Debug::start_compile($this->template); + } + } + + /** + * display compiler error messages without dying + * + * If parameter $args is empty it is a parser detected syntax error. + * In this case the parser is called to obtain information about expected tokens. + * + * If parameter $args contains a string this is used as error message + * + * @param string $args individual error message or null + * @param string $line line-number + * @throws SmartyCompilerException when an unexpected token is found + */ + public function trigger_template_error($args = null, $line = null) + { + // get template source line which has error + if (!isset($line)) { + $line = $this->lex->line; + } +// $line += $this->trace_line_offset; + $match = preg_split("/\n/", $this->lex->data); + $error_text = 'Syntax error in template "' . (empty($this->trace_filepath) ? $this->template->source->filepath : $this->trace_filepath) . '" on line ' . ($line + $this->trace_line_offset) . ' "' . trim(preg_replace('![\t\r\n]+!', ' ', $match[$line - 1])) . '" '; + if (isset($args)) { + // individual error message + $error_text .= $args; + } else { + // expected token from parser + $error_text .= ' - Unexpected "' . $this->lex->value . '"'; + if (count($this->parser->yy_get_expected_tokens($this->parser->yymajor)) <= 4) { + foreach ($this->parser->yy_get_expected_tokens($this->parser->yymajor) as $token) { + $exp_token = $this->parser->yyTokenName[$token]; + if (isset($this->lex->smarty_token_names[$exp_token])) { + // token type from lexer + $expect[] = '"' . $this->lex->smarty_token_names[$exp_token] . '"'; + } else { + // otherwise internal token name + $expect[] = $this->parser->yyTokenName[$token]; + } + } + $error_text .= ', expected one of: ' . implode(' , ', $expect); + } + } + $e = new SmartyCompilerException($error_text); + $e->line = $line; + $e->source = trim(preg_replace('![\t\r\n]+!', ' ', $match[$line - 1])); + $e->desc = $args; + $e->template = $this->template->source->filepath; + throw $e; + } + +} diff --git a/resources/templates/engine/smarty/sysplugins/smarty_internal_utility.php b/resources/templates/engine/smarty/sysplugins/smarty_internal_utility.php index 5e763b7813..8c8f9e6bea 100644 --- a/resources/templates/engine/smarty/sysplugins/smarty_internal_utility.php +++ b/resources/templates/engine/smarty/sysplugins/smarty_internal_utility.php @@ -1,822 +1,822 @@ - - * @author Uwe Tews - * @package Smarty - * @subpackage PluginsInternal - * @version 3-SVN$Rev: 3286 $ - */ - -/** - * Utility class - * - * @package Smarty - * @subpackage Security - */ -class Smarty_Internal_Utility -{ - /** - * private constructor to prevent calls creation of new instances - */ - final private function __construct() - { - // intentionally left blank - } - - /** - * Compile all template files - * - * @param string $extension template file name extension - * @param bool $force_compile force all to recompile - * @param int $time_limit set maximum execution time - * @param int $max_errors set maximum allowed errors - * @param Smarty $smarty Smarty instance - * @return integer number of template files compiled - */ - public static function compileAllTemplates($extension, $force_compile, $time_limit, $max_errors, Smarty $smarty) - { - // switch off time limit - if (function_exists('set_time_limit')) { - @set_time_limit($time_limit); - } - $smarty->force_compile = $force_compile; - $_count = 0; - $_error_count = 0; - // loop over array of template directories - foreach ($smarty->getTemplateDir() as $_dir) { - $_compileDirs = new RecursiveDirectoryIterator($_dir); - $_compile = new RecursiveIteratorIterator($_compileDirs); - foreach ($_compile as $_fileinfo) { - $_file = $_fileinfo->getFilename(); - if (substr(basename($_fileinfo->getPathname()),0,1) == '.' || strpos($_file, '.svn') !== false || strpos($_file, '.git') !== false) continue; - if (!substr_compare($_file, $extension, - strlen($extension)) == 0) continue; - if ($_fileinfo->getPath() == substr($_dir, 0, -1)) { - $_template_file = $_file; - } else { - $_template_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file; - } - echo '
', $_dir, '---', $_template_file; - flush(); - $_start_time = microtime(true); - try { - $_tpl = $smarty->createTemplate($_template_file,null,null,null,false); - if ($_tpl->mustCompile()) { - $_tpl->compileTemplateSource(); - $_count++; - echo ' compiled in ', microtime(true) - $_start_time, ' seconds'; - flush(); - } else { - echo ' is up to date'; - flush(); - } - } catch (Exception $e) { - echo 'Error: ', $e->getMessage(), "

"; - $_error_count++; - } - // free memory - $smarty->template_objects = array(); - $_tpl->smarty->template_objects = array(); - $_tpl = null; - if ($max_errors !== null && $_error_count == $max_errors) { - echo '

too many errors'; - exit(); - } - } - } - - return $_count; - } - - /** - * Compile all config files - * - * @param string $extension config file name extension - * @param bool $force_compile force all to recompile - * @param int $time_limit set maximum execution time - * @param int $max_errors set maximum allowed errors - * @param Smarty $smarty Smarty instance - * @return integer number of config files compiled - */ - public static function compileAllConfig($extension, $force_compile, $time_limit, $max_errors, Smarty $smarty) - { - // switch off time limit - if (function_exists('set_time_limit')) { - @set_time_limit($time_limit); - } - $smarty->force_compile = $force_compile; - $_count = 0; - $_error_count = 0; - // loop over array of template directories - foreach ($smarty->getConfigDir() as $_dir) { - $_compileDirs = new RecursiveDirectoryIterator($_dir); - $_compile = new RecursiveIteratorIterator($_compileDirs); - foreach ($_compile as $_fileinfo) { - $_file = $_fileinfo->getFilename(); - if (substr(basename($_fileinfo->getPathname()),0,1) == '.' || strpos($_file, '.svn') !== false || strpos($_file, '.git') !== false) continue; - if (!substr_compare($_file, $extension, - strlen($extension)) == 0) continue; - if ($_fileinfo->getPath() == substr($_dir, 0, -1)) { - $_config_file = $_file; - } else { - $_config_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file; - } - echo '
', $_dir, '---', $_config_file; - flush(); - $_start_time = microtime(true); - try { - $_config = new Smarty_Internal_Config($_config_file, $smarty); - if ($_config->mustCompile()) { - $_config->compileConfigSource(); - $_count++; - echo ' compiled in ', microtime(true) - $_start_time, ' seconds'; - flush(); - } else { - echo ' is up to date'; - flush(); - } - } catch (Exception $e) { - echo 'Error: ', $e->getMessage(), "

"; - $_error_count++; - } - if ($max_errors !== null && $_error_count == $max_errors) { - echo '

too many errors'; - exit(); - } - } - } - - return $_count; - } - - /** - * Delete compiled template file - * - * @param string $resource_name template name - * @param string $compile_id compile id - * @param integer $exp_time expiration time - * @param Smarty $smarty Smarty instance - * @return integer number of template files deleted - */ - public static function clearCompiledTemplate($resource_name, $compile_id, $exp_time, Smarty $smarty) - { - $_compile_dir = $smarty->getCompileDir(); - $_compile_id = isset($compile_id) ? preg_replace('![^\w\|]+!', '_', $compile_id) : null; - $_dir_sep = $smarty->use_sub_dirs ? DS : '^'; - if (isset($resource_name)) { - $_save_stat = $smarty->caching; - $smarty->caching = false; - $tpl = new $smarty->template_class($resource_name, $smarty); - $smarty->caching = $_save_stat; - - // remove from template cache - $tpl->source; // have the template registered before unset() - if ($smarty->allow_ambiguous_resources) { - $_templateId = $tpl->source->unique_resource . $tpl->cache_id . $tpl->compile_id; - } else { - $_templateId = $smarty->joined_template_dir . '#' . $resource_name . $tpl->cache_id . $tpl->compile_id; - } - if (isset($_templateId[150])) { - $_templateId = sha1($_templateId); - } - unset($smarty->template_objects[$_templateId]); - - if ($tpl->source->exists) { - $_resource_part_1 = basename(str_replace('^', '/', $tpl->compiled->filepath)); - $_resource_part_1_length = strlen($_resource_part_1); - } else { - return 0; - } - - $_resource_part_2 = str_replace('.php','.cache.php',$_resource_part_1); - $_resource_part_2_length = strlen($_resource_part_2); - } - $_dir = $_compile_dir; - if ($smarty->use_sub_dirs && isset($_compile_id)) { - $_dir .= $_compile_id . $_dir_sep; - } - if (isset($_compile_id)) { - $_compile_id_part = $_compile_dir . $_compile_id . $_dir_sep; - $_compile_id_part_length = strlen($_compile_id_part); - } - $_count = 0; - try { - $_compileDirs = new RecursiveDirectoryIterator($_dir); - // NOTE: UnexpectedValueException thrown for PHP >= 5.3 - } catch (Exception $e) { - return 0; - } - $_compile = new RecursiveIteratorIterator($_compileDirs, RecursiveIteratorIterator::CHILD_FIRST); - foreach ($_compile as $_file) { - if (substr(basename($_file->getPathname()), 0, 1) == '.' || strpos($_file, '.svn') !== false || strpos($_file, '.git') !== false) continue; - - $_filepath = (string) $_file; - - if ($_file->isDir()) { - if (!$_compile->isDot()) { - // delete folder if empty - @rmdir($_file->getPathname()); - } - } else { - $unlink = false; - if ((!isset($_compile_id) || (isset($_filepath[$_compile_id_part_length]) && !strncmp($_filepath, $_compile_id_part, $_compile_id_part_length))) - && (!isset($resource_name) - || (isset($_filepath[$_resource_part_1_length]) - && substr_compare($_filepath, $_resource_part_1, -$_resource_part_1_length, $_resource_part_1_length) == 0) - || (isset($_filepath[$_resource_part_2_length]) - && substr_compare($_filepath, $_resource_part_2, -$_resource_part_2_length, $_resource_part_2_length) == 0))) { - if (isset($exp_time)) { - if (time() - @filemtime($_filepath) >= $exp_time) { - $unlink = true; - } - } else { - $unlink = true; - } - } - - if ($unlink && @unlink($_filepath)) { - $_count++; - } - } - } - // clear compiled cache - Smarty_Resource::$sources = array(); - Smarty_Resource::$compileds = array(); - - return $_count; - } - - /** - * Return array of tag/attributes of all tags used by an template - * - * @param Smarty_Internal_Template $templae template object - * @return array of tag/attributes - */ - public static function getTags(Smarty_Internal_Template $template) - { - $template->smarty->get_used_tags = true; - $template->compileTemplateSource(); - - return $template->used_tags; - } - - /** - * diagnose Smarty setup - * - * If $errors is secified, the diagnostic report will be appended to the array, rather than being output. - * - * @param Smarty $smarty Smarty instance to test - * @param array $errors array to push results into rather than outputting them - * @return bool status, true if everything is fine, false else - */ - public static function testInstall(Smarty $smarty, &$errors=null) - { - $status = true; - - if ($errors === null) { - echo "
\n";
-            echo "Smarty Installation test...\n";
-            echo "Testing template directory...\n";
-        }
-
-        $_stream_resolve_include_path = function_exists('stream_resolve_include_path');
-
-        // test if all registered template_dir are accessible
-        foreach ($smarty->getTemplateDir() as $template_dir) {
-            $_template_dir = $template_dir;
-            $template_dir = realpath($template_dir);
-            // resolve include_path or fail existence
-            if (!$template_dir) {
-                if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_template_dir)) {
-                    // try PHP include_path
-                    if ($_stream_resolve_include_path) {
-                        $template_dir = stream_resolve_include_path($_template_dir);
-                    } else {
-                        $template_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_template_dir);
-                    }
-
-                    if ($template_dir !== false) {
-                        if ($errors === null) {
-                            echo "$template_dir is OK.\n";
-                        }
-
-                        continue;
-                    } else {
-                        $status = false;
-                        $message = "FAILED: $_template_dir does not exist (and couldn't be found in include_path either)";
-                        if ($errors === null) {
-                            echo $message . ".\n";
-                        } else {
-                            $errors['template_dir'] = $message;
-                        }
-
-                        continue;
-                    }
-                } else {
-                    $status = false;
-                    $message = "FAILED: $_template_dir does not exist";
-                    if ($errors === null) {
-                        echo $message . ".\n";
-                    } else {
-                        $errors['template_dir'] = $message;
-                    }
-
-                    continue;
-                }
-            }
-
-            if (!is_dir($template_dir)) {
-                $status = false;
-                $message = "FAILED: $template_dir is not a directory";
-                if ($errors === null) {
-                    echo $message . ".\n";
-                } else {
-                    $errors['template_dir'] = $message;
-                }
-            } elseif (!is_readable($template_dir)) {
-                $status = false;
-                $message = "FAILED: $template_dir is not readable";
-                if ($errors === null) {
-                    echo $message . ".\n";
-                } else {
-                    $errors['template_dir'] = $message;
-                }
-            } else {
-                if ($errors === null) {
-                    echo "$template_dir is OK.\n";
-                }
-            }
-        }
-
-        if ($errors === null) {
-            echo "Testing compile directory...\n";
-        }
-
-        // test if registered compile_dir is accessible
-        $__compile_dir = $smarty->getCompileDir();
-        $_compile_dir = realpath($__compile_dir);
-        if (!$_compile_dir) {
-            $status = false;
-            $message = "FAILED: {$__compile_dir} does not exist";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['compile_dir'] = $message;
-            }
-        } elseif (!is_dir($_compile_dir)) {
-            $status = false;
-            $message = "FAILED: {$_compile_dir} is not a directory";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['compile_dir'] = $message;
-            }
-        } elseif (!is_readable($_compile_dir)) {
-            $status = false;
-            $message = "FAILED: {$_compile_dir} is not readable";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['compile_dir'] = $message;
-            }
-        } elseif (!is_writable($_compile_dir)) {
-            $status = false;
-            $message = "FAILED: {$_compile_dir} is not writable";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['compile_dir'] = $message;
-            }
-        } else {
-            if ($errors === null) {
-                echo "{$_compile_dir} is OK.\n";
-            }
-        }
-
-        if ($errors === null) {
-            echo "Testing plugins directory...\n";
-        }
-
-        // test if all registered plugins_dir are accessible
-        // and if core plugins directory is still registered
-        $_core_plugins_dir = realpath(dirname(__FILE__) .'/../plugins');
-        $_core_plugins_available = false;
-        foreach ($smarty->getPluginsDir() as $plugin_dir) {
-            $_plugin_dir = $plugin_dir;
-            $plugin_dir = realpath($plugin_dir);
-            // resolve include_path or fail existence
-            if (!$plugin_dir) {
-                if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_plugin_dir)) {
-                    // try PHP include_path
-                    if ($_stream_resolve_include_path) {
-                        $plugin_dir = stream_resolve_include_path($_plugin_dir);
-                    } else {
-                        $plugin_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_plugin_dir);
-                    }
-
-                    if ($plugin_dir !== false) {
-                        if ($errors === null) {
-                            echo "$plugin_dir is OK.\n";
-                        }
-
-                        continue;
-                    } else {
-                        $status = false;
-                        $message = "FAILED: $_plugin_dir does not exist (and couldn't be found in include_path either)";
-                        if ($errors === null) {
-                            echo $message . ".\n";
-                        } else {
-                            $errors['plugins_dir'] = $message;
-                        }
-
-                        continue;
-                    }
-                } else {
-                    $status = false;
-                    $message = "FAILED: $_plugin_dir does not exist";
-                    if ($errors === null) {
-                        echo $message . ".\n";
-                    } else {
-                        $errors['plugins_dir'] = $message;
-                    }
-
-                    continue;
-                }
-            }
-
-            if (!is_dir($plugin_dir)) {
-                $status = false;
-                $message = "FAILED: $plugin_dir is not a directory";
-                if ($errors === null) {
-                    echo $message . ".\n";
-                } else {
-                    $errors['plugins_dir'] = $message;
-                }
-            } elseif (!is_readable($plugin_dir)) {
-                $status = false;
-                $message = "FAILED: $plugin_dir is not readable";
-                if ($errors === null) {
-                    echo $message . ".\n";
-                } else {
-                    $errors['plugins_dir'] = $message;
-                }
-            } elseif ($_core_plugins_dir && $_core_plugins_dir == realpath($plugin_dir)) {
-                $_core_plugins_available = true;
-                if ($errors === null) {
-                    echo "$plugin_dir is OK.\n";
-                }
-            } else {
-                if ($errors === null) {
-                    echo "$plugin_dir is OK.\n";
-                }
-            }
-        }
-        if (!$_core_plugins_available) {
-            $status = false;
-            $message = "WARNING: Smarty's own libs/plugins is not available";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } elseif (!isset($errors['plugins_dir'])) {
-                $errors['plugins_dir'] = $message;
-            }
-        }
-
-        if ($errors === null) {
-            echo "Testing cache directory...\n";
-        }
-
-        // test if all registered cache_dir is accessible
-        $__cache_dir = $smarty->getCacheDir();
-        $_cache_dir = realpath($__cache_dir);
-        if (!$_cache_dir) {
-            $status = false;
-            $message = "FAILED: {$__cache_dir} does not exist";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['cache_dir'] = $message;
-            }
-        } elseif (!is_dir($_cache_dir)) {
-            $status = false;
-            $message = "FAILED: {$_cache_dir} is not a directory";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['cache_dir'] = $message;
-            }
-        } elseif (!is_readable($_cache_dir)) {
-            $status = false;
-            $message = "FAILED: {$_cache_dir} is not readable";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['cache_dir'] = $message;
-            }
-        } elseif (!is_writable($_cache_dir)) {
-            $status = false;
-            $message = "FAILED: {$_cache_dir} is not writable";
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['cache_dir'] = $message;
-            }
-        } else {
-            if ($errors === null) {
-                echo "{$_cache_dir} is OK.\n";
-            }
-        }
-
-        if ($errors === null) {
-            echo "Testing configs directory...\n";
-        }
-
-        // test if all registered config_dir are accessible
-        foreach ($smarty->getConfigDir() as $config_dir) {
-            $_config_dir = $config_dir;
-            $config_dir = realpath($config_dir);
-            // resolve include_path or fail existence
-            if (!$config_dir) {
-                if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_config_dir)) {
-                    // try PHP include_path
-                    if ($_stream_resolve_include_path) {
-                        $config_dir = stream_resolve_include_path($_config_dir);
-                    } else {
-                        $config_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_config_dir);
-                    }
-
-                    if ($config_dir !== false) {
-                        if ($errors === null) {
-                            echo "$config_dir is OK.\n";
-                        }
-
-                        continue;
-                    } else {
-                        $status = false;
-                        $message = "FAILED: $_config_dir does not exist (and couldn't be found in include_path either)";
-                        if ($errors === null) {
-                            echo $message . ".\n";
-                        } else {
-                            $errors['config_dir'] = $message;
-                        }
-
-                        continue;
-                    }
-                } else {
-                    $status = false;
-                    $message = "FAILED: $_config_dir does not exist";
-                    if ($errors === null) {
-                        echo $message . ".\n";
-                    } else {
-                        $errors['config_dir'] = $message;
-                    }
-
-                    continue;
-                }
-            }
-
-            if (!is_dir($config_dir)) {
-                $status = false;
-                $message = "FAILED: $config_dir is not a directory";
-                if ($errors === null) {
-                    echo $message . ".\n";
-                } else {
-                    $errors['config_dir'] = $message;
-                }
-            } elseif (!is_readable($config_dir)) {
-                $status = false;
-                $message = "FAILED: $config_dir is not readable";
-                if ($errors === null) {
-                    echo $message . ".\n";
-                } else {
-                    $errors['config_dir'] = $message;
-                }
-            } else {
-                if ($errors === null) {
-                    echo "$config_dir is OK.\n";
-                }
-            }
-        }
-
-        if ($errors === null) {
-            echo "Testing sysplugin files...\n";
-        }
-        // test if sysplugins are available
-        $source = SMARTY_SYSPLUGINS_DIR;
-        if (is_dir($source)) {
-            $expected = array(
-                "smarty_cacheresource.php" => true,
-                "smarty_cacheresource_custom.php" => true,
-                "smarty_cacheresource_keyvaluestore.php" => true,
-                "smarty_config_source.php" => true,
-                "smarty_internal_cacheresource_file.php" => true,
-                "smarty_internal_compile_append.php" => true,
-                "smarty_internal_compile_assign.php" => true,
-                "smarty_internal_compile_block.php" => true,
-                "smarty_internal_compile_break.php" => true,
-                "smarty_internal_compile_call.php" => true,
-                "smarty_internal_compile_capture.php" => true,
-                "smarty_internal_compile_config_load.php" => true,
-                "smarty_internal_compile_continue.php" => true,
-                "smarty_internal_compile_debug.php" => true,
-                "smarty_internal_compile_eval.php" => true,
-                "smarty_internal_compile_extends.php" => true,
-                "smarty_internal_compile_for.php" => true,
-                "smarty_internal_compile_foreach.php" => true,
-                "smarty_internal_compile_function.php" => true,
-                "smarty_internal_compile_if.php" => true,
-                "smarty_internal_compile_include.php" => true,
-                "smarty_internal_compile_include_php.php" => true,
-                "smarty_internal_compile_insert.php" => true,
-                "smarty_internal_compile_ldelim.php" => true,
-                "smarty_internal_compile_nocache.php" => true,
-                "smarty_internal_compile_private_block_plugin.php" => true,
-                "smarty_internal_compile_private_function_plugin.php" => true,
-                "smarty_internal_compile_private_modifier.php" => true,
-                "smarty_internal_compile_private_object_block_function.php" => true,
-                "smarty_internal_compile_private_object_function.php" => true,
-                "smarty_internal_compile_private_print_expression.php" => true,
-                "smarty_internal_compile_private_registered_block.php" => true,
-                "smarty_internal_compile_private_registered_function.php" => true,
-                "smarty_internal_compile_private_special_variable.php" => true,
-                "smarty_internal_compile_rdelim.php" => true,
-                "smarty_internal_compile_section.php" => true,
-                "smarty_internal_compile_setfilter.php" => true,
-                "smarty_internal_compile_while.php" => true,
-                "smarty_internal_compilebase.php" => true,
-                "smarty_internal_config.php" => true,
-                "smarty_internal_config_file_compiler.php" => true,
-                "smarty_internal_configfilelexer.php" => true,
-                "smarty_internal_configfileparser.php" => true,
-                "smarty_internal_data.php" => true,
-                "smarty_internal_debug.php" => true,
-                "smarty_internal_filter_handler.php" => true,
-                "smarty_internal_function_call_handler.php" => true,
-                "smarty_internal_get_include_path.php" => true,
-                "smarty_internal_nocache_insert.php" => true,
-                "smarty_internal_parsetree.php" => true,
-                "smarty_internal_resource_eval.php" => true,
-                "smarty_internal_resource_extends.php" => true,
-                "smarty_internal_resource_file.php" => true,
-                "smarty_internal_resource_registered.php" => true,
-                "smarty_internal_resource_stream.php" => true,
-                "smarty_internal_resource_string.php" => true,
-                "smarty_internal_smartytemplatecompiler.php" => true,
-                "smarty_internal_template.php" => true,
-                "smarty_internal_templatebase.php" => true,
-                "smarty_internal_templatecompilerbase.php" => true,
-                "smarty_internal_templatelexer.php" => true,
-                "smarty_internal_templateparser.php" => true,
-                "smarty_internal_utility.php" => true,
-                "smarty_internal_write_file.php" => true,
-                "smarty_resource.php" => true,
-                "smarty_resource_custom.php" => true,
-                "smarty_resource_recompiled.php" => true,
-                "smarty_resource_uncompiled.php" => true,
-                "smarty_security.php" => true,
-            );
-            $iterator = new DirectoryIterator($source);
-            foreach ($iterator as $file) {
-                if (!$file->isDot()) {
-                    $filename = $file->getFilename();
-                    if (isset($expected[$filename])) {
-                        unset($expected[$filename]);
-                    }
-                }
-            }
-            if ($expected) {
-                $status = false;
-                $message = "FAILED: files missing from libs/sysplugins: ". join(', ', array_keys($expected));
-                if ($errors === null) {
-                    echo $message . ".\n";
-                } else {
-                    $errors['sysplugins'] = $message;
-                }
-            } elseif ($errors === null) {
-                echo "... OK\n";
-            }
-        } else {
-            $status = false;
-            $message = "FAILED: ". SMARTY_SYSPLUGINS_DIR .' is not a directory';
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['sysplugins_dir_constant'] = $message;
-            }
-        }
-
-        if ($errors === null) {
-            echo "Testing plugin files...\n";
-        }
-        // test if core plugins are available
-        $source = SMARTY_PLUGINS_DIR;
-        if (is_dir($source)) {
-            $expected = array(
-                "block.textformat.php" => true,
-                "function.counter.php" => true,
-                "function.cycle.php" => true,
-                "function.fetch.php" => true,
-                "function.html_checkboxes.php" => true,
-                "function.html_image.php" => true,
-                "function.html_options.php" => true,
-                "function.html_radios.php" => true,
-                "function.html_select_date.php" => true,
-                "function.html_select_time.php" => true,
-                "function.html_table.php" => true,
-                "function.mailto.php" => true,
-                "function.math.php" => true,
-                "modifier.capitalize.php" => true,
-                "modifier.date_format.php" => true,
-                "modifier.debug_print_var.php" => true,
-                "modifier.escape.php" => true,
-                "modifier.regex_replace.php" => true,
-                "modifier.replace.php" => true,
-                "modifier.spacify.php" => true,
-                "modifier.truncate.php" => true,
-                "modifiercompiler.cat.php" => true,
-                "modifiercompiler.count_characters.php" => true,
-                "modifiercompiler.count_paragraphs.php" => true,
-                "modifiercompiler.count_sentences.php" => true,
-                "modifiercompiler.count_words.php" => true,
-                "modifiercompiler.default.php" => true,
-                "modifiercompiler.escape.php" => true,
-                "modifiercompiler.from_charset.php" => true,
-                "modifiercompiler.indent.php" => true,
-                "modifiercompiler.lower.php" => true,
-                "modifiercompiler.noprint.php" => true,
-                "modifiercompiler.string_format.php" => true,
-                "modifiercompiler.strip.php" => true,
-                "modifiercompiler.strip_tags.php" => true,
-                "modifiercompiler.to_charset.php" => true,
-                "modifiercompiler.unescape.php" => true,
-                "modifiercompiler.upper.php" => true,
-                "modifiercompiler.wordwrap.php" => true,
-                "outputfilter.trimwhitespace.php" => true,
-                "shared.escape_special_chars.php" => true,
-                "shared.literal_compiler_param.php" => true,
-                "shared.make_timestamp.php" => true,
-                "shared.mb_str_replace.php" => true,
-                "shared.mb_unicode.php" => true,
-                "shared.mb_wordwrap.php" => true,
-                "variablefilter.htmlspecialchars.php" => true,
-            );
-            $iterator = new DirectoryIterator($source);
-            foreach ($iterator as $file) {
-                if (!$file->isDot()) {
-                    $filename = $file->getFilename();
-                    if (isset($expected[$filename])) {
-                        unset($expected[$filename]);
-                    }
-                }
-            }
-            if ($expected) {
-                $status = false;
-                $message = "FAILED: files missing from libs/plugins: ". join(', ', array_keys($expected));
-                if ($errors === null) {
-                    echo $message . ".\n";
-                } else {
-                    $errors['plugins'] = $message;
-                }
-            } elseif ($errors === null) {
-                echo "... OK\n";
-            }
-        } else {
-            $status = false;
-            $message = "FAILED: ". SMARTY_PLUGINS_DIR .' is not a directory';
-            if ($errors === null) {
-                echo $message . ".\n";
-            } else {
-                $errors['plugins_dir_constant'] = $message;
-            }
-        }
-
-        if ($errors === null) {
-            echo "Tests complete.\n";
-            echo "
\n"; - } - - return $status; - } - -} + + * @author Uwe Tews + * @package Smarty + * @subpackage PluginsInternal + * @version 3-SVN$Rev: 3286 $ + */ + +/** + * Utility class + * + * @package Smarty + * @subpackage Security + */ +class Smarty_Internal_Utility +{ + /** + * private constructor to prevent calls creation of new instances + */ + final private function __construct() + { + // intentionally left blank + } + + /** + * Compile all template files + * + * @param string $extension template file name extension + * @param bool $force_compile force all to recompile + * @param int $time_limit set maximum execution time + * @param int $max_errors set maximum allowed errors + * @param Smarty $smarty Smarty instance + * @return integer number of template files compiled + */ + public static function compileAllTemplates($extension, $force_compile, $time_limit, $max_errors, Smarty $smarty) + { + // switch off time limit + if (function_exists('set_time_limit')) { + @set_time_limit($time_limit); + } + $smarty->force_compile = $force_compile; + $_count = 0; + $_error_count = 0; + // loop over array of template directories + foreach ($smarty->getTemplateDir() as $_dir) { + $_compileDirs = new RecursiveDirectoryIterator($_dir); + $_compile = new RecursiveIteratorIterator($_compileDirs); + foreach ($_compile as $_fileinfo) { + $_file = $_fileinfo->getFilename(); + if (substr(basename($_fileinfo->getPathname()),0,1) == '.' || strpos($_file, '.svn') !== false || strpos($_file, '.git') !== false) continue; + if (!substr_compare($_file, $extension, - strlen($extension)) == 0) continue; + if ($_fileinfo->getPath() == substr($_dir, 0, -1)) { + $_template_file = $_file; + } else { + $_template_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file; + } + echo '
', $_dir, '---', $_template_file; + flush(); + $_start_time = microtime(true); + try { + $_tpl = $smarty->createTemplate($_template_file,null,null,null,false); + if ($_tpl->mustCompile()) { + $_tpl->compileTemplateSource(); + $_count++; + echo ' compiled in ', microtime(true) - $_start_time, ' seconds'; + flush(); + } else { + echo ' is up to date'; + flush(); + } + } catch (Exception $e) { + echo 'Error: ', $e->getMessage(), "

"; + $_error_count++; + } + // free memory + $smarty->template_objects = array(); + $_tpl->smarty->template_objects = array(); + $_tpl = null; + if ($max_errors !== null && $_error_count == $max_errors) { + echo '

too many errors'; + exit(); + } + } + } + + return $_count; + } + + /** + * Compile all config files + * + * @param string $extension config file name extension + * @param bool $force_compile force all to recompile + * @param int $time_limit set maximum execution time + * @param int $max_errors set maximum allowed errors + * @param Smarty $smarty Smarty instance + * @return integer number of config files compiled + */ + public static function compileAllConfig($extension, $force_compile, $time_limit, $max_errors, Smarty $smarty) + { + // switch off time limit + if (function_exists('set_time_limit')) { + @set_time_limit($time_limit); + } + $smarty->force_compile = $force_compile; + $_count = 0; + $_error_count = 0; + // loop over array of template directories + foreach ($smarty->getConfigDir() as $_dir) { + $_compileDirs = new RecursiveDirectoryIterator($_dir); + $_compile = new RecursiveIteratorIterator($_compileDirs); + foreach ($_compile as $_fileinfo) { + $_file = $_fileinfo->getFilename(); + if (substr(basename($_fileinfo->getPathname()),0,1) == '.' || strpos($_file, '.svn') !== false || strpos($_file, '.git') !== false) continue; + if (!substr_compare($_file, $extension, - strlen($extension)) == 0) continue; + if ($_fileinfo->getPath() == substr($_dir, 0, -1)) { + $_config_file = $_file; + } else { + $_config_file = substr($_fileinfo->getPath(), strlen($_dir)) . DS . $_file; + } + echo '
', $_dir, '---', $_config_file; + flush(); + $_start_time = microtime(true); + try { + $_config = new Smarty_Internal_Config($_config_file, $smarty); + if ($_config->mustCompile()) { + $_config->compileConfigSource(); + $_count++; + echo ' compiled in ', microtime(true) - $_start_time, ' seconds'; + flush(); + } else { + echo ' is up to date'; + flush(); + } + } catch (Exception $e) { + echo 'Error: ', $e->getMessage(), "

"; + $_error_count++; + } + if ($max_errors !== null && $_error_count == $max_errors) { + echo '

too many errors'; + exit(); + } + } + } + + return $_count; + } + + /** + * Delete compiled template file + * + * @param string $resource_name template name + * @param string $compile_id compile id + * @param integer $exp_time expiration time + * @param Smarty $smarty Smarty instance + * @return integer number of template files deleted + */ + public static function clearCompiledTemplate($resource_name, $compile_id, $exp_time, Smarty $smarty) + { + $_compile_dir = $smarty->getCompileDir(); + $_compile_id = isset($compile_id) ? preg_replace('![^\w\|]+!', '_', $compile_id) : null; + $_dir_sep = $smarty->use_sub_dirs ? DS : '^'; + if (isset($resource_name)) { + $_save_stat = $smarty->caching; + $smarty->caching = false; + $tpl = new $smarty->template_class($resource_name, $smarty); + $smarty->caching = $_save_stat; + + // remove from template cache + $tpl->source; // have the template registered before unset() + if ($smarty->allow_ambiguous_resources) { + $_templateId = $tpl->source->unique_resource . $tpl->cache_id . $tpl->compile_id; + } else { + $_templateId = $smarty->joined_template_dir . '#' . $resource_name . $tpl->cache_id . $tpl->compile_id; + } + if (isset($_templateId[150])) { + $_templateId = sha1($_templateId); + } + unset($smarty->template_objects[$_templateId]); + + if ($tpl->source->exists) { + $_resource_part_1 = basename(str_replace('^', '/', $tpl->compiled->filepath)); + $_resource_part_1_length = strlen($_resource_part_1); + } else { + return 0; + } + + $_resource_part_2 = str_replace('.php','.cache.php',$_resource_part_1); + $_resource_part_2_length = strlen($_resource_part_2); + } + $_dir = $_compile_dir; + if ($smarty->use_sub_dirs && isset($_compile_id)) { + $_dir .= $_compile_id . $_dir_sep; + } + if (isset($_compile_id)) { + $_compile_id_part = $_compile_dir . $_compile_id . $_dir_sep; + $_compile_id_part_length = strlen($_compile_id_part); + } + $_count = 0; + try { + $_compileDirs = new RecursiveDirectoryIterator($_dir); + // NOTE: UnexpectedValueException thrown for PHP >= 5.3 + } catch (Exception $e) { + return 0; + } + $_compile = new RecursiveIteratorIterator($_compileDirs, RecursiveIteratorIterator::CHILD_FIRST); + foreach ($_compile as $_file) { + if (substr(basename($_file->getPathname()), 0, 1) == '.' || strpos($_file, '.svn') !== false || strpos($_file, '.git') !== false) continue; + + $_filepath = (string) $_file; + + if ($_file->isDir()) { + if (!$_compile->isDot()) { + // delete folder if empty + @rmdir($_file->getPathname()); + } + } else { + $unlink = false; + if ((!isset($_compile_id) || (isset($_filepath[$_compile_id_part_length]) && !strncmp($_filepath, $_compile_id_part, $_compile_id_part_length))) + && (!isset($resource_name) + || (isset($_filepath[$_resource_part_1_length]) + && substr_compare($_filepath, $_resource_part_1, -$_resource_part_1_length, $_resource_part_1_length) == 0) + || (isset($_filepath[$_resource_part_2_length]) + && substr_compare($_filepath, $_resource_part_2, -$_resource_part_2_length, $_resource_part_2_length) == 0))) { + if (isset($exp_time)) { + if (time() - @filemtime($_filepath) >= $exp_time) { + $unlink = true; + } + } else { + $unlink = true; + } + } + + if ($unlink && @unlink($_filepath)) { + $_count++; + } + } + } + // clear compiled cache + Smarty_Resource::$sources = array(); + Smarty_Resource::$compileds = array(); + + return $_count; + } + + /** + * Return array of tag/attributes of all tags used by an template + * + * @param Smarty_Internal_Template $templae template object + * @return array of tag/attributes + */ + public static function getTags(Smarty_Internal_Template $template) + { + $template->smarty->get_used_tags = true; + $template->compileTemplateSource(); + + return $template->used_tags; + } + + /** + * diagnose Smarty setup + * + * If $errors is secified, the diagnostic report will be appended to the array, rather than being output. + * + * @param Smarty $smarty Smarty instance to test + * @param array $errors array to push results into rather than outputting them + * @return bool status, true if everything is fine, false else + */ + public static function testInstall(Smarty $smarty, &$errors=null) + { + $status = true; + + if ($errors === null) { + echo "
\n";
+            echo "Smarty Installation test...\n";
+            echo "Testing template directory...\n";
+        }
+
+        $_stream_resolve_include_path = function_exists('stream_resolve_include_path');
+
+        // test if all registered template_dir are accessible
+        foreach ($smarty->getTemplateDir() as $template_dir) {
+            $_template_dir = $template_dir;
+            $template_dir = realpath($template_dir);
+            // resolve include_path or fail existence
+            if (!$template_dir) {
+                if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_template_dir)) {
+                    // try PHP include_path
+                    if ($_stream_resolve_include_path) {
+                        $template_dir = stream_resolve_include_path($_template_dir);
+                    } else {
+                        $template_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_template_dir);
+                    }
+
+                    if ($template_dir !== false) {
+                        if ($errors === null) {
+                            echo "$template_dir is OK.\n";
+                        }
+
+                        continue;
+                    } else {
+                        $status = false;
+                        $message = "FAILED: $_template_dir does not exist (and couldn't be found in include_path either)";
+                        if ($errors === null) {
+                            echo $message . ".\n";
+                        } else {
+                            $errors['template_dir'] = $message;
+                        }
+
+                        continue;
+                    }
+                } else {
+                    $status = false;
+                    $message = "FAILED: $_template_dir does not exist";
+                    if ($errors === null) {
+                        echo $message . ".\n";
+                    } else {
+                        $errors['template_dir'] = $message;
+                    }
+
+                    continue;
+                }
+            }
+
+            if (!is_dir($template_dir)) {
+                $status = false;
+                $message = "FAILED: $template_dir is not a directory";
+                if ($errors === null) {
+                    echo $message . ".\n";
+                } else {
+                    $errors['template_dir'] = $message;
+                }
+            } elseif (!is_readable($template_dir)) {
+                $status = false;
+                $message = "FAILED: $template_dir is not readable";
+                if ($errors === null) {
+                    echo $message . ".\n";
+                } else {
+                    $errors['template_dir'] = $message;
+                }
+            } else {
+                if ($errors === null) {
+                    echo "$template_dir is OK.\n";
+                }
+            }
+        }
+
+        if ($errors === null) {
+            echo "Testing compile directory...\n";
+        }
+
+        // test if registered compile_dir is accessible
+        $__compile_dir = $smarty->getCompileDir();
+        $_compile_dir = realpath($__compile_dir);
+        if (!$_compile_dir) {
+            $status = false;
+            $message = "FAILED: {$__compile_dir} does not exist";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['compile_dir'] = $message;
+            }
+        } elseif (!is_dir($_compile_dir)) {
+            $status = false;
+            $message = "FAILED: {$_compile_dir} is not a directory";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['compile_dir'] = $message;
+            }
+        } elseif (!is_readable($_compile_dir)) {
+            $status = false;
+            $message = "FAILED: {$_compile_dir} is not readable";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['compile_dir'] = $message;
+            }
+        } elseif (!is_writable($_compile_dir)) {
+            $status = false;
+            $message = "FAILED: {$_compile_dir} is not writable";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['compile_dir'] = $message;
+            }
+        } else {
+            if ($errors === null) {
+                echo "{$_compile_dir} is OK.\n";
+            }
+        }
+
+        if ($errors === null) {
+            echo "Testing plugins directory...\n";
+        }
+
+        // test if all registered plugins_dir are accessible
+        // and if core plugins directory is still registered
+        $_core_plugins_dir = realpath(dirname(__FILE__) .'/../plugins');
+        $_core_plugins_available = false;
+        foreach ($smarty->getPluginsDir() as $plugin_dir) {
+            $_plugin_dir = $plugin_dir;
+            $plugin_dir = realpath($plugin_dir);
+            // resolve include_path or fail existence
+            if (!$plugin_dir) {
+                if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_plugin_dir)) {
+                    // try PHP include_path
+                    if ($_stream_resolve_include_path) {
+                        $plugin_dir = stream_resolve_include_path($_plugin_dir);
+                    } else {
+                        $plugin_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_plugin_dir);
+                    }
+
+                    if ($plugin_dir !== false) {
+                        if ($errors === null) {
+                            echo "$plugin_dir is OK.\n";
+                        }
+
+                        continue;
+                    } else {
+                        $status = false;
+                        $message = "FAILED: $_plugin_dir does not exist (and couldn't be found in include_path either)";
+                        if ($errors === null) {
+                            echo $message . ".\n";
+                        } else {
+                            $errors['plugins_dir'] = $message;
+                        }
+
+                        continue;
+                    }
+                } else {
+                    $status = false;
+                    $message = "FAILED: $_plugin_dir does not exist";
+                    if ($errors === null) {
+                        echo $message . ".\n";
+                    } else {
+                        $errors['plugins_dir'] = $message;
+                    }
+
+                    continue;
+                }
+            }
+
+            if (!is_dir($plugin_dir)) {
+                $status = false;
+                $message = "FAILED: $plugin_dir is not a directory";
+                if ($errors === null) {
+                    echo $message . ".\n";
+                } else {
+                    $errors['plugins_dir'] = $message;
+                }
+            } elseif (!is_readable($plugin_dir)) {
+                $status = false;
+                $message = "FAILED: $plugin_dir is not readable";
+                if ($errors === null) {
+                    echo $message . ".\n";
+                } else {
+                    $errors['plugins_dir'] = $message;
+                }
+            } elseif ($_core_plugins_dir && $_core_plugins_dir == realpath($plugin_dir)) {
+                $_core_plugins_available = true;
+                if ($errors === null) {
+                    echo "$plugin_dir is OK.\n";
+                }
+            } else {
+                if ($errors === null) {
+                    echo "$plugin_dir is OK.\n";
+                }
+            }
+        }
+        if (!$_core_plugins_available) {
+            $status = false;
+            $message = "WARNING: Smarty's own libs/plugins is not available";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } elseif (!isset($errors['plugins_dir'])) {
+                $errors['plugins_dir'] = $message;
+            }
+        }
+
+        if ($errors === null) {
+            echo "Testing cache directory...\n";
+        }
+
+        // test if all registered cache_dir is accessible
+        $__cache_dir = $smarty->getCacheDir();
+        $_cache_dir = realpath($__cache_dir);
+        if (!$_cache_dir) {
+            $status = false;
+            $message = "FAILED: {$__cache_dir} does not exist";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['cache_dir'] = $message;
+            }
+        } elseif (!is_dir($_cache_dir)) {
+            $status = false;
+            $message = "FAILED: {$_cache_dir} is not a directory";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['cache_dir'] = $message;
+            }
+        } elseif (!is_readable($_cache_dir)) {
+            $status = false;
+            $message = "FAILED: {$_cache_dir} is not readable";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['cache_dir'] = $message;
+            }
+        } elseif (!is_writable($_cache_dir)) {
+            $status = false;
+            $message = "FAILED: {$_cache_dir} is not writable";
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['cache_dir'] = $message;
+            }
+        } else {
+            if ($errors === null) {
+                echo "{$_cache_dir} is OK.\n";
+            }
+        }
+
+        if ($errors === null) {
+            echo "Testing configs directory...\n";
+        }
+
+        // test if all registered config_dir are accessible
+        foreach ($smarty->getConfigDir() as $config_dir) {
+            $_config_dir = $config_dir;
+            $config_dir = realpath($config_dir);
+            // resolve include_path or fail existence
+            if (!$config_dir) {
+                if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_config_dir)) {
+                    // try PHP include_path
+                    if ($_stream_resolve_include_path) {
+                        $config_dir = stream_resolve_include_path($_config_dir);
+                    } else {
+                        $config_dir = Smarty_Internal_Get_Include_Path::getIncludePath($_config_dir);
+                    }
+
+                    if ($config_dir !== false) {
+                        if ($errors === null) {
+                            echo "$config_dir is OK.\n";
+                        }
+
+                        continue;
+                    } else {
+                        $status = false;
+                        $message = "FAILED: $_config_dir does not exist (and couldn't be found in include_path either)";
+                        if ($errors === null) {
+                            echo $message . ".\n";
+                        } else {
+                            $errors['config_dir'] = $message;
+                        }
+
+                        continue;
+                    }
+                } else {
+                    $status = false;
+                    $message = "FAILED: $_config_dir does not exist";
+                    if ($errors === null) {
+                        echo $message . ".\n";
+                    } else {
+                        $errors['config_dir'] = $message;
+                    }
+
+                    continue;
+                }
+            }
+
+            if (!is_dir($config_dir)) {
+                $status = false;
+                $message = "FAILED: $config_dir is not a directory";
+                if ($errors === null) {
+                    echo $message . ".\n";
+                } else {
+                    $errors['config_dir'] = $message;
+                }
+            } elseif (!is_readable($config_dir)) {
+                $status = false;
+                $message = "FAILED: $config_dir is not readable";
+                if ($errors === null) {
+                    echo $message . ".\n";
+                } else {
+                    $errors['config_dir'] = $message;
+                }
+            } else {
+                if ($errors === null) {
+                    echo "$config_dir is OK.\n";
+                }
+            }
+        }
+
+        if ($errors === null) {
+            echo "Testing sysplugin files...\n";
+        }
+        // test if sysplugins are available
+        $source = SMARTY_SYSPLUGINS_DIR;
+        if (is_dir($source)) {
+            $expected = array(
+                "smarty_cacheresource.php" => true,
+                "smarty_cacheresource_custom.php" => true,
+                "smarty_cacheresource_keyvaluestore.php" => true,
+                "smarty_config_source.php" => true,
+                "smarty_internal_cacheresource_file.php" => true,
+                "smarty_internal_compile_append.php" => true,
+                "smarty_internal_compile_assign.php" => true,
+                "smarty_internal_compile_block.php" => true,
+                "smarty_internal_compile_break.php" => true,
+                "smarty_internal_compile_call.php" => true,
+                "smarty_internal_compile_capture.php" => true,
+                "smarty_internal_compile_config_load.php" => true,
+                "smarty_internal_compile_continue.php" => true,
+                "smarty_internal_compile_debug.php" => true,
+                "smarty_internal_compile_eval.php" => true,
+                "smarty_internal_compile_extends.php" => true,
+                "smarty_internal_compile_for.php" => true,
+                "smarty_internal_compile_foreach.php" => true,
+                "smarty_internal_compile_function.php" => true,
+                "smarty_internal_compile_if.php" => true,
+                "smarty_internal_compile_include.php" => true,
+                "smarty_internal_compile_include_php.php" => true,
+                "smarty_internal_compile_insert.php" => true,
+                "smarty_internal_compile_ldelim.php" => true,
+                "smarty_internal_compile_nocache.php" => true,
+                "smarty_internal_compile_private_block_plugin.php" => true,
+                "smarty_internal_compile_private_function_plugin.php" => true,
+                "smarty_internal_compile_private_modifier.php" => true,
+                "smarty_internal_compile_private_object_block_function.php" => true,
+                "smarty_internal_compile_private_object_function.php" => true,
+                "smarty_internal_compile_private_print_expression.php" => true,
+                "smarty_internal_compile_private_registered_block.php" => true,
+                "smarty_internal_compile_private_registered_function.php" => true,
+                "smarty_internal_compile_private_special_variable.php" => true,
+                "smarty_internal_compile_rdelim.php" => true,
+                "smarty_internal_compile_section.php" => true,
+                "smarty_internal_compile_setfilter.php" => true,
+                "smarty_internal_compile_while.php" => true,
+                "smarty_internal_compilebase.php" => true,
+                "smarty_internal_config.php" => true,
+                "smarty_internal_config_file_compiler.php" => true,
+                "smarty_internal_configfilelexer.php" => true,
+                "smarty_internal_configfileparser.php" => true,
+                "smarty_internal_data.php" => true,
+                "smarty_internal_debug.php" => true,
+                "smarty_internal_filter_handler.php" => true,
+                "smarty_internal_function_call_handler.php" => true,
+                "smarty_internal_get_include_path.php" => true,
+                "smarty_internal_nocache_insert.php" => true,
+                "smarty_internal_parsetree.php" => true,
+                "smarty_internal_resource_eval.php" => true,
+                "smarty_internal_resource_extends.php" => true,
+                "smarty_internal_resource_file.php" => true,
+                "smarty_internal_resource_registered.php" => true,
+                "smarty_internal_resource_stream.php" => true,
+                "smarty_internal_resource_string.php" => true,
+                "smarty_internal_smartytemplatecompiler.php" => true,
+                "smarty_internal_template.php" => true,
+                "smarty_internal_templatebase.php" => true,
+                "smarty_internal_templatecompilerbase.php" => true,
+                "smarty_internal_templatelexer.php" => true,
+                "smarty_internal_templateparser.php" => true,
+                "smarty_internal_utility.php" => true,
+                "smarty_internal_write_file.php" => true,
+                "smarty_resource.php" => true,
+                "smarty_resource_custom.php" => true,
+                "smarty_resource_recompiled.php" => true,
+                "smarty_resource_uncompiled.php" => true,
+                "smarty_security.php" => true,
+            );
+            $iterator = new DirectoryIterator($source);
+            foreach ($iterator as $file) {
+                if (!$file->isDot()) {
+                    $filename = $file->getFilename();
+                    if (isset($expected[$filename])) {
+                        unset($expected[$filename]);
+                    }
+                }
+            }
+            if ($expected) {
+                $status = false;
+                $message = "FAILED: files missing from libs/sysplugins: ". join(', ', array_keys($expected));
+                if ($errors === null) {
+                    echo $message . ".\n";
+                } else {
+                    $errors['sysplugins'] = $message;
+                }
+            } elseif ($errors === null) {
+                echo "... OK\n";
+            }
+        } else {
+            $status = false;
+            $message = "FAILED: ". SMARTY_SYSPLUGINS_DIR .' is not a directory';
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['sysplugins_dir_constant'] = $message;
+            }
+        }
+
+        if ($errors === null) {
+            echo "Testing plugin files...\n";
+        }
+        // test if core plugins are available
+        $source = SMARTY_PLUGINS_DIR;
+        if (is_dir($source)) {
+            $expected = array(
+                "block.textformat.php" => true,
+                "function.counter.php" => true,
+                "function.cycle.php" => true,
+                "function.fetch.php" => true,
+                "function.html_checkboxes.php" => true,
+                "function.html_image.php" => true,
+                "function.html_options.php" => true,
+                "function.html_radios.php" => true,
+                "function.html_select_date.php" => true,
+                "function.html_select_time.php" => true,
+                "function.html_table.php" => true,
+                "function.mailto.php" => true,
+                "function.math.php" => true,
+                "modifier.capitalize.php" => true,
+                "modifier.date_format.php" => true,
+                "modifier.debug_print_var.php" => true,
+                "modifier.escape.php" => true,
+                "modifier.regex_replace.php" => true,
+                "modifier.replace.php" => true,
+                "modifier.spacify.php" => true,
+                "modifier.truncate.php" => true,
+                "modifiercompiler.cat.php" => true,
+                "modifiercompiler.count_characters.php" => true,
+                "modifiercompiler.count_paragraphs.php" => true,
+                "modifiercompiler.count_sentences.php" => true,
+                "modifiercompiler.count_words.php" => true,
+                "modifiercompiler.default.php" => true,
+                "modifiercompiler.escape.php" => true,
+                "modifiercompiler.from_charset.php" => true,
+                "modifiercompiler.indent.php" => true,
+                "modifiercompiler.lower.php" => true,
+                "modifiercompiler.noprint.php" => true,
+                "modifiercompiler.string_format.php" => true,
+                "modifiercompiler.strip.php" => true,
+                "modifiercompiler.strip_tags.php" => true,
+                "modifiercompiler.to_charset.php" => true,
+                "modifiercompiler.unescape.php" => true,
+                "modifiercompiler.upper.php" => true,
+                "modifiercompiler.wordwrap.php" => true,
+                "outputfilter.trimwhitespace.php" => true,
+                "shared.escape_special_chars.php" => true,
+                "shared.literal_compiler_param.php" => true,
+                "shared.make_timestamp.php" => true,
+                "shared.mb_str_replace.php" => true,
+                "shared.mb_unicode.php" => true,
+                "shared.mb_wordwrap.php" => true,
+                "variablefilter.htmlspecialchars.php" => true,
+            );
+            $iterator = new DirectoryIterator($source);
+            foreach ($iterator as $file) {
+                if (!$file->isDot()) {
+                    $filename = $file->getFilename();
+                    if (isset($expected[$filename])) {
+                        unset($expected[$filename]);
+                    }
+                }
+            }
+            if ($expected) {
+                $status = false;
+                $message = "FAILED: files missing from libs/plugins: ". join(', ', array_keys($expected));
+                if ($errors === null) {
+                    echo $message . ".\n";
+                } else {
+                    $errors['plugins'] = $message;
+                }
+            } elseif ($errors === null) {
+                echo "... OK\n";
+            }
+        } else {
+            $status = false;
+            $message = "FAILED: ". SMARTY_PLUGINS_DIR .' is not a directory';
+            if ($errors === null) {
+                echo $message . ".\n";
+            } else {
+                $errors['plugins_dir_constant'] = $message;
+            }
+        }
+
+        if ($errors === null) {
+            echo "Tests complete.\n";
+            echo "
\n"; + } + + return $status; + } + +} diff --git a/themes/default/app_defaults.php b/themes/default/app_defaults.php index 47769b72dc..07cc71c7b5 100644 --- a/themes/default/app_defaults.php +++ b/themes/default/app_defaults.php @@ -1,1381 +1,1381 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2016 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -if ($domains_processed == 1) { - - //get the background images - $relative_path = PROJECT_PATH.'/themes/default/images/backgrounds'; - $backgrounds = opendir($_SERVER["DOCUMENT_ROOT"].'/'.$relative_path); - unset($array); - $x = 0; - while (false !== ($file = readdir($backgrounds))) { - if ($file != "." AND $file != ".."){ - $ext = pathinfo($file, PATHINFO_EXTENSION); - if ($ext == "png" || $ext == "jpg" || $ext == "jpeg" || $ext == "gif") { - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'background_image'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = $relative_path.'/'.$file; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set a relative path or URL within a selected compatible template.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_background_image'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = $relative_path.'/'.$file; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set a relative path or URL within a selected compatible template.'; - $x++; - } - if ($x > 300) { break; }; - } - } - - //define array of settings - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'background_color'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = '#6c89b5'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_order'] = '0'; - $array[$x]['default_setting_description'] = 'Set a background color.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'background_color'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = '#144794'; - $array[$x]['default_setting_order'] = '1'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set a secondary background color, for a gradient effect.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'domain_visible'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'true'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the visibility of the name of the domain currently being managed.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'logout_icon_visible'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'false'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the visibility of the logout icon.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'domain_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#69e5ff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text color (and opacity) for domain name.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'footer_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'rgba(0,0,0,0.1)'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) for the footer bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'footer_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'rgba(255,255,255,0.1)'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text color (and opacity) for the footer bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'footer_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '0 0 4px 4px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of the footer bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'message_default_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ccffcc'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the background color for the positive (default) message bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'message_default_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#004200'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the text color for the positive (default) message bar text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'message_negative_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffcdcd'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the background color for the negative message bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'message_negative_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#670000'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the text color for the negative message bar text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'message_alert_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffe585'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the background color for the alert message bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'message_alert_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#d66721'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the text color for the alert message bar text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'message_opacity'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '0.9'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the opacity of the message bar (decimal).'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'message_delay'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '1.75'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the hide delay of the message bar (seconds).'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'background_image_enabled'; - $array[$x]['default_setting_name'] = 'boolean'; - $array[$x]['default_setting_value'] = 'true'; - $array[$x]['default_setting_enabled'] = 'false'; - if ($background_image_enabled) { $array[$x]['default_setting_enabled'] = 'true'; } - $array[$x]['default_setting_description'] = 'Enable use of background images.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'body_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set then body background color (and opacity) of the content.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'body_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the body.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'body_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '4px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of the body.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'cache'; - $array[$x]['default_setting_name'] = 'boolean'; - $array[$x]['default_setting_value'] = 'false'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set whether to cache the theme in the session.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'domain_selector_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#888888'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the domain selector pane.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'logo_align'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'center'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the alignment of the header logo (Inline menu only)'; - $x++; - /* menu elements */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ff0000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set a background color (and opacity) of the main menu bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_background_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ff0000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set a background hover color (and opacity) of the main menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_icons'; - $array[$x]['default_setting_name'] = 'boolean'; - $array[$x]['default_setting_value'] = 'false'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Show icons next to main menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_background_image'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '/themes/default/images/background_black.png'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set a background image for the main menu bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the main menu bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text color of the main menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_text_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#69e5ff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text hover color of the main menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of the main menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '10.25pt'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text size of the main menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '0 0 4px 4px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of the main menu.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_border_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '1px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border size of the main menu.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_main_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of the main menu.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_position'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'top'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the position of the main menu (Fixed menu only).'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_style'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'fixed'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the style of the main menu.'; - $x++; - /* sub menu items */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = ''; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the sub menus.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_background_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = ''; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the hover background color (and opacity) of the sub menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_icons'; - $array[$x]['default_setting_name'] = 'boolean'; - $array[$x]['default_setting_value'] = 'false'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Show indicator icons next to selected sub menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of sub menus.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of sub menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_text_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#69e5ff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the hover text color (and opacity) of sub menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of the sub menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '10pt'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text size of the sub menu items.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '0 0 4px 4px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of the sub menu.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_border_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '1px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border size of the sub menu.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'menu_sub_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of the sub menu.'; - $x++; - /* body elements */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'heading_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of the page heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'heading_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '15px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of the page heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'heading_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#952424'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the page heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'body_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of body text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'body_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '12px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of the body text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'body_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#5f5f5f'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the body text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'text_link_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#004083'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the link color (and opacity) of text links outside tables.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'text_link_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#5082ca'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of text links outside tables.'; - $x++; - /* data tables */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_heading_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text font of table header rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_heading_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '12px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text size of table header rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_heading_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#3164ad'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of table header rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_heading_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of table header rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_heading_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#a4aebf'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the bottom border color (and opacity) of table header rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_row_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text font of table data rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_row_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '12px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text size of table data rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_row_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of table data rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_row_background_color_dark'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#e5e9f0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the darker background color (and opacity) of table data rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_row_background_color_medium'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#f0f2f6'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the medium background color (and opacity) of table data rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_row_background_color_light'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#fff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the lighter background color (and opacity) of table data rows.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'table_row_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#c5d1e5'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the bottom border (dividing line) color (and opacity) of table data rows.'; - /* dashboard elements */ - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#dbe0ea'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of the Dashboard blocks.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_border_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#cbd3e1'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border hover color (and opacity) of the Dashboard block.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '5px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of the Dashboard block.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_heading_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#8e96a5'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the Dashboard block heading.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_heading_background_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#969dab'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background hover color (and opacity) of the Dashboard block heading.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the Dashboard block heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of the Dashboard block heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of the Dashboard block heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '10.5pt'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the Dashboard block heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_shadow_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the shadow hover color (and opacity) of the Dashboard block heading text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#a4aebf'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the Dashboard block number.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_background_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#aeb7c5'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background hover color (and opacity) of the Dashboard block number.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the Dashboard block number.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of the Dashboard block number.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of the Dashboard block number.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '60pt'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block number.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#737983'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the Dashboard block number.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_shadow_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#737983'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the shadow hover color (and opacity) of the Dashboard block number.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_title_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the Dashboard block number title.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_title_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of the Dashboard block number title.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_title_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '14px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block number title.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_number_title_text_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#737983'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the Dashboard block number title.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_detail_heading_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '11px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block detail header text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_detail_row_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '11px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block detail row text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_detail_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#737983'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the shadow color of the Dashboard block detail box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_detail_background_color_center'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#f9fbfe'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the center gradient color of the Dashboard block detail area.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_detail_background_color_edge'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#edf1f7'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the edge gradient color of the Dashboard block detail area.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_footer_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#e5e9f0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the Dashboard block footer bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_footer_background_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ebeef3'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background hover color (and opacity) of the Dashboard block footer bar.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_footer_dots_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#a4aebf'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the Dashboard block footer bar dots.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'dashboard_footer_dots_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#a4aebf'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of the Dashboard block footer bar dots.'; - $x++; - /* form table elements */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_padding'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '7px 8px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the padding of the form label cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#e5e9f0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the form label cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the bottom-border color (and opacity) of the form label cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '4px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of the form label cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '9pt'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text size of the form label.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text font of the form label.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of the form label.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_required_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#e5e9f0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color of the required form label cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_required_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#cbcfd5'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the right-border color (and opacity) of the required form label cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_required_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of the required form label.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_label_required_text_weight'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'bold'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the text weight of the required form label.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_field_padding'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '6px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the padding of the form field cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_field_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the form field cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_field_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#e5e9f0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the bottom-border color (and opacity) of the form field cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_field_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of the form label cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_field_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '8pt'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of text in the form field cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_field_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of text in the form field cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_field_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#666666'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of text in the form field cell.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_heading_padding'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '8px 8px 4px 8px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the padding of form column headings.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_row_padding'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '3px 0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the padding of form row cells.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'form_table_row_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '9pt'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of text in the form rows.'; - $x++; - /* login box */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_background_color'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = '#6c89b5'; - $array[$x]['default_setting_order'] = '0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color of the login page.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_background_color'; - $array[$x]['default_setting_name'] = 'array'; - $array[$x]['default_setting_value'] = '#144794'; - $array[$x]['default_setting_order'] = '1'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set a secondary background color of the login page, for a gradient effect.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_background_image_enabled'; - $array[$x]['default_setting_name'] = 'boolean'; - $array[$x]['default_setting_value'] = 'true'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Enable use of background images on the login page.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_body_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'rgba(255,255,255,0.3)'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the background color for the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_body_shadow_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'rgba(140,140,140,0.3)'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the shadow color of the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_body_padding'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '30px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the padding of the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_body_width'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '100%'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the width of the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_body_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '4px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_body_border_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '1px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border size of the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_body_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_link_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#004083'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of text links on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_link_text_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#5082ca'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of text links on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_link_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '11px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of text links on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_link_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of text links on the login box.'; - $x++; - /* buttons */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#4f4f4f'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background main/top color (and opacity) of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_background_color_bottom'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background bottom color (and opacity) of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_background_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background main/top hover color (and opacity) of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_background_color_bottom_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background bottom hover color (and opacity) of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_border_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '1px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border size of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#242424'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_border_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border hover color (and opacity) of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '3px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '11px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of button text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Candara, Calibri, Segoe, "Segoe UI", Optima, Arial, sans-serif'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of button text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of button text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_text_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of button text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_text_weight'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'bold'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the weight of button text.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_padding'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '5px 8px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the padding of buttons.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'button_height'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '28px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the height of buttons.'; - $x++; - /* form input fields */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#c0c0c0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_border_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#c0c0c0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border hover color (and opacity) of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_border_color_focus'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#c0c0c0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border focus color (and opacity) of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_border_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '1px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border size of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '3px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_shadow_inner_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#cddaf0'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the inner shadow color (and opacity) of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_shadow_inner_color_focus'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the inner focus shadow color (and opacity) of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_shadow_outer_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the outer shadow color (and opacity) of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_shadow_outer_color_focus'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#cddaf0'; - $array[$x]['default_setting_enabled'] = 'true'; - $array[$x]['default_setting_description'] = 'Set the outer focus shadow color (and opacity) of text inputs.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '12px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of text input content.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of text input content.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of text input content.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'input_text_placeholder_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#999999'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of input placeholder text.'; - $x++; - /* login form input fields */ - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_background_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_border_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#c0c0c0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_border_color_hover'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#c0c0c0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border hover color (and opacity) of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_border_color_focus'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#c0c0c0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border focus color (and opacity) of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_border_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '1px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border size of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_border_radius'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '3px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the border radius of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_shadow_inner_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#cddaf0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the inner shadow color (and opacity) of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_shadow_inner_color_focus'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the inner focus shadow color (and opacity) of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_shadow_outer_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#ffffff'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the outer shadow color (and opacity) of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_shadow_outer_color_focus'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#cddaf0'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the outer focus shadow color (and opacity) of text inputs on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_text_size'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '12px'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the size of text input content on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_text_font'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = 'Arial'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the font of text input content on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_text_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#000000'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of text input content on the login box.'; - $x++; - $array[$x]['default_setting_category'] = 'theme'; - $array[$x]['default_setting_subcategory'] = 'login_input_text_placeholder_color'; - $array[$x]['default_setting_name'] = 'text'; - $array[$x]['default_setting_value'] = '#999999'; - $array[$x]['default_setting_enabled'] = 'false'; - $array[$x]['default_setting_description'] = 'Set the color (and opacity) of input placeholder text on the login box.'; - $x++; - - //get an array of the default settings - $sql = "select * from v_default_settings "; - $sql .= "where default_setting_category = 'theme' "; - $prep_statement = $db->prepare($sql); - $prep_statement->execute(); - $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); - unset ($prep_statement, $sql); - - //find the missing default settings - $i = 0; - foreach ($array as $setting) { - $found = false; - $missing[$i] = $setting; - foreach ($default_settings as $row) { - if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { - $found = true; - //remove items from the array that were found - unset($missing[$i]); - } - } - $i++; - } - - //get the missing count - $i = 0; - foreach ($missing as $row) { $i++; } - $missing_count = $i; - - //add the missing default settings - $sql = "insert into v_default_settings ("; - $sql .= "default_setting_uuid, "; - $sql .= "default_setting_category, "; - $sql .= "default_setting_subcategory, "; - $sql .= "default_setting_name, "; - $sql .= "default_setting_value, "; - $sql .= "default_setting_enabled, "; - $sql .= "default_setting_description "; - $sql .= ") values \n"; - $i = 1; - foreach ($missing as $row) { - $sql .= "("; - $sql .= "'".uuid()."', "; - $sql .= "'".check_str($row['default_setting_category'])."', "; - $sql .= "'".check_str($row['default_setting_subcategory'])."', "; - $sql .= "'".check_str($row['default_setting_name'])."', "; - $sql .= "'".check_str($row['default_setting_value'])."', "; - $sql .= "'".check_str($row['default_setting_enabled'])."', "; - $sql .= "'".check_str($row['default_setting_description'])."' "; - $sql .= ")"; - if ($missing_count != $i) { - $sql .= ",\n"; - } - $i++; - } - $db->exec(check_sql($sql)); - unset($missing); - - //unset the array variable - unset($array); -} - + + Portions created by the Initial Developer are Copyright (C) 2008-2016 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +if ($domains_processed == 1) { + + //get the background images + $relative_path = PROJECT_PATH.'/themes/default/images/backgrounds'; + $backgrounds = opendir($_SERVER["DOCUMENT_ROOT"].'/'.$relative_path); + unset($array); + $x = 0; + while (false !== ($file = readdir($backgrounds))) { + if ($file != "." AND $file != ".."){ + $ext = pathinfo($file, PATHINFO_EXTENSION); + if ($ext == "png" || $ext == "jpg" || $ext == "jpeg" || $ext == "gif") { + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'background_image'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = $relative_path.'/'.$file; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set a relative path or URL within a selected compatible template.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_background_image'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = $relative_path.'/'.$file; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set a relative path or URL within a selected compatible template.'; + $x++; + } + if ($x > 300) { break; }; + } + } + + //define array of settings + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'background_color'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = '#6c89b5'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_order'] = '0'; + $array[$x]['default_setting_description'] = 'Set a background color.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'background_color'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = '#144794'; + $array[$x]['default_setting_order'] = '1'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set a secondary background color, for a gradient effect.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'domain_visible'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'true'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the visibility of the name of the domain currently being managed.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'logout_icon_visible'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'false'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the visibility of the logout icon.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'domain_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#69e5ff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text color (and opacity) for domain name.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'footer_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'rgba(0,0,0,0.1)'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) for the footer bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'footer_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'rgba(255,255,255,0.1)'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text color (and opacity) for the footer bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'footer_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '0 0 4px 4px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of the footer bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'message_default_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ccffcc'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the background color for the positive (default) message bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'message_default_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#004200'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the text color for the positive (default) message bar text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'message_negative_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffcdcd'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the background color for the negative message bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'message_negative_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#670000'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the text color for the negative message bar text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'message_alert_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffe585'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the background color for the alert message bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'message_alert_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#d66721'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the text color for the alert message bar text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'message_opacity'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '0.9'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the opacity of the message bar (decimal).'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'message_delay'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '1.75'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the hide delay of the message bar (seconds).'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'background_image_enabled'; + $array[$x]['default_setting_name'] = 'boolean'; + $array[$x]['default_setting_value'] = 'true'; + $array[$x]['default_setting_enabled'] = 'false'; + if ($background_image_enabled) { $array[$x]['default_setting_enabled'] = 'true'; } + $array[$x]['default_setting_description'] = 'Enable use of background images.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'body_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set then body background color (and opacity) of the content.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'body_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the body.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'body_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '4px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of the body.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'cache'; + $array[$x]['default_setting_name'] = 'boolean'; + $array[$x]['default_setting_value'] = 'false'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set whether to cache the theme in the session.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'domain_selector_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#888888'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the domain selector pane.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'logo_align'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'center'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the alignment of the header logo (Inline menu only)'; + $x++; + /* menu elements */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ff0000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set a background color (and opacity) of the main menu bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_background_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ff0000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set a background hover color (and opacity) of the main menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_icons'; + $array[$x]['default_setting_name'] = 'boolean'; + $array[$x]['default_setting_value'] = 'false'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Show icons next to main menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_background_image'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '/themes/default/images/background_black.png'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set a background image for the main menu bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the main menu bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text color of the main menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_text_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#69e5ff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text hover color of the main menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of the main menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '10.25pt'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text size of the main menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '0 0 4px 4px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of the main menu.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_border_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '1px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border size of the main menu.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_main_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of the main menu.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_position'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'top'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the position of the main menu (Fixed menu only).'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_style'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'fixed'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the style of the main menu.'; + $x++; + /* sub menu items */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = ''; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the sub menus.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_background_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = ''; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the hover background color (and opacity) of the sub menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_icons'; + $array[$x]['default_setting_name'] = 'boolean'; + $array[$x]['default_setting_value'] = 'false'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Show indicator icons next to selected sub menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of sub menus.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of sub menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_text_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#69e5ff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the hover text color (and opacity) of sub menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of the sub menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '10pt'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text size of the sub menu items.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '0 0 4px 4px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of the sub menu.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_border_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '1px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border size of the sub menu.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'menu_sub_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of the sub menu.'; + $x++; + /* body elements */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'heading_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of the page heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'heading_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '15px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of the page heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'heading_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#952424'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the page heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'body_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of body text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'body_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '12px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of the body text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'body_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#5f5f5f'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the body text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'text_link_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#004083'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the link color (and opacity) of text links outside tables.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'text_link_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#5082ca'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of text links outside tables.'; + $x++; + /* data tables */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_heading_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text font of table header rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_heading_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '12px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text size of table header rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_heading_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#3164ad'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of table header rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_heading_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of table header rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_heading_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#a4aebf'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the bottom border color (and opacity) of table header rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_row_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text font of table data rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_row_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '12px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text size of table data rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_row_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of table data rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_row_background_color_dark'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#e5e9f0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the darker background color (and opacity) of table data rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_row_background_color_medium'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#f0f2f6'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the medium background color (and opacity) of table data rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_row_background_color_light'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#fff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the lighter background color (and opacity) of table data rows.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'table_row_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#c5d1e5'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the bottom border (dividing line) color (and opacity) of table data rows.'; + /* dashboard elements */ + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#dbe0ea'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of the Dashboard blocks.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_border_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#cbd3e1'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border hover color (and opacity) of the Dashboard block.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '5px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of the Dashboard block.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_heading_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#8e96a5'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the Dashboard block heading.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_heading_background_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#969dab'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background hover color (and opacity) of the Dashboard block heading.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the Dashboard block heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of the Dashboard block heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of the Dashboard block heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '10.5pt'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the Dashboard block heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_heading_text_shadow_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the shadow hover color (and opacity) of the Dashboard block heading text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#a4aebf'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the Dashboard block number.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_background_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#aeb7c5'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background hover color (and opacity) of the Dashboard block number.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the Dashboard block number.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of the Dashboard block number.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of the Dashboard block number.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '60pt'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block number.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#737983'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the Dashboard block number.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_text_shadow_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#737983'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the shadow hover color (and opacity) of the Dashboard block number.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_title_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the Dashboard block number title.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_title_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Calibri, Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of the Dashboard block number title.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_title_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '14px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block number title.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_number_title_text_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#737983'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the shadow color (and opacity) of the Dashboard block number title.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_detail_heading_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '11px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block detail header text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_detail_row_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '11px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of the Dashboard block detail row text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_detail_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#737983'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the shadow color of the Dashboard block detail box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_detail_background_color_center'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#f9fbfe'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the center gradient color of the Dashboard block detail area.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_detail_background_color_edge'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#edf1f7'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the edge gradient color of the Dashboard block detail area.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_footer_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#e5e9f0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the Dashboard block footer bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_footer_background_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ebeef3'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background hover color (and opacity) of the Dashboard block footer bar.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_footer_dots_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#a4aebf'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of the Dashboard block footer bar dots.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'dashboard_footer_dots_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#a4aebf'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of the Dashboard block footer bar dots.'; + $x++; + /* form table elements */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_padding'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '7px 8px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the padding of the form label cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#e5e9f0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the form label cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the bottom-border color (and opacity) of the form label cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '4px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of the form label cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '9pt'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text size of the form label.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text font of the form label.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of the form label.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_required_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#e5e9f0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color of the required form label cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_required_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#cbcfd5'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the right-border color (and opacity) of the required form label cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_required_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text color (and opacity) of the required form label.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_label_required_text_weight'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'bold'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the text weight of the required form label.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_field_padding'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '6px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the padding of the form field cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_field_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of the form field cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_field_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#e5e9f0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the bottom-border color (and opacity) of the form field cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_field_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of the form label cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_field_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '8pt'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of text in the form field cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_field_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of text in the form field cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_field_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#666666'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of text in the form field cell.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_heading_padding'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '8px 8px 4px 8px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the padding of form column headings.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_row_padding'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '3px 0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the padding of form row cells.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'form_table_row_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '9pt'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of text in the form rows.'; + $x++; + /* login box */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_background_color'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = '#6c89b5'; + $array[$x]['default_setting_order'] = '0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color of the login page.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_background_color'; + $array[$x]['default_setting_name'] = 'array'; + $array[$x]['default_setting_value'] = '#144794'; + $array[$x]['default_setting_order'] = '1'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set a secondary background color of the login page, for a gradient effect.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_background_image_enabled'; + $array[$x]['default_setting_name'] = 'boolean'; + $array[$x]['default_setting_value'] = 'true'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Enable use of background images on the login page.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_body_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'rgba(255,255,255,0.3)'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the background color for the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_body_shadow_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'rgba(140,140,140,0.3)'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the shadow color of the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_body_padding'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '30px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the padding of the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_body_width'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '100%'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the width of the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_body_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '4px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_body_border_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '1px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border size of the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_body_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_link_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#004083'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of text links on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_link_text_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#5082ca'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of text links on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_link_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '11px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of text links on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_link_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of text links on the login box.'; + $x++; + /* buttons */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#4f4f4f'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background main/top color (and opacity) of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_background_color_bottom'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background bottom color (and opacity) of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_background_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background main/top hover color (and opacity) of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_background_color_bottom_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background bottom hover color (and opacity) of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_border_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '1px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border size of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#242424'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_border_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border hover color (and opacity) of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '3px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '11px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of button text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Candara, Calibri, Segoe, "Segoe UI", Optima, Arial, sans-serif'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of button text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of button text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_text_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the hover color (and opacity) of button text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_text_weight'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'bold'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the weight of button text.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_padding'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '5px 8px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the padding of buttons.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'button_height'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '28px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the height of buttons.'; + $x++; + /* form input fields */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#c0c0c0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_border_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#c0c0c0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border hover color (and opacity) of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_border_color_focus'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#c0c0c0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border focus color (and opacity) of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_border_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '1px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border size of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '3px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_shadow_inner_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#cddaf0'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the inner shadow color (and opacity) of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_shadow_inner_color_focus'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the inner focus shadow color (and opacity) of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_shadow_outer_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the outer shadow color (and opacity) of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_shadow_outer_color_focus'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#cddaf0'; + $array[$x]['default_setting_enabled'] = 'true'; + $array[$x]['default_setting_description'] = 'Set the outer focus shadow color (and opacity) of text inputs.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '12px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of text input content.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of text input content.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of text input content.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'input_text_placeholder_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#999999'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of input placeholder text.'; + $x++; + /* login form input fields */ + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_background_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the background color (and opacity) of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_border_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#c0c0c0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border color (and opacity) of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_border_color_hover'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#c0c0c0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border hover color (and opacity) of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_border_color_focus'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#c0c0c0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border focus color (and opacity) of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_border_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '1px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border size of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_border_radius'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '3px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the border radius of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_shadow_inner_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#cddaf0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the inner shadow color (and opacity) of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_shadow_inner_color_focus'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the inner focus shadow color (and opacity) of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_shadow_outer_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#ffffff'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the outer shadow color (and opacity) of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_shadow_outer_color_focus'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#cddaf0'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the outer focus shadow color (and opacity) of text inputs on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_text_size'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '12px'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the size of text input content on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_text_font'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = 'Arial'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the font of text input content on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_text_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#000000'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of text input content on the login box.'; + $x++; + $array[$x]['default_setting_category'] = 'theme'; + $array[$x]['default_setting_subcategory'] = 'login_input_text_placeholder_color'; + $array[$x]['default_setting_name'] = 'text'; + $array[$x]['default_setting_value'] = '#999999'; + $array[$x]['default_setting_enabled'] = 'false'; + $array[$x]['default_setting_description'] = 'Set the color (and opacity) of input placeholder text on the login box.'; + $x++; + + //get an array of the default settings + $sql = "select * from v_default_settings "; + $sql .= "where default_setting_category = 'theme' "; + $prep_statement = $db->prepare($sql); + $prep_statement->execute(); + $default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED); + unset ($prep_statement, $sql); + + //find the missing default settings + $i = 0; + foreach ($array as $setting) { + $found = false; + $missing[$i] = $setting; + foreach ($default_settings as $row) { + if (trim($row['default_setting_subcategory']) == trim($setting['default_setting_subcategory'])) { + $found = true; + //remove items from the array that were found + unset($missing[$i]); + } + } + $i++; + } + + //get the missing count + $i = 0; + foreach ($missing as $row) { $i++; } + $missing_count = $i; + + //add the missing default settings + $sql = "insert into v_default_settings ("; + $sql .= "default_setting_uuid, "; + $sql .= "default_setting_category, "; + $sql .= "default_setting_subcategory, "; + $sql .= "default_setting_name, "; + $sql .= "default_setting_value, "; + $sql .= "default_setting_enabled, "; + $sql .= "default_setting_description "; + $sql .= ") values \n"; + $i = 1; + foreach ($missing as $row) { + $sql .= "("; + $sql .= "'".uuid()."', "; + $sql .= "'".check_str($row['default_setting_category'])."', "; + $sql .= "'".check_str($row['default_setting_subcategory'])."', "; + $sql .= "'".check_str($row['default_setting_name'])."', "; + $sql .= "'".check_str($row['default_setting_value'])."', "; + $sql .= "'".check_str($row['default_setting_enabled'])."', "; + $sql .= "'".check_str($row['default_setting_description'])."' "; + $sql .= ")"; + if ($missing_count != $i) { + $sql .= ",\n"; + } + $i++; + } + $db->exec(check_sql($sql)); + unset($missing); + + //unset the array variable + unset($array); +} + ?> \ No newline at end of file