Files
PHPApp/func.php

1356 lines
46 KiB
PHP

<?php
require_once "classes/RestCall.php";
foreach (glob("config_aziende/*.class.php") as $filename) {
$className = basename($filename, ".class.php");
if ($className !== "common") {
$arrAziende[] = $className;
}
}
if (isset($arrAziende)) {
ksort($arrAziende);
}
function deserialize($vars)
{
$arr_all_vars = explode("&", $vars);
foreach ($arr_all_vars as $var) {
list ($key, $value) = explode("=", $var);
$post_vars[urldecode($key)] = urldecode($value);
//$post_vars[strtolower(urldecode($key))] = urldecode($value);
}
return $post_vars;
}
function fullTrim($str)
{ // trim anche di più spazi interni in uno unico
return trim(preg_replace("/\s+/", " ", $str));
}
function nullIfEmpty($var)
{
return strlen(trim($var)) == 0 ? null : $var;
}
function fileIntoString($filepath)
{
return (file_exists($filepath)) ? file_get_contents($filepath) : false;
}
function addwhereCond($sql, $whereCond)
{ // non va sulle union ancora
$whereCond = "($whereCond)";
$where_pos = strrpos($sql, "WHERE");
if ($where_pos !== false) { // HA WHERE
$SQL_select_from = substr($sql, 0, $where_pos);
$SQL_where = substr(substr($sql, $where_pos, strlen($sql)), 5);
$whereCond .= " AND ";
} else {
$SQL_select_from = $sql;
$SQL_where = "";
}
$SQL_where = "WHERE " . $whereCond . " " . $SQL_where;
return $SQL_select_from . " " . $SQL_where;
}
function sql2array($sql, $options = array())
{
$ret = array();
$return_class = false;
try {
$db = new Cms;
$db->query($sql);
$k = 0;
$retData = array();
$flag_date2Ts = in_array("date2timestamp", $options);
while ($db->next_record()) {
if ($k == 0) { // LETTURA NOME COLONNE
for ($i = 0; $i < $db->num_fields(); $i++) {
$fieldsarray[] = $db->field_name($i);
}
}
foreach ($fieldsarray as $i => $field) { // LETTURA RIGA
$row[$field] = $db->f($field);
if ($flag_date2Ts && $db->field_type($i) == "datetime") {
$row[$field] = strtotime($row[$field]);
}
}
$retData[] = $row;
$k++;
}
if ($return_class) {
$ret = array("returnId" => 1, "returnArray" => $retData);
} else {
$ret = $retData;
}
} catch (Exception $ex) {
if ($return_class) {
$ret = array("returnId" => -1, "errorText" => "Catch: " . $ex);
} else {
$ret = null;
}
}
return $ret;
}
function array2JsonFile($array, $filePrefix)
{
deleteCachePattern(json_cache_folder . "/*.json", 2 * 3600);
$uid_file = md5(uniqid(rand(), true));
if (!file_exists(json_cache_folder)) {
mkdir(json_cache_folder, 0777, true);
}
$file = json_cache_folder . "/{$filePrefix}_{$uid_file}.json";
/***************
* Warning: file_put_contents(cache/json/clienti_9a1964a6477cd18ba757c55949f628ac.json): failed to open stream: Permission denied in /var/www/phpapptest/func.php on line 101
*/
if (file_put_contents($file, JSON_stringify($array))) {
return $uid_file;
} else {
return false;
}
}
function sql2JsonFile($sql, $filePrefix)
{
$returnArray = sql2array($sql);
if (count($returnArray) > 0) {
$uid_file = array2JsonFile($returnArray, $filePrefix);
} else {
$uid_file = false;
}
return $uid_file;
}
function deleteCachePattern($pattern, $time_in_cache = time_in_cache)
{
$filelist = glob($pattern, GLOB_BRACE);
foreach ($filelist as $filepath) {
deleteCacheFile($filepath, $time_in_cache);
}
}
function deleteCacheFile($fpath, $time_in_cache, $ext = false)
{
if (file_exists($fpath) && !is_dir($fpath)) {
$fpath_ext = strtolower(pathinfo($fpath, PATHINFO_EXTENSION));
if (!$ext || $fpath_ext == strtolower($ext)) {
$filelastmodified = filemtime($fpath);
if ((time() - $filelastmodified) > $time_in_cache) {
unlink($fpath);
}
}
}
}
function check_file_ext($pathfile, $ext)
{
$ext_file = strtolower(pathinfo($pathfile, PATHINFO_EXTENSION));
return (strtolower($ext) == $ext_file) ? true : false;
}
function get_time()
{
$time_now = microtime();// Rileva il tempo
$array_time = explode(" ", $time_now);// Separa in array secondi e millisecondi
$time_return = floatval($array_time[1]) + floatval($array_time[0]);// Metto insieme secondi e microsecondi per ricavarne il valore
return $time_return;
}
function isSmartDevice()
{
//Detect special conditions devices
$iPod = stripos($_SERVER["HTTP_USER_AGENT"], "iPod");
$iPhone = stripos($_SERVER["HTTP_USER_AGENT"], "iPhone");
$iPad = stripos($_SERVER["HTTP_USER_AGENT"], "iPad");
$Android = stripos($_SERVER["HTTP_USER_AGENT"], "Android");
$webOS = stripos($_SERVER["HTTP_USER_AGENT"], "webOS");
return ($iPod || $iPhone || $iPad || $Android || $webOS) ? true : false;
}
function writeLog($message)
{
$filename = "cache/log.txt";
file_put_contents($filename, $message, FILE_APPEND);
}
function getFlagTd($cod_anag)
{
$db = new Cms;
$db->query("SELECT flag_td FROM vtb_clie WHERE cod_anag='$cod_anag'");
$flag_td = '';
while ($db->next_record()) {
$flag_td = $db->f("flag_td");
}
return $flag_td;
}
function alert($message)
{
echo "<script>alert('$message')</script>";
}
function getSerie()
{
if (isset($_SESSION["gruppo"])) {
if ($_SESSION["gruppo"] == _agenti) {
$db = new Cms;
$sql = "SELECT ISNULL(serie, 'WEB') AS serie FROM vtb_agen WHERE cod_vage = '" . $_SESSION["user_code"] . "'";
$db->query($sql);
if ($db->next_record()) {
return $db->f("serie");
}
}
}
return "WEB";
}
function js_redirect($url)
{
echo "<script>window.location.replace('$url');</script>";
}
function formatDateDb($date, $format)
{ // PRENDE LA DATA DALLA SELECT SQL E LA CONVERTE COL FORMATO RICHIESTO
return strftime($format, strtotime($date));
}
function formatDateGeneral($date, $format)
{
// return formatDatetimeGeneral($date, $format);
$date = str_replace("/", "-", substr($date, 0, 10));
if (preg_match("/^\d{4}-\d{2}-\d{2}$/", $date)) {// FORMATO AAAA-MM-GG
$time = strtotime($date);
} else {// FORMATO GG-MM-AAAA
$date = implode("-", array_reverse(explode("-", $date)));
$time = strtotime($date);
}
return strftime($format, $time);
}
function formatDatetimeGeneral($date, $format)
{
$timestamp = strtotime($date);
return strftime($format, $timestamp);
//return date("d/m/Y H:i:s", $timestamp);
}
function getNewNumOrd($gestione, $serie, $anno)
{
try {
$db = new Cms;
$client = new RestCall($db->getEndpoint());
$body = array(
"gestione" => $gestione, /***string **/
"serie" => $serie, /** string */
"anno" => $anno, /* int */
"numOrd" => 0 /* int */
);
$params = array(
"profileDb" => $db->getDbname(),
"username" => $db->getUtenteWEB(),
"password" => $db->getPasswordWEB(),
"body" => $body);
$client->nextNumOrdWeb($params);
$returnId = $client->return->esito;
/* ****** ret is = to the newNumOrd **********/
$ret = ($returnId == 1) ? $client->return->dto : -1;
} catch (Exception $e) {
$ret = -1;
}
return $ret;
}
// echo found_constant_free();
function found_constant_free()
{
$filename = "language/lang_it/_it_.php";
$handle = fopen($filename, "r");
$contents_file = fread($handle, filesize($filename));
fclose($handle);
$pattern = "_TEXT_";
$found = false;
$i = 1;
while (!$found) {
if (!strpos($contents_file, $pattern . $i)) {
return $i;
}
$i++;
}
}
function cust_strpos($condStatus, $statusArtChar)
{
$ret = strlen(stristr($condStatus, $statusArtChar));
if ($ret <= 0) $ret = false;
return $ret;
}
function gen_data_cons()
{
global $conf;
$d = new DateTime;
$d->setTime(0, 0, 0);
$daysToAdd = $conf["date_offset_cons"];
if (isset($conf["add_1_day_if_after_time"])) {
$nowH = date("H");
if ($nowH > $conf["add_1_day_if_after_time"]) {
$daysToAdd++;
}
}
$d->modify("+ {$daysToAdd} day");
if (!isDayOk($d)) {
$found = false;
do {
$d->modify("+ 1 day");
$found = isDayOk($d);
} while (!$found);
}
return $d->getTimestamp();
}
function isDayOk($d)
{
global $conf, $array_festivi;
return !(in_array($d->format("D"), $conf["ggNoCons"]) || in_array($d->format("d/m"), $array_festivi));
}
function genPageNumeraton($thispage, $total_pages, $adjacents = 3, $n_extr_pages = 2)
{
$lastpage = $total_pages;
for ($counter = 1; $counter <= $lastpage; $counter++) {
if ($lastpage < 7 + $adjacents * 2) {
$array[] = $counter;
} else if ($lastpage > 5 + $adjacents * 2) {
if ($thispage < 1 + $adjacents * 2) { //close to beginning; only hide later pages
if ($counter < 4 + $adjacents * 2 || ($counter <= $lastpage && $counter >= $lastpage - ($n_extr_pages - 1))) {
$array[] = $counter;
}
} else if ($lastpage - $adjacents * 2 > $thispage && $thispage > $adjacents * 2) { //in middle; hide some front and some back
if ($counter <= $n_extr_pages || ($counter >= $thispage - $adjacents && $counter <= $thispage + $adjacents) || ($counter >= $lastpage - ($n_extr_pages - 1) || $counter <= $n_extr_pages)) {
$array[] = $counter; // PRIME PAGINE || PAGINE NEL MEZZO || ULTIME PAGINE
}
} else { //close to end; only hide early pages
if ($counter <= $n_extr_pages || ($counter >= $lastpage - (2 + $adjacents * 2) && $counter <= $lastpage)) {
$array[] = $counter; // PRIME PAGINE || PAGINE NEL MEZZO || ULTIME PAGINE
}
}
}
}
return $array;
}
// SOSTITUITA CON QUELLA SOPRA
function genPagination($thispage, $total_pages, $targetPage, $getParam, $adjacents, $aClass)
{
/* Setup page vars for display. */
if ($thispage == 0) $thispage = 1; //if no page var is given, default to 1.
$prev = $thispage - 1; //previous page is page - 1
$next = $thispage + 1; //next page is page + 1
$lastpage = $total_pages; //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1; //last page minus 1
$pagination = "";
if ($lastpage > 1) { //previous button
$pagination .= ($thispage > 1) ? " <a class='$aClass' href=\"$targetPage?$getParam=$prev\"><< prec.</a>&nbsp;" : "";
//pages
if ($lastpage < 7 + ($adjacents * 2)) {
for ($counter = 1; $counter <= $lastpage; $counter++) {
$pagination .= (($counter == $thispage) ? " <span class=\"current\">$counter</span>" : "<a class='$aClass' href=\"$targetPage?$getParam=$counter\">$counter</a>") . "&nbsp;|&nbsp;";
}
} else if ($lastpage > 5 + ($adjacents * 2)) {
//close to beginning; only hide later pages
if ($thispage < 1 + ($adjacents * 2)) {
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) {
$pagination .= (($counter == $thispage) ? " <span class=\"current\">$counter</span>" : "<a class='$aClass' href=\"$targetPage?$getParam=$counter\">$counter</a>") . "&nbsp;|&nbsp;";
}
$pagination .= "...&nbsp;|&nbsp;";
$pagination .= "<a class='$aClass' href=\"$targetPage?$getParam=$lpm1\">$lpm1</a>&nbsp;|&nbsp;";
$pagination .= "<a class='$aClass' href=\"$targetPage?$getParam=$lastpage\">$lastpage</a>&nbsp;|&nbsp;";
} //in middle; hide some front and some back
else if ($lastpage - ($adjacents * 2) > $thispage && $thispage > ($adjacents * 2)) {
$pagination .= "<a class='$aClass' href=\"$targetPage?$getParam=1\">1</a>&nbsp;|&nbsp;";
$pagination .= "<a class='$aClass' href=\"$targetPage?$getParam=2\">2</a>&nbsp;|&nbsp;";
$pagination .= "...&nbsp;|&nbsp;";
for ($counter = $thispage - $adjacents; $counter <= $thispage + $adjacents; $counter++) {
$pagination .= (($counter == $thispage) ? "<span class=\"current\">$counter</span>" : "<a class='$aClass' href=\"$targetPage?$getParam=$counter\">$counter</a>") . "&nbsp;|&nbsp;";
}
$pagination .= "...&nbsp;|&nbsp;";
$pagination .= "<a class='$aClass' href=\"$targetPage?$getParam=$lpm1\">$lpm1</a> ";
$pagination .= "<a class='$aClass' href=\"$targetPage?$getParam=$lastpage\">$lastpage</a> ";
} else { //close to end; only hide early pages
$pagination .= "<a class='$aClass' href=\"$targetPage?$getParam=1\">1</a>&nbsp;|&nbsp;";
$pagination .= "<a class='$aClass' href=\"$targetPage?$getParam=2\">2</a>&nbsp;|&nbsp;";
$pagination .= "...&nbsp;|&nbsp;";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
$pagination .= (($counter == $thispage) ? "<span class=\"current\">$counter</span>" : "<a class='$aClass' href=\"$targetPage?$getParam=$counter\">$counter</a>") . "&nbsp;|&nbsp;";
}
}
}
//next button
$pagination .= ($thispage < $counter - 1) ? "<a class='$aClass' href=\"$targetPage?$getParam=$next\">succ. >></a>" : "";
return $pagination;
}
}
function clean2($value)
{
$value = trim($value);
$value = str_replace("\r", "", $value);
$value = str_replace("\n", "", $value);
$value = str_replace('"', "&quot;", $value);
$value = str_replace("'", "&rsquo;", $value);
$value = str_replace("`", "&lsquo;", $value);
$value = stripslashes($value);
return $value;
}
function ReadSessionCookie($vett, $variabile)
{
if (!isset($_SESSION[$variabile])) {
if (isset($_COOKIE["dulciar_$vett[$variabile]"])) {
$ret = $_COOKIE["dulciar_$vett[$variabile]"];
$_SESSION[$variabile] = $ret;
} else {
$ret = "";
}
} else {
$ret = $_SESSION[$variabile];
}
return $ret;
}
function DeleteCookieArray($array)
{
setcookie("$array");
}
function sanitize($input)
{
if (is_array($input)) {
foreach ($input as $var => $val) {
$output[$var] = sanitize($val);
}
} else {
$output = escape($input);
}
return $output;
}
function escape($string)
{
if (true === (bool)get_magic_quotes_gpc()) {
$string = stripslashes_deep($string);
}
if (!is_numeric($string)) {
$string = str_replace("'", "''", $string);
}
return $string;
}
if (!function_exists("stripslashes_deep")) {
function stripslashes_deep($value)
{
return is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value);
}
}
function ConcatSconti($ls_sconto1, $ls_sconto2, $ls_sconto3, $ls_sconto4)
{
$ls_sconti = "";
$ls_sconto1 = ((double)$ls_sconto1 == 0) ? "" : ((!is_float($ls_sconto1)) ? $ls_sconto1 = number_format($ls_sconto1, 0, ".", "'") : $ls_sconto1);
$ls_sconto2 = ((double)$ls_sconto2 == 0) ? "" : ((!is_float($ls_sconto2)) ? $ls_sconto2 = number_format($ls_sconto2, 0, ".", "'") : $ls_sconto2);
$ls_sconto3 = ((double)$ls_sconto3 == 0) ? "" : ((!is_float($ls_sconto3)) ? $ls_sconto3 = number_format($ls_sconto3, 0, ".", "'") : $ls_sconto3);
$ls_sconto4 = ((double)$ls_sconto4 == 0) ? "" : ((!is_float($ls_sconto4)) ? $ls_sconto4 = number_format($ls_sconto4, 0, ".", "'") : $ls_sconto4);
if (strlen($ls_sconto1) == 0) {
if (strlen($ls_sconto2) == 0) {
if (strlen($ls_sconto3) == 0) {
$ls_sconti = (strlen($ls_sconto4) == 0) ? "" : $ls_sconto4;
} else {
$ls_sconti = (strlen($ls_sconto4) == 0) ? $ls_sconto3 : ($ls_sconto3 . "+" . $ls_sconto4);
}
} else {
if (strlen($ls_sconto3) == 0) {
$ls_sconti = (strlen($ls_sconto4) == 0) ? $ls_sconto2 : ($ls_sconto2 . "+" . $ls_sconto4);
} else {
$ls_sconti = (strlen($ls_sconto3) == 0) ? ($ls_sconto2 . "+" . $ls_sconto3) : ($ls_sconto2 . "+" . $ls_sconto3 . "+" . $ls_sconto4);
}
}
} else {
if (strlen($ls_sconto2) == 0) {
if (strlen($ls_sconto3) == 0) {
$ls_sconti = (strlen($ls_sconto4) == 0) ? $ls_sconto1 : ($ls_sconto1 . "+" . $ls_sconto4);
} else {
$ls_sconti = (strlen($ls_sconto4) == 0) ? ($ls_sconto1 . "+" . $ls_sconto3) : ($ls_sconto1 . "+" . $ls_sconto3 . "+" . $ls_sconto4);
}
} else {
if (strlen($ls_sconto3) == 0) {
$ls_sconti = (strlen($ls_sconto4) == 0) ? ($ls_sconto1 . "+" . $ls_sconto2) : ($ls_sconto1 . "+" . $ls_sconto2 . "+" . $ls_sconto4);
} else {
$ls_sconti = (strlen($ls_sconto4) == 0) ? ($ls_sconto1 . "+" . $ls_sconto2 . "+" . $ls_sconto3) : ($ls_sconto1 . "+" . $ls_sconto2 . "+" . $ls_sconto3 . "+" . $ls_sconto4);
}
}
}
return $ls_sconti;
}
function get_last_price_from($cod_anag, $cod_vdes, $ddmm_from, $cod_mart)
{ // usata da dulciar
$cod_vdes_condition = "dtb_ordt.cod_vdes = '{$cod_vdes}'";
if (is_null($cod_vdes) || empty($cod_vdes)) {
$cod_vdes_condition = "dtb_ordt.cod_vdes IS NULL";
}
$dt_dateFrom = date_create_from_format("d/m/Y H:i:s", $ddmm_from . "/" . date("Y") . " 00:00:00");
$dt_today = date_create_from_format("d/m/Y H:i:s", date("d/m/Y") . " 00:00:00");
if ($dt_dateFrom > $dt_today) {
$dt_dateFrom->modify("-1 year");
}
$data_da = $dt_dateFrom->format("Y-m-d");
$sql = "SELECT TOP 1 val_unt,
CASE WHEN sconto5 = 0 THEN null ELSE sconto5 END AS sconto5,
CASE WHEN sconto6 = 0 THEN null ELSE sconto6 END AS sconto6,
CASE WHEN sconto7 = 0 THEN null ELSE sconto7 END AS sconto7,
CASE WHEN sconto8 = 0 THEN null ELSE sconto8 END AS sconto8,
dtb_ordt.cod_vdes
FROM dtb_ordt, dtb_ordr
WHERE dtb_ordt.gestione = dtb_ordr.gestione AND
dtb_ordt.data_ord = dtb_ordr.data_ord AND
dtb_ordt.num_ord = dtb_ordr.num_ord AND
dtb_ordt.data_ord > = '{$data_da}' AND
dtb_ordt.cod_anag = '{$cod_anag}' AND
{$cod_vdes_condition} AND
dtb_ordr.cod_mart = '{$cod_mart}'
ORDER BY dtb_ordr.data_ord DESC, dtb_ordr.num_ord DESC, dtb_ordr.riga_ord";
return sql2array($sql);
}
function phraseToArrayLimit($stringa, $max_char)
{
$ret = array();
$i = 0;
while (1) {
if ($i > 0) {
$stringa = trim(str_replace($ret[$i - 1], "", $stringa));
}
if (strlen(trim($stringa)) == 0) {
break;
} else {
$ret[$i] = cutSavingWords($stringa, $max_char);
$i++;
}
}
return $ret;
}
function cutSavingWords($stringa, $max_char)
{
if (strlen($stringa) > $max_char) {
$stringa_tagliata = substr($stringa, 0, $max_char);
$last_space = strrpos($stringa_tagliata, " ");
$stringa_ok = substr($stringa_tagliata, 0, $last_space);
return $stringa_ok;
} else {
return $stringa;
}
}
function checkStralci()
{
if (!isset($_SESSION["stralci"])) {
$sql = "SELECT 'C' AS flag_elaborato
FROM dtb_ordr, wtb_users, dtb_ordt
WHERE dtb_ordt.num_ord = dtb_ordr.num_ord AND
dtb_ordt.data_ord = dtb_ordr.data_ord AND
dtb_ordt.gestione = dtb_ordr.gestione AND
qta_ord - qta_evasa <> qta_ord AND
flag_evaso = 'I' AND
dtb_ordr.gestione = 'V' AND
dtb_ordt.cod_vage = wtb_users.user_code AND
wtb_users.user_name = '" . $_SESSION["username"] . "'
GROUP BY dtb_ordt.num_ord,dtb_ordt.data_ord, dtb_ordt.serie";
$db = new Cms;
$db->query($sql);
$_SESSION["stralci"] = $db->num_rows();
}
$ret = "Stralci di ordine" . " (";
if ($_SESSION["stralci"] > 0) {
$ret .= "<b>" . $_SESSION["stralci"] . "</b>";
} else {
$ret .= $_SESSION["stralci"];
}
$ret .= ")";
return $ret;
}
function cal_dec2($value)
{ // conta cifre decimali significative
return strlen(substr(strrchr($value, "."), 1));
}
function cal_dec($value, $min_dec = 2, $max_dec = false)
{ // conta decimali
//$value = (string)$value;
$n_dec = strlen($value) - strrpos($value, ".") - 1;
if ($max_dec) {
if ($n_dec > $max_dec) {
$n_dec = $max_dec;
}
}
if ($n_dec < $min_dec) {
$n_dec = $min_dec;
}
return $n_dec;
}
function printSconto($val)
{
if (!$val == "" && (!(double)$val == 0)) {
return number_format($val, cal_dec2($val), ".", "'") . "%";
}
return "&nbsp;";
}
function firstLetterUpPhrase($string)
{
return ucwords(strtolower($string));
}
function cutStringMiddle($string, $max = 50, $rep = "[...]")
{
$strLen = strlen($string);
$difLen = $strLen - $max;
$leftText = substr($string, 0, $max / 2);
$repText = substr($string, $max / 2, $difLen);
$string = str_replace($repText, $rep, $string);
$string = str_replace($leftText, rtrim($leftText), $string);
return $string;
}
function getClientInfo()
{
$u_agent = $_SERVER["HTTP_USER_AGENT"];
$bname = "Unknown";
$version = "";
$smartDev = true;
if (preg_match("/iPod/i", $u_agent)) {
$platform = $os = "iPod";
} elseif (preg_match("/iPhone/i", $u_agent)) {
$platform = $os = "iPod";
} elseif (preg_match("/iPad/i", $u_agent)) {
$platform = $os = "iPad";
} elseif (preg_match("/Android/i", $u_agent)) {
$platform = $os = "Android";
} elseif (preg_match("/webOS/i", $u_agent)) {
$platform = $os = "webOS";
} else {//First get the platform?
$smartDev = false;
if (preg_match("/linux/i", $u_agent)) {
$platform = "linux";
} elseif (preg_match("/macintosh|mac os x/i", $u_agent)) {
$platform = "mac";
} elseif (preg_match("/windows|win32/i", $u_agent)) {
$platform = "windows";
} else {
$platform = "Unknown";
}
if (preg_match("/Win16/i", $u_agent))
$os = "Windows 3.11";
elseif (preg_match("/(Windows 95)|(Win95)|(Windows_95)/i", $u_agent))
$os = "Windows 95";
elseif (preg_match("/(Windows 98)|(Win98)/i", $u_agent))
$os = "Windows 98";
elseif (preg_match("/(Windows NT 5.0)|(Windows 2000)/i", $u_agent))
$os = "Windows 2000";
elseif (preg_match("/(Windows NT 5.1)|(Windows XP)/i", $u_agent))
$os = "Windows XP";
elseif (preg_match("/(Windows NT 5.2)/i", $u_agent))
$os = "Windows Server 2003";
elseif (preg_match("/(Windows NT 6.0)/i", $u_agent))
$os = "Windows Vista";
elseif (preg_match("/(Windows NT 6.1)/i", $u_agent))
$os = "Windows 7";
elseif (preg_match("/(Windows NT 6.2)/i", $u_agent))
$os = "Windows 8";
elseif (preg_match("/(Windows NT 6.3)/i", $u_agent))
$os = "Windows 8.1";
elseif (preg_match("/(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)/i", $u_agent))
$os = "Windows NT 4.0";
elseif (preg_match("/Windows ME/i", $u_agent))
$os = "Windows ME";
elseif (preg_match("/OpenBSD/i", $u_agent))
$os = "Open BSD";
elseif (preg_match("/SunOS/i", $u_agent))
$os = "Sun OS";
elseif (preg_match("/(Linux)|(X11)/i", $u_agent))
$os = "Linux";
elseif (preg_match("/Mac_PowerPC|Macintosh|mac os x/i", $u_agent))
$os = "Mac OS";
elseif (preg_match("/QNX/i", $u_agent))
$os = "QNX";
elseif (preg_match("/BeOS/i", $u_agent))
$os = "BeOS";
elseif (preg_match("/OS/2/i", $u_agent))
$os = "OS/2";
elseif (preg_match("/(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves/Teoma)|(ia_archiver)/i", $u_agent))
$os = "Search Bot";
else
$os = "Unknown";
}
// Next get the name of the useragent yes seperately and for good reason
if (preg_match("/MSIE/i", $u_agent) && !preg_match("/Opera/i", $u_agent)) {
$bname = "Internet Explorer";
$ub = "MSIE";
} elseif (preg_match("/Firefox/i", $u_agent)) {
$bname = "Mozilla Firefox";
$ub = "Firefox";
} elseif (preg_match("/Chrome/i", $u_agent)) {
$bname = "Google Chrome";
$ub = "Chrome";
} elseif (preg_match("/Safari/i", $u_agent)) {
$bname = "Apple Safari";
$ub = "Safari";
} elseif (preg_match("/Opera/i", $u_agent)) {
$bname = "Opera";
$ub = "Opera";
} elseif (preg_match("/Netscape/i", $u_agent)) {
$bname = "Netscape";
$ub = "Netscape";
}
// finally get the correct version number
$known = array("Version", $ub, "other");
$pattern = "#(?<browser>" . join("|", $known) . ")[/ ]+(?<version>[0-9.|a-zA-Z.]*)#";
if (!preg_match_all($pattern, $u_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($u_agent, "Version") < strripos($u_agent, $ub)) {
$version = $matches["version"][0];
} else {
$version = $matches["version"][1];
}
} else {
$version = $matches["version"][0];
}
if ($version == null) {
$version = "";
}
// detect os
return array(
"smartDev" => $smartDev,
"userAgent" => $u_agent,
"browser" => $bname,
"version" => $version,
"platform" => $platform,
"ub" => $ub,
"pattern" => $pattern,
"os" => $os);
}
function checkClientComp()
{
$clientInfo = getClientInfo();
$clientInfo["checkBrowser"] = true;
if (!$clientInfo["smartDev"]) {
switch ($clientInfo["ub"]) {
case "MSIE":
if ((int)$clientInfo["version"] < 9) {
$clientInfo["checkBrowser"] = false;
if ($clientInfo["os"] != "Windows 8.1" && $clientInfo["os"] != "Windows 8" &&
$clientInfo["os"] != "Windows 7" && $clientInfo["os"] != "Windows Vista"
) {
$clientInfo["xpabove"] = true;
}
}
break;
case "Firefox":
if ((int)$clientInfo["version"] < 4) {
$clientInfo["checkBrowser"] = false;
}
break;
}
}
return $clientInfo;
}
function array_flatten($array)
{
if (!is_array($array)) {
return false;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
} else {
$result[$key] = $value;
}
}
return $result;
}
function scandir_recursive($dir, $fileext = null, $exclude_dir = null)
{
$ret = array();
$items = scandir($dir);
foreach ($items as $item) {
if ($item == "." || $item == "..") {
continue;
}
$file = $dir . "/" . $item;
if (is_dir($file)) {
if ($exclude_dir == null || $file != $exclude_dir) {
$ret[] = scandir_recursive($file, $fileext, $exclude_dir);
}
} elseif (strlen($file) > 0 && ($fileext == null || strtolower($fileext) == strtolower(pathinfo($item, PATHINFO_EXTENSION)))) {
$ret[] = $file;
}
}
return $ret;
}
function check_userkonst_unused($folder, $pattern)
{
$all_k = get_defined_constants(true);
$all_k = $all_k["user"];
ksort($all_k);
$list_file_array = array_flatten(scandir_recursive($folder, "php", "../PHPapp_Ordini/language"));
foreach ($all_k as $k_name => $k_value) {
if (strpos($k_name, $pattern) !== false) {
$found = false;
foreach ($list_file_array as $singlefile) {
$file_content = file_get_contents($singlefile);
if (strpos($file_content, $k_name) !== false) {
$found = true;
break; // risparmia cicli
}
}
if (!$found) {
echo $k_name . " <br/>";
}
}
}
}
function extract_email_from($string)
{ // ESTRAE EMAIL DA CAMPO EMAIL "SPORCO"
$pattern = "/([A-Za-z0-9\.\-\_\!\#\$\%\&\'\*\+\/\=\?\^\`\{\|\}]+)\@([A-Za-z0-9.-_]+)(\.[A-Za-z]{2,5})/";
preg_match_all($pattern, $string, $emails);
$new_emails = array_unique($emails[0]); // remove duplicate emails
foreach ($new_emails as $key => $val) {
return $val;
}
return "";
}
function getFilename($filename, $ext = true)
{ // ESTRAE SOLO NOME FILE, true default con estensione, false senza estensione
if ($ext) {
$filename = basename($filename);
} else {
$file_ext = pathinfo($filename, PATHINFO_EXTENSION);
$filename = basename($filename, ".$file_ext");
}
return $filename;
}
function send_newfile_notify_user($to, $full_name, $filename, $note)
{
global $conf;
ini_set("SMTP", "127.0.0.1");
$subject = "Notifica ricezione file su " . $conf["webapp_title"];
$message = "Gentile $full_name,<br/>
ti comunichiamo che hai ricevuto il nuovo file <b>" . getFilename($filename, false) . "</b>.<br/>";
if (strlen($note) > 0) {
$message .= "<br/>Note del mittente: <i>$note</i><br/><br/>";
}
$message .= "Per consultare il file <a href='" . $conf["official_url"] . "file_received.php' target='blank' title='Apri file ricevuti'>collegati nel nostro portale ordini</a>
con le credenziali già in tuo possesso.<br/><br/>
Cordiali saluti,<br/>" . $_SESSION["fullname"] . "<br/><br/><br/>
Non rispondere direttamente a questa e-mail poiché è stata spedita da un indirizzo di sola notifica e non accetta posta in entrata.";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: ' . $conf["email_from"] . "\r\n";
mail($to, $subject, $message, $headers);
}
function deleteCache($ext = false, $time_in_cache = false)
{
if (!$time_in_cache) {
$time_in_cache = time_in_cache;
}
if (is_dir(cache_folder) && $handle = opendir(cache_folder)) {
while (false !== ($file = readdir($handle))) {
$fpath = cache_folder . $file;
if (file_exists($fpath) && !is_dir($fpath)) {
$fpath_ext = strtolower(pathinfo($fpath, PATHINFO_EXTENSION));
if (!$ext || $fpath_ext == strtolower($ext)) {
$filelastmodified = filemtime($fpath);
if ((time() - $filelastmodified) > $time_in_cache) {
unlink($fpath);
}
}
}
}
closedir($handle);
}
}
function addGetQs($GET, $key, $var)
{
unset($GET[$key]);
$GET[$key] = $var;
parse_str(http_build_query($GET), $HttpQuery);
return http_build_query($HttpQuery);
}
function get_user_email($username = null)
{
if (is_null($username) && isset($_SESSION["username"])) {
$username = $_SESSION["username"];
}
if (is_null($username)) {
return null;
}
$db = new Cms;
$sql = "SELECT e_mail, wtb_user_groups.user_group, user_code, full_name
FROM wtb_users INNER JOIN wtb_user_groups ON wtb_user_groups.Key_group = wtb_users.key_group
WHERE User_name = '{$username}'";
$db->query($sql);
if ($db->next_record()) {
$user_group = strtolower($db->f("user_group"));
$user_code = $db->f("user_code");
$name = ucwords(strtolower($db->f("full_name")));
$e_mail = trim($db->f("e_mail"));
if (strlen($e_mail) == 0) {
$res = array();
if ($user_group == _agenti) {
$sql = "SELECT e_mail, rag_soc FROM vtb_agen WHERE cod_vage='$user_code'";
$res = sql2array($sql);
} else if ($user_group == _ispettori) {
$sql = "SELECT e_mail, rag_soc FROM vtb_ispe WHERE cod_visp='$user_code'";
$res = sql2array($sql);
} else {
$sql = "SELECT gtb_anag.e_mail, gtb_anag.rag_soc
FROM wtb_users, gtb_anag, wtb_clie
WHERE gtb_anag.cod_anag = wtb_clie.cod_anag AND
wtb_clie.user_name = wtb_users.user_name AND
wtb_users.user_name = '{$username}'";
$res = sql2array($sql);
}
if (count($res) > 0) {
$e_mail = $res[0]["e_mail"];
$name = $res[0]["rag_soc"];
if (!is_null($e_mail) && strlen(trim($e_mail)) > 0) {
return array("name" => $name, "email" => trim($e_mail));
}
}
} else {
return array("name" => $name, "email" => $e_mail);
}
}
return null;
}
function sendmail($to, $subject, $message)
{
global $conf, $debugMode;
$arr_to = array();
if (isset($to[0])) { // è array
$arr_to = $to;
} else {
$arr_to[] = $to;
}
/*isset($conf["email_ws_sender"]) && $conf["email_ws_sender"]*/
if ($debugMode) {
/***************** mail_ws method CALLS THE RESTCLASS TO USE API SERVICES **********************/
$result = mail_ws("developer@integry.it", $subject, $message, $conf["email_from"]["email"]);
} else {
foreach ($arr_to as $to) {
$result[] = mail_ws($to["email"], $subject, $message, $conf["email_from"]["email"]);
}
}
/****** at the moment we don't know who has not received the email if it goes wrong ********/
if (is_array($result)) {
for ($i = 1; $i <= count($result); $i++) {
/********** if one mail has not been sent *****************/
if ($result[$i] == false) {
$result = false;
break;
}
}
}
return $result;
/*else {
var_dump(file_exists("./vendor/PHPMailer-master/src/PHPMailer.php"));
$mailer = new PHPMailer(true);
if ($debugMode) {
$mailer->AddAddress("f.maino@integry.it", $to["name"]);
} else {
foreach ($arr_to as $to) {
$mailer->AddAddress($to["email"], $to["name"]);
}
}
if ($debugMode) {
$mailer->IsSMTP();
$mailer->Host = "192.168.3.12";
}
//$mailer->SMTPDebug = 2;
// $mailer->AddBCC("tony.fanelli@gmail.com");
$mailer->From = $conf["email_from"]["email"];
$mailer->FromName = $conf["email_from"]["name"];
$mailer->Subject = $subject;
$mailer->Body = $message;
$mailer->IsHTML(true);
$r = $mailer->Send();
return $r;
}*/
}
function mail_new_order($num_ord, $data_ord)
{
global $conf, $debugMode;
try {
$username = ucwords(strtolower($_SESSION["username"]));
$fullname = ucwords(strtolower($_SESSION["fullname"]));
if ($debugMode) {
return;
}
if (isset($conf["email_notify"])) {
$sql = "SELECT gtb_anag.cod_anag,
gtb_anag.rag_soc
FROM gtb_anag, wdtb_ordt
WHERE gtb_anag.cod_anag = wdtb_ordt.cod_anag AND
wdtb_ordt.data_ord = '{$data_ord}' AND
wdtb_ordt.num_ord = {$num_ord}";
$res = sql2array($sql);
if (count($res) > 0) {
$cod_anag = $res[0]["cod_anag"];
$rag_soc = $res[0]["rag_soc"];
}
$subject = "Avviso nuovo ordine inserito da $username per {$cod_anag} {$rag_soc}";
$message = "Egregio amministratore,<br/>
in data " . date("d/m/Y H:i") . " &egrave; stato creato l'ordine n. provv. {$num_ord} dall'utente <b>$fullname</b> ($username)";
if (isset($cod_anag) && isset($rag_soc)) {
$message .= " a carico del cliente <b>{$cod_anag}, {$rag_soc}</b>";
}
$message .= ".<br/><br/><br/>Non rispondere direttamente a questa e-mail poich&eacute; &egrave; stata spedita da un indirizzo di sola notifica e non accetta posta in entrata.";
sendmail($conf["email_notify"], $subject, $message);
}
if ($_SESSION["gruppo"] == _clienti && isset($conf["email_notify_clienti"]) && $conf["email_notify_clienti"]) {
$emailTo = get_user_email();
if (!is_null($emailTo)) {
/*
$sql = "SELECT ISNULL(wtb_users.full_name, gtb_anag.rag_soc) AS full_name,
ISNULL(wtb_users.e_mail, gtb_anag.e_mail) AS e_mail
FROM wtb_users, gtb_anag, wtb_clie
WHERE gtb_anag.cod_anag = wtb_clie.cod_anag AND
wtb_clie.user_name = wtb_users.user_name AND
wtb_users.user_name = '{$_SESSION["username"]}'";
$res = sql2array($sql);//echo $sql;
if(count($res)>0){
//echo $res[0]["full_name"]." <".$res[0]["e_mail"].">;";
//$emailTo .= $res[0]["full_name"]." <".$res[0]["e_mail"].">;";
$emailTo = $res[0]["e_mail"];
*/
$subject = "Ricezione del tuo ordine n. {$num_ord}";
$message = "Gentile {$fullname},<br/>
Abbiamo il piacere di confermarti la registrazione del tuo ordine, di cui troverai il dettaglio qui sotto<br/>
<b>N. ordine</b>: {$num_ord}<br/>
<b>Data</b>: " . $data_ord . "<br/><br/><br/>";
$message .= "Non rispondere direttamente a questa e-mail poiché è stata spedita da un indirizzo di sola notifica e non accetta posta in entrata.";
sendmail($emailTo, $subject, $message);
}
}
} catch (Exception $e) {
print_r($e);
}
}
function get_constIfDef($const_name, $default_value)
{
return defined($const_name) ? constant($const_name) : $default_value;
}
/**
* @param $to , $subject, $message, $from;
* calls the API rest method to send email
* */
function mail_ws($to, $subject, $message, $from)
{
try {
$db = new Cms;
$body = array(
"to" => $to,
"subject" => $subject,
"text" => $message,
"from" => $from);
$params = array(
"username" => $db->getUtenteWEB(),
"password" => $db->getPasswordWEB(),
"profileDb" => $db->getDbname(),
"body" => $body
);
$sendMail = new RestCall($db->getEndpoint());
$sendMail->sendMailHtml($params);
if ($sendMail->return->esito == 1) {
return true;
} else {
throw new Exception("API Services answer was negative or not available");
};
} catch (Exception $e) {
print_r($e);
return false;
}
}
function getVersionDate()
{
$aar = array_flatten(scandir_recursive(getcwd(), "php"));
foreach ($aar as $fpath) {
if (!isset($filelastmodified)) {
$filelastmodified = filemtime($fpath);
}
if (file_exists($fpath) && !is_dir($fpath) && $filelastmodified < filemtime($fpath)) {
$filelastmodified = filemtime($fpath);
}
}
return strftime("%d/%m/%Y %H:%M:%S", $filelastmodified);
}
function autocompile_email($user_code, $user_group, $user_email)
{ // AUTOCOMPLETA L'EMAIL DELL'UTENTE WEB PRENDENDOLA DALL'ANAGRAFICA
if (strlen(trim($user_email)) == 0) {
$tab_name = (defined("tb_$user_group")) ? constant("tb_$user_group") : "";
if (strlen($tab_name) > 0) {
list($tab_name, $id_key) = explode(".", $tab_name);
$sql = "SELECT e_mail FROM $tab_name WHERE $id_key = '$user_code'";
$db = new Cms;
$db->query($sql);
if ($db->next_record()) {
$user_email = $db->f("e_mail");
}
if (strlen($user_email) > 0) { // SE C'E UN EMAIL NELL'ANAGRAFICA E NON NELL'UTENTE WEB, VIENE IN AUTOMATICO INSERITA
$sql = "UPDATE wtb_users SET e_mail = '$user_email' WHERE user_code='$user_code'";
$db->query($sql);
}
}
}
}
function unset_order_in_session()
{
unset($_SESSION["data_ord"], $_SESSION["num_ord"], $_SESSION["data_cons"], $_SESSION["cod_anag"], $_SESSION["cod_vdes"], $_SESSION["xml_1"]);
}
function popup_temp_show($message)
{
echo "<div class='popup_temp'><div>$message</div></div>";
}
function echoifisset(&$var, $default = false)
{
return isset($var) ? $var : $default;
}
function isNewClieObbl($fieldname)
{ // controlla se il campo nuovo cliente è obbligatorio o meno
global $arr_newClieObbl;
return (in_array($fieldname, $arr_newClieObbl)) ? " paramObbl='1' " : "";
}
function isDate($date)
{
if (DateTime::createFromFormat("d-m-Y", $date) !== false) {
$ret = false;
} else {
$d = date($date);
$ret = (preg_match("/\d{2}\/\d{2}\/\d{4}/", $d));
}
return $ret;
}
function getCodeVarValue($string)
{
if (strlen($string) > 0) {
if (strpos($string, '$_SESSION[') !== false) { // PRENDE UNA VARIABILE DI SESSIONE
$string = str_replace('$_SESSION[', "", str_replace("]", "", $string));
$string = str_replace('"', "", str_replace("'", "", $string));
$string = $_SESSION[trim($string)];
} else if ($string{0} == "$") { // PRENDE UNA VARIABILE DEL CODICE
$string = substr($string, 1);
$string = $GLOBALS[$string];
}
return $string;
} else {
return $string;
}
}
function convertSqlVar2Values($sql)
{
preg_match_all("~{(.+?)}~", $sql, $m);
$values = $m[1];
foreach ($values as $val) {
$varname = '{' . $val . '}';
$sql = str_replace($varname, getCodeVarValue($val), $sql);
}
return $sql;
}
function getWeekNumber($date)
{
try {
$date = str_replace("/", "-", $date);
$duedt = explode("-", $date);
$date = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]);
return (int)date("W", $date);
} catch (Exception $e) {
return 1;
}
}
function getAzienda()
{
$nome_file = "nome_azienda.txt";
// SALE FINO A 5 LIVELLI PER CERCARE IL FILE
for ($i = 1; $i <= 5; $i++) {
$nome_file = "../$nome_file";
if (file_exists($nome_file)) break;
}
if (file_exists($nome_file)) {
$var = fopen($nome_file, "r");
$azienda = trim(strtolower((string)fread($var, filesize($nome_file))));
fclose($var);
return $azienda;
//return ($azienda=="STUDIOML") ? $default : $azienda;
} else {
echo "nome_azienda.txt non trovato";
}
}
function get_prod_images($cod_mart)
{
return array();
$db = new Cms;
$sql = "SELECT path_link, descrizione_link FROM mtb_aart_link WHERE cod_mart='{$cod_mart}'";
$arr_items = sql2array($sql);//var_dump($arr_items);
$arr_images = array();
foreach ($arr_items as $item) {
$path_link = $item["path_link"];
$url_image = "../" . $path_link;
if (file_exists($url_image) && is_file($url_image)) {
$arr_images[] = array("url" => $url_image, "didascalia" => $item["descrizione_link"]);
}
}
return $arr_images;
}
function is_decimal($val)
{
return is_numeric($val) && floor($val) != $val;
}
function days_diff($ts1, $ts2)
{
// formati intervallo: http://php.net/manual/en/dateinterval.format.php
$d1 = new \DateTime(date("Y-m-d", $ts1));
$d2 = new \DateTime(date("Y-m-d", $ts2));
$diff = $d1->diff($d2);
return (int)$diff->format("%r%d");
}
function limitaScontoListino()
{
$GestSetup = new GestSetup;
return $GestSetup->gest_name("PVM")->section("ORDINI_WEB_AGENTI")->key_section("LIMITA_SCONTO_MASSIMO_LISTINO")->default_value("N")->get() == "S";
}
function isEnabled_checkDataConsClie()
{
$GestSetup = new GestSetup;
return $GestSetup->gest_name("W_DDOCU_ORD_RC")->section("SETUP")->key_section("CHECK_DATA_CONS_CLIE")->default_value("N")->get() == "S";
}
function isGzCompress($data)
{
return !(@gzuncompress($data) === false);
}
if (!(function_exists("gzdecode"))) {
function gzdecode($data)
{
return gzinflate(substr($data, 10, -8));
}
}
if (!(function_exists("gzencode"))) {
function gzencode($data)
{
return $data;
}
}