From 53779d50d388d4001816b2aeb8ea99f5915530f9 Mon Sep 17 00:00:00 2001 From: markjcrane Date: Thu, 29 Jun 2023 23:40:11 -0600 Subject: [PATCH] Change device_mac_address to device_address --- app/devices/app_config.php | 6 +- app/devices/app_languages.php | 134 +- app/devices/device_copy.php | 22 +- app/devices/device_download.php | 2 +- app/devices/device_edit.php | 66 +- app/devices/device_imports.php | 1128 ++--- app/devices/devices.php | 8 +- app/extensions/app_languages.php | 46 +- app/extensions/extension_edit.php | 68 +- app/provision/app_defaults.php | 12 +- app/provision/index.php | 95 +- app/provision/resources/classes/provision.php | 117 +- .../resources/functions/device_by.php | 6 +- resources/functions.php | 4431 +++++++++-------- 14 files changed, 3077 insertions(+), 3064 deletions(-) diff --git a/app/devices/app_config.php b/app/devices/app_config.php index 81c6793bbb..f6ee6bada2 100644 --- a/app/devices/app_config.php +++ b/app/devices/app_config.php @@ -48,7 +48,7 @@ $apps[$x]['permissions'][$y]['groups'][] = "admin"; $apps[$x]['permissions'][$y]['groups'][] = "superadmin"; $y++; - $apps[$x]['permissions'][$y]['name'] = "device_mac_address"; + $apps[$x]['permissions'][$y]['name'] = "device_address"; $apps[$x]['permissions'][$y]['groups'][] = "superadmin"; $apps[$x]['permissions'][$y]['groups'][] = "admin"; $y++; @@ -411,8 +411,8 @@ $apps[$x]['db'][$y]['fields'][$z]['description']['en-us'] = ""; $apps[$x]['db'][$y]['fields'][$z]['deprecated'] = "true"; $z++; - $apps[$x]['db'][$y]['fields'][$z]['name']['text'] = "device_mac_address"; - $apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = "phone_mac_address"; + $apps[$x]['db'][$y]['fields'][$z]['name']['text'] = "device_address"; + $apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = "device_mac_address"; $apps[$x]['db'][$y]['fields'][$z]['type'] = "text"; $apps[$x]['db'][$y]['fields'][$z]['search'] = 'true'; $apps[$x]['db'][$y]['fields'][$z]['description']['en-us'] = ""; diff --git a/app/devices/app_languages.php b/app/devices/app_languages.php index 83b530eb0d..91081e87e5 100644 --- a/app/devices/app_languages.php +++ b/app/devices/app_languages.php @@ -220,29 +220,29 @@ $text['select-global']['zh-cn'] = "全球的"; $text['select-global']['ja-jp'] = "グローバル"; $text['select-global']['ko-kr'] = "글로벌"; -$text['message_device']['en-us'] = "Enter the New MAC Address"; -$text['message_device']['en-gb'] = "Enter the New MAC Address"; +$text['message_device']['en-us'] = "Enter the New Address"; +$text['message_device']['en-gb'] = "Enter the New Address"; $text['message_device']['ar-eg'] = "أدخل العنوان الجديد"; -$text['message_device']['de-at'] = "Geben Sie die neue MAC Adresse ein"; -$text['message_device']['de-ch'] = "Geben Sie die neue MAC Adresse ein"; -$text['message_device']['de-de'] = "Geben Sie die neue MAC Adresse ein"; -$text['message_device']['es-cl'] = "Introduzca la nueva dirección MAC"; -$text['message_device']['es-mx'] = "Introduzca la nueva dirección MAC"; -$text['message_device']['fr-ca'] = "Insérer la nouvelle adresse MAC"; -$text['message_device']['fr-fr'] = "Insérer la nouvelle adresse MAC"; +$text['message_device']['de-at'] = "Geben Sie die neue Adresse ein"; +$text['message_device']['de-ch'] = "Geben Sie die neue Adresse ein"; +$text['message_device']['de-de'] = "Geben Sie die neue Adresse ein"; +$text['message_device']['es-cl'] = "Introduzca la nueva dirección"; +$text['message_device']['es-mx'] = "Introduzca la nueva dirección"; +$text['message_device']['fr-ca'] = "Insérer la nouvelle adresse"; +$text['message_device']['fr-fr'] = "Insérer la nouvelle adresse"; $text['message_device']['he-il'] = "הכנס כתובת מאק חדשה"; -$text['message_device']['it-it'] = "Inserire il nuovo MAC address"; -$text['message_device']['nl-nl'] = "Voer het nieuwe MAC adres in"; -$text['message_device']['pl-pl'] = "Wpisz nowy adres MAC"; -$text['message_device']['pt-br'] = "Insira o novo endereço MAC"; -$text['message_device']['pt-pt'] = "Introduza o novo endereço MAC"; -$text['message_device']['ro-ro'] = "Introduceți noua adresă MAC"; -$text['message_device']['ru-ru'] = "Введите новый MAC-адрес"; -$text['message_device']['sv-se'] = "Fyll i den nya MAC-adressen"; -$text['message_device']['uk-ua'] = "Введіть нову MAC адресу"; -$text['message_device']['zh-cn'] = "输入新的 MAC 地址"; -$text['message_device']['ja-jp'] = "新しいMACアドレスを入力してください"; -$text['message_device']['ko-kr'] = "새 MAC 주소를 입력하십시오"; +$text['message_device']['it-it'] = "Inserire il nuovo address"; +$text['message_device']['nl-nl'] = "Voer het nieuwe adres in"; +$text['message_device']['pl-pl'] = "Wpisz nowy adres"; +$text['message_device']['pt-br'] = "Insira o novo endereço"; +$text['message_device']['pt-pt'] = "Introduza o novo endereço"; +$text['message_device']['ro-ro'] = "Introduceți noua adresă"; +$text['message_device']['ru-ru'] = "Введите новый адрес"; +$text['message_device']['sv-se'] = "Fyll i den nya adressen"; +$text['message_device']['uk-ua'] = "Введіть нову адресу"; +$text['message_device']['zh-cn'] = "输入新的 地址"; +$text['message_device']['ja-jp'] = "新しいアドレスを入力してください"; +$text['message_device']['ko-kr'] = "새 주소를 입력하십시오"; $text['message-maximum_devices']['en-us'] = "Maximum Devices:"; $text['message-maximum_devices']['en-gb'] = "Maximum Devices:"; @@ -3266,29 +3266,29 @@ $text['label-device_model']['zh-cn'] = "模型"; $text['label-device_model']['ja-jp'] = "モデル"; $text['label-device_model']['ko-kr'] = "모델"; -$text['label-device_mac_address']['en-us'] = "MAC Address"; -$text['label-device_mac_address']['en-gb'] = "MAC Address"; -$text['label-device_mac_address']['ar-eg'] = "العنوان الرئيسي"; -$text['label-device_mac_address']['de-at'] = "MAC Adresse"; -$text['label-device_mac_address']['de-ch'] = "MAC Adresse"; -$text['label-device_mac_address']['de-de'] = "MAC Adresse"; -$text['label-device_mac_address']['es-cl'] = "Dirección MAC"; -$text['label-device_mac_address']['es-mx'] = "Dirección MAC"; -$text['label-device_mac_address']['fr-ca'] = "Adresse MAC"; -$text['label-device_mac_address']['fr-fr'] = "Adresse MAC"; -$text['label-device_mac_address']['he-il'] = "כתובת MAC"; -$text['label-device_mac_address']['it-it'] = "MAC Address"; -$text['label-device_mac_address']['nl-nl'] = "MAC Adres"; -$text['label-device_mac_address']['pl-pl'] = "Adres MAC"; -$text['label-device_mac_address']['pt-br'] = "Endereço MAC"; -$text['label-device_mac_address']['pt-pt'] = "Endereço MAC"; -$text['label-device_mac_address']['ro-ro'] = "Adresa mac"; -$text['label-device_mac_address']['ru-ru'] = "MAC-адрес"; -$text['label-device_mac_address']['sv-se'] = "MAC-adress"; -$text['label-device_mac_address']['uk-ua'] = "Адреса MAC"; -$text['label-device_mac_address']['zh-cn'] = "MAC地址"; -$text['label-device_mac_address']['ja-jp'] = "Macアドレス"; -$text['label-device_mac_address']['ko-kr'] = "MAC 주소"; +$text['label-device_address']['en-us'] = "Address"; +$text['label-device_address']['en-gb'] = "Address"; +$text['label-device_address']['ar-eg'] = "العنوان الرئيسي"; +$text['label-device_address']['de-at'] = "Adresse"; +$text['label-device_address']['de-ch'] = "Adresse"; +$text['label-device_address']['de-de'] = "Adresse"; +$text['label-device_address']['es-cl'] = "Dirección"; +$text['label-device_address']['es-mx'] = "Dirección"; +$text['label-device_address']['fr-ca'] = "Adresse"; +$text['label-device_address']['fr-fr'] = "Adresse"; +$text['label-device_address']['he-il'] = "כתובת "; +$text['label-device_address']['it-it'] = "Address"; +$text['label-device_address']['nl-nl'] = "Adres"; +$text['label-device_address']['pl-pl'] = "Adres"; +$text['label-device_address']['pt-br'] = "Endereço"; +$text['label-device_address']['pt-pt'] = "Endereço"; +$text['label-device_address']['ro-ro'] = "Adresa"; +$text['label-device_address']['ru-ru'] = "адрес"; +$text['label-device_address']['sv-se'] = "adress"; +$text['label-device_address']['uk-ua'] = "Адреса"; +$text['label-device_address']['zh-cn'] = "地址"; +$text['label-device_address']['ja-jp'] = "アドレス"; +$text['label-device_address']['ko-kr'] = "주소"; $text['label-download']['en-us'] = "Download"; $text['label-download']['en-gb'] = "Download"; @@ -6104,29 +6104,29 @@ $text['description-device_model']['zh-cn'] = "输入型号名称或编号。"; $text['description-device_model']['ja-jp'] = "モデル名またはモデル番号を入力します。"; $text['description-device_model']['ko-kr'] = "모델명 또는 번호를 입력하세요."; -$text['description-device_mac_address']['en-us'] = "Enter the MAC address."; -$text['description-device_mac_address']['en-gb'] = "Enter the MAC address."; -$text['description-device_mac_address']['ar-eg'] = "أدخل العنوان"; -$text['description-device_mac_address']['de-at'] = "Geben Sie die MAC Adresse ein."; -$text['description-device_mac_address']['de-ch'] = "Geben Sie die MAC Adresse ein."; -$text['description-device_mac_address']['de-de'] = "Geben Sie die MAC Adresse ein."; -$text['description-device_mac_address']['es-cl'] = "Ingrese la dirección MAC"; -$text['description-device_mac_address']['es-mx'] = "Ingrese la dirección MAC"; -$text['description-device_mac_address']['fr-ca'] = "Entrez l'adresse MAC."; -$text['description-device_mac_address']['fr-fr'] = "Entrez l'adresse MAC."; -$text['description-device_mac_address']['he-il'] = "היכנס לכתובת MAC"; -$text['description-device_mac_address']['it-it'] = "Inserire il MAC address."; -$text['description-device_mac_address']['nl-nl'] = "Voer het MAC adres in."; -$text['description-device_mac_address']['pl-pl'] = "Wprowadź adres MAC"; -$text['description-device_mac_address']['pt-br'] = "Insira o endereço MAC"; -$text['description-device_mac_address']['pt-pt'] = "Introduza o endereço MAC."; -$text['description-device_mac_address']['ro-ro'] = "Introduceți adresa MAC."; -$text['description-device_mac_address']['ru-ru'] = "Введите MAC-адрес."; -$text['description-device_mac_address']['sv-se'] = "Fyll i MAC-adress."; -$text['description-device_mac_address']['uk-ua'] = "Введіть адресу MAC."; -$text['description-device_mac_address']['zh-cn'] = "输入 MAC 地址。"; -$text['description-device_mac_address']['ja-jp'] = "MAC アドレスを入力します。"; -$text['description-device_mac_address']['ko-kr'] = "MAC 주소를 입력합니다."; +$text['description-device_address']['en-us'] = "Enter the address."; +$text['description-device_address']['en-gb'] = "Enter the address."; +$text['description-device_address']['ar-eg'] = "أدخل العنوان"; +$text['description-device_address']['de-at'] = "Geben Sie die Adresse ein."; +$text['description-device_address']['de-ch'] = "Geben Sie die Adresse ein."; +$text['description-device_address']['de-de'] = "Geben Sie die Adresse ein."; +$text['description-device_address']['es-cl'] = "Ingrese la dirección"; +$text['description-device_address']['es-mx'] = "Ingrese la dirección"; +$text['description-device_address']['fr-ca'] = "Entrez l'adresse."; +$text['description-device_address']['fr-fr'] = "Entrez l'adresse."; +$text['description-device_address']['he-il'] = "היכנס לכתובת MAC"; +$text['description-device_address']['it-it'] = "Inserire il address."; +$text['description-device_address']['nl-nl'] = "Voer het adres in."; +$text['description-device_address']['pl-pl'] = "Wprowadź adres"; +$text['description-device_address']['pt-br'] = "Insira o endereço"; +$text['description-device_address']['pt-pt'] = "Introduza o endereço."; +$text['description-device_address']['ro-ro'] = "Introduceți adresa."; +$text['description-device_address']['ru-ru'] = "Введите адрес."; +$text['description-device_address']['sv-se'] = "Fyll i adress."; +$text['description-device_address']['uk-ua'] = "Введіть адресу."; +$text['description-device_address']['zh-cn'] = "输入 地址。"; +$text['description-device_address']['ja-jp'] = "アドレスを入力します。"; +$text['description-device_address']['ko-kr'] = "주소를 입력합니다."; $text['description-device_label']['en-us'] = "Enter the device label."; $text['description-device_label']['en-gb'] = "Enter the device label."; diff --git a/app/devices/device_copy.php b/app/devices/device_copy.php index 0dc11f9090..a467de98a1 100644 --- a/app/devices/device_copy.php +++ b/app/devices/device_copy.php @@ -44,21 +44,21 @@ //set the http get/post variable(s) to a php variable if (is_uuid($_REQUEST["id"]) && isset($_REQUEST["mac"])) { $device_uuid = $_REQUEST["id"]; - $device_mac_address = $_REQUEST["mac"]; - $device_mac_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_mac_address); + $device_address = $_REQUEST["mac"]; + $device_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_address); } //set the default $save = true; -//check to see if the mac address exists - if ($device_mac_address == "" || $device_mac_address == "000000000000") { +//check to see if the device address exists + if ($device_address == "" || $device_address == "000000000000") { //allow duplicates to be used as templaes } else { $sql = "select count(*) from v_devices "; - $sql .= "where device_mac_address = :device_mac_address "; - $parameters['device_mac_address'] = $device_mac_address; + $sql .= "where device_address = :device_address "; + $parameters['device_address'] = $device_address; $database = new database; $num_rows = $database->select($sql, $parameters, 'column'); if ($num_rows == 0) { @@ -151,15 +151,15 @@ } } -//normalize the mac address - if (isset($device_mac_address) && !empty($device_mac_address)) { - $device_mac_address = strtolower($device_mac_address); - $device_mac_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_mac_address); +//normalize the device address + if (isset($device_address) && !empty($device_address)) { + $device_address = strtolower($device_address); + $device_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_address); } //create the device array $device = $devices[0]; - $device["device_mac_address"] = $device_mac_address; + $device["device_address"] = $device_address; $device["device_lines"] = $device_lines; $device["device_keys"] = $device_keys; $device["device_settings"] = $device_settings; diff --git a/app/devices/device_download.php b/app/devices/device_download.php index 6484bae929..f0fdda687a 100644 --- a/app/devices/device_download.php +++ b/app/devices/device_download.php @@ -76,7 +76,7 @@ //define possible columns in the array $available_columns['devices'][] = 'device_uuid'; $available_columns['devices'][] = 'device_profile_uuid'; - $available_columns['devices'][] = 'device_mac_address'; + $available_columns['devices'][] = 'device_address'; $available_columns['devices'][] = 'device_label'; $available_columns['devices'][] = 'device_vendor'; $available_columns['devices'][] = 'device_template'; diff --git a/app/devices/device_edit.php b/app/devices/device_edit.php index 7f61485541..dd23b7f2db 100644 --- a/app/devices/device_edit.php +++ b/app/devices/device_edit.php @@ -92,9 +92,9 @@ exit; } - //device mac address - if (permission_exists('device_mac_address')) { - $device_mac_address = $_POST["device_mac_address"]; + //device device address + if (permission_exists('device_address')) { + $device_address = $_POST["device_address"]; } else { $sql = "select * from v_devices "; @@ -103,7 +103,7 @@ $database = new database; $row = $database->select($sql, $parameters, 'row'); if (is_array($row) && @sizeof($row) != 0) { - $device_mac_address = $row["device_mac_address"]; + $device_address = $row["device_address"]; } unset($sql, $parameters, $row); } @@ -161,16 +161,16 @@ //$device_setting_enabled = $_POST["device_setting_enabled"]; //$device_setting_description = $_POST["device_setting_description"]; - //normalize the mac address - if (!empty($device_mac_address)) { - $device_mac_address = strtolower($device_mac_address); - $device_mac_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_mac_address); + //normalize the address + if (!empty($device_address)) { + $device_address = strtolower($device_address); + $device_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_address); } } -//use the mac address to get the vendor +//use the device address to get the vendor if (empty($device_vendor)) { - $device_vendor = device::get_vendor($device_mac_address ?? null); + $device_vendor = device::get_vendor($device_address ?? null); } //add or update the database @@ -186,7 +186,7 @@ //check for all required data $msg = ''; - if (empty($device_mac_address)) { $msg .= $text['message-required'].$text['label-device_mac_address']."
\n"; } + if (empty($device_address)) { $msg .= $text['message-required'].$text['label-device_address']."
\n"; } //if (empty($device_label)) { $msg .= "Please provide: Label
\n"; } //if (empty($device_vendor)) { $msg .= "Please provide: Vendor
\n"; } //if (empty($device_model)) { $msg .= "Please provide: Model
\n"; } @@ -210,7 +210,7 @@ } //check for duplicates - if ($action == 'add' && $device_mac_address != "000000000000") { + if ($action == 'add' && $device_address != "000000000000") { $sql = "select "; $sql .= "d2.domain_name "; $sql .= "from "; @@ -218,11 +218,11 @@ $sql .= "v_domains as d2 "; $sql .= "where "; $sql .= "d1.domain_uuid = d2.domain_uuid and "; - $sql .= "d1.device_mac_address = :device_mac_address "; + $sql .= "d1.device_address = :device_address "; if (!empty($_GET["device_uuid"]) && is_uuid($_GET["device_uuid"])) { $sql .= " and d1.device_uuid <> :device_uuid "; } - $parameters['device_mac_address'] = $device_mac_address; + $parameters['device_address'] = $device_address; $database = new database; $domain_name = $database->select($sql, $parameters, 'column'); if ($domain_name != '') { @@ -245,8 +245,8 @@ //prepare the array $array['devices'][0]['domain_uuid'] = $domain_uuid; $array['devices'][0]['device_uuid'] = $device_uuid; - if (permission_exists('device_mac_address')) { - $array['devices'][0]['device_mac_address'] = $device_mac_address; + if (permission_exists('device_address')) { + $array['devices'][0]['device_address'] = $device_address; } //$array['devices'][0]['device_provisioned_ip'] = $device_provisioned_ip; if (permission_exists('device_label')) { @@ -509,11 +509,11 @@ $database = new database; $row = $database->select($sql, $parameters, 'row'); if (is_array($row) && @sizeof($row) != 0) { - $device_mac_address = $row["device_mac_address"]; + $device_address = $row["device_address"]; $device_provisioned_ip = $row["device_provisioned_ip"]; $domain_uuid = $row["domain_uuid"]; $device_label = $row["device_label"]; - //$device_mac_address = substr($device_mac_address, 0,2).'-'.substr($device_mac_address, 2,2).'-'.substr($device_mac_address, 4,2).'-'.substr($device_mac_address, 6,2).'-'.substr($device_mac_address, 8,2).'-'.substr($device_mac_address, 10,2); + //$device_address = substr($device_address, 0,2).'-'.substr($device_address, 2,2).'-'.substr($device_address, 4,2).'-'.substr($device_address, 6,2).'-'.substr($device_address, 8,2).'-'.substr($device_address, 10,2); $device_label = $row["device_label"]; $device_user_uuid = $row["device_user_uuid"]; $device_username = $row["device_username"]; @@ -534,12 +534,12 @@ //set the defaults if (empty($device_enabled)) { $device_enabled = 'true'; } -//use the mac address to get the vendor +//use the device address to get the vendor if (empty($device_vendor)) { - //get the device vendor using the mac address - $device_vendor = device::get_vendor($device_mac_address ?? null); + //get the device vendor using the device address + $device_vendor = device::get_vendor($device_address ?? null); - //if the vendor was not found using the mac address use an alternative method + //if the vendor was not found using the device address use an alternative method if (empty($device_vendor)) { $template_array = explode("/", $device_template ?? ''); $device_vendor = $template_array[0] ?? ''; @@ -664,9 +664,9 @@ $users = $database->select($sql, $parameters, 'all'); unset($sql, $parameters); -//use the mac address to get the vendor +//use the device address to get the vendor if (empty($device_vendor)) { - $device_vendor = device::get_vendor($device_mac_address ?? null); + $device_vendor = device::get_vendor($device_address ?? null); } //get the device line info for provision button @@ -720,7 +720,7 @@ if ($_SERVER['HTTPS'] == 'on') { $_SERVER['HTTP_PROTOCOL'] = 'https'; } if ($_SERVER['SERVER_PORT'] == '443') { $_SERVER['HTTP_PROTOCOL'] = 'https'; } } - echo " window.location = '".$_SERVER['HTTP_PROTOCOL']."://".$domain_name.PROJECT_PATH."/app/provision/index.php?mac=".escape($device_mac_address ?? '')."&file=' + d + '&content_type=application/octet-stream';\n"; + echo " window.location = '".$_SERVER['HTTP_PROTOCOL']."://".$domain_name.PROJECT_PATH."/app/provision/index.php?mac=".escape($device_address ?? '')."&file=' + d + '&content_type=application/octet-stream';\n"; echo " }\n"; echo "\n"; @@ -869,9 +869,9 @@ echo "\n"; + if (permission_exists('device_address')) { + echo " \n"; echo "
\n"; - echo $text['description-device_mac_address']."\n"; + echo $text['description-device_address']."\n"; } else { - echo escape($device_mac_address ?? ''); + echo escape($device_address ?? ''); } echo " \n"; echo " ".escape($device_provisioned_ip ?? '')." (http|https)\n"; @@ -1794,7 +1794,7 @@ echo "\n"; $label = $device_alternate[0]['device_label']; if (empty($label)) { $label = $device_alternate[0]['device_description']; } - if (empty($label)) { $label = $device_alternate[0]['device_mac_address']; } + if (empty($label)) { $label = $device_alternate[0]['device_address']; } echo " \n"; echo " \n"; echo " "; diff --git a/app/devices/device_imports.php b/app/devices/device_imports.php index a2a16fda17..f76de89c0a 100644 --- a/app/devices/device_imports.php +++ b/app/devices/device_imports.php @@ -1,564 +1,564 @@ - - Portions created by the Initial Developer are Copyright (C) 2018-2023 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane -*/ - -//includes files - require_once dirname(__DIR__, 2) . "/resources/require.php"; - require_once "resources/check_auth.php"; - -//check permissions - if (permission_exists('device_add')) { - //access granted - } - else { - echo "access denied"; - exit; - } - -//add multi-lingual support - $language = new text; - $text = $language->get(); - -//built in str_getcsv requires PHP 5.3 or higher, this function can be used to reproduct the functionality but requirs PHP 5.1.0 or higher - if (!function_exists('str_getcsv')) { - function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") { - $fp = fopen("php://memory", 'r+'); - fputs($fp, $input); - rewind($fp); - $data = fgetcsv($fp, null, $delimiter, $enclosure, $escape); - fclose($fp); - return $data; - } - } - -//set the max php execution time - ini_set('max_execution_time',7200); - -//get the http get values and set them as php variables - $action = $_POST["action"] ?? null; - $from_row = $_POST["from_row"] ?? null; - $delimiter = $_POST["data_delimiter"] ?? null; - $enclosure = $_POST["data_enclosure"] ?? null; - -//save the data to the csv file - if (isset($_POST['data'])) { - $file = $_SESSION['server']['temp']['dir']."/devices-".$_SESSION['domain_name'].".csv"; - if (file_put_contents($file, $_POST['data'])) { - $_SESSION['file'] = $file; - } - } - -//copy the csv file - //$_POST['submit'] == "Upload" && - if (!empty($_FILES['ulfile']['tmp_name']) && is_uploaded_file($_FILES['ulfile']['tmp_name']) && permission_exists('device_import')) { - if ($_POST['type'] == 'csv') { - $file = $_SESSION['server']['temp']['dir']."/devices-".$_SESSION['domain_name'].".csv"; - if (move_uploaded_file($_FILES['ulfile']['tmp_name'], $file)) { - $_SESSION['file'] = $file; - } - } - } - -//get the schema - if (!empty($delimiter) && file_exists($_SESSION['file'] ?? '')) { - //get the first line - $line = fgets(fopen($_SESSION['file'], 'r')); - $line_fields = explode($delimiter, $line); - - //get the schema - $x = 0; - include "app/devices/app_config.php"; - $i = 0; - foreach ($apps[0]['db'] as $table) { - //get the table name and parent name - $table_name = $table["table"]['name']; - $parent_name = $table["table"]['parent']; - - //remove the v_ table prefix - if (substr($table_name, 0, 2) == 'v_') { - $table_name = substr($table_name, 2); - } - if (substr($parent_name, 0, 2) == 'v_') { - $parent_name = substr($parent_name, 2); - } - - //filter for specific tables and build the schema array - if ($table_name == "devices" || $table_name == "device_lines" || - $table_name == "device_keys" || $table_name == "device_settings") { - $schema[$i]['table'] = $table_name; - $schema[$i]['parent'] = $parent_name; - foreach ($table['fields'] as $row) { - if (empty($row['deprecated']) || $row['deprecated'] !== 'true') { - if (is_array($row['name'])) { - $field_name = $row['name']['text']; - } - else { - $field_name = $row['name']; - } - $schema[$i]['fields'][] = $field_name; - } - } - $i++; - } - } - - $i++; - $schema[$i]['table'] = 'devices'; - $schema[$i]['parent'] = ''; - $schema[$i]['fields'][] = 'username'; - } - -//match the column names to the field names - if (!empty($delimiter) && file_exists($_SESSION['file'] ?? '') && $action != 'import') { - - //validate the token - $token = new token; - if (!$token->validate($_SERVER['PHP_SELF'])) { - message::add($text['message-invalid_token'],'negative'); - header('Location: device_imports.php'); - exit; - } - - //create token - $object = new token; - $token = $object->create($_SERVER['PHP_SELF']); - - //include header - $document['title'] = $text['title-device_import']; - require_once "resources/header.php"; - - //form to match the fields to the column names - echo "
\n"; - - echo "
\n"; - echo "
".$text['header-device_import']."
\n"; - echo "
\n"; - echo button::create(['type'=>'button','label'=>$text['button-back'],'icon'=>$_SESSION['theme']['button_icon_back'],'id'=>'btn_back','style'=>'margin-right: 15px;','link'=>'device_imports.php']); - echo button::create(['type'=>'submit','label'=>$text['button-import'],'icon'=>$_SESSION['theme']['button_icon_import'],'id'=>'btn_save']); - echo "
\n"; - echo "
\n"; - echo "
\n"; - - echo $text['description-import']."\n"; - echo "

\n"; - - echo "
".escape($label)." 
\n"; - - //loop through user columns - $x = 0; - foreach ($line_fields as $line_field) { - $line_field = preg_replace('#[^a-zA-Z0-9_]#', '', $line_field); - echo "\n"; - echo " \n"; - echo " \n"; - echo "\n"; - $x++; - } - - echo "
\n"; - //echo " ".$text['label-zzz']."\n"; - echo $line_field; - echo " \n"; - echo " \n"; - //echo "
\n"; - //echo $text['description-zzz']."\n"; - echo "
\n"; - echo "

\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - - require_once "resources/footer.php"; - - //normalize the column names - //$line = strtolower($line); - //$line = str_replace("-", "_", $line); - //$line = str_replace($delimiter."title".$delimiter, $delimiter."contact_title".$delimiter, $line); - //$line = str_replace("firstname", "name_given", $line); - //$line = str_replace("lastname", "name_family", $line); - //$line = str_replace("company", "organization", $line); - //$line = str_replace("company", "contact_email", $line); - - //end the script - exit; - } - -//get the parent table - function get_parent($schema,$table_name) { - foreach ($schema as $row) { - if ($row['table'] == $table_name) { - return $row['parent']; - } - } - } - -//upload the csv - if (file_exists($_SESSION['file'] ?? '') && $action == 'import') { - - //validate the token - $token = new token; - if (!$token->validate($_SERVER['PHP_SELF'])) { - message::add($text['message-invalid_token'],'negative'); - header('Location: device_imports.php'); - exit; - } - - //user selected fields - $fields = $_POST['fields']; - - //set the domain_uuid - $domain_uuid = $_SESSION['domain_uuid']; - - //open the database - $database = new database; - $database->app_name = 'devices'; - $database->app_uuid = '4efa1a1a-32e7-bf83-534b-6c8299958a8e'; - - //get the users - $sql = "select * from v_users where domain_uuid = :domain_uuid "; - $parameters['domain_uuid'] = $domain_uuid; - $users = $database->select($sql, $parameters, 'all'); - unset($sql, $parameters); - - //get the contents of the csv file and convert them into an array - $handle = @fopen($_SESSION['file'], "r"); - if ($handle) { - //set the starting identifiers - $row_id = 0; - $row_number = 1; - - //loop through the array - while (($line = fgets($handle, 4096)) !== false) { - if ($from_row <= $row_number) { - //format the data - $y = 0; - foreach ($fields as $key => $value) { - //get the line - $result = str_getcsv($line, $delimiter, $enclosure); - - //get the table and field name - $field_array = explode(".",$value); - $table_name = $field_array[0]; - $field_name = $field_array[1]; - //echo "value: $value
\n"; - //echo "table_name: $table_name
\n"; - //echo "field_name: $field_name
\n"; - - //get the parent table name - $parent = get_parent($schema, $table_name); - - //count the field names - if (isset($field_count[$table_name][$field_name])) { - $field_count[$table_name][$field_name]++; - } - else { - $field_count[$table_name][$field_name] = 0; - } - - //set the ordinal ID - $id = $field_count[$table_name][$field_name]; - - //remove formatting from the phone number - if ($field_name == "phone_number") { - $result[$key] = preg_replace('{\D}', '', $result[$key]); - } - - //normalize the MAC address - if ($field_name == "device_mac_address") { - $result[$key] = strtolower($result[$key]); - $result[$key] = preg_replace('#[^a-fA-F0-9./]#', '', $result[$key]); - } - - //build the data array - if (!empty($table_name)) { - if (empty($parent)) { - if ($field_name != "username") { - $array[$table_name][$row_id]['domain_uuid'] = $domain_uuid; - $array[$table_name][$row_id][$field_name] = $result[$key]; - } - } - else { - $array[$parent][$row_id][$table_name][$id]['domain_uuid'] = $domain_uuid; - $array[$parent][$row_id][$table_name][$id][$field_name] = $result[$key]; - } - - if ($field_name == "username") { - foreach ($users as $field) { - if ($field['username'] == $result[$key]) { - $array[$parent][$table_name][$id]['device_user_uuid'] = $field['user_uuid']; - } - } - } - } - } - - // Do not duplicate MAC addresses, get the device UUID from the database and set it in the array - if (isset($array['devices']) && !isset($array['devices'][$row_id]['device_uuid']) && - isset($array['devices'][$row_id]['device_mac_address'])) { - $sql = "SELECT device_uuid, domain_uuid FROM v_devices "; - $sql .= "WHERE device_mac_address = :mac "; - $parameters['mac'] = $array['devices'][$row_id]['device_mac_address']; - $row = $database->select($sql, $parameters, 'row'); - if (is_array($row)) { - // Validate that the hit we got is for the same domain, if not add a message stating the fact - if ($array['devices'][$row_id]['domain_uuid'] == $row['domain_uuid']) { - $array['devices'][$row_id]['device_uuid'] = $row['device_uuid']; - } else { - // Maybe add in a better new message stating that it was found in a different domain? - message::add($text['message-duplicate'] . ": " . $parameters['mac']); - unset($array['devices'][$row_id]); - } - } - unset($sql, $parameters); - } - - //debug information - //view_array($field_count); - - //process a chunk of the array - if ($row_id === 1000) { - - //remove sub table data if it doesn't have more details than domain_uuid an device_uuid - $x = 0; - foreach ($array['devices'] as $row) { - //remove empty device keys - if (isset($row['device_keys'])) { - $y = 0; - foreach ($row['device_keys'] as &$sub_row) { - if (count($sub_row) == 2) { - unset($array['devices'][$x]['device_keys']); - } - $y++; - } - } - - //remove empty device lines - if (isset($row['device_lines'])) { - $y = 0; - foreach ($row['device_lines'] as &$sub_row) { - if (count($sub_row) == 2) { - unset($array['devices'][$x]['device_lines']); - } - $y++; - } - } - - //increment device id - $x++; - } - - //save to the data - $database->save($array); - //$message = $database->message; - - //clear the array - unset($array); - - //set the row id back to 0 - $row_id = 0; - } - - } //if ($from_row <= $row_id) - unset($field_count); - $row_number++; - $row_id++; - } //end while - fclose($handle); - - //remove sub table data if it doesn't have more details than domain_uuid an device_uuid - $x = 0; - foreach ($array['devices'] as $row) { - //remove empty device keys - if (isset($row['device_keys'])) { - $y = 0; - foreach ($row['device_keys'] as &$sub_row) { - if (count($sub_row) == 2) { - unset($array['devices'][$x]['device_keys']); - } - $y++; - } - } - - //remove empty device lines - if (isset($row['device_lines'])) { - $y = 0; - foreach ($row['device_lines'] as &$sub_row) { - if (count($sub_row) == 2) { - unset($array['devices'][$x]['device_lines']); - } - $y++; - } - } - - //increment device id - $x++; - } - - //debug info - //view_array($array); - - //save to the data - if (is_array($array)) { - $database->save($array); - //$message = $database->message; - //view_array($message); - } - - if (!empty($_SESSION['provision']['path']['text'])) { - $prov = new provision; - $prov->domain_uuid = $domain_uuid; - $response = $prov->write(); - } - - //send the redirect header - header("Location: devices.php"); - return; - } - } - -//create token - $object = new token; - $token = $object->create($_SERVER['PHP_SELF']); - -//include the header - $document['title'] = $text['title-device_import']; - require_once "resources/header.php"; - -//show content - echo "
\n"; - - echo "
\n"; - echo "
".$text['header-device_import']."
\n"; - echo "
\n"; - echo button::create(['type'=>'button','label'=>$text['button-back'],'icon'=>$_SESSION['theme']['button_icon_back'],'id'=>'btn_back','style'=>'margin-right: 15px;','link'=>'devices.php']); - echo button::create(['type'=>'submit','label'=>$text['button-continue'],'icon'=>$_SESSION['theme']['button_icon_upload'],'id'=>'btn_save']); - echo "
\n"; - echo "
\n"; - echo "
\n"; - - echo $text['description-import']."\n"; - echo "

\n"; - - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; - - echo "\n"; - echo "\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_data']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['description-import_data']."\n"; - echo "
\n"; - echo " ".$text['label-from_row']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['description-from_row']."\n"; - echo "
\n"; - echo " ".$text['label-import_delimiter']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['description-import_delimiter']."\n"; - echo "
\n"; - echo " ".$text['label-import_enclosure']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo $text['description-import_enclosure']."\n"; - echo "
\n"; - echo " ".$text['label-import_file_upload']."\n"; - echo "\n"; - echo " \n"; - echo "
\n"; - echo "
\n"; - echo "

"; - - echo "\n"; - echo "\n"; - - echo "
"; - -//include the footer - require_once "resources/footer.php"; - -?> + + Portions created by the Initial Developer are Copyright (C) 2018-2023 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane +*/ + +//includes files + require_once dirname(__DIR__, 2) . "/resources/require.php"; + require_once "resources/check_auth.php"; + +//check permissions + if (permission_exists('device_add')) { + //access granted + } + else { + echo "access denied"; + exit; + } + +//add multi-lingual support + $language = new text; + $text = $language->get(); + +//built in str_getcsv requires PHP 5.3 or higher, this function can be used to reproduct the functionality but requirs PHP 5.1.0 or higher + if (!function_exists('str_getcsv')) { + function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") { + $fp = fopen("php://memory", 'r+'); + fputs($fp, $input); + rewind($fp); + $data = fgetcsv($fp, null, $delimiter, $enclosure, $escape); + fclose($fp); + return $data; + } + } + +//set the max php execution time + ini_set('max_execution_time',7200); + +//get the http get values and set them as php variables + $action = $_POST["action"] ?? null; + $from_row = $_POST["from_row"] ?? null; + $delimiter = $_POST["data_delimiter"] ?? null; + $enclosure = $_POST["data_enclosure"] ?? null; + +//save the data to the csv file + if (isset($_POST['data'])) { + $file = $_SESSION['server']['temp']['dir']."/devices-".$_SESSION['domain_name'].".csv"; + if (file_put_contents($file, $_POST['data'])) { + $_SESSION['file'] = $file; + } + } + +//copy the csv file + //$_POST['submit'] == "Upload" && + if (!empty($_FILES['ulfile']['tmp_name']) && is_uploaded_file($_FILES['ulfile']['tmp_name']) && permission_exists('device_import')) { + if ($_POST['type'] == 'csv') { + $file = $_SESSION['server']['temp']['dir']."/devices-".$_SESSION['domain_name'].".csv"; + if (move_uploaded_file($_FILES['ulfile']['tmp_name'], $file)) { + $_SESSION['file'] = $file; + } + } + } + +//get the schema + if (!empty($delimiter) && file_exists($_SESSION['file'] ?? '')) { + //get the first line + $line = fgets(fopen($_SESSION['file'], 'r')); + $line_fields = explode($delimiter, $line); + + //get the schema + $x = 0; + include "app/devices/app_config.php"; + $i = 0; + foreach ($apps[0]['db'] as $table) { + //get the table name and parent name + $table_name = $table["table"]['name']; + $parent_name = $table["table"]['parent']; + + //remove the v_ table prefix + if (substr($table_name, 0, 2) == 'v_') { + $table_name = substr($table_name, 2); + } + if (substr($parent_name, 0, 2) == 'v_') { + $parent_name = substr($parent_name, 2); + } + + //filter for specific tables and build the schema array + if ($table_name == "devices" || $table_name == "device_lines" || + $table_name == "device_keys" || $table_name == "device_settings") { + $schema[$i]['table'] = $table_name; + $schema[$i]['parent'] = $parent_name; + foreach ($table['fields'] as $row) { + if (empty($row['deprecated']) || $row['deprecated'] !== 'true') { + if (is_array($row['name'])) { + $field_name = $row['name']['text']; + } + else { + $field_name = $row['name']; + } + $schema[$i]['fields'][] = $field_name; + } + } + $i++; + } + } + + $i++; + $schema[$i]['table'] = 'devices'; + $schema[$i]['parent'] = ''; + $schema[$i]['fields'][] = 'username'; + } + +//match the column names to the field names + if (!empty($delimiter) && file_exists($_SESSION['file'] ?? '') && $action != 'import') { + + //validate the token + $token = new token; + if (!$token->validate($_SERVER['PHP_SELF'])) { + message::add($text['message-invalid_token'],'negative'); + header('Location: device_imports.php'); + exit; + } + + //create token + $object = new token; + $token = $object->create($_SERVER['PHP_SELF']); + + //include header + $document['title'] = $text['title-device_import']; + require_once "resources/header.php"; + + //form to match the fields to the column names + echo "
\n"; + + echo "
\n"; + echo "
".$text['header-device_import']."
\n"; + echo "
\n"; + echo button::create(['type'=>'button','label'=>$text['button-back'],'icon'=>$_SESSION['theme']['button_icon_back'],'id'=>'btn_back','style'=>'margin-right: 15px;','link'=>'device_imports.php']); + echo button::create(['type'=>'submit','label'=>$text['button-import'],'icon'=>$_SESSION['theme']['button_icon_import'],'id'=>'btn_save']); + echo "
\n"; + echo "
\n"; + echo "
\n"; + + echo $text['description-import']."\n"; + echo "

\n"; + + echo "\n"; + + //loop through user columns + $x = 0; + foreach ($line_fields as $line_field) { + $line_field = preg_replace('#[^a-zA-Z0-9_]#', '', $line_field); + echo "\n"; + echo " \n"; + echo " \n"; + echo "\n"; + $x++; + } + + echo "
\n"; + //echo " ".$text['label-zzz']."\n"; + echo $line_field; + echo " \n"; + echo " \n"; + //echo "
\n"; + //echo $text['description-zzz']."\n"; + echo "
\n"; + echo "

\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "
\n"; + + require_once "resources/footer.php"; + + //normalize the column names + //$line = strtolower($line); + //$line = str_replace("-", "_", $line); + //$line = str_replace($delimiter."title".$delimiter, $delimiter."contact_title".$delimiter, $line); + //$line = str_replace("firstname", "name_given", $line); + //$line = str_replace("lastname", "name_family", $line); + //$line = str_replace("company", "organization", $line); + //$line = str_replace("company", "contact_email", $line); + + //end the script + exit; + } + +//get the parent table + function get_parent($schema,$table_name) { + foreach ($schema as $row) { + if ($row['table'] == $table_name) { + return $row['parent']; + } + } + } + +//upload the csv + if (file_exists($_SESSION['file'] ?? '') && $action == 'import') { + + //validate the token + $token = new token; + if (!$token->validate($_SERVER['PHP_SELF'])) { + message::add($text['message-invalid_token'],'negative'); + header('Location: device_imports.php'); + exit; + } + + //user selected fields + $fields = $_POST['fields']; + + //set the domain_uuid + $domain_uuid = $_SESSION['domain_uuid']; + + //open the database + $database = new database; + $database->app_name = 'devices'; + $database->app_uuid = '4efa1a1a-32e7-bf83-534b-6c8299958a8e'; + + //get the users + $sql = "select * from v_users where domain_uuid = :domain_uuid "; + $parameters['domain_uuid'] = $domain_uuid; + $users = $database->select($sql, $parameters, 'all'); + unset($sql, $parameters); + + //get the contents of the csv file and convert them into an array + $handle = @fopen($_SESSION['file'], "r"); + if ($handle) { + //set the starting identifiers + $row_id = 0; + $row_number = 1; + + //loop through the array + while (($line = fgets($handle, 4096)) !== false) { + if ($from_row <= $row_number) { + //format the data + $y = 0; + foreach ($fields as $key => $value) { + //get the line + $result = str_getcsv($line, $delimiter, $enclosure); + + //get the table and field name + $field_array = explode(".",$value); + $table_name = $field_array[0]; + $field_name = $field_array[1]; + //echo "value: $value
\n"; + //echo "table_name: $table_name
\n"; + //echo "field_name: $field_name
\n"; + + //get the parent table name + $parent = get_parent($schema, $table_name); + + //count the field names + if (isset($field_count[$table_name][$field_name])) { + $field_count[$table_name][$field_name]++; + } + else { + $field_count[$table_name][$field_name] = 0; + } + + //set the ordinal ID + $id = $field_count[$table_name][$field_name]; + + //remove formatting from the phone number + if ($field_name == "phone_number") { + $result[$key] = preg_replace('{\D}', '', $result[$key]); + } + + //normalize the device address + if ($field_name == "device_address") { + $result[$key] = strtolower($result[$key]); + $result[$key] = preg_replace('#[^a-fA-F0-9./]#', '', $result[$key]); + } + + //build the data array + if (!empty($table_name)) { + if (empty($parent)) { + if ($field_name != "username") { + $array[$table_name][$row_id]['domain_uuid'] = $domain_uuid; + $array[$table_name][$row_id][$field_name] = $result[$key]; + } + } + else { + $array[$parent][$row_id][$table_name][$id]['domain_uuid'] = $domain_uuid; + $array[$parent][$row_id][$table_name][$id][$field_name] = $result[$key]; + } + + if ($field_name == "username") { + foreach ($users as $field) { + if ($field['username'] == $result[$key]) { + $array[$parent][$table_name][$id]['device_user_uuid'] = $field['user_uuid']; + } + } + } + } + } + + // Do not duplicate device addresses, get the device UUID from the database and set it in the array + if (isset($array['devices']) && !isset($array['devices'][$row_id]['device_uuid']) && + isset($array['devices'][$row_id]['device_address'])) { + $sql = "SELECT device_uuid, domain_uuid FROM v_devices "; + $sql .= "WHERE device_address = :mac "; + $parameters['mac'] = $array['devices'][$row_id]['device_address']; + $row = $database->select($sql, $parameters, 'row'); + if (is_array($row)) { + // Validate that the hit we got is for the same domain, if not add a message stating the fact + if ($array['devices'][$row_id]['domain_uuid'] == $row['domain_uuid']) { + $array['devices'][$row_id]['device_uuid'] = $row['device_uuid']; + } else { + // Maybe add in a better new message stating that it was found in a different domain? + message::add($text['message-duplicate'] . ": " . $parameters['mac']); + unset($array['devices'][$row_id]); + } + } + unset($sql, $parameters); + } + + //debug information + //view_array($field_count); + + //process a chunk of the array + if ($row_id === 1000) { + + //remove sub table data if it doesn't have more details than domain_uuid an device_uuid + $x = 0; + foreach ($array['devices'] as $row) { + //remove empty device keys + if (isset($row['device_keys'])) { + $y = 0; + foreach ($row['device_keys'] as &$sub_row) { + if (count($sub_row) == 2) { + unset($array['devices'][$x]['device_keys']); + } + $y++; + } + } + + //remove empty device lines + if (isset($row['device_lines'])) { + $y = 0; + foreach ($row['device_lines'] as &$sub_row) { + if (count($sub_row) == 2) { + unset($array['devices'][$x]['device_lines']); + } + $y++; + } + } + + //increment device id + $x++; + } + + //save to the data + $database->save($array); + //$message = $database->message; + + //clear the array + unset($array); + + //set the row id back to 0 + $row_id = 0; + } + + } //if ($from_row <= $row_id) + unset($field_count); + $row_number++; + $row_id++; + } //end while + fclose($handle); + + //remove sub table data if it doesn't have more details than domain_uuid an device_uuid + $x = 0; + foreach ($array['devices'] as $row) { + //remove empty device keys + if (isset($row['device_keys'])) { + $y = 0; + foreach ($row['device_keys'] as &$sub_row) { + if (count($sub_row) == 2) { + unset($array['devices'][$x]['device_keys']); + } + $y++; + } + } + + //remove empty device lines + if (isset($row['device_lines'])) { + $y = 0; + foreach ($row['device_lines'] as &$sub_row) { + if (count($sub_row) == 2) { + unset($array['devices'][$x]['device_lines']); + } + $y++; + } + } + + //increment device id + $x++; + } + + //debug info + //view_array($array); + + //save to the data + if (is_array($array)) { + $database->save($array); + //$message = $database->message; + //view_array($message); + } + + if (!empty($_SESSION['provision']['path']['text'])) { + $prov = new provision; + $prov->domain_uuid = $domain_uuid; + $response = $prov->write(); + } + + //send the redirect header + header("Location: devices.php"); + return; + } + } + +//create token + $object = new token; + $token = $object->create($_SERVER['PHP_SELF']); + +//include the header + $document['title'] = $text['title-device_import']; + require_once "resources/header.php"; + +//show content + echo "
\n"; + + echo "
\n"; + echo "
".$text['header-device_import']."
\n"; + echo "
\n"; + echo button::create(['type'=>'button','label'=>$text['button-back'],'icon'=>$_SESSION['theme']['button_icon_back'],'id'=>'btn_back','style'=>'margin-right: 15px;','link'=>'devices.php']); + echo button::create(['type'=>'submit','label'=>$text['button-continue'],'icon'=>$_SESSION['theme']['button_icon_upload'],'id'=>'btn_save']); + echo "
\n"; + echo "
\n"; + echo "
\n"; + + echo $text['description-import']."\n"; + echo "

\n"; + + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; + + echo "\n"; + echo "\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_data']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['description-import_data']."\n"; + echo "
\n"; + echo " ".$text['label-from_row']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['description-from_row']."\n"; + echo "
\n"; + echo " ".$text['label-import_delimiter']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['description-import_delimiter']."\n"; + echo "
\n"; + echo " ".$text['label-import_enclosure']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo $text['description-import_enclosure']."\n"; + echo "
\n"; + echo " ".$text['label-import_file_upload']."\n"; + echo "\n"; + echo " \n"; + echo "
\n"; + echo "
\n"; + echo "

"; + + echo "\n"; + echo "\n"; + + echo "
"; + +//include the footer + require_once "resources/footer.php"; + +?> diff --git a/app/devices/devices.php b/app/devices/devices.php index 520825591a..894378d934 100644 --- a/app/devices/devices.php +++ b/app/devices/devices.php @@ -126,7 +126,7 @@ } if (!empty($search)) { $sql .= "("; - $sql .= " lower(d.device_mac_address) like :search "; + $sql .= " lower(d.device_address) like :search "; $sql .= " or lower(d.device_label) like :search "; $sql .= " or lower(d.device_vendor) like :search "; $sql .= " or lower(d.device_enabled) like :search "; @@ -212,7 +212,7 @@ } if (!empty($search)) { $sql .= "and ("; - $sql .= " lower(d.device_mac_address) like :search "; + $sql .= " lower(d.device_address) like :search "; $sql .= " or lower(d.device_label) like :search "; $sql .= " or lower(d.device_vendor) like :search "; $sql .= " or lower(d.device_enabled) like :search "; @@ -361,7 +361,7 @@ if (!empty($_GET['show']) && $_GET['show'] == "all" && permission_exists('device_all')) { echo th_order_by('domain_name', $text['label-domain'], $order_by, $order, null, null, $param); } - echo th_order_by('device_mac_address', $text['label-device_mac_address'], $order_by, $order, null, null, $param ?? null); + echo th_order_by('device_address', $text['label-device_address'], $order_by, $order, null, null, $param ?? null); echo th_order_by('device_label', $text['label-device_label'], $order_by, $order, null, null, $param ?? null); if ($device_alternate) { echo th_order_by('device_template', $text['label-device_uuid_alternate'], $order_by, $order, null, null, $param ?? null); @@ -413,7 +413,7 @@ echo " ".escape($_SESSION['domains'][$row['domain_uuid']]['domain_name'])."\n"; } echo " "; - echo permission_exists('device_edit') ? "".escape(format_mac($row['device_mac_address']))."" : escape(format_mac($row['device_mac_address'])); + echo permission_exists('device_edit') ? "".escape(format_device_address($row['device_address']))."" : escape(format_device_address($row['device_address'])); echo " \n"; echo " ".escape($row['device_label'])." \n"; if ($device_alternate) { diff --git a/app/extensions/app_languages.php b/app/extensions/app_languages.php index 630d131d5a..10341b3f9d 100644 --- a/app/extensions/app_languages.php +++ b/app/extensions/app_languages.php @@ -1687,29 +1687,29 @@ $text['label-device_template']['zh-cn'] = "模板"; $text['label-device_template']['ja-jp'] = "レンプレート"; $text['label-device_template']['ko-kr'] = "주형"; -$text['label-device_mac_address']['en-us'] = "MAC Address"; -$text['label-device_mac_address']['en-gb'] = "MAC Address"; -$text['label-device_mac_address']['ar-eg'] = "العنوان الرئيسي"; -$text['label-device_mac_address']['de-at'] = "MAC Adresse"; -$text['label-device_mac_address']['de-ch'] = "MAC Adresse"; -$text['label-device_mac_address']['de-de'] = "MAC Adresse"; -$text['label-device_mac_address']['es-cl'] = "Mac dirección"; -$text['label-device_mac_address']['es-mx'] = "Mac dirección"; -$text['label-device_mac_address']['fr-ca'] = "Adresse MAC"; -$text['label-device_mac_address']['fr-fr'] = "Adresse MAC"; -$text['label-device_mac_address']['he-il'] = "כתובת MAC"; -$text['label-device_mac_address']['it-it'] = "MAC Address"; -$text['label-device_mac_address']['nl-nl'] = "MAC-Adres"; -$text['label-device_mac_address']['pl-pl'] = "Adres MAC"; -$text['label-device_mac_address']['pt-br'] = "Endereço MAC"; -$text['label-device_mac_address']['pt-pt'] = "Endereço MAC"; -$text['label-device_mac_address']['ro-ro'] = "Adresa mac"; -$text['label-device_mac_address']['ru-ru'] = "MAC Адреса"; -$text['label-device_mac_address']['sv-se'] = "MAC-adress"; -$text['label-device_mac_address']['uk-ua'] = "Адреса MAC"; -$text['label-device_mac_address']['zh-cn'] = "MAC地址"; -$text['label-device_mac_address']['ja-jp'] = "Macアドレス"; -$text['label-device_mac_address']['ko-kr'] = "MAC 주소"; +$text['label-device_address']['en-us'] = "Address"; +$text['label-device_address']['en-gb'] = "Address"; +$text['label-device_address']['ar-eg'] = "العنوان الرئيسي"; +$text['label-device_address']['de-at'] = "Adresse"; +$text['label-device_address']['de-ch'] = "Adresse"; +$text['label-device_address']['de-de'] = "Adresse"; +$text['label-device_address']['es-cl'] = "dirección"; +$text['label-device_address']['es-mx'] = "dirección"; +$text['label-device_address']['fr-ca'] = "Adresse"; +$text['label-device_address']['fr-fr'] = "Adresse"; +$text['label-device_address']['he-il'] = "כתובת"; +$text['label-device_address']['it-it'] = "Address"; +$text['label-device_address']['nl-nl'] = "Adres"; +$text['label-device_address']['pl-pl'] = "Adres"; +$text['label-device_address']['pt-br'] = "Endereço"; +$text['label-device_address']['pt-pt'] = "Endereço"; +$text['label-device_address']['ro-ro'] = "Adresa"; +$text['label-device_address']['ru-ru'] = "Адреса"; +$text['label-device_address']['sv-se'] = "adress"; +$text['label-device_address']['uk-ua'] = "Адреса"; +$text['label-device_address']['zh-cn'] = "地址"; +$text['label-device_address']['ja-jp'] = "アドレス"; +$text['label-device_address']['ko-kr'] = "주소"; $text['label-description']['en-us'] = "Description"; $text['label-description']['en-gb'] = "Description"; diff --git a/app/extensions/extension_edit.php b/app/extensions/extension_edit.php index 4766f6d833..f8022f6970 100644 --- a/app/extensions/extension_edit.php +++ b/app/extensions/extension_edit.php @@ -172,20 +172,20 @@ //device provisioning variables if (is_array($_POST["devices"]) && @sizeof($_POST["devices"]) != 0) { foreach ($_POST["devices"] as $d => $device) { - $device_mac_address = strtolower($device["device_mac_address"]); - $device_mac_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_mac_address); + $device_address = strtolower($device["device_address"]); + $device_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_address); $line_numbers[$d] = $device["line_number"]; - $device_mac_addresses[$d] = $device_mac_address; + $device_addresses[$d] = $device_address; $device_templates[$d] = $device["device_template"]; } } //get or set the device_uuid - if (!empty($device_mac_addresses) && is_array($device_mac_addresses) && @sizeof($device_mac_addresses) != 0) { - foreach ($device_mac_addresses as $d => $device_mac_address) { - $device_mac_address = strtolower($device_mac_address); - $device_mac_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_mac_address); + if (!empty($device_addresses) && is_array($device_addresses) && @sizeof($device_addresses) != 0) { + foreach ($device_addresses as $d => $device_address) { + $device_address = strtolower($device_address); + $device_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_address); $sql = "select "; $sql .= "d1.device_uuid, "; @@ -196,8 +196,8 @@ $sql .= "v_domains as d2 "; $sql .= "where "; $sql .= "d1.domain_uuid = d2.domain_uuid and "; - $sql .= "d1.device_mac_address = :device_mac_address "; - $parameters['device_mac_address'] = $device_mac_address; + $sql .= "d1.device_address = :device_address "; + $parameters['device_address'] = $device_address; $database = new database; $row = $database->select($sql, $parameters, 'row'); if (is_array($row)) { @@ -520,9 +520,9 @@ } //assign the device to the extension(s) - if (is_array($device_mac_addresses) && @sizeof($device_mac_addresses) != 0) { - foreach ($device_mac_addresses as $d => $device_mac_address) { - if (is_mac($device_mac_address)) { + if (is_array($device_addresses) && @sizeof($device_addresses) != 0) { + foreach ($device_addresses as $d => $device_address) { + if (!emtpy($device_address)) { //get the device vendor if (isset($device_templates[$d])) { //use the the template to get the vendor @@ -530,8 +530,8 @@ $device_vendor = $template_array[0]; } else { - //use the mac address to get the vendor - $device_vendor = device::get_vendor($device_mac_address); + //use the device address to get the vendor + $device_vendor = device::get_vendor($device_address); } //determine the name @@ -592,10 +592,10 @@ } //build the devices array - if ($device_unique && $device_mac_address != '000000000000') { + if ($device_unique && $device_address != '000000000000') { $array["devices"][$j]["device_uuid"] = $device_uuids[$d]; $array["devices"][$j]["domain_uuid"] = $_SESSION['domain_uuid']; - $array["devices"][$j]["device_mac_address"] = $device_mac_address; + $array["devices"][$j]["device_address"] = $device_address; $array["devices"][$j]["device_label"] = $extension; if (!empty($device_vendor)) { $array["devices"][$j]["device_vendor"] = $device_vendor; @@ -898,12 +898,12 @@ } //get the device lines - $sql = "select d.device_mac_address, d.device_template, d.device_description, l.device_line_uuid, l.device_uuid, l.line_number "; + $sql = "select d.device_address, d.device_template, d.device_description, l.device_line_uuid, l.device_uuid, l.line_number "; $sql .= "from v_device_lines as l, v_devices as d "; $sql .= "where (l.user_id = :user_id_1 or l.user_id = :user_id_2)"; $sql .= "and l.domain_uuid = :domain_uuid "; $sql .= "and l.device_uuid = d.device_uuid "; - $sql .= "order by l.line_number, d.device_mac_address asc "; + $sql .= "order by l.line_number, d.device_address asc "; $parameters['user_id_1'] = $extension ?? null; $parameters['user_id_2'] = $number_alias ?? null; $parameters['domain_uuid'] = $domain_uuid; @@ -914,7 +914,7 @@ //get the devices $sql = "select * from v_devices "; $sql .= "where domain_uuid = :domain_uuid "; - $sql .= "order by device_mac_address asc "; + $sql .= "order by device_address asc "; $parameters['domain_uuid'] = $domain_uuid; $database = new database; $devices = $database->select($sql, $parameters, 'all'); @@ -1252,7 +1252,7 @@ echo " ".$text['label-line']." \n"; echo " \n"; echo " \n"; - echo " ".$text['label-device_mac_address']." \n"; + echo " ".$text['label-device_address']." \n"; echo " \n"; echo " \n"; echo " ".$text['label-device_template']." \n"; @@ -1264,10 +1264,10 @@ if ($action == 'update') { if (is_array($device_lines) && @sizeof($device_lines) != 0) { foreach ($device_lines as $row) { - $device_mac_address = format_mac($row['device_mac_address']); + $device_address = format_device_address($row['device_address']); echo " \n"; echo " ".escape($row['line_number'])."\n"; - echo " ".escape($device_mac_address)."\n"; + echo " ".escape($device_address)."\n"; echo " ".escape($row['device_template'])." \n"; //echo " ".$row['device_description']." \n"; echo " \n"; @@ -1295,49 +1295,49 @@ ?> \n"; + echo " \n"; - echo " \n"; + echo " \n"; echo " \n"; echo " \n"; echo " \n"; diff --git a/app/provision/app_defaults.php b/app/provision/app_defaults.php index 211235abd3..7c0dcc1ed5 100644 --- a/app/provision/app_defaults.php +++ b/app/provision/app_defaults.php @@ -28,21 +28,21 @@ if ($domains_processed == 1) { //normalize the mac address - $sql = "select device_uuid, device_mac_address "; + $sql = "select device_uuid, device_address "; $sql .= "from v_devices "; - $sql .= "where (device_mac_address like '%-%' or device_mac_address like '%:%') "; + $sql .= "where (device_address like '%-%' or device_address like '%:%') "; $database = new database; $result = $database->select($sql, null, 'all'); if (is_array($result) && @sizeof($result) != 0) { foreach ($result as $row) { //define update values $device_uuid = $row["device_uuid"]; - $device_mac_address = $row["device_mac_address"]; - $device_mac_address = strtolower($device_mac_address); - $device_mac_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_mac_address); + $device_address = $row["device_address"]; + $device_address = strtolower($device_address); + $device_address = preg_replace('#[^a-fA-F0-9./]#', '', $device_address); //build update array $array['devices'][0]['device_uuid'] = $device_uuid; - $array['devices'][0]['device_mac_address'] = $device_mac_address; + $array['devices'][0]['device_address'] = $device_address; //grant temporary permissions $p = new permissions; $p->add('device_add', 'temp'); diff --git a/app/provision/index.php b/app/provision/index.php index 6054e483bb..1bab4c09b2 100644 --- a/app/provision/index.php +++ b/app/provision/index.php @@ -38,18 +38,23 @@ $device_template = ''; //define PHP variables from the HTTP values - $mac = $_REQUEST['mac']; + if (isset($_REQUEST['mac'])) { + $device_address = $_REQUEST['mac']; + } + if (isset($_REQUEST['address'])) { + $device_address = $_REQUEST['address']; + } $file = $_REQUEST['file']; $ext = $_REQUEST['ext']; //if (!empty($_REQUEST['template'])) { // $device_template = $_REQUEST['template']; //} -//get the mac address for Cisco 79xx in the URL as &name=SEP000000000000 - if (empty($mac)) { +//get the device address for Cisco 79xx in the URL as &name=SEP000000000000 + if (empty($device_address)) { $name = $_REQUEST['name']; if (substr($name, 0, 3) == "SEP") { - $mac = strtolower(substr($name, 3, 12)); + $device_address = strtolower(substr($name, 3, 12)); unset($name); } } @@ -57,12 +62,12 @@ // Escence make request based on UserID for Memory keys // The file name is fixed to `Account1_Extern.xml`. // (Account1 is the first account you register) - if (empty($mac) && !empty($ext)) { + if (empty($device_address) && !empty($ext)) { $domain_array = explode(":", $_SERVER["HTTP_HOST"]); $domain_name = $domain_array[0]; $device = device_by_ext($ext, $domain_name); if ($device !== false && ($device['device_vendor'] == 'escene' || $device['device_vendor'] == 'grandstream')) { - $mac = $device['device_mac_address']; + $device_address = $device['device_address']; } } @@ -81,71 +86,71 @@ exit; } -//check alternate MAC source - if (empty($mac)) { +//check alternate device address source + if (empty($device_address)) { //set the http user agent //$_SERVER['HTTP_USER_AGENT'] = "Yealink SIP-T38G 38.70.0.125 00:15:65:00:00:00"; //$_SERVER['HTTP_USER_AGENT'] = "Yealink SIP-T56A 58.80.0.25 001565f429a4"; //Yealink: 17 digit mac appended to the user agent, so check for a space exactly 17 digits before the end. if (strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,7)) == "yealink" || strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,5)) == "vp530") { if (strstr(substr($_SERVER['HTTP_USER_AGENT'],-4), ':')) { //remove colons if they exist - $mac = substr($_SERVER['HTTP_USER_AGENT'],-17); - $mac = preg_replace("#[^a-fA-F0-9./]#", "", $mac); + $device_address = substr($_SERVER['HTTP_USER_AGENT'],-17); + $device_address = preg_replace("#[^a-fA-F0-9./]#", "", $device_address); } else { //take mac as is - fixes T5X series - $mac = substr($_SERVER['HTTP_USER_AGENT'],-12); + $device_address = substr($_SERVER['HTTP_USER_AGENT'],-12); } } //HTek: $_SERVER['HTTP_USER_AGENT'] = "Htek UC926 2.0.4.2 00:1f:c1:00:00:00" if (substr($_SERVER['HTTP_USER_AGENT'],0,4) == "Htek") { - $mac = substr($_SERVER['HTTP_USER_AGENT'],-17); - $mac = preg_replace("#[^a-fA-F0-9./]#", "", $mac); + $device_address = substr($_SERVER['HTTP_USER_AGENT'],-17); + $device_address = preg_replace("#[^a-fA-F0-9./]#", "", $device_address); } //Panasonic: $_SERVER['HTTP_USER_AGENT'] = "Panasonic_KX-UT670/01.022 (0080f000000)" if (substr($_SERVER['HTTP_USER_AGENT'],0,9) == "Panasonic") { - $mac = substr($_SERVER['HTTP_USER_AGENT'],-14); - $mac = preg_replace("#[^a-fA-F0-9./]#", "", $mac); + $device_address = substr($_SERVER['HTTP_USER_AGENT'],-14); + $device_address = preg_replace("#[^a-fA-F0-9./]#", "", $device_address); } //Grandstream: $_SERVER['HTTP_USER_AGENT'] = "Grandstream Model HW GXP2135 SW 1.0.7.97 DevId 000b828aa872" if (substr($_SERVER['HTTP_USER_AGENT'],0,11) == "Grandstream") { - $mac = substr($_SERVER['HTTP_USER_AGENT'],-12); - $mac = preg_replace("#[^a-fA-F0-9./]#", "", $mac); + $device_address = substr($_SERVER['HTTP_USER_AGENT'],-12); + $device_address = preg_replace("#[^a-fA-F0-9./]#", "", $device_address); } //Audiocodes: $_SERVER['HTTP_USER_AGENT'] = "AUDC-IPPhone/2.2.8.61 (440HDG-Rev0; 00908F602AAC)" if (substr($_SERVER['HTTP_USER_AGENT'],0,12) == "AUDC-IPPhone") { - $mac = substr($_SERVER['HTTP_USER_AGENT'],-13); - $mac = preg_replace("#[^a-fA-F0-9./]#", "", $mac); + $device_address = substr($_SERVER['HTTP_USER_AGENT'],-13); + $device_address = preg_replace("#[^a-fA-F0-9./]#", "", $device_address); } //Aastra: $_SERVER['HTTP_USER_AGENT'] = "Aastra6731i MAC:00-08-5D-29-4C-6B V:3.3.1.4365-SIP" if (substr($_SERVER['HTTP_USER_AGENT'],0,6) == "Aastra") { preg_match("/MAC:([A-F0-9-]{17})/", $_SERVER['HTTP_USER_AGENT'], $matches); - $mac = $matches[1]; - $mac = preg_replace("#[^a-fA-F0-9./]#", "", $mac); + $device_address = $matches[1]; + $device_address = preg_replace("#[^a-fA-F0-9./]#", "", $device_address); } //Flyingvoice: $_SERVER['HTTP_USER_AGENT'] = "Flyingvoice FIP13G V0.6.24 00:21:F2:22:AE:F1" if (strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,11)) == "flyingvoice") { - $mac = substr($_SERVER['HTTP_USER_AGENT'],-17); - $mac = preg_replace("#[^a-fA-F0-9./]#", "", $mac); + $device_address = substr($_SERVER['HTTP_USER_AGENT'],-17); + $device_address = preg_replace("#[^a-fA-F0-9./]#", "", $device_address); } } -//prepare the mac address - if (isset($mac)) { - //normalize the mac address to lower case - $mac = strtolower($mac); - //replace all non hexadecimal values and validate the mac address - $mac = preg_replace("#[^a-fA-F0-9./]#", "", $mac); - if (strlen($mac) != 12) { - echo "invalid mac address"; - exit; - } +//prepare the device address + if (isset($device_address)) { + //normalize the device address to lower case + $device_address = strtolower($device_address); + //replace all non hexadecimal values and validate the device address + $device_address = preg_replace("#[^a-fA-F0-9./]#", "", $device_address); + //if (strlen($device_address) != 12) { + // echo "invalid mac address"; + // exit; + //} } //get the domain_uuid, domain_name, device_name and device_vendor $sql = "select d.device_uuid, d.domain_uuid, d.device_vendor, n.domain_name "; $sql .= "from v_devices as d, v_domains as n "; - $sql .= "where device_mac_address = :mac "; + $sql .= "where device_address = :device_address "; $sql .= "and d.domain_uuid = n.domain_uuid; "; - $parameters['mac'] = $mac; + $parameters['device_address'] = $device_address; $database = new database; $row = $database->select($sql, $parameters, 'row'); if (is_array($row)) { @@ -267,22 +272,22 @@ //check if provisioning has been enabled if ($provision["enabled"] != "true") { - syslog(LOG_WARNING, '['.$_SERVER['REMOTE_ADDR']."] provision attempt but provisioning is not enabled for ".check_str($_REQUEST['mac'])); + syslog(LOG_WARNING, '['.$_SERVER['REMOTE_ADDR']."] provision attempt but provisioning is not enabled for ".escape($_REQUEST['mac'])); http_error('404'); } //send a request to a remote server to validate the MAC address and secret if (!empty($_SERVER['auth_server'])) { - $result = send_http_request($_SERVER['auth_server'], 'mac='.check_str($_REQUEST['mac']).'&secret='.check_str($_REQUEST['secret'])); + $result = send_http_request($_SERVER['auth_server'], 'mac='.url_encode($_REQUEST['mac']).'&secret='.url_encode($_REQUEST['secret'])); if ($result == "false") { - syslog(LOG_WARNING, '['.$_SERVER['REMOTE_ADDR']."] provision attempt but the remote auth server said no for ".check_str($_REQUEST['mac'])); + syslog(LOG_WARNING, '['.$_SERVER['REMOTE_ADDR']."] provision attempt but the remote auth server said no for ".escape($_REQUEST['mac'])); http_error('404'); } } -//use the mac address to get the vendor +//use the device address to get the vendor if (empty($device_vendor)) { - $device_vendor = device::get_vendor($mac); + $device_vendor = device::get_vendor($device_address); } //keep backwards compatibility @@ -300,7 +305,7 @@ } } if (!$found) { - syslog(LOG_WARNING, '['.$_SERVER['REMOTE_ADDR']."] provision attempt but failed CIDR check for ".check_str($_REQUEST['mac'])); + syslog(LOG_WARNING, '['.$_SERVER['REMOTE_ADDR']."] provision attempt but failed CIDR check for ".escape($_REQUEST['mac'])); http_error('404'); } } @@ -429,18 +434,18 @@ //output template to string for header processing $prov = new provision; $prov->domain_uuid = $domain_uuid; - $prov->mac = $mac; + $prov->device_address = $device_address; $prov->file = $file; $file_contents = $prov->render(); //deliver the customized config over HTTP/HTTPS //need to make sure content-type is correct if ($_REQUEST['content_type'] == 'application/octet-stream') { - //format the mac address and - $mac = $prov->format_mac($mac, $device_vendor); + //format the device address and + $device_address_formatted = $prov->format_address($device_address, $device_vendor); //replace the variable name with the value - $file_name = str_replace("{\$mac}", $mac, $file); + $file_name = str_replace("{\$device_address}", $device_address_formatted, $file); //set the headers header('Content-Description: File Transfer'); diff --git a/app/provision/resources/classes/provision.php b/app/provision/resources/classes/provision.php index 121954f23d..0023701aa7 100644 --- a/app/provision/resources/classes/provision.php +++ b/app/provision/resources/classes/provision.php @@ -31,7 +31,7 @@ public $domain_uuid; public $domain_name; public $template_dir; - public $mac; + public $device_address; public function __construct() { //set the default template directory @@ -82,9 +82,9 @@ } } - //normalize the mac address - if (isset($this->mac)) { - $this->mac = strtolower(preg_replace('#[^a-fA-F0-9./]#', '', $this->mac)); + //normalize the device address + if (isset($this->device_address)) { + $this->device_address = strtolower(preg_replace('#[^a-fA-F0-9./]#', '', $this->device_address)); } } @@ -92,14 +92,14 @@ 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 + //define the function which checks to see if the device address exists in devices + private function device_exists($device_address) { + //normalize the device address + $device_address = strtolower(preg_replace('#[^a-fA-F0-9./]#', '', $device_address)); + //check in the devices table for a specific device address $sql = "select count(*) from v_devices "; - $sql .= "where device_mac_address = :mac "; - $parameters['mac'] = $mac; + $sql .= "where device_address = :device_address "; + $parameters['device_address'] = $device_address; $database = new database; $num_rows = $database->select($sql, $parameters, 'column'); if ($num_rows > 0) { @@ -111,44 +111,44 @@ unset($sql, $parameters, $num_rows); } - //set the mac address in the correct format for the specific vendor - public function format_mac($mac, $vendor) { + //set the device address in the correct format for the specific vendor + public function format_address($device_address, $vendor) { switch (strtolower($vendor)) { case "algo": - return strtoupper($mac); + return strtoupper($device_address); break; case "aastra": - return strtoupper($mac); + return strtoupper($device_address); break; case "cisco": - return strtoupper($mac); + return strtoupper($device_address); break; case "linksys": - return strtolower($mac); + return strtolower($device_address); break; case "mitel": - return strtoupper($mac); + return strtoupper($device_address); break; case "polycom": - return strtolower($mac); + return strtolower($device_address); break; case "snom": - return strtolower($mac); + return strtolower($device_address); break; case "escene": - return strtolower($mac); + return strtolower($device_address); break; case "grandstream": - return strtolower($mac); + return strtolower($device_address); break; case "yealink": - return strtolower($mac); + return strtolower($device_address); break; case "gigaset": - return strtoupper($mac); + return strtoupper($device_address); break; default: - return strtolower($mac); + return strtolower($device_address); } } @@ -257,11 +257,11 @@ $domain_uuid = $this->domain_uuid; $device_template = $this->device_template; $template_dir = $this->template_dir; - $mac = $this->mac; + $device_address = $this->device_address; $file = $this->file; - //set the mac address to lower case to be consistent with the database - $mac = strtolower($mac); + //set the device address to lower case to be consistent with the database + $device_address = strtolower($device_address); //get the device template //if (!empty($_REQUEST['template'])) { @@ -296,7 +296,8 @@ elseif (is_array($val) && !is_uuid($val['uuid'])) { $value = $val; } if (isset($value)) { $value = str_replace('${domain_name}', $domain_name, $value); - $value = str_replace('${mac_address}', $mac, $value); + $value = str_replace('${mac_address}', $device_address, $value); + $value = str_replace('${device_address}', $device_address, $value); $provision[$key] = $value; } unset($value); @@ -308,18 +309,18 @@ $provision["http_auth_password"] = $_SESSION['provision']["http_auth_password"][0]; } - //check to see if the mac_address exists in devices + //check to see if the device_address exists in devices //if (empty($_REQUEST['user_id']) || empty($_REQUEST['userid'])) { - if ($this->mac_exists($mac)) { + if ($this->device_exists($device_address)) { //get the device_template $sql = "select * from v_devices "; - $sql .= "where device_mac_address = :mac_address "; + $sql .= "where device_address = :device_address "; if ($provision['http_domain_filter'] == "true") { $sql .= "and domain_uuid=:domain_uuid "; $parameters['domain_uuid'] = $domain_uuid; } - $parameters['mac_address'] = $mac; + $parameters['device_address'] = $device_address; $database = new database; $row = $database->select($sql, $parameters, 'row'); unset($parameters); @@ -340,9 +341,9 @@ //register that we have seen the device $sql = "update v_devices "; $sql .= "set device_provisioned_date = :device_provisioned_date, device_provisioned_method = :device_provisioned_method, device_provisioned_ip = :device_provisioned_ip, device_provisioned_agent = :device_provisioned_agent "; - $sql .= "where domain_uuid = :domain_uuid and device_mac_address = :device_mac_address "; + $sql .= "where domain_uuid = :domain_uuid and device_address = :device_address "; $parameters['domain_uuid'] = $domain_uuid; - $parameters['device_mac_address'] = strtolower($mac); + $parameters['device_address'] = strtolower($device_address); $parameters['device_provisioned_date'] = 'now()'; $parameters['device_provisioned_method'] = (isset($_SERVER["HTTPS"]) ? 'https' : 'http'); $parameters['device_provisioned_ip'] = $_SERVER['REMOTE_ADDR']; @@ -521,7 +522,7 @@ } unset($templates); - //mac address does not exist in the table so add it + //device address does not exist in the table so add it if ($_SESSION['provision']['auto_insert_enabled']['boolean'] == "true" && is_uuid($domain_uuid)) { //get a new primary key @@ -531,7 +532,7 @@ $x = 0; $array['devices'][$x]['domain_uuid'] = $domain_uuid; $array['devices'][$x]['device_uuid'] = $device_uuid; - $array['devices'][$x]['device_mac_address'] = $mac; + $array['devices'][$x]['device_address'] = $device_address; $array['devices'][$x]['device_vendor'] = $device_vendor; $array['devices'][$x]['device_enabled'] = 'true'; $array['devices'][$x]['device_template'] = $device_template; @@ -665,8 +666,8 @@ //replace the variables in the template in the future loop through all the line numbers to do a replace for each possible line number - //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); + //create a device address with back slashes for backwards compatability + //$address_dash = substr($device_address, 0,2).'-'.substr($device_address, 2,2).'-'.substr($device_address, 4,2).'-'.substr($device_address, 6,2).'-'.substr($device_address, 8,2).'-'.substr($device_address, 10,2); //get the provisioning information if (is_uuid($device_uuid)) { @@ -1110,8 +1111,8 @@ } } - //set the mac address in the correct format - $mac = $this->format_mac($mac, $device_vendor); + //set the device address in the correct format + $device_address = $this->format_address($device_address, $device_vendor); // set date/time for versioning provisioning templates if (!empty($_SESSION['provision']['version_format']['text'])) { @@ -1122,8 +1123,10 @@ } //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("time" , $time); + $view->assign("device_address", $device_address); + $view->assign("address", $device_address); + $view->assign("mac", $device_address); + $view->assign("time", $time); $view->assign("label", $device_label); $view->assign("device_label", $device_label); $view->assign("firmware_version", $device_firmware_version); @@ -1131,12 +1134,12 @@ $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); - $view->assign("location",$device_location); - $view->assign("device_location",$device_location); - $view->assign("microtime",microtime(true)); + $view->assign("user_id", $user_id); + $view->assign("password", $password); + $view->assign("template", $device_template); + $view->assign("location", $device_location); + $view->assign("device_location", $device_location); + $view->assign("microtime", microtime(true)); //personal ldap password global $laddr_salt; @@ -1188,6 +1191,9 @@ //if $file is not provided then look for a default file that exists if (empty($file)) { + if (file_exists($template_dir."/".$device_template ."/{\$address}")) { + $file = "{\$address}"; + } if (file_exists($template_dir."/".$device_template ."/{\$mac}")) { $file = "{\$mac}"; } @@ -1223,7 +1229,7 @@ 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"; + $tmp_string = $device_address."\n"; fwrite($fh, $tmp_string); fclose($fh); } @@ -1267,7 +1273,7 @@ //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_address = $row["device_address"]; $device_label = $row["device_label"]; $device_vendor = strtolower($row["device_vendor"]); $device_model = $row["device_model"]; @@ -1314,14 +1320,15 @@ //configure device object $this->domain_uuid = $domain_uuid; - $this->mac = $device_mac_address; + $this->device_address = $device_address; $this->file = $file_name; - //format the mac address - $mac = $this->format_mac($device_mac_address, $device_vendor); + //format the device address + $address_formatted = $this->format_address($device_address, $device_vendor); //replace {$mac} in the file name - $file_name = str_replace("{\$mac}", $mac, $file_name); + $file_name = str_replace("{\$mac}", $address_formatted, $file_name); + $file_name = str_replace("{\$address}", $address_formatted, $file_name); //render and write configuration to file $provision_dir_array = explode(";", $provision["path"]); diff --git a/app/provision/resources/functions/device_by.php b/app/provision/resources/functions/device_by.php index 0290d6bf69..91a97883b8 100644 --- a/app/provision/resources/functions/device_by.php +++ b/app/provision/resources/functions/device_by.php @@ -1,10 +1,10 @@ select($sql, $parameters, 'row'); return is_array($row) && @sizeof($row) != 0 ? $row : false; diff --git a/resources/functions.php b/resources/functions.php index 3a4b195a0f..775d00f335 100644 --- a/resources/functions.php +++ b/resources/functions.php @@ -1,2215 +1,2216 @@ - - Portions created by the Initial Developer are Copyright (C) 2008-2022 - the Initial Developer. All Rights Reserved. - - Contributor(s): - Mark J Crane - Luis Daniel Lucio Quiroz -*/ - - if (!function_exists('mb_strtoupper')) { - function mb_strtoupper($string) { - return strtoupper($string); - } - } - - if (!function_exists('check_float')) { - function check_float($string) { - $string = str_replace(",",".",$string ?? ''); - return trim($string); - } - } - - if (!function_exists('check_str')) { - function check_str($string, $trim = true) { - global $db_type, $db; - //when code in db is urlencoded the ' does not need to be modified - if ($db_type == "sqlite") { - if (function_exists('sqlite_escape_string')) { - $string = sqlite_escape_string($string); - } - else { - $string = str_replace("'","''",$string); - } - } - if ($db_type == "pgsql") { - $string = str_replace("'","''",$string); - } - if ($db_type == "mysql") { - if(function_exists('mysql_real_escape_string')){ - $tmp_str = mysql_real_escape_string($string); - } - else { - $tmp_str = mysqli_real_escape_string($db, $string); - } - if (!empty($tmp_str)) { - $string = $tmp_str; - } - else { - $search = array("\x00", "\n", "\r", "\\", "'", "\"", "\x1a"); - $replace = array("\\x00", "\\n", "\\r", "\\\\" ,"\'", "\\\"", "\\\x1a"); - $string = str_replace($search, $replace, $string); - } - } - $string = ($trim) ? trim($string) : $string; - return $string; - } - } - - if (!function_exists('check_sql')) { - function check_sql($string) { - return trim($string); //remove white space - } - } - - if (!function_exists('check_cidr')) { - function check_cidr($cidr, $ip_address) { - if (isset($cidr) && !empty($cidr)) { - list ($subnet, $mask) = explode ('/', $cidr); - return ( ip2long ($ip_address) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet); - } - else { - return false; - } - } - } - - if (!function_exists('fix_postback')) { - function fix_postback($post_array) { - foreach ($post_array as $index => $value) { - if (is_array($value)) { fix_postback($value); } - else { - $value = str_replace('"', """, $value); - $value = str_replace("'", "'", $value); - $post_array[$index] = $value; - } - } - return $post_array; - } - } - - if (!function_exists('uuid')) { - function uuid() { - $uuid = null; - if (PHP_OS === 'FreeBSD') { - $uuid = trim(shell_exec("uuid -v 4")); - if (is_uuid($uuid)) { - return $uuid; - } - else { - echo "Please install the following package.\n"; - echo "pkg install ossp-uuid\n"; - exit; - } - } - if (PHP_OS === 'Linux') { - $uuid = trim(file_get_contents('/proc/sys/kernel/random/uuid')); - if (is_uuid($uuid)) { - return $uuid; - } - else { - $uuid = trim(shell_exec("uuidgen")); - if (is_uuid($uuid)) { - return $uuid; - } - else { - echo "Please install the uuidgen.\n"; - exit; - } - } - } - if ((strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') && function_exists('com_create_guid')) { - $uuid = trim(com_create_guid(), '{}'); - if (is_uuid($uuid)) { - return $uuid; - } - else { - echo "The com_create_guid() function failed to create a uuid.\n"; - exit; - } - } - } - } - - if (!function_exists('is_uuid')) { - function is_uuid($uuid) { - if (gettype($uuid) == 'string') { - $regex = '/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i'; - return preg_match($regex, $uuid); - } - return false; - } - } - - if (!function_exists('is_xml')) { - function is_xml($string) { - $pattern = '/^<\?xml(?:\s+[^>]+\s*)?\?>\s*<(\w+)>.*<\/\1>\s*$/s'; - return preg_match($pattern, $string) === 1; - } - } - - if (!function_exists('recursive_copy')) { - if (file_exists('/bin/cp')) { - function recursive_copy($source, $destination, $options = '') { - if (strtoupper(substr(PHP_OS, 0, 3)) === 'SUN') { - //copy -R recursive, preserve attributes for SUN - $cmd = 'cp -Rp '.$source.'/* '.$destination; - } - else { - //copy -R recursive, -L follow symbolic links, -p preserve attributes for other Posix systemss - $cmd = 'cp -RLp '.$options.' '.$source.'/* '.$destination; - } - exec ($cmd); - } - } - elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - function recursive_copy($source, $destination, $options = '') { - $source = normalize_path_to_os($source); - $destination = normalize_path_to_os($destination); - exec("xcopy /E /Y \"$source\" \"$destination\""); - } - } - else { - function recursive_copy($source, $destination, $options = '') { - $dir = opendir($source); - if (!$dir) { - throw new Exception("recursive_copy() source directory '".$source."' does not exist."); - } - if (!is_dir($destination)) { - if (!mkdir($destination,02770,true)) { - throw new Exception("recursive_copy() failed to create destination directory '".$destination."'"); - } - } - while(false !== ( $file = readdir($dir)) ) { - if (( $file != '.' ) && ( $file != '..' )) { - if ( is_dir($source . '/' . $file) ) { - recursive_copy($source . '/' . $file,$destination . '/' . $file); - } - else { - copy($source . '/' . $file,$destination . '/' . $file); - } - } - } - closedir($dir); - } - } - } - - if (!function_exists('recursive_delete')) { - if (file_exists('/usr/bin/find')) { - function recursive_delete($directory) { - if (isset($directory) && strlen($directory) > 8) { - exec('/usr/bin/find '.$directory.'/* -name "*" -delete'); - //exec('rm -Rf '.$directory.'/*'); - clearstatcache(); - } - } - } - elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - function recursive_delete($directory) { - $directory = normalize_path_to_os($directory); - //$this->write_debug("del /S /F /Q \"$dir\""); - exec("del /S /F /Q \"$directory\""); - clearstatcache(); - } - } - else { - function recursive_delete($directory) { - foreach (glob($directory) as $file) { - if (is_dir($file)) { - //$this->write_debug("rm dir: ".$file); - recursive_delete("$file/*"); - rmdir($file); - } - else { - //$this->write_debug("delete file: ".$file); - unlink($file); - } - } - clearstatcache(); - } - } - } - - if (!function_exists('if_group')) { - function if_group($group) { - //set default false - $result = false; - //search for the permission - if (count($_SESSION["groups"]) > 0) { - foreach($_SESSION["groups"] as $row) { - if ($row['group_name'] == $group) { - $result = true; - break; - } - } - } - //return the result - return $result; - } - } - - if (!function_exists('permission_exists')) { - function permission_exists($permission, $operator = 'or') { - //set default - $result = false; - //permissions exist - if (is_array($_SESSION["permissions"]) && @sizeof($_SESSION['permissions']) != 0) { - //array - if (is_array($permission) && @sizeof($permission) != 0) { - if ($operator == 'and') { - $exists_all = true; - foreach ($permission as $perm) { - if ($_SESSION["permissions"][$permission] != true) { - $exists_all = false; - break; - } - } - $result = $exists_all; - } - else { - $exists_one = false; - foreach ($permission as $perm) { - if (isset($_SESSION["permissions"][$perm]) && $_SESSION["permissions"][$perm] != true) { - $exists_one = true; - break; - } - } - $result = $exists_one; - } - } - //single - else { - if (isset($_SESSION["permissions"][$permission]) && $_SESSION["permissions"][$permission] == true) { - $result = true; - } - } - } - //return the result - return $result; - } - } - - if (!function_exists('if_group_member')) { - function if_group_member($group_members, $group) { - if (stripos($group_members, "||".$group."||") === false) { - return false; //group does not exist - } - else { - return true; //group exists - } - } - } - - if (!function_exists('superadmin_list')) { - function superadmin_list() { - global $domain_uuid; - $sql = "select * from v_user_groups "; - $sql .= "where group_name = 'superadmin' "; - $database = new database; - $result = $database->select($sql, null, 'all'); - $superadmin_list = "||"; - if (is_array($result) && @sizeof($result) != 0) { - foreach ($result as $field) { - //get the list of superadmins - $superadmin_list .= $field['user_uuid']."||"; - } - } - unset($sql, $result, $field); - return $superadmin_list; - } - } - - if (!function_exists('if_superadmin')) { - function if_superadmin($superadmin_list, $user_uuid) { - if (stripos($superadmin_list, "||".$user_uuid."||") === false) { - return false; - } - else { - return true; //user_uuid exists - } - } - } - - if (!function_exists('html_select_other')) { - function html_select_other($table_name, $field_name, $sql_where_optional, $field_current_value, $sql_order_by = null, $label_other = 'Other...') { - //html select other: build a select box from distinct items in db with option for other - global $domain_uuid; - $table_name = preg_replace("#[^a-zA-Z0-9_]#", "", $table_name); - $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name); - - $html = "\n"; - $html .= "\n"; - $html .= "\n"; - $html .= "\n"; - $html .= "\n"; - $html .= "
\n"; - $html .= "\n"; - $html .= "\n"; - $html .= "\n"; - $html .= "\n"; - $html .= "
"; - - return $html; - } - } - - if (!function_exists('html_select')) { - function html_select($table_name, $field_name, $sql_where_optional, $field_current_value, $field_value = '', $style = '', $on_change = '') { - //html select: build a select box from distinct items in db - global $domain_uuid; - - $table_name = preg_replace("#[^a-zA-Z0-9_]#", "", $table_name); - $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name); - $field_value = preg_replace("#[^a-zA-Z0-9_]#", "", $field_value); - - if (!empty($field_value)) { - $html .= "\n"; - $html .= " \n"; - - $sql = "select distinct(".$field_name.") as ".$field_name." from ".$table_name." ".$sql_where_optional." "; - } - - $database = new database; - $result = $database->select($sql, null, 'all'); - if (is_array($result) && @sizeof($result) != 0) { - foreach($result as $field) { - if (!empty($field[$field_name])) { - $selected = $field_current_value == $field[$field_name] ? "selected='selected'" : null; - $array_key = empty($field_value) ? $field_name : $field_value; - $html .= "\n"; - } - } - } - unset($sql, $result, $field); - $html .= "\n"; - - return $html; - } - } - - if (!function_exists('th_order_by')) { - //html table header order by - function th_order_by($field_name, $column_title, $order_by, $order, $app_uuid = '', $css = '', $http_get_params = '', $description = '') { - global $text; - if (is_uuid($app_uuid) > 0) { $app_uuid = "&app_uuid=".urlencode($app_uuid); } // accomodate need to pass app_uuid where necessary (inbound/outbound routes lists) - - $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name); - $field_value = preg_replace("#[^a-zA-Z0-9_]#", "", $field_value ?? ''); - - $sanitized_parameters = ''; - if (isset($http_get_params) && !empty($http_get_params)) { - $parameters = explode('&', $http_get_params); - if (is_array($parameters)) { - foreach ($parameters as $parameter) { - if (substr_count($parameter, '=') != 0) { - $array = explode('=', $parameter); - $key = preg_replace('#[^a-zA-Z0-9_\-]#', '', $array['0']); - $value = urldecode($array['1']); - if ($key == 'order_by' && !empty($value)) { - //validate order by - $sanitized_parameters .= "&order_by=". preg_replace('#[^a-zA-Z0-9_\-]#', '', $value); - } - else if ($key == 'order' && !empty($value)) { - //validate order - switch ($value) { - case 'asc': - $sanitized_parameters .= "&order=asc"; - break; - case 'desc': - $sanitized_parameters .= "&order=desc"; - break; - } - } - else if (!empty($value) && is_numeric($value)) { - $sanitized_parameters .= "&".$key."=".$value; - } - else { - $sanitized_parameters .= "&".$key."=".urlencode($value); - } - } - } - } - } - - $html = ""; - $description = empty($description) ? '' : $description . ', '; - if (empty($order_by)) { - $order = 'asc'; - } - if ($order_by == $field_name) { - if ($order == "asc") { - $description .= $text['label-order'].' '.$text['label-descending']; - $html .= "".escape($column_title).""; - } - else { - $description .= $text['label-order'].' '.$text['label-ascending']; - $html .= "".escape($column_title).""; - } - } - else { - $description .= $text['label-order'].' '.$text['label-ascending']; - $html .= "".escape($column_title).""; - } - $html .= ""; - return $html; - } - } - - if (!function_exists('get_ext')) { - function get_ext($filename) { - preg_match('/[^?]*/', $filename, $matches); - $string = $matches[0]; - - $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE); - - // check if there is any extension - if(count($pattern) == 1){ - //echo 'No File Extension Present'; - return ''; - } - - if(count($pattern) > 1) { - $filenamepart = $pattern[count($pattern)-1][0]; - preg_match('/[^?]*/', $filenamepart, $matches); - return $matches[0]; - } - } - //echo "ext: ".get_ext('test.txt'); - } - - if (!function_exists('file_upload')) { - function file_upload($field = '', $file_type = '', $dest_dir = '') { - - $uploadtempdir = $_ENV["TEMP"]."\\"; - ini_set('upload_tmp_dir', $uploadtempdir); - - $tmp_name = $_FILES[$field]["tmp_name"]; - $file_name = $_FILES[$field]["name"]; - $file_type = $_FILES[$field]["type"]; - $file_size = $_FILES[$field]["size"]; - $file_ext = get_ext($file_name); - $file_name_orig = $file_name; - $file_name_base = substr($file_name, 0, (strlen($file_name) - (strlen($file_ext)+1))); - //$dest_dir = '/tmp'; - - if ($file_size == 0) { - return; - } - - if (!is_dir($dest_dir)) { - echo "dest_dir not found
\n"; - return; - } - - //check if allowed file type - if ($file_type == "img") { - switch (strtolower($file_ext)) { - case "jpg": - case "png": - case "gif": - case "bmp": - case "psd": - case "tif": break; - default: return false; - } - } - if ($file_type == "file") { - switch (strtolower($file_ext)) { - case "doc": - case "pdf": - case "ppt": - case "xls": - case "zip": - case "exe": break; - default: return false; - } - } - - //find unique filename: check if file exists if it does then increment the filename - $i = 1; - while( file_exists($dest_dir.'/'.$file_name)) { - if (!empty($file_ext)) { - $file_name = $file_name_base . $i .'.'. $file_ext; - } - else { - $file_name = $file_name_orig . $i; - } - $i++; - } - - //echo "file_type: ".$file_type."
\n"; - //echo "tmp_name: ".$tmp_name."
\n"; - //echo "file_name: ".$file_name."
\n"; - //echo "file_ext: ".$file_ext."
\n"; - //echo "file_name_orig: ".$file_name_orig."
\n"; - //echo "file_name_base: ".$file_name_base."
\n"; - //echo "dest_dir: ".$dest_dir."
\n"; - - //move the file to upload directory - //bool move_uploaded_file ( string $filename, string $destination ) - - if (move_uploaded_file($tmp_name, $dest_dir.'/'.$file_name)) { - return $file_name; - } - else { - echo "File upload failed! Here's some debugging info:\n"; - return false; - } - exit; - - } - } - - if (!function_exists('sys_get_temp_dir')) { - function sys_get_temp_dir() { - if ($temp = getenv('TMP')) { return $temp; } - if ($temp = getenv('TEMP')) { return $temp; } - if ($temp = getenv('TMPDIR')) { return $temp; } - $temp = tempnam(__FILE__,''); - if (file_exists($temp)) { - unlink($temp); - return dirname($temp); - } - return null; - } - } - //echo realpath(sys_get_temp_dir()); - - if (!function_exists('normalize_path')) { - //don't use DIRECTORY_SEPARATOR as it will change on a per platform basis and we need consistency - function normalize_path($path) { - return str_replace(array('/','\\'), '/', $path); - } - } - - if (!function_exists('normalize_path_to_os')) { - function normalize_path_to_os($path) { - return str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $path); - } - } - - if (!function_exists('username_exists')) { - function username_exists($username) { - global $domain_uuid; - $sql = "select count(*) from v_users "; - $sql .= "where domain_uuid = :domain_uuid "; - $sql .= "and username = :username "; - $parameters['domain_uuid'] = $domain_uuid; - $parameters['username'] = $username; - $database = new database; - $num_rows = $database->select($sql, $parameters, 'column'); - return $num_rows > 0 ? true : false; - } - } - - if (!function_exists('add_extension_user')) { - function add_extension_user($extension_uuid, $username) { - global $domain_uuid; - //get the user_uuid by using the username - $sql = "select user_uuid from v_users "; - $sql .= "where domain_uuid = :domain_uuid "; - $sql .= "and username = :username "; - $parameters['domain_uuid'] = $domain_uuid; - $parameters['username'] = $username; - $database = new database; - $user_uuid = $database->select($sql, $parameters, 'column'); - unset($sql, $parameters); - - if (is_uuid($user_uuid)) { - //check if the user_uuid exists in v_extension_users - $sql = "select count(*) from v_extension_users "; - $sql .= "where domain_uuid = :domain_uuid "; - $sql .= "and user_uuid = :user_uuid "; - $parameters['domain_uuid'] = $domain_uuid; - $parameters['user_uuid'] = $user_uuid; - $database = new database; - $num_rows = $database->select($sql, $parameters, 'column'); - unset($sql, $parameters); - - //assign the extension to the user - if ($num_rows == 0) { - //build insert array - $extension_user_uuid = uuid(); - $array['extension_users'][$x]['extension_user_uuid'] = $extension_user_uuid; - $array['extension_users'][$x]['domain_uuid'] = $domain_uuid; - $array['extension_users'][$x]['extension_uuid'] = $extension_uuid; - $array['extension_users'][$x]['user_uuid'] = $row["user_uuid"]; - //grant temporary permissions - $p = new permissions; - $p->add('extension_user_add', 'temp'); - //execute insert - $database = new database; - $database->app_name = 'function-add_extension_user'; - $database->app_uuid = 'e68d9689-2769-e013-28fa-6214bf47fca3'; - $database->save($array); - unset($array); - //revoke temporary permissions - $p->delete('extension_user_add', 'temp'); - } - } - } - } - - if (!function_exists('user_add')) { - function user_add($username, $password, $user_email = '') { - global $domain_uuid; - if (empty($username)) { return false; } - if (empty($password)) { return false; } - if (!username_exists($username)) { - //build user insert array - $user_uuid = uuid(); - $salt = generate_password('20', '4'); - $array['users'][0]['user_uuid'] = $user_uuid; - $array['users'][0]['domain_uuid'] = $domain_uuid; - $array['users'][0]['username'] = $username; - $array['users'][0]['password'] = md5($salt.$password); - $array['users'][0]['salt'] = $salt; - if (valid_email($user_email)) { - $array['users'][0]['user_email'] = $user_email; - } - $array['users'][0]['add_date'] = 'now()'; - $array['users'][0]['add_user'] = $_SESSION["username"]; - - //build user group insert array - $user_group_uuid = uuid(); - $array['user_groups'][0]['user_group_uuid'] = $user_group_uuid; - $array['user_groups'][0]['domain_uuid'] = $domain_uuid; - $array['user_groups'][0]['group_name'] = 'user'; - $array['user_groups'][0]['user_uuid'] = $user_uuid; - - //grant temporary permissions - $p = new permissions; - $p->add('user_add', 'temp'); - $p->add('user_group_add', 'temp'); - //execute insert - $database = new database; - $database->app_name = 'function-user_add'; - $database->app_uuid = '15a8d74b-ac7e-4468-add4-3e6ebdcb8e22'; - $database->save($array); - unset($array); - //revoke temporary permissions - $p->delete('user_add', 'temp'); - $p->delete('user_group_add', 'temp'); - } - } - } - -function switch_module_is_running($fp, $mod) { - if (!$fp) { - //if the handle does not exist create it - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - //if the handle still does not exist show an error message - if (!$fp) { - $msg = "
Connection to Event Socket failed.
"; - } - } - if ($fp) { - //send the api command to check if the module exists - $switchcmd = "module_exists $mod"; - $switch_result = event_socket_request($fp, 'api '.$switchcmd); - unset($switchcmd); - if (trim($switch_result) == "true") { - return true; - } - else { - return false; - } - } - else { - return false; - } -} -//switch_module_is_running('mod_spidermonkey'); - -//format a number (n) replace with a number (r) remove the number -function format_string($format, $data) { - //nothing to do so return - if(empty($format)) - return $data; - - //preset values - $x=0; - $tmp = ''; - - //count the characters - $format_count = substr_count($format, 'x'); - $format_count = $format_count + substr_count($format, 'R'); - $format_count = $format_count + substr_count($format, 'r'); - - //format the string if it matches - if ($format_count == strlen($data)) { - for ($i = 0; $i <= strlen($format); $i++) { - $tmp_format = strtolower(substr($format, $i, 1)); - if ($tmp_format == 'x') { - $tmp .= substr($data, $x, 1); - $x++; - } - elseif ($tmp_format == 'r') { - $x++; - } - else { - $tmp .= $tmp_format; - } - } - } - if (empty($tmp)) { - return $data; - } - else { - return $tmp; - } -} - -//get the format and use it to format the phone number - function format_phone($phone_number) { - if (is_numeric(trim($phone_number ?? '', ' +'))) { - if (isset($_SESSION["format"]["phone"])) { - $phone_number = trim($phone_number, ' +'); - foreach ($_SESSION["format"]["phone"] as &$format) { - $format_count = substr_count($format, 'x'); - $format_count = $format_count + substr_count($format, 'R'); - $format_count = $format_count + substr_count($format, 'r'); - if ($format_count == strlen($phone_number)) { - //format the number - $phone_number = format_string($format, $phone_number); - } - } - } - } - return $phone_number; - } - -//format seconds into hh:mm:ss - function format_hours($seconds) { - $hours = floor($seconds / 3600); - $minutes = floor(floor($seconds / 60) % 60); - $seconds = $seconds % 60; - if (strlen($minutes) == 1) { $minutes = '0'.$minutes; } - if (strlen($seconds) == 1) { $seconds = '0'.$seconds; } - return "$hours:$minutes:$seconds"; - } - -//browser detection without browscap.ini dependency - function http_user_agent($info = '') { - - //set default values - $user_agent = $_SERVER['HTTP_USER_AGENT']; - $browser_name = 'Unknown'; - $platform = 'Unknown'; - $version = ''; - $mobile = false; - - //get the platform - if (preg_match('/linux/i', $user_agent)) { - $platform = 'Linux'; - } - elseif (preg_match('/macintosh|mac os x/i', $user_agent)) { - $platform = 'Apple'; - } - elseif (preg_match('/windows|win32/i', $user_agent)) { - $platform = 'Windows'; - } - - //set mobile to true or false - if (preg_match('/mobile/i', $user_agent)) { - $platform = 'Mobile'; - $mobile = true; - } - elseif (preg_match('/android/i', $user_agent)) { - $platform = 'Android'; - $mobile = true; - } - - //get the name of the useragent - if (preg_match('/MSIE/i',$user_agent) || preg_match('/Trident/i',$user_agent)) { - $browser_name = 'Internet Explorer'; - $browser_name_short = 'MSIE'; - } - elseif (preg_match('/Firefox/i',$user_agent)) { - $browser_name = 'Mozilla Firefox'; - $browser_name_short = 'Firefox'; - } - elseif (preg_match('/Chrome/i',$user_agent)) { - $browser_name = 'Google Chrome'; - $browser_name_short = 'Chrome'; - } - elseif (preg_match('/Safari/i',$user_agent)) { - $browser_name = 'Apple Safari'; - $browser_name_short = 'Safari'; - } - elseif (preg_match('/Opera/i',$user_agent)) { - $browser_name = 'Opera'; - $browser_name_short = 'Opera'; - } - elseif (preg_match('/Netscape/i',$user_agent)) { - $browser_name = 'Netscape'; - $browser_name_short = 'Netscape'; - } - else { - $browser_name = 'Unknown'; - $browser_name_short = 'Unknown'; - } - - //finally get the correct version number - $known = array('Version', $browser_name_short, 'other'); - $pattern = '#(?' . join('|', $known) . ')[/ ]+(?[0-9.|a-zA-Z.]*)#'; - if (!preg_match_all($pattern, $user_agent, $matches)) { - //we have no matching number just continue - } - - //see how many we have - $i = count($matches['browser']); - if ($i != 1) { - //we will have two since we are not using 'other' argument yet - //see if version is before or after the name - if (strripos($user_agent,"Version") < strripos($user_agent,$browser_name_short)) { - $version= $matches['version'][0]; - } - else { - $version= $matches['version'][1]; - } - } - else { - $version= $matches['version'][0]; - } - - //check if we have a number - if ($version == null || $version == "") { $version = "?"; } - - //return the data - switch ($info) { - case "agent": return $user_agent; break; - case "name": return $browser_name; break; - case "name_short": return $browser_name_short; break; - case "version": return $version; break; - case "platform": return $platform; break; - case "mobile": return $mobile; break; - case "pattern": return $pattern; break; - default : - return array( - 'user_agent' => $user_agent, - 'name' => $browser_name, - 'name_short' => $browser_name_short, - 'version' => $version, - 'platform' => $platform, - 'mobile' => $mobile, - 'pattern' => $pattern - ); - } - } - -//tail php function for non posix systems - function tail($file, $num_to_get=10) { - $fp = fopen($file, 'r'); - $position = filesize($file); - $chunklen = 4096; - if($position-$chunklen<=0) { - fseek($fp,0); - } - else { - fseek($fp, $position-$chunklen); - } - $data="";$ret="";$lc=0; - while($chunklen > 0) { - $data = fread($fp, $chunklen); - $dl=strlen($data); - for($i=$dl-1;$i>=0;$i--){ - if($data[$i]=="\n"){ - if($lc==0 && $ret!="")$lc++; - $lc++; - if($lc>$num_to_get)return $ret; - } - $ret=$data[$i].$ret; - } - if($position-$chunklen<=0){ - fseek($fp,0); - $chunklen=$chunklen-abs($position-$chunklen); - } - else { - fseek($fp, $position-$chunklen); - } - $position = $position - $chunklen; - } - fclose($fp); - return $ret; - } - -//generate a random password with upper, lowercase and symbols - function generate_password($length = 0, $strength = 0) { - $password = ''; - $chars = ''; - if ($length === 0 && $strength === 0) { //set length and strenth if specified in default settings and strength isn't numeric-only - $length = (is_numeric($_SESSION["users"]["password_length"]["numeric"])) ? $_SESSION["users"]["password_length"]["numeric"] : 20; - $strength = (is_numeric($_SESSION["users"]["password_strength"]["numeric"])) ? $_SESSION["users"]["password_strength"]["numeric"] : 4; - } - if ($strength >= 1) { $chars .= "0123456789"; } - if ($strength >= 2) { $chars .= "abcdefghijkmnopqrstuvwxyz"; } - if ($strength >= 3) { $chars .= "ABCDEFGHIJKLMNPQRSTUVWXYZ"; } - if ($strength >= 4) { $chars .= "!^$%*?."; } - for ($i = 0; $i < $length; $i++) { - $password .= $chars[random_int(0, strlen($chars)-1)]; - } - return $password; - } - -//check password strength against requirements (if any) - function check_password_strength($password, $text, $type = 'default') { - if ($password != '') { - if ($type == 'default') { - $req['length'] = $_SESSION['extension']['password_length']['numeric']; - $req['number'] = ($_SESSION['extension']['password_number']['boolean'] == 'true') ? true : false; - $req['lowercase'] = ($_SESSION['extension']['password_lowercase']['boolean'] == 'true') ? true : false; - $req['uppercase'] = ($_SESSION['extension']['password_uppercase']['boolean'] == 'true') ? true : false; - $req['special'] = ($_SESSION['extension']['password_special']['boolean'] == 'true') ? true : false; - } elseif ($type == 'user') { - $req['length'] = $_SESSION['user']['password_length']['numeric']; - $req['number'] = ($_SESSION['user']['password_number']['boolean'] == 'true') ? true : false; - $req['lowercase'] = ($_SESSION['user']['password_lowercase']['boolean'] == 'true') ? true : false; - $req['uppercase'] = ($_SESSION['user']['password_uppercase']['boolean'] == 'true') ? true : false; - $req['special'] = ($_SESSION['user']['password_special']['boolean'] == 'true') ? true : false; - } - if (is_numeric($req['length']) && $req['length'] != 0 && !preg_match_all('$\S*(?=\S{'.$req['length'].',})\S*$', $password)) { // length - $msg_errors[] = $req['length'].'+ '.$text['label-characters']; - } - if ($req['number'] && !preg_match_all('$\S*(?=\S*[\d])\S*$', $password)) { //number - $msg_errors[] = '1+ '.$text['label-numbers']; - } - if ($req['lowercase'] && !preg_match_all('$\S*(?=\S*[a-z])\S*$', $password)) { //lowercase - $msg_errors[] = '1+ '.$text['label-lowercase_letters']; - } - if ($req['uppercase'] && !preg_match_all('$\S*(?=\S*[A-Z])\S*$', $password)) { //uppercase - $msg_errors[] = '1+ '.$text['label-uppercase_letters']; - } - if ($req['special'] && !preg_match_all('$\S*(?=\S*[\W])\S*$', $password)) { //special - $msg_errors[] = '1+ '.$text['label-special_characters']; - } - if (is_array($msg_errors) && sizeof($msg_errors) > 0) { - message::add($_SESSION["message"] = $text['message-password_requirements'].': '.implode(', ', $msg_errors), 'negative', 6000); - return false; - } - else { - return true; - } - } - return true; - } - -//based on Wez Furlong do_post_request - if (!function_exists('send_http_request')) { - function send_http_request($url, $data, $method = "POST", $optional_headers = null) { - $params = array('http' => array( - 'method' => $method, - 'content' => $data - )); - if ($optional_headers !== null) { - $params['http']['header'] = $optional_headers; - } - $ctx = stream_context_create($params); - $fp = @fopen($url, 'rb', false, $ctx); - if (!$fp) { - throw new Exception("Problem with $url, $php_errormsg"); - } - $response = @stream_get_contents($fp); - if ($response === false) { - throw new Exception("Problem reading data from $url, $php_errormsg"); - } - return $response; - } - } - -//convert the string to a named array - if(!function_exists('csv_to_named_array')) { - function csv_to_named_array($tmp_str, $tmp_delimiter) { - $tmp_array = explode ("\n", $tmp_str); - $result = array(); - if (trim(strtoupper($tmp_array[0])) !== "+OK") { - $tmp_field_name_array = explode ($tmp_delimiter, $tmp_array[0]); - $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; - } - } - -function get_time_zone_offset($remote_tz, $origin_tz = 'UTC') { - $origin_dtz = new DateTimeZone($origin_tz); - $remote_dtz = new DateTimeZone($remote_tz); - $origin_dt = new DateTime("now", $origin_dtz); - $remote_dt = new DateTime("now", $remote_dtz); - $offset = $remote_dtz->getOffset($remote_dt) - $origin_dtz->getOffset($origin_dt); - return $offset; -} - -function number_pad($number,$n) { - return str_pad((int) $number,$n,"0",STR_PAD_LEFT); -} - -// validate email address syntax - if(!function_exists('valid_email')) { - function valid_email($email) { - return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? true : false; - } - } - -//function to convert hexidecimal color value to rgb string/array value - if (!function_exists('hex_to_rgb')) { - function hex_to_rgb($hex, $delim = '') { - $hex = str_replace("#", "", $hex); - - if (strlen($hex) == 3) { - $r = hexdec(substr($hex,0,1).substr($hex,0,1)); - $g = hexdec(substr($hex,1,1).substr($hex,1,1)); - $b = hexdec(substr($hex,2,1).substr($hex,2,1)); - } - else { - $r = hexdec(substr($hex,0,2)); - $g = hexdec(substr($hex,2,2)); - $b = hexdec(substr($hex,4,2)); - } - $rgb = array($r, $g, $b); - - if ($delim != '') { - return implode($delim, $rgb); // return rgb delimited string - } - else { - return $rgb; // return array of rgb values - } - } - } - -//function to get a color's luminence level -- dependencies: rgb_to_hsl() - if (!function_exists('get_color_luminence')) { - function get_color_luminence($color) { - //convert hex to rgb - if (substr_count($color, ',') == 0) { - $color = str_replace(' ', '', $color); - $color = str_replace('#', '', $color); - if (strlen($color) == 3) { - $r = hexdec(substr($color,0,1).substr($color,0,1)); - $g = hexdec(substr($color,1,1).substr($color,1,1)); - $b = hexdec(substr($color,2,1).substr($color,2,1)); - } - else { - $r = hexdec(substr($color,0,2)); - $g = hexdec(substr($color,2,2)); - $b = hexdec(substr($color,4,2)); - } - $color = $r.','.$g.','.$b; - } - - //color to array, pop alpha - if (substr_count($color, ',') > 0) { - $color = str_replace(' ', '', $color); - $color = str_replace('rgb', '', $color); - $color = str_replace('a(', '', $color); - $color = str_replace(')', '', $color); - $color = explode(',', $color); - $hsl = rgb_to_hsl($color[0], $color[1], $color[2]); - } - - //return luminence value - return (is_array($hsl) && is_numeric($hsl[2])) ? $hsl[2] : null; - } - } - -//function to lighten or darken a hexidecimal, rgb, or rgba color value by a percentage -- dependencies: rgb_to_hsl(), hsl_to_rgb() - if (!function_exists('color_adjust')) { - function color_adjust($color, $percent) { - /* - USAGE - 20% Lighter - color_adjust('#3f4265', 0.2); - color_adjust('234,120,6,0.3', 0.2); - 20% Darker - color_adjust('#3f4265', -0.2); // - color_adjust('rgba(234,120,6,0.3)', -0.2); - RETURNS - Same color format provided (hex in = hex out, rgb(a) in = rgb(a) out) - */ - - //convert hex to rgb - if (substr_count($color, ',') == 0) { - $color = str_replace(' ', '', $color); - if (substr_count($color, '#') > 0) { - $color = str_replace('#', '', $color); - $hash = '#'; - } - if (strlen($color) == 3) { - $r = hexdec(substr($color,0,1).substr($color,0,1)); - $g = hexdec(substr($color,1,1).substr($color,1,1)); - $b = hexdec(substr($color,2,1).substr($color,2,1)); - } - else { - $r = hexdec(substr($color,0,2)); - $g = hexdec(substr($color,2,2)); - $b = hexdec(substr($color,4,2)); - } - $color = $r.','.$g.','.$b; - } - - //color to array, pop alpha - if (substr_count($color, ',') > 0) { - $color = str_replace(' ', '', $color); - $wrapper = false; - if (substr_count($color, 'rgb') != 0) { - $color = str_replace('rgb', '', $color); - $color = str_replace('a(', '', $color); - $color = str_replace(')', '', $color); - $wrapper = true; - } - $colors = explode(',', $color); - $alpha = (sizeof($colors) == 4) ? array_pop($colors) : null; - $color = $colors; - unset($colors); - - //adjust color using rgb > hsl > rgb conversion - $hsl = rgb_to_hsl($color[0], $color[1], $color[2]); - $hsl[2] = $hsl[2] + $percent; - $color = hsl_to_rgb($hsl[0], $hsl[1], $hsl[2]); - - //return adjusted color in format received - if (isset($hash) && $hash == '#') { //hex - $hex = ''; - for ($i = 0; $i <= 2; $i++) { - $hex_color = dechex($color[$i]); - if (strlen($hex_color) == 1) { $hex_color = '0'.$hex_color; } - $hex .= $hex_color; - } - return $hash.$hex; - } - else { //rgb(a) - $rgb = implode(',', $color); - if ($alpha != '') { $rgb .= ','.$alpha; $a = 'a'; } - if ($wrapper) { $rgb = 'rgb'.$a.'('.$rgb.')'; } - return $rgb; - } - } - - return $color; - } - } - -//function to convert an rgb color array to an hsl color array - if (!function_exists('rgb_to_hsl')) { - function rgb_to_hsl($r, $g, $b) { - $r /= 255; - $g /= 255; - $b /= 255; - - $max = max($r, $g, $b); - $min = min($r, $g, $b); - - $h; - $s; - $l = ($max + $min) / 2; - $d = $max - $min; - - if ($d == 0) { - $h = $s = 0; // achromatic - } - else { - $s = $d / (1 - abs((2 * $l) - 1)); - switch($max){ - case $r: - $h = 60 * fmod((($g - $b) / $d), 6); - if ($b > $g) { $h += 360; } - break; - case $g: - $h = 60 * (($b - $r) / $d + 2); - break; - case $b: - $h = 60 * (($r - $g) / $d + 4); - break; - } - } - - return array(round($h, 2), round($s, 2), round($l, 2)); - } - } - -//function to convert an hsl color array to an rgb color array - if (!function_exists('hsl_to_rgb')) { - function hsl_to_rgb($h, $s, $l){ - $r; - $g; - $b; - - $c = (1 - abs((2 * $l) - 1)) * $s; - $x = $c * (1 - abs(fmod(($h / 60), 2) - 1)); - $m = $l - ($c / 2); - - if ($h < 60) { - $r = $c; - $g = $x; - $b = 0; - } - else if ($h < 120) { - $r = $x; - $g = $c; - $b = 0; - } - else if ($h < 180) { - $r = 0; - $g = $c; - $b = $x; - } - else if ($h < 240) { - $r = 0; - $g = $x; - $b = $c; - } - else if ($h < 300) { - $r = $x; - $g = 0; - $b = $c; - } - else { - $r = $c; - $g = 0; - $b = $x; - } - - $r = ($r + $m) * 255; - $g = ($g + $m) * 255; - $b = ($b + $m) * 255; - - if ($r > 255) { $r = 255; } - if ($g > 255) { $g = 255; } - if ($b > 255) { $b = 255; } - - if ($r < 0) { $r = 0; } - if ($g < 0) { $g = 0; } - if ($b < 0) { $b = 0; } - - return array(floor($r), floor($g), floor($b)); - } - } - -//function to send email - if (!function_exists('send_email')) { - function send_email($email_recipients, $email_subject, $email_body, &$email_error = '', $email_from_address = '', $email_from_name = '', $email_priority = 3, $email_debug_level = 0, $email_attachments = '', $email_read_confirmation = false) { - /* - RECIPIENTS NOTE: - - Pass in a single email address... - - user@domain.com - - Pass in a comma or semi-colon delimited string of e-mail addresses... - - user@domain.com,user2@domain2.com,user3@domain3.com - user@domain.com;user2@domain2.com;user3@domain3.com - - Pass in a simple array of email addresses... - - Array ( - [0] => user@domain.com - [1] => user2@domain2.com - [2] => user3@domain3.com - ) - - Pass in a multi-dimentional array of addresses (delivery, address, name)... - - Array ( - [0] => Array ( - [delivery] => to - [address] => user@domain.com - [name] => user 1 - ) - [1] => Array ( - [delivery] => cc - [address] => user2@domain2.com - [name] => user 2 - ) - [2] => Array ( - [delivery] => bcc - [address] => user3@domain3.com - [name] => user 3 - ) - ) - - ATTACHMENTS NOTE: - - Pass in as many files as necessary in an array in the following format... - - Array ( - [0] => Array ( - [type] => file (or 'path') - [name] => filename.ext - [value] => /folder/filename.ext - ) - [1] => Array ( - [type] => string - [name] => filename.ext - [value] => (string of file contents - if base64, will be decoded automatically) - ) - ) - - ERROR RESPONSE: - - Error messages are stored in the variable passed into $email_error BY REFERENCE - - */ - - //add the email recipients - $address_found = false; - if (!is_array($email_recipients)) { // must be a single or delimited recipient address(s) - $email_recipients = str_replace(' ', '', $email_recipients); - $email_recipients = str_replace(',', ';', $email_recipients); - $email_recipients = explode(';', $email_recipients); // convert to array of addresses - } - - foreach ($email_recipients as $email_recipient) { - if (is_array($email_recipient)) { // check if each recipient has multiple fields - if ($email_recipient["address"] != '' && valid_email($email_recipient["address"])) { // check if valid address - $recipients = $email_recipient["address"]; - $address_found = true; - } - } - else if ($email_recipient != '' && valid_email($email_recipient)) { // check if recipient value is simply (only) an address - $email_recipients = $email_recipient; - $address_found = true; - } - } - if (is_array($recipients)) { - $email_recipients = implode(",", $recipients); - } - if (!$address_found) { - $email_error = "No valid e-mail address provided."; - return false; - } - - //get the from address and name - $email_from_address = ($email_from_address != '') ? $email_from_address : $_SESSION['email']['smtp_from']['text']; - $email_from_name = ($email_from_name != '') ? $email_from_name : $_SESSION['email']['smtp_from_name']['text']; - - //send email - $email = new email; - $email->recipients = $email_recipients; - $email->subject = $email_subject; - $email->body = $email_body; - $email->from_address = $email_from_address; - $email->from_name = $email_from_name; - $email->attachments = $email_attachments; - $email->debug_level = 3; - $sent = $email->send(); - //$email_error = $email->email_error; - - } - } - -//encrypt a string - if (!function_exists('encrypt')) { - function encrypt($key, $data) { - $encryption_key = base64_decode($key); - $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); - $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv); - return base64_encode($encrypted.'::'.$iv); - } - } - -//decrypt a string - if (!function_exists('decrypt')) { - function decrypt($key, $data) { - $encryption_key = base64_decode($key); - list($encrypted_data, $iv) = explode('::', base64_decode($data), 2); - return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv); - } - } - -//json detection - if (!function_exists('is_json')) { - function is_json($str) { - return (is_string($str) && is_object(json_decode($str))) ? true : false; - } - } - -//mac detection - if (!function_exists('is_mac')) { - function is_mac($str) { - return (preg_match('/([a-fA-F0-9]{2}[:|\-]?){6}/', $str) == 1) ? true : false; - } - } - -//detect if php is running as command line interface - if (!function_exists('is_cli')) { - function is_cli() { - if (defined('STDIN')) { - return true; - } - if (php_sapi_name() == 'cli' && !isset($_SERVER['HTTP_USER_AGENT']) && is_numeric($_SERVER['argc'])) { - return true; - } - return false; - } - } - -//format mac address - if (!function_exists('format_mac')) { - function format_mac($str, $delim = '-', $case = 'lower') { - if (is_mac($str)) { - $str = join($delim, str_split($str, 2)); - $str = ($case == 'upper') ? strtoupper($str) : strtolower($str); - } - return $str; - } - } - -//transparent gif - if (!function_exists('img_spacer')) { - function img_spacer($width = '1px', $height = '1px', $custom = null) { - return ""; - } - } - -//lower case - function lower_case($string) { - if (function_exists('mb_strtolower')) { - return mb_strtolower($string, 'UTF-8'); - } - else { - return strtolower($string); - } - } - -//upper case - function upper_case($string) { - if (function_exists('mb_strtoupper')) { - return mb_strtoupper($string, 'UTF-8'); - } - else { - return strtoupper($string); - } - } - -//write javascript function that detects select key combinations to perform designated actions - if (!function_exists('key_press')) { - function key_press($key, $direction = 'up', $subject = 'document', $exceptions = array(), $prompt = null, $action = null, $script_wrapper = true) { - //determine key code - switch (strtolower($key)) { - case 'escape': - $key_code = '(e.which == 27)'; - break; - case 'delete': - $key_code = '(e.which == 46)'; - break; - case 'enter': - $key_code = '(e.which == 13)'; - break; - case 'backspace': - $key_code = '(e.which == 8)'; - break; - case 'space': - $key_code = '(e.which == 32)'; - break; - case 'ctrl+s': - $key_code = '(((e.which == 115 || e.which == 83) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - case 'ctrl+q': - $key_code = '(((e.which == 113 || e.which == 81) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - case 'ctrl+a': - $key_code = '(((e.which == 97 || e.which == 65) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - case 'ctrl+c': - $key_code = '(((e.which == 99 || e.which == 67) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - case 'ctrl+enter': - $key_code = '(((e.which == 13 || e.which == 10) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; - break; - default: - return; - } - //filter direction - switch ($direction) { - case 'down': $direction = 'keydown'; break; - case 'press': $direction = 'keypress'; break; - case 'up': $direction = 'keyup'; break; - } - //check for element exceptions - if (is_array($exceptions)) { - if (sizeof($exceptions) > 0) { - $exceptions = "!$(e.target).is('".implode(',', $exceptions)."') && "; - } - } - //quote if selector is id or class - $subject = ($subject != 'window' && $subject != 'document') ? "'".$subject."'" : $subject; - //output script - echo "\n\n\n"; - if ($script_wrapper) { - echo "\n"; - } - echo "\n\n\n"; - } - } - -//format border radius values - if (!function_exists('format_border_radius')) { - function format_border_radius($radius_value, $default = 5) { - $radius_value = ($radius_value != '') ? $radius_value : $default; - $br_a = explode(' ', $radius_value); - foreach ($br_a as $index => $br) { - if (substr_count($br, '%') > 0) { - $br_b[$index]['number'] = str_replace('%', '', $br); - $br_b[$index]['unit'] = '%'; - } - else { - $br_b[$index]['number'] = str_replace('px', '', strtolower($br)); - $br_b[$index]['unit'] = 'px'; - } - } - unset($br_a, $br); - if (sizeof($br_b) == 4) { - $br['tl']['n'] = $br_b[0]['number']; - $br['tr']['n'] = $br_b[1]['number']; - $br['br']['n'] = $br_b[2]['number']; - $br['bl']['n'] = $br_b[3]['number']; - $br['tl']['u'] = $br_b[0]['unit']; - $br['tr']['u'] = $br_b[1]['unit']; - $br['br']['u'] = $br_b[2]['unit']; - $br['bl']['u'] = $br_b[3]['unit']; - } - else if (sizeof($br_b) == 2) { - $br['tl']['n'] = $br_b[0]['number']; - $br['tr']['n'] = $br_b[0]['number']; - $br['br']['n'] = $br_b[1]['number']; - $br['bl']['n'] = $br_b[1]['number']; - $br['tl']['u'] = $br_b[0]['unit']; - $br['tr']['u'] = $br_b[0]['unit']; - $br['br']['u'] = $br_b[1]['unit']; - $br['bl']['u'] = $br_b[1]['unit']; - } - else { - $br['tl']['n'] = $br_b[0]['number']; - $br['tr']['n'] = $br_b[0]['number']; - $br['br']['n'] = $br_b[0]['number']; - $br['bl']['n'] = $br_b[0]['number']; - $br['tl']['u'] = $br_b[0]['unit']; - $br['tr']['u'] = $br_b[0]['unit']; - $br['br']['u'] = $br_b[0]['unit']; - $br['bl']['u'] = $br_b[0]['unit']; - } - unset($br_b); - - return $br; //array - } - } - -//converts a string to a regular expression - if (!function_exists('string_to_regex')) { - function string_to_regex($string, $prefix='') { - $original_string = $string; - //escape the plus - if (substr($string, 0, 1) == "+") { - $string = "^\\+(".substr($string, 1).")$"; - } - //add prefix - if (!empty($prefix)) { - if (!empty($prefix) && strlen($prefix) < 4) { - $plus = (substr($string, 0, 1) == "+") ? '' : '\+?'; - $prefix = $plus.$prefix.'?'; - } - else { - $prefix = '(?:'.$prefix.')?'; - } - } - //convert N,X,Z syntax to regex - if (preg_match('/^[NnXxZz]+$/', $original_string)) { - $string = str_ireplace("N", "[2-9]", $string); - $string = str_ireplace("X", "[0-9]", $string); - $string = str_ireplace("Z", "[1-9]", $string); - } - //add ^ to the start of the string if missing - if (substr($string, 0, 1) != "^") { - $string = "^".$string; - } - //add $ to the end of the string if missing - if (substr($string, -1) != "$") { - $string = $string."$"; - } - //add the round brackets - if (!strstr($string, '(')) { - if (strstr($string, '^')) { - $string = str_replace("^", "^".$prefix."(", $string); - } - else { - $string = '^('.$string; - } - if (strstr($string, '$')) { - $string = str_replace("$", ")$", $string); - } - else { - $string = $string.')$'; - } - } - //return the result - return $string; - } - //$string = "+12089068227"; echo $string." ".string_to_regex($string)."\n"; - //$string = "12089068227"; echo $string." ".string_to_regex($string)."\n"; - //$string = "2089068227"; echo $string." ".string_to_regex($string)."\n"; - //$string = "^(20890682[0-9][0-9])$"; echo $string." ".string_to_regex($string)."\n"; - //$string = "1208906xxxx"; echo $string." ".string_to_regex($string)."\n"; - //$string = "nxxnxxxxxxx"; echo $string." ".string_to_regex($string)."\n"; - //$string = "208906xxxx"; echo $string." ".string_to_regex($string)."\n"; - //$string = "^(2089068227"; echo $string." ".string_to_regex($string)."\n"; - //$string = "^2089068227)"; echo $string." ".string_to_regex($string)."\n"; - //$string = "2089068227$"; echo $string." ".string_to_regex($string)."\n"; - //$string = "2089068227)$"; echo $string." ".string_to_regex($string)."\n"; - } - -//dynamically load available web fonts - if (!function_exists('get_available_fonts')) { - function get_available_fonts($sort = 'alpha') { - if ($_SESSION['theme']['font_source_key']['text'] != '') { - if (!is_array($_SESSION['fonts_available']) || sizeof($_SESSION['fonts_available']) == 0) { - /* - sort options: - alpha - alphabetically - date - by date added (most recent font added or updated first) - popularity - by popularity (most popular family first) - style - by number of styles available (family with most styles first) - trending - by families seeing growth in usage (family seeing the most growth first) - */ - $google_api_url = 'https://www.googleapis.com/webfonts/v1/webfonts?key='.$_SESSION['theme']['font_source_key']['text'].'&sort='.$sort; - $response = file_get_contents($google_api_url); - if ($response != '') { - $data = json_decode($response, true); - $items = $data['items']; - foreach ($items as $item) { - $fonts[] = $item['family']; - } - //echo "
".print_r($font_list, true)."
"; - } - $_SESSION['fonts_available'] = $fonts; - unset($fonts); - } - return (is_array($_SESSION['fonts_available']) && sizeof($_SESSION['fonts_available']) > 0) ? $_SESSION['fonts_available'] : array(); - } - else { - return false; - } - } - } - -//dynamically import web fonts (by reading static css file) - if (!function_exists('import_fonts')) { - function import_fonts($file_to_parse, $line_styles_begin = null) { - /* - This function reads the contents of $file_to_parse, beginning at $line_styles_begin (if set), - and attempts to parse the specified google fonts used. The assumption is that each curly brace - will be on its own line, each CSS style (attribute: value;) will be on its own line, a single - Google Fonts name will be used per selector, and that it will be surrounded by SINGLE quotes, - as shown in the example below: - - .class_name { - font-family: 'Google Font'; - font-weight: 300; - font-style: italic; - } - - If the CSS styles are formatted as described, the necessary @import string should be generated - correctly. - */ - - $file = file_get_contents($_SERVER["DOCUMENT_ROOT"].$file_to_parse); - $lines = explode("\n", $file); - - $style_counter = 0; - foreach ($lines as $line_number => $line) { - if ($line_styles_begin != '' && $line_number < $line_styles_begin - 1) { continue; } - if (substr_count($line, "{") > 0) { - $style_lines[$style_counter]['begins'] = $line_number; - } - if (substr_count($line, "}") > 0) { - $style_lines[$style_counter]['ends'] = $line_number; - $style_counter++; - } - } - //echo "\n\n".print_r($style_lines, true)."\n\n"; - - if (is_array($style_lines) && sizeof($style_lines) > 0) { - - foreach ($style_lines as $index => $style_line) { - for ($l = $style_line['begins']+1; $l < $style_line['ends']; $l++) { - $tmp[] = $lines[$l]; - } - $style_groups[] = $tmp; - unset($tmp); - } - //echo "\n\n".print_r($style_groups, true)."\n\n"; - - if (is_array($style_groups) && sizeof($style_groups) > 0) { - - foreach ($style_groups as $style_group_index => $style_group) { - foreach ($style_group as $style_index => $style) { - $tmp = explode(':', $style); - $attribute = trim($tmp[0]); - $value = trim(trim($tmp[1]),';'); - $style_array[$attribute] = $value; - } - $style_groups[$style_group_index] = $style_array; - unset($style_array); - } - //echo "\n\n".print_r($style_groups, true)."\n\n"; - - foreach ($style_groups as $style_group_index => $style_group) { - $style_value = $style_group['font-family']; - if (substr_count($style_value, "'") > 0) { - //determine font - $font_begin = strpos($style_value, "'")+1; - $font_end = strpos($style_value, "'", $font_begin); - $font_name = substr($style_value, $font_begin, $font_end - $font_begin); - //determine modifiers - $weight = (is_numeric($style_group['font-weight']) || strtolower($style_group['font-weight']) == 'bold') ? strtolower($style_group['font-weight']) : null; - $italic = (strtolower($style_group['font-style']) == 'italic') ? 'italic' : null; - //add font to array - $fonts[$font_name][] = $weight.$italic; - } - } - //echo "\n\n/*".print_r($fonts, true)."*/\n\n"; - - if (is_array($fonts)) { - foreach ($fonts as $font_name => $modifiers) { - $modifiers = array_unique($modifiers); - $import_font_string = str_replace(' ', '+', $font_name); - if (is_array($modifiers) && sizeof($modifiers) > 0) { - $import_font_string .= ':'.implode(',', $modifiers); - } - $import_fonts[] = $import_font_string; - } - //echo "\n\n/*".print_r($import_fonts, true)."*/\n\n"; - $import_string = "@import url(//fonts.googleapis.com/css?family=".implode('|', $import_fonts).");"; - echo $import_string."\n"; - } - - } - - } - - } - } - -//retrieve array of countries - if (!function_exists('get_countries')) { - function get_countries() { - $sql = "select * from v_countries order by country asc"; - $database = new database; - $result = $database->select($sql, null, 'all'); - unset($sql); - - return is_array($result) && @sizeof($result) != 0 ? $result : false; - } - } - -//make directory with event socket - function event_socket_mkdir($dir) { - //connect to fs - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if (!$fp) { - return false; - } - //send the mkdir command to freeswitch - if ($fp) { - //build and send the mkdir command to freeswitch - $switch_cmd = "lua mkdir.lua ".escapeshellarg($dir); - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); - fclose($fp); - //check result - if (trim($switch_result) == "-ERR no reply") { - return true; - } - } - //can not create directory - return false; - } - -//escape user data - function escape($string) { - if (is_string($string)) { - return htmlentities($string, ENT_QUOTES | ENT_HTML5, 'UTF-8'); - } - elseif (is_numeric($string)) { - return $string; - } - else { - $string = (array) $string; - if (isset($string[0])) { - return htmlentities($string[0], ENT_QUOTES | ENT_HTML5, 'UTF-8'); - } - } - return false; - } - -//output pre-formatted array keys and values - if (!function_exists('view_array')) { - function view_array($array, $exit = true, $return = false) { - $html = "
".print_r($array, true).'

'; - if ($return) { - return $html; - } - else { - echo $html; - } - $exit and exit(); - } - } - -//format db date and/or time to local date and/or time - if (!function_exists('format_when_local')) { - function format_when_local($when, $format = 'dt', $include_seconds = false) { - if ($when != '') { - // determine when format - if (substr_count($when, ' ') > 0) { // date and time - $tmp = explode(' ', $when); - $date = $tmp[0]; - $time = $tmp[1]; - } - else if (substr_count($when, '-') > 0) { // date only - $date = $when; - } - else if (substr_count($when, ':') > 0) { // time only - $time = $when; - } - unset($when, $tmp); - - // format date - if ($date != '') { - $tmp = explode('-', $date); - $date = $tmp[1].'-'.$tmp[2].'-'.$tmp[0]; - } - - // format time - if ($time != '') { - $tmp = explode(':', $time); - if ($tmp[0] >= 0 && $tmp[0] <= 11) { - $meridiem = 'AM'; - $hour = ($tmp[0] == 0) ? 12 : $tmp[0]; - } - else { - $meridiem = 'PM'; - $hour = ($tmp[0] > 12) ? ($tmp[0] - 12) : $tmp[0]; - } - $minute = $tmp[1]; - $second = $tmp[2]; - } - - // structure requested time format - $time = $hour.':'.$minute; - if ($include_seconds) { $time .= ':'.$second; } - $time .= ' '.$meridiem; - - $return['d'] = $date; - $return['t'] = $time; - $return['dt'] = $date.' '.$time; - - return $return[$format]; - } - else { - return false; - } - } - } - -//define email button (src: https://buttons.cm) - if (!function_exists('email_button')) { - function email_button($text = 'Click Here!', $link = URL, $bg_color = '#dddddd', $fg_color = '#000000', $radius = '') { - - // default button radius - $radius = $radius != '' ? $radius : '3px'; - - // retrieve single/first numeric radius value for ms arc - $tmp = $radius; - if (substr_count($radius, ' ') > 0) { - $tmp = explode(' ', $radius); - $tmp = $tmp[0]; - } - $tmp = preg_replace("/[^0-9,.]/", '', $tmp); // remove non-numeric characters - $arc = floor($tmp / 35 * 100); // calculate percentage - - // create button code - $btn = " -
- - ".$text." - -
- "; - - return $btn; - } - } - -//validate and format order by clause of select statement - if (!function_exists('order_by')) { - function order_by($col, $dir, $col_default = '', $dir_default = 'asc') { - $order_by = ' order by '; - $col = preg_replace('#[^a-zA-Z0-9-_.]#', '', $col ?? ''); - if(!empty($dir)) - $dir = strtolower($dir) == 'desc' ? 'desc' : 'asc'; - if ($col != '') { - return $order_by.$col.' '.$dir.' '; - } - else if (is_array($col_default) || $col_default != '') { - if (is_array($col_default) && @sizeof($col_default) != 0) { - foreach ($col_default as $k => $column) { - $direction = (is_array($dir_default) && @sizeof($dir_default) != 0 && (strtolower($dir_default[$k]) == 'asc' || strtolower($dir_default[$k]) == 'desc')) ? $dir_default[$k] : 'asc'; - $order_bys[] = $column.' '.$direction.' '; - } - if (is_array($order_bys) && @sizeof($order_bys) != 0) { - return $order_by.implode(', ', $order_bys); - } - } - else { - return $order_by.$col_default.' '.$dir_default.' '; - } - } - } - } - -//validate and format limit and offset clause of select statement - if (!function_exists('limit_offset')) { - function limit_offset($limit = null, $offset = 0) { - $regex = '#[^0-9]#'; - if (!empty($limit)) { - $limit = preg_replace($regex, '', $limit); - $offset = preg_replace($regex, '', $offset ?? ''); - if (is_numeric($limit) && $limit > 0) { - $clause = ' limit '.$limit; - $offset = is_numeric($offset) ? $offset : 0; - $clause .= ' offset '.$offset; - } - return $clause.' '; - } - else { - return ''; - } - } - } - -//add a random_bytes function when it doesn't exist for old versions of PHP - if (!function_exists('random_bytes')) { - function random_bytes($length) { - $chars .= "0123456789"; - $chars .= "abcdefghijkmnopqrstuvwxyz"; - $chars .= "ABCDEFGHIJKLMNPQRSTUVWXYZ"; - for ($i = 0; $i < $length; $i++) { - $string .= $chars[random_int(0, strlen($chars)-1)]; - } - return $string.' '; - } - } - -//add a hash_equals function when it doesn't exist for old versions of PHP - if (!function_exists('hash_equals')) { - function hash_equals($var1, $var2) { - if ($var1 == $var2) { - return true; - } - else { - return false; - } - } - } - -//convert bytes to readable human format - if (!function_exists('byte_convert')) { - function byte_convert($bytes, $precision = 2) { - static $units = array('B','KB','MB','GB','TB','PB','EB','ZB','YB'); - $step = 1024; - $i = 0; - while (($bytes / $step) > 0.9) { - $bytes = $bytes / $step; - $i++; - } - return round($bytes, $precision).' '.$units[$i]; - } - } - -//convert bytes to readable human format - if (!function_exists('random_int')) { - function random_int($min, $max) { - return rand ($min, $max); - } - } - -//manage submitted form values in a session array - if (!function_exists('persistent_form_values')) { - function persistent_form_values($action, $array = null) { - switch ($action) { - case 'store': - // $array is expected to be an array of key / value pairs to store in the session - if (is_array($array) && @sizeof($array) != 0) { - $_SESSION['persistent'][$_SERVER['PHP_SELF']] = $array; - } - break; - case 'exists': - return !empty($_SESSION['persistent']) && is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0 ? true : false; - break; - case 'load': - // $array is expected to be the name of the array to create containing the key / value pairs - if ($array && !is_array($array)) { - global $$array; - } - if (!empty($_SESSION['persistent']) && is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0) { - foreach ($_SESSION['persistent'][$_SERVER['PHP_SELF']] as $key => $value) { - if ($key != 'XID' && $key != 'ACT' && $key != 'RET') { - if ($array && !is_array($array)) { - $$array[$key] = $value; - } - else { - global $$key; - $$key = $value; - } - } - } - global $unsaved; - $unsaved = true; - } - break; - case 'view': - if (is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0) { - view_array($_SESSION['persistent'][$_SERVER['PHP_SELF']], false); - } - break; - case 'clear': - unset($_SESSION['persistent'][$_SERVER['PHP_SELF']]); - break; - } - } - } - -//add alternative array_key_first for older verisons of PHP - if (!function_exists('array_key_first')) { - function array_key_first(array $arr) { - foreach($arr as $key => $unused) { - return $key; - } - return NULL; - } - } - -//get accountcode - if (!function_exists('get_accountcode')) { - function get_accountcode() { - if (!empty($accountcode = $_SESSION['domain']['accountcode']['text'] ?? '')) { - if ($accountcode == "none") { - return; - } - } - else { - $accountcode = $_SESSION['domain_name']; - } - return $accountcode; - } - } - -// User exists - if (!function_exists('user_exists')) { - function user_exists($login, $domain_name = null) { - //connect to freeswitch - $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); - if (!$fp) { - return false; - } - - //send the user_exists command to freeswitch - if ($fp) { - if (is_null($domain_name)) { - $domain_name = $_SESSION['domain_name']; - } - $switch_cmd = "user_exists id '$login' '$domain_name'"; - $switch_result = event_socket_request($fp, 'api '.$switch_cmd); - fclose($fp); - return ($switch_result == 'true' ? true: false); - } - - //can not create directory - return null; - } - } - -?> + + Portions created by the Initial Developer are Copyright (C) 2008-2022 + the Initial Developer. All Rights Reserved. + + Contributor(s): + Mark J Crane + Luis Daniel Lucio Quiroz +*/ + + if (!function_exists('mb_strtoupper')) { + function mb_strtoupper($string) { + return strtoupper($string); + } + } + + if (!function_exists('check_float')) { + function check_float($string) { + $string = str_replace(",",".",$string ?? ''); + return trim($string); + } + } + + if (!function_exists('check_str')) { + function check_str($string, $trim = true) { + global $db_type, $db; + //when code in db is urlencoded the ' does not need to be modified + if ($db_type == "sqlite") { + if (function_exists('sqlite_escape_string')) { + $string = sqlite_escape_string($string); + } + else { + $string = str_replace("'","''",$string); + } + } + if ($db_type == "pgsql") { + $string = str_replace("'","''",$string); + } + if ($db_type == "mysql") { + if(function_exists('mysql_real_escape_string')){ + $tmp_str = mysql_real_escape_string($string); + } + else { + $tmp_str = mysqli_real_escape_string($db, $string); + } + if (!empty($tmp_str)) { + $string = $tmp_str; + } + else { + $search = array("\x00", "\n", "\r", "\\", "'", "\"", "\x1a"); + $replace = array("\\x00", "\\n", "\\r", "\\\\" ,"\'", "\\\"", "\\\x1a"); + $string = str_replace($search, $replace, $string); + } + } + $string = ($trim) ? trim($string) : $string; + return $string; + } + } + + if (!function_exists('check_sql')) { + function check_sql($string) { + return trim($string); //remove white space + } + } + + if (!function_exists('check_cidr')) { + function check_cidr($cidr, $ip_address) { + if (isset($cidr) && !empty($cidr)) { + list ($subnet, $mask) = explode ('/', $cidr); + return ( ip2long ($ip_address) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet); + } + else { + return false; + } + } + } + + if (!function_exists('fix_postback')) { + function fix_postback($post_array) { + foreach ($post_array as $index => $value) { + if (is_array($value)) { fix_postback($value); } + else { + $value = str_replace('"', """, $value); + $value = str_replace("'", "'", $value); + $post_array[$index] = $value; + } + } + return $post_array; + } + } + + if (!function_exists('uuid')) { + function uuid() { + $uuid = null; + if (PHP_OS === 'FreeBSD') { + $uuid = trim(shell_exec("uuid -v 4")); + if (is_uuid($uuid)) { + return $uuid; + } + else { + echo "Please install the following package.\n"; + echo "pkg install ossp-uuid\n"; + exit; + } + } + if (PHP_OS === 'Linux') { + $uuid = trim(file_get_contents('/proc/sys/kernel/random/uuid')); + if (is_uuid($uuid)) { + return $uuid; + } + else { + $uuid = trim(shell_exec("uuidgen")); + if (is_uuid($uuid)) { + return $uuid; + } + else { + echo "Please install the uuidgen.\n"; + exit; + } + } + } + if ((strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') && function_exists('com_create_guid')) { + $uuid = trim(com_create_guid(), '{}'); + if (is_uuid($uuid)) { + return $uuid; + } + else { + echo "The com_create_guid() function failed to create a uuid.\n"; + exit; + } + } + } + } + + if (!function_exists('is_uuid')) { + function is_uuid($uuid) { + if (gettype($uuid) == 'string') { + $regex = '/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i'; + return preg_match($regex, $uuid); + } + return false; + } + } + + if (!function_exists('is_xml')) { + function is_xml($string) { + $pattern = '/^<\?xml(?:\s+[^>]+\s*)?\?>\s*<(\w+)>.*<\/\1>\s*$/s'; + return preg_match($pattern, $string) === 1; + } + } + + if (!function_exists('recursive_copy')) { + if (file_exists('/bin/cp')) { + function recursive_copy($source, $destination, $options = '') { + if (strtoupper(substr(PHP_OS, 0, 3)) === 'SUN') { + //copy -R recursive, preserve attributes for SUN + $cmd = 'cp -Rp '.$source.'/* '.$destination; + } + else { + //copy -R recursive, -L follow symbolic links, -p preserve attributes for other Posix systemss + $cmd = 'cp -RLp '.$options.' '.$source.'/* '.$destination; + } + exec ($cmd); + } + } + elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + function recursive_copy($source, $destination, $options = '') { + $source = normalize_path_to_os($source); + $destination = normalize_path_to_os($destination); + exec("xcopy /E /Y \"$source\" \"$destination\""); + } + } + else { + function recursive_copy($source, $destination, $options = '') { + $dir = opendir($source); + if (!$dir) { + throw new Exception("recursive_copy() source directory '".$source."' does not exist."); + } + if (!is_dir($destination)) { + if (!mkdir($destination,02770,true)) { + throw new Exception("recursive_copy() failed to create destination directory '".$destination."'"); + } + } + while(false !== ( $file = readdir($dir)) ) { + if (( $file != '.' ) && ( $file != '..' )) { + if ( is_dir($source . '/' . $file) ) { + recursive_copy($source . '/' . $file,$destination . '/' . $file); + } + else { + copy($source . '/' . $file,$destination . '/' . $file); + } + } + } + closedir($dir); + } + } + } + + if (!function_exists('recursive_delete')) { + if (file_exists('/usr/bin/find')) { + function recursive_delete($directory) { + if (isset($directory) && strlen($directory) > 8) { + exec('/usr/bin/find '.$directory.'/* -name "*" -delete'); + //exec('rm -Rf '.$directory.'/*'); + clearstatcache(); + } + } + } + elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + function recursive_delete($directory) { + $directory = normalize_path_to_os($directory); + //$this->write_debug("del /S /F /Q \"$dir\""); + exec("del /S /F /Q \"$directory\""); + clearstatcache(); + } + } + else { + function recursive_delete($directory) { + foreach (glob($directory) as $file) { + if (is_dir($file)) { + //$this->write_debug("rm dir: ".$file); + recursive_delete("$file/*"); + rmdir($file); + } + else { + //$this->write_debug("delete file: ".$file); + unlink($file); + } + } + clearstatcache(); + } + } + } + + if (!function_exists('if_group')) { + function if_group($group) { + //set default false + $result = false; + //search for the permission + if (count($_SESSION["groups"]) > 0) { + foreach($_SESSION["groups"] as $row) { + if ($row['group_name'] == $group) { + $result = true; + break; + } + } + } + //return the result + return $result; + } + } + + if (!function_exists('permission_exists')) { + function permission_exists($permission, $operator = 'or') { + //set default + $result = false; + //permissions exist + if (is_array($_SESSION["permissions"]) && @sizeof($_SESSION['permissions']) != 0) { + //array + if (is_array($permission) && @sizeof($permission) != 0) { + if ($operator == 'and') { + $exists_all = true; + foreach ($permission as $perm) { + if ($_SESSION["permissions"][$permission] != true) { + $exists_all = false; + break; + } + } + $result = $exists_all; + } + else { + $exists_one = false; + foreach ($permission as $perm) { + if (isset($_SESSION["permissions"][$perm]) && $_SESSION["permissions"][$perm] != true) { + $exists_one = true; + break; + } + } + $result = $exists_one; + } + } + //single + else { + if (isset($_SESSION["permissions"][$permission]) && $_SESSION["permissions"][$permission] == true) { + $result = true; + } + } + } + //return the result + return $result; + } + } + + if (!function_exists('if_group_member')) { + function if_group_member($group_members, $group) { + if (stripos($group_members, "||".$group."||") === false) { + return false; //group does not exist + } + else { + return true; //group exists + } + } + } + + if (!function_exists('superadmin_list')) { + function superadmin_list() { + global $domain_uuid; + $sql = "select * from v_user_groups "; + $sql .= "where group_name = 'superadmin' "; + $database = new database; + $result = $database->select($sql, null, 'all'); + $superadmin_list = "||"; + if (is_array($result) && @sizeof($result) != 0) { + foreach ($result as $field) { + //get the list of superadmins + $superadmin_list .= $field['user_uuid']."||"; + } + } + unset($sql, $result, $field); + return $superadmin_list; + } + } + + if (!function_exists('if_superadmin')) { + function if_superadmin($superadmin_list, $user_uuid) { + if (stripos($superadmin_list, "||".$user_uuid."||") === false) { + return false; + } + else { + return true; //user_uuid exists + } + } + } + + if (!function_exists('html_select_other')) { + function html_select_other($table_name, $field_name, $sql_where_optional, $field_current_value, $sql_order_by = null, $label_other = 'Other...') { + //html select other: build a select box from distinct items in db with option for other + global $domain_uuid; + $table_name = preg_replace("#[^a-zA-Z0-9_]#", "", $table_name); + $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name); + + $html = "\n"; + $html .= "\n"; + $html .= "\n"; + $html .= "\n"; + $html .= "\n"; + $html .= "
\n"; + $html .= "\n"; + $html .= "\n"; + $html .= "\n"; + $html .= "\n"; + $html .= "
"; + + return $html; + } + } + + if (!function_exists('html_select')) { + function html_select($table_name, $field_name, $sql_where_optional, $field_current_value, $field_value = '', $style = '', $on_change = '') { + //html select: build a select box from distinct items in db + global $domain_uuid; + + $table_name = preg_replace("#[^a-zA-Z0-9_]#", "", $table_name); + $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name); + $field_value = preg_replace("#[^a-zA-Z0-9_]#", "", $field_value); + + if (!empty($field_value)) { + $html .= "\n"; + $html .= " \n"; + + $sql = "select distinct(".$field_name.") as ".$field_name." from ".$table_name." ".$sql_where_optional." "; + } + + $database = new database; + $result = $database->select($sql, null, 'all'); + if (is_array($result) && @sizeof($result) != 0) { + foreach($result as $field) { + if (!empty($field[$field_name])) { + $selected = $field_current_value == $field[$field_name] ? "selected='selected'" : null; + $array_key = empty($field_value) ? $field_name : $field_value; + $html .= "\n"; + } + } + } + unset($sql, $result, $field); + $html .= "\n"; + + return $html; + } + } + + if (!function_exists('th_order_by')) { + //html table header order by + function th_order_by($field_name, $column_title, $order_by, $order, $app_uuid = '', $css = '', $http_get_params = '', $description = '') { + global $text; + if (is_uuid($app_uuid) > 0) { $app_uuid = "&app_uuid=".urlencode($app_uuid); } // accomodate need to pass app_uuid where necessary (inbound/outbound routes lists) + + $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name); + $field_value = preg_replace("#[^a-zA-Z0-9_]#", "", $field_value ?? ''); + + $sanitized_parameters = ''; + if (isset($http_get_params) && !empty($http_get_params)) { + $parameters = explode('&', $http_get_params); + if (is_array($parameters)) { + foreach ($parameters as $parameter) { + if (substr_count($parameter, '=') != 0) { + $array = explode('=', $parameter); + $key = preg_replace('#[^a-zA-Z0-9_\-]#', '', $array['0']); + $value = urldecode($array['1']); + if ($key == 'order_by' && !empty($value)) { + //validate order by + $sanitized_parameters .= "&order_by=". preg_replace('#[^a-zA-Z0-9_\-]#', '', $value); + } + else if ($key == 'order' && !empty($value)) { + //validate order + switch ($value) { + case 'asc': + $sanitized_parameters .= "&order=asc"; + break; + case 'desc': + $sanitized_parameters .= "&order=desc"; + break; + } + } + else if (!empty($value) && is_numeric($value)) { + $sanitized_parameters .= "&".$key."=".$value; + } + else { + $sanitized_parameters .= "&".$key."=".urlencode($value); + } + } + } + } + } + + $html = ""; + $description = empty($description) ? '' : $description . ', '; + if (empty($order_by)) { + $order = 'asc'; + } + if ($order_by == $field_name) { + if ($order == "asc") { + $description .= $text['label-order'].' '.$text['label-descending']; + $html .= "".escape($column_title).""; + } + else { + $description .= $text['label-order'].' '.$text['label-ascending']; + $html .= "".escape($column_title).""; + } + } + else { + $description .= $text['label-order'].' '.$text['label-ascending']; + $html .= "".escape($column_title).""; + } + $html .= ""; + return $html; + } + } + + if (!function_exists('get_ext')) { + function get_ext($filename) { + preg_match('/[^?]*/', $filename, $matches); + $string = $matches[0]; + + $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE); + + // check if there is any extension + if(count($pattern) == 1){ + //echo 'No File Extension Present'; + return ''; + } + + if(count($pattern) > 1) { + $filenamepart = $pattern[count($pattern)-1][0]; + preg_match('/[^?]*/', $filenamepart, $matches); + return $matches[0]; + } + } + //echo "ext: ".get_ext('test.txt'); + } + + if (!function_exists('file_upload')) { + function file_upload($field = '', $file_type = '', $dest_dir = '') { + + $uploadtempdir = $_ENV["TEMP"]."\\"; + ini_set('upload_tmp_dir', $uploadtempdir); + + $tmp_name = $_FILES[$field]["tmp_name"]; + $file_name = $_FILES[$field]["name"]; + $file_type = $_FILES[$field]["type"]; + $file_size = $_FILES[$field]["size"]; + $file_ext = get_ext($file_name); + $file_name_orig = $file_name; + $file_name_base = substr($file_name, 0, (strlen($file_name) - (strlen($file_ext)+1))); + //$dest_dir = '/tmp'; + + if ($file_size == 0) { + return; + } + + if (!is_dir($dest_dir)) { + echo "dest_dir not found
\n"; + return; + } + + //check if allowed file type + if ($file_type == "img") { + switch (strtolower($file_ext)) { + case "jpg": + case "png": + case "gif": + case "bmp": + case "psd": + case "tif": break; + default: return false; + } + } + if ($file_type == "file") { + switch (strtolower($file_ext)) { + case "doc": + case "pdf": + case "ppt": + case "xls": + case "zip": + case "exe": break; + default: return false; + } + } + + //find unique filename: check if file exists if it does then increment the filename + $i = 1; + while( file_exists($dest_dir.'/'.$file_name)) { + if (!empty($file_ext)) { + $file_name = $file_name_base . $i .'.'. $file_ext; + } + else { + $file_name = $file_name_orig . $i; + } + $i++; + } + + //echo "file_type: ".$file_type."
\n"; + //echo "tmp_name: ".$tmp_name."
\n"; + //echo "file_name: ".$file_name."
\n"; + //echo "file_ext: ".$file_ext."
\n"; + //echo "file_name_orig: ".$file_name_orig."
\n"; + //echo "file_name_base: ".$file_name_base."
\n"; + //echo "dest_dir: ".$dest_dir."
\n"; + + //move the file to upload directory + //bool move_uploaded_file ( string $filename, string $destination ) + + if (move_uploaded_file($tmp_name, $dest_dir.'/'.$file_name)) { + return $file_name; + } + else { + echo "File upload failed! Here's some debugging info:\n"; + return false; + } + exit; + + } + } + + if (!function_exists('sys_get_temp_dir')) { + function sys_get_temp_dir() { + if ($temp = getenv('TMP')) { return $temp; } + if ($temp = getenv('TEMP')) { return $temp; } + if ($temp = getenv('TMPDIR')) { return $temp; } + $temp = tempnam(__FILE__,''); + if (file_exists($temp)) { + unlink($temp); + return dirname($temp); + } + return null; + } + } + //echo realpath(sys_get_temp_dir()); + + if (!function_exists('normalize_path')) { + //don't use DIRECTORY_SEPARATOR as it will change on a per platform basis and we need consistency + function normalize_path($path) { + return str_replace(array('/','\\'), '/', $path); + } + } + + if (!function_exists('normalize_path_to_os')) { + function normalize_path_to_os($path) { + return str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $path); + } + } + + if (!function_exists('username_exists')) { + function username_exists($username) { + global $domain_uuid; + $sql = "select count(*) from v_users "; + $sql .= "where domain_uuid = :domain_uuid "; + $sql .= "and username = :username "; + $parameters['domain_uuid'] = $domain_uuid; + $parameters['username'] = $username; + $database = new database; + $num_rows = $database->select($sql, $parameters, 'column'); + return $num_rows > 0 ? true : false; + } + } + + if (!function_exists('add_extension_user')) { + function add_extension_user($extension_uuid, $username) { + global $domain_uuid; + //get the user_uuid by using the username + $sql = "select user_uuid from v_users "; + $sql .= "where domain_uuid = :domain_uuid "; + $sql .= "and username = :username "; + $parameters['domain_uuid'] = $domain_uuid; + $parameters['username'] = $username; + $database = new database; + $user_uuid = $database->select($sql, $parameters, 'column'); + unset($sql, $parameters); + + if (is_uuid($user_uuid)) { + //check if the user_uuid exists in v_extension_users + $sql = "select count(*) from v_extension_users "; + $sql .= "where domain_uuid = :domain_uuid "; + $sql .= "and user_uuid = :user_uuid "; + $parameters['domain_uuid'] = $domain_uuid; + $parameters['user_uuid'] = $user_uuid; + $database = new database; + $num_rows = $database->select($sql, $parameters, 'column'); + unset($sql, $parameters); + + //assign the extension to the user + if ($num_rows == 0) { + //build insert array + $extension_user_uuid = uuid(); + $array['extension_users'][$x]['extension_user_uuid'] = $extension_user_uuid; + $array['extension_users'][$x]['domain_uuid'] = $domain_uuid; + $array['extension_users'][$x]['extension_uuid'] = $extension_uuid; + $array['extension_users'][$x]['user_uuid'] = $row["user_uuid"]; + //grant temporary permissions + $p = new permissions; + $p->add('extension_user_add', 'temp'); + //execute insert + $database = new database; + $database->app_name = 'function-add_extension_user'; + $database->app_uuid = 'e68d9689-2769-e013-28fa-6214bf47fca3'; + $database->save($array); + unset($array); + //revoke temporary permissions + $p->delete('extension_user_add', 'temp'); + } + } + } + } + + if (!function_exists('user_add')) { + function user_add($username, $password, $user_email = '') { + global $domain_uuid; + if (empty($username)) { return false; } + if (empty($password)) { return false; } + if (!username_exists($username)) { + //build user insert array + $user_uuid = uuid(); + $salt = generate_password('20', '4'); + $array['users'][0]['user_uuid'] = $user_uuid; + $array['users'][0]['domain_uuid'] = $domain_uuid; + $array['users'][0]['username'] = $username; + $array['users'][0]['password'] = md5($salt.$password); + $array['users'][0]['salt'] = $salt; + if (valid_email($user_email)) { + $array['users'][0]['user_email'] = $user_email; + } + $array['users'][0]['add_date'] = 'now()'; + $array['users'][0]['add_user'] = $_SESSION["username"]; + + //build user group insert array + $user_group_uuid = uuid(); + $array['user_groups'][0]['user_group_uuid'] = $user_group_uuid; + $array['user_groups'][0]['domain_uuid'] = $domain_uuid; + $array['user_groups'][0]['group_name'] = 'user'; + $array['user_groups'][0]['user_uuid'] = $user_uuid; + + //grant temporary permissions + $p = new permissions; + $p->add('user_add', 'temp'); + $p->add('user_group_add', 'temp'); + //execute insert + $database = new database; + $database->app_name = 'function-user_add'; + $database->app_uuid = '15a8d74b-ac7e-4468-add4-3e6ebdcb8e22'; + $database->save($array); + unset($array); + //revoke temporary permissions + $p->delete('user_add', 'temp'); + $p->delete('user_group_add', 'temp'); + } + } + } + +function switch_module_is_running($fp, $mod) { + if (!$fp) { + //if the handle does not exist create it + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + //if the handle still does not exist show an error message + if (!$fp) { + $msg = "
Connection to Event Socket failed.
"; + } + } + if ($fp) { + //send the api command to check if the module exists + $switchcmd = "module_exists $mod"; + $switch_result = event_socket_request($fp, 'api '.$switchcmd); + unset($switchcmd); + if (trim($switch_result) == "true") { + return true; + } + else { + return false; + } + } + else { + return false; + } +} +//switch_module_is_running('mod_spidermonkey'); + +//format a number (n) replace with a number (r) remove the number +function format_string($format, $data) { + //nothing to do so return + if(empty($format)) + return $data; + + //preset values + $x=0; + $tmp = ''; + + //count the characters + $format_count = substr_count($format, 'x'); + $format_count = $format_count + substr_count($format, 'R'); + $format_count = $format_count + substr_count($format, 'r'); + + //format the string if it matches + if ($format_count == strlen($data)) { + for ($i = 0; $i <= strlen($format); $i++) { + $tmp_format = strtolower(substr($format, $i, 1)); + if ($tmp_format == 'x') { + $tmp .= substr($data, $x, 1); + $x++; + } + elseif ($tmp_format == 'r') { + $x++; + } + else { + $tmp .= $tmp_format; + } + } + } + if (empty($tmp)) { + return $data; + } + else { + return $tmp; + } +} + +//get the format and use it to format the phone number + function format_phone($phone_number) { + if (is_numeric(trim($phone_number ?? '', ' +'))) { + if (isset($_SESSION["format"]["phone"])) { + $phone_number = trim($phone_number, ' +'); + foreach ($_SESSION["format"]["phone"] as &$format) { + $format_count = substr_count($format, 'x'); + $format_count = $format_count + substr_count($format, 'R'); + $format_count = $format_count + substr_count($format, 'r'); + if ($format_count == strlen($phone_number)) { + //format the number + $phone_number = format_string($format, $phone_number); + } + } + } + } + return $phone_number; + } + +//format seconds into hh:mm:ss + function format_hours($seconds) { + $hours = floor($seconds / 3600); + $minutes = floor(floor($seconds / 60) % 60); + $seconds = $seconds % 60; + if (strlen($minutes) == 1) { $minutes = '0'.$minutes; } + if (strlen($seconds) == 1) { $seconds = '0'.$seconds; } + return "$hours:$minutes:$seconds"; + } + +//browser detection without browscap.ini dependency + function http_user_agent($info = '') { + + //set default values + $user_agent = $_SERVER['HTTP_USER_AGENT']; + $browser_name = 'Unknown'; + $platform = 'Unknown'; + $version = ''; + $mobile = false; + + //get the platform + if (preg_match('/linux/i', $user_agent)) { + $platform = 'Linux'; + } + elseif (preg_match('/macintosh|mac os x/i', $user_agent)) { + $platform = 'Apple'; + } + elseif (preg_match('/windows|win32/i', $user_agent)) { + $platform = 'Windows'; + } + + //set mobile to true or false + if (preg_match('/mobile/i', $user_agent)) { + $platform = 'Mobile'; + $mobile = true; + } + elseif (preg_match('/android/i', $user_agent)) { + $platform = 'Android'; + $mobile = true; + } + + //get the name of the useragent + if (preg_match('/MSIE/i',$user_agent) || preg_match('/Trident/i',$user_agent)) { + $browser_name = 'Internet Explorer'; + $browser_name_short = 'MSIE'; + } + elseif (preg_match('/Firefox/i',$user_agent)) { + $browser_name = 'Mozilla Firefox'; + $browser_name_short = 'Firefox'; + } + elseif (preg_match('/Chrome/i',$user_agent)) { + $browser_name = 'Google Chrome'; + $browser_name_short = 'Chrome'; + } + elseif (preg_match('/Safari/i',$user_agent)) { + $browser_name = 'Apple Safari'; + $browser_name_short = 'Safari'; + } + elseif (preg_match('/Opera/i',$user_agent)) { + $browser_name = 'Opera'; + $browser_name_short = 'Opera'; + } + elseif (preg_match('/Netscape/i',$user_agent)) { + $browser_name = 'Netscape'; + $browser_name_short = 'Netscape'; + } + else { + $browser_name = 'Unknown'; + $browser_name_short = 'Unknown'; + } + + //finally get the correct version number + $known = array('Version', $browser_name_short, 'other'); + $pattern = '#(?' . join('|', $known) . ')[/ ]+(?[0-9.|a-zA-Z.]*)#'; + if (!preg_match_all($pattern, $user_agent, $matches)) { + //we have no matching number just continue + } + + //see how many we have + $i = count($matches['browser']); + if ($i != 1) { + //we will have two since we are not using 'other' argument yet + //see if version is before or after the name + if (strripos($user_agent,"Version") < strripos($user_agent,$browser_name_short)) { + $version= $matches['version'][0]; + } + else { + $version= $matches['version'][1]; + } + } + else { + $version= $matches['version'][0]; + } + + //check if we have a number + if ($version == null || $version == "") { $version = "?"; } + + //return the data + switch ($info) { + case "agent": return $user_agent; break; + case "name": return $browser_name; break; + case "name_short": return $browser_name_short; break; + case "version": return $version; break; + case "platform": return $platform; break; + case "mobile": return $mobile; break; + case "pattern": return $pattern; break; + default : + return array( + 'user_agent' => $user_agent, + 'name' => $browser_name, + 'name_short' => $browser_name_short, + 'version' => $version, + 'platform' => $platform, + 'mobile' => $mobile, + 'pattern' => $pattern + ); + } + } + +//tail php function for non posix systems + function tail($file, $num_to_get=10) { + $fp = fopen($file, 'r'); + $position = filesize($file); + $chunklen = 4096; + if($position-$chunklen<=0) { + fseek($fp,0); + } + else { + fseek($fp, $position-$chunklen); + } + $data="";$ret="";$lc=0; + while($chunklen > 0) { + $data = fread($fp, $chunklen); + $dl=strlen($data); + for($i=$dl-1;$i>=0;$i--){ + if($data[$i]=="\n"){ + if($lc==0 && $ret!="")$lc++; + $lc++; + if($lc>$num_to_get)return $ret; + } + $ret=$data[$i].$ret; + } + if($position-$chunklen<=0){ + fseek($fp,0); + $chunklen=$chunklen-abs($position-$chunklen); + } + else { + fseek($fp, $position-$chunklen); + } + $position = $position - $chunklen; + } + fclose($fp); + return $ret; + } + +//generate a random password with upper, lowercase and symbols + function generate_password($length = 0, $strength = 0) { + $password = ''; + $chars = ''; + if ($length === 0 && $strength === 0) { //set length and strenth if specified in default settings and strength isn't numeric-only + $length = (is_numeric($_SESSION["users"]["password_length"]["numeric"])) ? $_SESSION["users"]["password_length"]["numeric"] : 20; + $strength = (is_numeric($_SESSION["users"]["password_strength"]["numeric"])) ? $_SESSION["users"]["password_strength"]["numeric"] : 4; + } + if ($strength >= 1) { $chars .= "0123456789"; } + if ($strength >= 2) { $chars .= "abcdefghijkmnopqrstuvwxyz"; } + if ($strength >= 3) { $chars .= "ABCDEFGHIJKLMNPQRSTUVWXYZ"; } + if ($strength >= 4) { $chars .= "!^$%*?."; } + for ($i = 0; $i < $length; $i++) { + $password .= $chars[random_int(0, strlen($chars)-1)]; + } + return $password; + } + +//check password strength against requirements (if any) + function check_password_strength($password, $text, $type = 'default') { + if ($password != '') { + if ($type == 'default') { + $req['length'] = $_SESSION['extension']['password_length']['numeric']; + $req['number'] = ($_SESSION['extension']['password_number']['boolean'] == 'true') ? true : false; + $req['lowercase'] = ($_SESSION['extension']['password_lowercase']['boolean'] == 'true') ? true : false; + $req['uppercase'] = ($_SESSION['extension']['password_uppercase']['boolean'] == 'true') ? true : false; + $req['special'] = ($_SESSION['extension']['password_special']['boolean'] == 'true') ? true : false; + } elseif ($type == 'user') { + $req['length'] = $_SESSION['user']['password_length']['numeric']; + $req['number'] = ($_SESSION['user']['password_number']['boolean'] == 'true') ? true : false; + $req['lowercase'] = ($_SESSION['user']['password_lowercase']['boolean'] == 'true') ? true : false; + $req['uppercase'] = ($_SESSION['user']['password_uppercase']['boolean'] == 'true') ? true : false; + $req['special'] = ($_SESSION['user']['password_special']['boolean'] == 'true') ? true : false; + } + if (is_numeric($req['length']) && $req['length'] != 0 && !preg_match_all('$\S*(?=\S{'.$req['length'].',})\S*$', $password)) { // length + $msg_errors[] = $req['length'].'+ '.$text['label-characters']; + } + if ($req['number'] && !preg_match_all('$\S*(?=\S*[\d])\S*$', $password)) { //number + $msg_errors[] = '1+ '.$text['label-numbers']; + } + if ($req['lowercase'] && !preg_match_all('$\S*(?=\S*[a-z])\S*$', $password)) { //lowercase + $msg_errors[] = '1+ '.$text['label-lowercase_letters']; + } + if ($req['uppercase'] && !preg_match_all('$\S*(?=\S*[A-Z])\S*$', $password)) { //uppercase + $msg_errors[] = '1+ '.$text['label-uppercase_letters']; + } + if ($req['special'] && !preg_match_all('$\S*(?=\S*[\W])\S*$', $password)) { //special + $msg_errors[] = '1+ '.$text['label-special_characters']; + } + if (is_array($msg_errors) && sizeof($msg_errors) > 0) { + message::add($_SESSION["message"] = $text['message-password_requirements'].': '.implode(', ', $msg_errors), 'negative', 6000); + return false; + } + else { + return true; + } + } + return true; + } + +//based on Wez Furlong do_post_request + if (!function_exists('send_http_request')) { + function send_http_request($url, $data, $method = "POST", $optional_headers = null) { + $params = array('http' => array( + 'method' => $method, + 'content' => $data + )); + if ($optional_headers !== null) { + $params['http']['header'] = $optional_headers; + } + $ctx = stream_context_create($params); + $fp = @fopen($url, 'rb', false, $ctx); + if (!$fp) { + throw new Exception("Problem with $url, $php_errormsg"); + } + $response = @stream_get_contents($fp); + if ($response === false) { + throw new Exception("Problem reading data from $url, $php_errormsg"); + } + return $response; + } + } + +//convert the string to a named array + if(!function_exists('csv_to_named_array')) { + function csv_to_named_array($tmp_str, $tmp_delimiter) { + $tmp_array = explode ("\n", $tmp_str); + $result = array(); + if (trim(strtoupper($tmp_array[0])) !== "+OK") { + $tmp_field_name_array = explode ($tmp_delimiter, $tmp_array[0]); + $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; + } + } + +function get_time_zone_offset($remote_tz, $origin_tz = 'UTC') { + $origin_dtz = new DateTimeZone($origin_tz); + $remote_dtz = new DateTimeZone($remote_tz); + $origin_dt = new DateTime("now", $origin_dtz); + $remote_dt = new DateTime("now", $remote_dtz); + $offset = $remote_dtz->getOffset($remote_dt) - $origin_dtz->getOffset($origin_dt); + return $offset; +} + +function number_pad($number,$n) { + return str_pad((int) $number,$n,"0",STR_PAD_LEFT); +} + +// validate email address syntax + if(!function_exists('valid_email')) { + function valid_email($email) { + return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? true : false; + } + } + +//function to convert hexidecimal color value to rgb string/array value + if (!function_exists('hex_to_rgb')) { + function hex_to_rgb($hex, $delim = '') { + $hex = str_replace("#", "", $hex); + + if (strlen($hex) == 3) { + $r = hexdec(substr($hex,0,1).substr($hex,0,1)); + $g = hexdec(substr($hex,1,1).substr($hex,1,1)); + $b = hexdec(substr($hex,2,1).substr($hex,2,1)); + } + else { + $r = hexdec(substr($hex,0,2)); + $g = hexdec(substr($hex,2,2)); + $b = hexdec(substr($hex,4,2)); + } + $rgb = array($r, $g, $b); + + if ($delim != '') { + return implode($delim, $rgb); // return rgb delimited string + } + else { + return $rgb; // return array of rgb values + } + } + } + +//function to get a color's luminence level -- dependencies: rgb_to_hsl() + if (!function_exists('get_color_luminence')) { + function get_color_luminence($color) { + //convert hex to rgb + if (substr_count($color, ',') == 0) { + $color = str_replace(' ', '', $color); + $color = str_replace('#', '', $color); + if (strlen($color) == 3) { + $r = hexdec(substr($color,0,1).substr($color,0,1)); + $g = hexdec(substr($color,1,1).substr($color,1,1)); + $b = hexdec(substr($color,2,1).substr($color,2,1)); + } + else { + $r = hexdec(substr($color,0,2)); + $g = hexdec(substr($color,2,2)); + $b = hexdec(substr($color,4,2)); + } + $color = $r.','.$g.','.$b; + } + + //color to array, pop alpha + if (substr_count($color, ',') > 0) { + $color = str_replace(' ', '', $color); + $color = str_replace('rgb', '', $color); + $color = str_replace('a(', '', $color); + $color = str_replace(')', '', $color); + $color = explode(',', $color); + $hsl = rgb_to_hsl($color[0], $color[1], $color[2]); + } + + //return luminence value + return (is_array($hsl) && is_numeric($hsl[2])) ? $hsl[2] : null; + } + } + +//function to lighten or darken a hexidecimal, rgb, or rgba color value by a percentage -- dependencies: rgb_to_hsl(), hsl_to_rgb() + if (!function_exists('color_adjust')) { + function color_adjust($color, $percent) { + /* + USAGE + 20% Lighter + color_adjust('#3f4265', 0.2); + color_adjust('234,120,6,0.3', 0.2); + 20% Darker + color_adjust('#3f4265', -0.2); // + color_adjust('rgba(234,120,6,0.3)', -0.2); + RETURNS + Same color format provided (hex in = hex out, rgb(a) in = rgb(a) out) + */ + + //convert hex to rgb + if (substr_count($color, ',') == 0) { + $color = str_replace(' ', '', $color); + if (substr_count($color, '#') > 0) { + $color = str_replace('#', '', $color); + $hash = '#'; + } + if (strlen($color) == 3) { + $r = hexdec(substr($color,0,1).substr($color,0,1)); + $g = hexdec(substr($color,1,1).substr($color,1,1)); + $b = hexdec(substr($color,2,1).substr($color,2,1)); + } + else { + $r = hexdec(substr($color,0,2)); + $g = hexdec(substr($color,2,2)); + $b = hexdec(substr($color,4,2)); + } + $color = $r.','.$g.','.$b; + } + + //color to array, pop alpha + if (substr_count($color, ',') > 0) { + $color = str_replace(' ', '', $color); + $wrapper = false; + if (substr_count($color, 'rgb') != 0) { + $color = str_replace('rgb', '', $color); + $color = str_replace('a(', '', $color); + $color = str_replace(')', '', $color); + $wrapper = true; + } + $colors = explode(',', $color); + $alpha = (sizeof($colors) == 4) ? array_pop($colors) : null; + $color = $colors; + unset($colors); + + //adjust color using rgb > hsl > rgb conversion + $hsl = rgb_to_hsl($color[0], $color[1], $color[2]); + $hsl[2] = $hsl[2] + $percent; + $color = hsl_to_rgb($hsl[0], $hsl[1], $hsl[2]); + + //return adjusted color in format received + if (isset($hash) && $hash == '#') { //hex + $hex = ''; + for ($i = 0; $i <= 2; $i++) { + $hex_color = dechex($color[$i]); + if (strlen($hex_color) == 1) { $hex_color = '0'.$hex_color; } + $hex .= $hex_color; + } + return $hash.$hex; + } + else { //rgb(a) + $rgb = implode(',', $color); + if ($alpha != '') { $rgb .= ','.$alpha; $a = 'a'; } + if ($wrapper) { $rgb = 'rgb'.$a.'('.$rgb.')'; } + return $rgb; + } + } + + return $color; + } + } + +//function to convert an rgb color array to an hsl color array + if (!function_exists('rgb_to_hsl')) { + function rgb_to_hsl($r, $g, $b) { + $r /= 255; + $g /= 255; + $b /= 255; + + $max = max($r, $g, $b); + $min = min($r, $g, $b); + + $h; + $s; + $l = ($max + $min) / 2; + $d = $max - $min; + + if ($d == 0) { + $h = $s = 0; // achromatic + } + else { + $s = $d / (1 - abs((2 * $l) - 1)); + switch($max){ + case $r: + $h = 60 * fmod((($g - $b) / $d), 6); + if ($b > $g) { $h += 360; } + break; + case $g: + $h = 60 * (($b - $r) / $d + 2); + break; + case $b: + $h = 60 * (($r - $g) / $d + 4); + break; + } + } + + return array(round($h, 2), round($s, 2), round($l, 2)); + } + } + +//function to convert an hsl color array to an rgb color array + if (!function_exists('hsl_to_rgb')) { + function hsl_to_rgb($h, $s, $l){ + $r; + $g; + $b; + + $c = (1 - abs((2 * $l) - 1)) * $s; + $x = $c * (1 - abs(fmod(($h / 60), 2) - 1)); + $m = $l - ($c / 2); + + if ($h < 60) { + $r = $c; + $g = $x; + $b = 0; + } + else if ($h < 120) { + $r = $x; + $g = $c; + $b = 0; + } + else if ($h < 180) { + $r = 0; + $g = $c; + $b = $x; + } + else if ($h < 240) { + $r = 0; + $g = $x; + $b = $c; + } + else if ($h < 300) { + $r = $x; + $g = 0; + $b = $c; + } + else { + $r = $c; + $g = 0; + $b = $x; + } + + $r = ($r + $m) * 255; + $g = ($g + $m) * 255; + $b = ($b + $m) * 255; + + if ($r > 255) { $r = 255; } + if ($g > 255) { $g = 255; } + if ($b > 255) { $b = 255; } + + if ($r < 0) { $r = 0; } + if ($g < 0) { $g = 0; } + if ($b < 0) { $b = 0; } + + return array(floor($r), floor($g), floor($b)); + } + } + +//function to send email + if (!function_exists('send_email')) { + function send_email($email_recipients, $email_subject, $email_body, &$email_error = '', $email_from_address = '', $email_from_name = '', $email_priority = 3, $email_debug_level = 0, $email_attachments = '', $email_read_confirmation = false) { + /* + RECIPIENTS NOTE: + + Pass in a single email address... + + user@domain.com + + Pass in a comma or semi-colon delimited string of e-mail addresses... + + user@domain.com,user2@domain2.com,user3@domain3.com + user@domain.com;user2@domain2.com;user3@domain3.com + + Pass in a simple array of email addresses... + + Array ( + [0] => user@domain.com + [1] => user2@domain2.com + [2] => user3@domain3.com + ) + + Pass in a multi-dimentional array of addresses (delivery, address, name)... + + Array ( + [0] => Array ( + [delivery] => to + [address] => user@domain.com + [name] => user 1 + ) + [1] => Array ( + [delivery] => cc + [address] => user2@domain2.com + [name] => user 2 + ) + [2] => Array ( + [delivery] => bcc + [address] => user3@domain3.com + [name] => user 3 + ) + ) + + ATTACHMENTS NOTE: + + Pass in as many files as necessary in an array in the following format... + + Array ( + [0] => Array ( + [type] => file (or 'path') + [name] => filename.ext + [value] => /folder/filename.ext + ) + [1] => Array ( + [type] => string + [name] => filename.ext + [value] => (string of file contents - if base64, will be decoded automatically) + ) + ) + + ERROR RESPONSE: + + Error messages are stored in the variable passed into $email_error BY REFERENCE + + */ + + //add the email recipients + $address_found = false; + if (!is_array($email_recipients)) { // must be a single or delimited recipient address(s) + $email_recipients = str_replace(' ', '', $email_recipients); + $email_recipients = str_replace(',', ';', $email_recipients); + $email_recipients = explode(';', $email_recipients); // convert to array of addresses + } + + foreach ($email_recipients as $email_recipient) { + if (is_array($email_recipient)) { // check if each recipient has multiple fields + if ($email_recipient["address"] != '' && valid_email($email_recipient["address"])) { // check if valid address + $recipients = $email_recipient["address"]; + $address_found = true; + } + } + else if ($email_recipient != '' && valid_email($email_recipient)) { // check if recipient value is simply (only) an address + $email_recipients = $email_recipient; + $address_found = true; + } + } + if (is_array($recipients)) { + $email_recipients = implode(",", $recipients); + } + if (!$address_found) { + $email_error = "No valid e-mail address provided."; + return false; + } + + //get the from address and name + $email_from_address = ($email_from_address != '') ? $email_from_address : $_SESSION['email']['smtp_from']['text']; + $email_from_name = ($email_from_name != '') ? $email_from_name : $_SESSION['email']['smtp_from_name']['text']; + + //send email + $email = new email; + $email->recipients = $email_recipients; + $email->subject = $email_subject; + $email->body = $email_body; + $email->from_address = $email_from_address; + $email->from_name = $email_from_name; + $email->attachments = $email_attachments; + $email->debug_level = 3; + $sent = $email->send(); + //$email_error = $email->email_error; + + } + } + +//encrypt a string + if (!function_exists('encrypt')) { + function encrypt($key, $data) { + $encryption_key = base64_decode($key); + $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); + $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv); + return base64_encode($encrypted.'::'.$iv); + } + } + +//decrypt a string + if (!function_exists('decrypt')) { + function decrypt($key, $data) { + $encryption_key = base64_decode($key); + list($encrypted_data, $iv) = explode('::', base64_decode($data), 2); + return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv); + } + } + +//json detection + if (!function_exists('is_json')) { + function is_json($str) { + return (is_string($str) && is_object(json_decode($str))) ? true : false; + } + } + +//mac detection + if (!function_exists('is_mac')) { + function is_mac($str) { + return (preg_match('/([a-fA-F0-9]{2}[:|\-]?){6}/', $str) == 1) ? true : false; + } + } + +//detect if php is running as command line interface + if (!function_exists('is_cli')) { + function is_cli() { + if (defined('STDIN')) { + return true; + } + if (php_sapi_name() == 'cli' && !isset($_SERVER['HTTP_USER_AGENT']) && is_numeric($_SERVER['argc'])) { + return true; + } + return false; + } + } + +//format device address + if (!function_exists('format_device_address')) { + function format_device_address($str, $delim = '-', $case = 'lower') { + if (empty($str)) { return false; } + if (is_mac($str)) { + $str = join($delim, str_split($str, 2)); + } + $str = ($case == 'upper') ? strtoupper($str) : strtolower($str); + return $str; + } + } + +//transparent gif + if (!function_exists('img_spacer')) { + function img_spacer($width = '1px', $height = '1px', $custom = null) { + return ""; + } + } + +//lower case + function lower_case($string) { + if (function_exists('mb_strtolower')) { + return mb_strtolower($string, 'UTF-8'); + } + else { + return strtolower($string); + } + } + +//upper case + function upper_case($string) { + if (function_exists('mb_strtoupper')) { + return mb_strtoupper($string, 'UTF-8'); + } + else { + return strtoupper($string); + } + } + +//write javascript function that detects select key combinations to perform designated actions + if (!function_exists('key_press')) { + function key_press($key, $direction = 'up', $subject = 'document', $exceptions = array(), $prompt = null, $action = null, $script_wrapper = true) { + //determine key code + switch (strtolower($key)) { + case 'escape': + $key_code = '(e.which == 27)'; + break; + case 'delete': + $key_code = '(e.which == 46)'; + break; + case 'enter': + $key_code = '(e.which == 13)'; + break; + case 'backspace': + $key_code = '(e.which == 8)'; + break; + case 'space': + $key_code = '(e.which == 32)'; + break; + case 'ctrl+s': + $key_code = '(((e.which == 115 || e.which == 83) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + case 'ctrl+q': + $key_code = '(((e.which == 113 || e.which == 81) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + case 'ctrl+a': + $key_code = '(((e.which == 97 || e.which == 65) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + case 'ctrl+c': + $key_code = '(((e.which == 99 || e.which == 67) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + case 'ctrl+enter': + $key_code = '(((e.which == 13 || e.which == 10) && (e.ctrlKey || e.metaKey)) || (e.which == 19))'; + break; + default: + return; + } + //filter direction + switch ($direction) { + case 'down': $direction = 'keydown'; break; + case 'press': $direction = 'keypress'; break; + case 'up': $direction = 'keyup'; break; + } + //check for element exceptions + if (is_array($exceptions)) { + if (sizeof($exceptions) > 0) { + $exceptions = "!$(e.target).is('".implode(',', $exceptions)."') && "; + } + } + //quote if selector is id or class + $subject = ($subject != 'window' && $subject != 'document') ? "'".$subject."'" : $subject; + //output script + echo "\n\n\n"; + if ($script_wrapper) { + echo "\n"; + } + echo "\n\n\n"; + } + } + +//format border radius values + if (!function_exists('format_border_radius')) { + function format_border_radius($radius_value, $default = 5) { + $radius_value = ($radius_value != '') ? $radius_value : $default; + $br_a = explode(' ', $radius_value); + foreach ($br_a as $index => $br) { + if (substr_count($br, '%') > 0) { + $br_b[$index]['number'] = str_replace('%', '', $br); + $br_b[$index]['unit'] = '%'; + } + else { + $br_b[$index]['number'] = str_replace('px', '', strtolower($br)); + $br_b[$index]['unit'] = 'px'; + } + } + unset($br_a, $br); + if (sizeof($br_b) == 4) { + $br['tl']['n'] = $br_b[0]['number']; + $br['tr']['n'] = $br_b[1]['number']; + $br['br']['n'] = $br_b[2]['number']; + $br['bl']['n'] = $br_b[3]['number']; + $br['tl']['u'] = $br_b[0]['unit']; + $br['tr']['u'] = $br_b[1]['unit']; + $br['br']['u'] = $br_b[2]['unit']; + $br['bl']['u'] = $br_b[3]['unit']; + } + else if (sizeof($br_b) == 2) { + $br['tl']['n'] = $br_b[0]['number']; + $br['tr']['n'] = $br_b[0]['number']; + $br['br']['n'] = $br_b[1]['number']; + $br['bl']['n'] = $br_b[1]['number']; + $br['tl']['u'] = $br_b[0]['unit']; + $br['tr']['u'] = $br_b[0]['unit']; + $br['br']['u'] = $br_b[1]['unit']; + $br['bl']['u'] = $br_b[1]['unit']; + } + else { + $br['tl']['n'] = $br_b[0]['number']; + $br['tr']['n'] = $br_b[0]['number']; + $br['br']['n'] = $br_b[0]['number']; + $br['bl']['n'] = $br_b[0]['number']; + $br['tl']['u'] = $br_b[0]['unit']; + $br['tr']['u'] = $br_b[0]['unit']; + $br['br']['u'] = $br_b[0]['unit']; + $br['bl']['u'] = $br_b[0]['unit']; + } + unset($br_b); + + return $br; //array + } + } + +//converts a string to a regular expression + if (!function_exists('string_to_regex')) { + function string_to_regex($string, $prefix='') { + $original_string = $string; + //escape the plus + if (substr($string, 0, 1) == "+") { + $string = "^\\+(".substr($string, 1).")$"; + } + //add prefix + if (!empty($prefix)) { + if (!empty($prefix) && strlen($prefix) < 4) { + $plus = (substr($string, 0, 1) == "+") ? '' : '\+?'; + $prefix = $plus.$prefix.'?'; + } + else { + $prefix = '(?:'.$prefix.')?'; + } + } + //convert N,X,Z syntax to regex + if (preg_match('/^[NnXxZz]+$/', $original_string)) { + $string = str_ireplace("N", "[2-9]", $string); + $string = str_ireplace("X", "[0-9]", $string); + $string = str_ireplace("Z", "[1-9]", $string); + } + //add ^ to the start of the string if missing + if (substr($string, 0, 1) != "^") { + $string = "^".$string; + } + //add $ to the end of the string if missing + if (substr($string, -1) != "$") { + $string = $string."$"; + } + //add the round brackets + if (!strstr($string, '(')) { + if (strstr($string, '^')) { + $string = str_replace("^", "^".$prefix."(", $string); + } + else { + $string = '^('.$string; + } + if (strstr($string, '$')) { + $string = str_replace("$", ")$", $string); + } + else { + $string = $string.')$'; + } + } + //return the result + return $string; + } + //$string = "+12089068227"; echo $string." ".string_to_regex($string)."\n"; + //$string = "12089068227"; echo $string." ".string_to_regex($string)."\n"; + //$string = "2089068227"; echo $string." ".string_to_regex($string)."\n"; + //$string = "^(20890682[0-9][0-9])$"; echo $string." ".string_to_regex($string)."\n"; + //$string = "1208906xxxx"; echo $string." ".string_to_regex($string)."\n"; + //$string = "nxxnxxxxxxx"; echo $string." ".string_to_regex($string)."\n"; + //$string = "208906xxxx"; echo $string." ".string_to_regex($string)."\n"; + //$string = "^(2089068227"; echo $string." ".string_to_regex($string)."\n"; + //$string = "^2089068227)"; echo $string." ".string_to_regex($string)."\n"; + //$string = "2089068227$"; echo $string." ".string_to_regex($string)."\n"; + //$string = "2089068227)$"; echo $string." ".string_to_regex($string)."\n"; + } + +//dynamically load available web fonts + if (!function_exists('get_available_fonts')) { + function get_available_fonts($sort = 'alpha') { + if ($_SESSION['theme']['font_source_key']['text'] != '') { + if (!is_array($_SESSION['fonts_available']) || sizeof($_SESSION['fonts_available']) == 0) { + /* + sort options: + alpha - alphabetically + date - by date added (most recent font added or updated first) + popularity - by popularity (most popular family first) + style - by number of styles available (family with most styles first) + trending - by families seeing growth in usage (family seeing the most growth first) + */ + $google_api_url = 'https://www.googleapis.com/webfonts/v1/webfonts?key='.$_SESSION['theme']['font_source_key']['text'].'&sort='.$sort; + $response = file_get_contents($google_api_url); + if ($response != '') { + $data = json_decode($response, true); + $items = $data['items']; + foreach ($items as $item) { + $fonts[] = $item['family']; + } + //echo "
".print_r($font_list, true)."
"; + } + $_SESSION['fonts_available'] = $fonts; + unset($fonts); + } + return (is_array($_SESSION['fonts_available']) && sizeof($_SESSION['fonts_available']) > 0) ? $_SESSION['fonts_available'] : array(); + } + else { + return false; + } + } + } + +//dynamically import web fonts (by reading static css file) + if (!function_exists('import_fonts')) { + function import_fonts($file_to_parse, $line_styles_begin = null) { + /* + This function reads the contents of $file_to_parse, beginning at $line_styles_begin (if set), + and attempts to parse the specified google fonts used. The assumption is that each curly brace + will be on its own line, each CSS style (attribute: value;) will be on its own line, a single + Google Fonts name will be used per selector, and that it will be surrounded by SINGLE quotes, + as shown in the example below: + + .class_name { + font-family: 'Google Font'; + font-weight: 300; + font-style: italic; + } + + If the CSS styles are formatted as described, the necessary @import string should be generated + correctly. + */ + + $file = file_get_contents($_SERVER["DOCUMENT_ROOT"].$file_to_parse); + $lines = explode("\n", $file); + + $style_counter = 0; + foreach ($lines as $line_number => $line) { + if ($line_styles_begin != '' && $line_number < $line_styles_begin - 1) { continue; } + if (substr_count($line, "{") > 0) { + $style_lines[$style_counter]['begins'] = $line_number; + } + if (substr_count($line, "}") > 0) { + $style_lines[$style_counter]['ends'] = $line_number; + $style_counter++; + } + } + //echo "\n\n".print_r($style_lines, true)."\n\n"; + + if (is_array($style_lines) && sizeof($style_lines) > 0) { + + foreach ($style_lines as $index => $style_line) { + for ($l = $style_line['begins']+1; $l < $style_line['ends']; $l++) { + $tmp[] = $lines[$l]; + } + $style_groups[] = $tmp; + unset($tmp); + } + //echo "\n\n".print_r($style_groups, true)."\n\n"; + + if (is_array($style_groups) && sizeof($style_groups) > 0) { + + foreach ($style_groups as $style_group_index => $style_group) { + foreach ($style_group as $style_index => $style) { + $tmp = explode(':', $style); + $attribute = trim($tmp[0]); + $value = trim(trim($tmp[1]),';'); + $style_array[$attribute] = $value; + } + $style_groups[$style_group_index] = $style_array; + unset($style_array); + } + //echo "\n\n".print_r($style_groups, true)."\n\n"; + + foreach ($style_groups as $style_group_index => $style_group) { + $style_value = $style_group['font-family']; + if (substr_count($style_value, "'") > 0) { + //determine font + $font_begin = strpos($style_value, "'")+1; + $font_end = strpos($style_value, "'", $font_begin); + $font_name = substr($style_value, $font_begin, $font_end - $font_begin); + //determine modifiers + $weight = (is_numeric($style_group['font-weight']) || strtolower($style_group['font-weight']) == 'bold') ? strtolower($style_group['font-weight']) : null; + $italic = (strtolower($style_group['font-style']) == 'italic') ? 'italic' : null; + //add font to array + $fonts[$font_name][] = $weight.$italic; + } + } + //echo "\n\n/*".print_r($fonts, true)."*/\n\n"; + + if (is_array($fonts)) { + foreach ($fonts as $font_name => $modifiers) { + $modifiers = array_unique($modifiers); + $import_font_string = str_replace(' ', '+', $font_name); + if (is_array($modifiers) && sizeof($modifiers) > 0) { + $import_font_string .= ':'.implode(',', $modifiers); + } + $import_fonts[] = $import_font_string; + } + //echo "\n\n/*".print_r($import_fonts, true)."*/\n\n"; + $import_string = "@import url(//fonts.googleapis.com/css?family=".implode('|', $import_fonts).");"; + echo $import_string."\n"; + } + + } + + } + + } + } + +//retrieve array of countries + if (!function_exists('get_countries')) { + function get_countries() { + $sql = "select * from v_countries order by country asc"; + $database = new database; + $result = $database->select($sql, null, 'all'); + unset($sql); + + return is_array($result) && @sizeof($result) != 0 ? $result : false; + } + } + +//make directory with event socket + function event_socket_mkdir($dir) { + //connect to fs + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if (!$fp) { + return false; + } + //send the mkdir command to freeswitch + if ($fp) { + //build and send the mkdir command to freeswitch + $switch_cmd = "lua mkdir.lua ".escapeshellarg($dir); + $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + fclose($fp); + //check result + if (trim($switch_result) == "-ERR no reply") { + return true; + } + } + //can not create directory + return false; + } + +//escape user data + function escape($string) { + if (is_string($string)) { + return htmlentities($string, ENT_QUOTES | ENT_HTML5, 'UTF-8'); + } + elseif (is_numeric($string)) { + return $string; + } + else { + $string = (array) $string; + if (isset($string[0])) { + return htmlentities($string[0], ENT_QUOTES | ENT_HTML5, 'UTF-8'); + } + } + return false; + } + +//output pre-formatted array keys and values + if (!function_exists('view_array')) { + function view_array($array, $exit = true, $return = false) { + $html = "
".print_r($array, true).'

'; + if ($return) { + return $html; + } + else { + echo $html; + } + $exit and exit(); + } + } + +//format db date and/or time to local date and/or time + if (!function_exists('format_when_local')) { + function format_when_local($when, $format = 'dt', $include_seconds = false) { + if ($when != '') { + // determine when format + if (substr_count($when, ' ') > 0) { // date and time + $tmp = explode(' ', $when); + $date = $tmp[0]; + $time = $tmp[1]; + } + else if (substr_count($when, '-') > 0) { // date only + $date = $when; + } + else if (substr_count($when, ':') > 0) { // time only + $time = $when; + } + unset($when, $tmp); + + // format date + if ($date != '') { + $tmp = explode('-', $date); + $date = $tmp[1].'-'.$tmp[2].'-'.$tmp[0]; + } + + // format time + if ($time != '') { + $tmp = explode(':', $time); + if ($tmp[0] >= 0 && $tmp[0] <= 11) { + $meridiem = 'AM'; + $hour = ($tmp[0] == 0) ? 12 : $tmp[0]; + } + else { + $meridiem = 'PM'; + $hour = ($tmp[0] > 12) ? ($tmp[0] - 12) : $tmp[0]; + } + $minute = $tmp[1]; + $second = $tmp[2]; + } + + // structure requested time format + $time = $hour.':'.$minute; + if ($include_seconds) { $time .= ':'.$second; } + $time .= ' '.$meridiem; + + $return['d'] = $date; + $return['t'] = $time; + $return['dt'] = $date.' '.$time; + + return $return[$format]; + } + else { + return false; + } + } + } + +//define email button (src: https://buttons.cm) + if (!function_exists('email_button')) { + function email_button($text = 'Click Here!', $link = URL, $bg_color = '#dddddd', $fg_color = '#000000', $radius = '') { + + // default button radius + $radius = $radius != '' ? $radius : '3px'; + + // retrieve single/first numeric radius value for ms arc + $tmp = $radius; + if (substr_count($radius, ' ') > 0) { + $tmp = explode(' ', $radius); + $tmp = $tmp[0]; + } + $tmp = preg_replace("/[^0-9,.]/", '', $tmp); // remove non-numeric characters + $arc = floor($tmp / 35 * 100); // calculate percentage + + // create button code + $btn = " +
+ + ".$text." + +
+ "; + + return $btn; + } + } + +//validate and format order by clause of select statement + if (!function_exists('order_by')) { + function order_by($col, $dir, $col_default = '', $dir_default = 'asc') { + $order_by = ' order by '; + $col = preg_replace('#[^a-zA-Z0-9-_.]#', '', $col ?? ''); + if(!empty($dir)) + $dir = strtolower($dir) == 'desc' ? 'desc' : 'asc'; + if ($col != '') { + return $order_by.$col.' '.$dir.' '; + } + else if (is_array($col_default) || $col_default != '') { + if (is_array($col_default) && @sizeof($col_default) != 0) { + foreach ($col_default as $k => $column) { + $direction = (is_array($dir_default) && @sizeof($dir_default) != 0 && (strtolower($dir_default[$k]) == 'asc' || strtolower($dir_default[$k]) == 'desc')) ? $dir_default[$k] : 'asc'; + $order_bys[] = $column.' '.$direction.' '; + } + if (is_array($order_bys) && @sizeof($order_bys) != 0) { + return $order_by.implode(', ', $order_bys); + } + } + else { + return $order_by.$col_default.' '.$dir_default.' '; + } + } + } + } + +//validate and format limit and offset clause of select statement + if (!function_exists('limit_offset')) { + function limit_offset($limit = null, $offset = 0) { + $regex = '#[^0-9]#'; + if (!empty($limit)) { + $limit = preg_replace($regex, '', $limit); + $offset = preg_replace($regex, '', $offset ?? ''); + if (is_numeric($limit) && $limit > 0) { + $clause = ' limit '.$limit; + $offset = is_numeric($offset) ? $offset : 0; + $clause .= ' offset '.$offset; + } + return $clause.' '; + } + else { + return ''; + } + } + } + +//add a random_bytes function when it doesn't exist for old versions of PHP + if (!function_exists('random_bytes')) { + function random_bytes($length) { + $chars .= "0123456789"; + $chars .= "abcdefghijkmnopqrstuvwxyz"; + $chars .= "ABCDEFGHIJKLMNPQRSTUVWXYZ"; + for ($i = 0; $i < $length; $i++) { + $string .= $chars[random_int(0, strlen($chars)-1)]; + } + return $string.' '; + } + } + +//add a hash_equals function when it doesn't exist for old versions of PHP + if (!function_exists('hash_equals')) { + function hash_equals($var1, $var2) { + if ($var1 == $var2) { + return true; + } + else { + return false; + } + } + } + +//convert bytes to readable human format + if (!function_exists('byte_convert')) { + function byte_convert($bytes, $precision = 2) { + static $units = array('B','KB','MB','GB','TB','PB','EB','ZB','YB'); + $step = 1024; + $i = 0; + while (($bytes / $step) > 0.9) { + $bytes = $bytes / $step; + $i++; + } + return round($bytes, $precision).' '.$units[$i]; + } + } + +//convert bytes to readable human format + if (!function_exists('random_int')) { + function random_int($min, $max) { + return rand ($min, $max); + } + } + +//manage submitted form values in a session array + if (!function_exists('persistent_form_values')) { + function persistent_form_values($action, $array = null) { + switch ($action) { + case 'store': + // $array is expected to be an array of key / value pairs to store in the session + if (is_array($array) && @sizeof($array) != 0) { + $_SESSION['persistent'][$_SERVER['PHP_SELF']] = $array; + } + break; + case 'exists': + return !empty($_SESSION['persistent']) && is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0 ? true : false; + break; + case 'load': + // $array is expected to be the name of the array to create containing the key / value pairs + if ($array && !is_array($array)) { + global $$array; + } + if (!empty($_SESSION['persistent']) && is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0) { + foreach ($_SESSION['persistent'][$_SERVER['PHP_SELF']] as $key => $value) { + if ($key != 'XID' && $key != 'ACT' && $key != 'RET') { + if ($array && !is_array($array)) { + $$array[$key] = $value; + } + else { + global $$key; + $$key = $value; + } + } + } + global $unsaved; + $unsaved = true; + } + break; + case 'view': + if (is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0) { + view_array($_SESSION['persistent'][$_SERVER['PHP_SELF']], false); + } + break; + case 'clear': + unset($_SESSION['persistent'][$_SERVER['PHP_SELF']]); + break; + } + } + } + +//add alternative array_key_first for older verisons of PHP + if (!function_exists('array_key_first')) { + function array_key_first(array $arr) { + foreach($arr as $key => $unused) { + return $key; + } + return NULL; + } + } + +//get accountcode + if (!function_exists('get_accountcode')) { + function get_accountcode() { + if (!empty($accountcode = $_SESSION['domain']['accountcode']['text'] ?? '')) { + if ($accountcode == "none") { + return; + } + } + else { + $accountcode = $_SESSION['domain_name']; + } + return $accountcode; + } + } + +// User exists + if (!function_exists('user_exists')) { + function user_exists($login, $domain_name = null) { + //connect to freeswitch + $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']); + if (!$fp) { + return false; + } + + //send the user_exists command to freeswitch + if ($fp) { + if (is_null($domain_name)) { + $domain_name = $_SESSION['domain_name']; + } + $switch_cmd = "user_exists id '$login' '$domain_name'"; + $switch_result = event_socket_request($fp, 'api '.$switch_cmd); + fclose($fp); + return ($switch_result == 'true' ? true: false); + } + + //can not create directory + return null; + } + } + +?>