<?php
/**
 * Created by Roman Liashko.
 * Date: 10/12/2017
 * Time: 10:05 AM
 *
 * common functions to get data from REDIS
 *
 */

if(!function_exists('ip2location')) {
    function ip2location($ip)
    {
        $ip = ip2long($ip);
        $redis = new Redis();

        // Use socket Redis connection for east coast
        if(isset($_SERVER['dc']) && $_SERVER['dc'] == 'ec')
            $connection = '/var/run/redis_6380.sock';
        else
            $connection = '192.168.30.110';

        try {
            $redis->pconnect($connection);
            $ip_data = $redis->zRangeByScore('envoyip', $ip, 4294967296, array('limit' => array(0, 1)));
        } catch (RedisException $e) {
            return array();
        }

        $ip_data = explode(':', $ip_data[0]);

        return array(
            'country2'   => $ip_data[1],
            'country3'   => $ip_data[2],
            'city'       => $ip_data[3],
            'state'      => $ip_data[4],
            'postal'     => $ip_data[5],
            'metro_code' => $ip_data[6]
        );
    }
}

if(!function_exists('maxmindIp2location')) {
    function maxmindIp2location($ip)
    {
        if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            $ip = ip2long_v6($ip);
        }else{
            $ip = ip2long($ip);
        }
        $redis = new Redis();

        // Use socket Redis connection for east coast

        $connection = '/var/run/redis_6386.sock';

        try {
            // $redis->pconnect($connection);
            $redis->pconnect('127.0.0.1',22146);
            $ip_data = $redis->zRangeByScore('maxmindip', $ip, 340282366920938463463374607431768211456, array('limit' => array(0, 1)));
        } catch (RedisException $e) {
            return array();
        }

        $ip_data = explode(':', $ip_data[0]);

        return array(
            'country2'   => $ip_data[1],
            'country3'   => $ip_data[2],
            'city'       => $ip_data[3],
            'state'      => $ip_data[4],
            'postal'     => $ip_data[5],
            'metro_code' => $ip_data[6],
            'lat'        => $ip_data[7],
            'lon'        => $ip_data[8]
        );
    }
}

if(!function_exists('ip2long_v6')){
    function ip2long_v6($ip) {
        $ip_n = inet_pton($ip);
        $bin = '';
        for ($bit = strlen($ip_n) - 1; $bit >= 0; $bit--) {
            $bin = sprintf('%08b', ord($ip_n[$bit])) . $bin;
        }

        if (function_exists('gmp_init')) {
            return gmp_strval(gmp_init($bin, 2), 10);
        } elseif (function_exists('bcadd')) {
            $dec = '0';
            for ($i = 0; $i < strlen($bin); $i++) {
                $dec = bcmul($dec, '2', 0);
                $dec = bcadd($dec, $bin[$i], 0);
            }
            return $dec;
        } else {
            trigger_error('GMP or BCMATH extension not installed!', E_USER_ERROR);
        }
    }
}

if(!function_exists('haversine_distance')) {
    /**
    * Use the haversine formula to calculate distance between
    * two coordinates
    * @param type $lat1
    * @param type $lng1
    * @param type $lat2
    * @param type $lng2
    * @param type $miles
    * @return distance in miles
    */
   function haversine_distance($lat1, $lng1, $lat2, $lng2, $miles = true){
       $pi80 = M_PI / 180;
       $lat1 *= $pi80;
       $lng1 *= $pi80;
       $lat2 *= $pi80;
       $lng2 *= $pi80;

       $r = 6372.797; // mean radius of Earth in km
       $dlat = $lat2 - $lat1;
       $dlng = $lng2 - $lng1;
       $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
       $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
       $km = $r * $c;

       return ($miles ? ($km * 0.621371192) : $km);
   }
}

if(!function_exists('closest_country')) {
   /**
    * 
    * @param type $user_country
    * example: CA
    * 
    * @param type $active_feeds
    * example: ['US', 'EU']
    * @return string
    */ 
    function closest_country($user_country, $active_feeds, $uppercase=true) {
        $user_country = strtoupper($user_country);

        $compare = [];
        // FEED_COUNTRY => [LAT,LNG]
        $country_locs = [
            'AD' => ['42.546245','1.601554'],
            'AE' => ['23.424076','53.847818'],
            'AF' => ['33.93911','67.709953'],
            'AG' => ['17.060816','-61.796428'],
            'AI' => ['18.220554','-63.068615'],
            'AL' => ['41.153332','20.168331'],
            'AM' => ['40.069099','45.038189'],
            'AN' => ['12.226079','-69.060087'],
            'AO' => ['-11.202692','17.873887'],
            'AQ' => ['-75.250973','-0.071389'],
            'AR' => ['-38.416097','-63.616672'],
            'AS' => ['-14.270972','-170.132217'],
            'AT' => ['47.516231','14.550072'],
            'AU' => ['-25.274398','133.775136'],
            'AW' => ['12.52111','-69.968338'],
            'AZ' => ['40.143105','47.576927'],
            'BA' => ['43.915886','17.679076'],
            'BB' => ['13.193887','-59.543198'],
            'BD' => ['23.684994','90.356331'],
            'BE' => ['50.503887','4.469936'],
            'BF' => ['12.238333','-1.561593'],
            'BG' => ['42.733883','25.48583'],
            'BH' => ['25.930414','50.637772'],
            'BI' => ['-3.373056','29.918886'],
            'BJ' => ['9.30769','2.315834'],
            'BM' => ['32.321384','-64.75737'],
            'BN' => ['4.535277','114.727669'],
            'BO' => ['-16.290154','-63.588653'],
            'BR' => ['-14.235004','-51.92528'],
            'BS' => ['25.03428','-77.39628'],
            'BT' => ['27.514162','90.433601'],
            'BV' => ['-54.423199','3.413194'],
            'BW' => ['-22.328474','24.684866'],
            'BY' => ['53.709807','27.953389'],
            'BZ' => ['17.189877','-88.49765'],
            'CA' => ['56.130366','-106.346771'],
            'CC' => ['-12.164165','96.870956'],
            'CD' => ['-4.038333','21.758664'],
            'CF' => ['6.611111','20.939444'],
            'CG' => ['-0.228021','15.827659'],
            'CH' => ['46.818188','8.227512'],
            'CI' => ['7.539989','-5.54708'],
            'CK' => ['-21.236736','-159.777671'],
            'CL' => ['-35.675147','-71.542969'],
            'CM' => ['7.369722','12.354722'],
            'CN' => ['35.86166','104.195397'],
            'CO' => ['4.570868','-74.297333'],
            'CR' => ['9.748917','-83.753428'],
            'CU' => ['21.521757','-77.781167'],
            'CV' => ['16.002082','-24.013197'],
            'CX' => ['-10.447525','105.690449'],
            'CY' => ['35.126413','33.429859'],
            'CZ' => ['49.817492','15.472962'],
            'DE' => ['51.165691','10.451526'],
            'DJ' => ['11.825138','42.590275'],
            'DK' => ['56.26392','9.501785'],
            'DM' => ['15.414999','-61.370976'],
            'DO' => ['18.735693','-70.162651'],
            'DZ' => ['28.033886','1.659626'],
            'EC' => ['-1.831239','-78.183406'],
            'EE' => ['58.595272','25.013607'],
            'EG' => ['26.820553','30.802498'],
            'EH' => ['24.215527','-12.885834'],
            'ER' => ['15.179384','39.782334'],
            'ES' => ['40.463667','-3.74922'],
            'ET' => ['9.145','40.489673'],
            'EU' => ['46.227638','2.213749'],
            'FI' => ['61.92411','25.748151'],
            'FJ' => ['-16.578193','179.414413'],
            'FK' => ['-51.796253','-59.523613'],
            'FM' => ['7.425554','150.550812'],
            'FO' => ['61.892635','-6.911806'],
            'FR' => ['46.227638','2.213749'],
            'GA' => ['-0.803689','11.609444'],
            'GB' => ['55.378051','-3.435973'],
            'GD' => ['12.262776','-61.604171'],
            'GE' => ['42.315407','43.356892'],
            'GF' => ['3.933889','-53.125782'],
            'GG' => ['49.465691','-2.585278'],
            'GH' => ['7.946527','-1.023194'],
            'GI' => ['36.137741','-5.345374'],
            'GL' => ['71.706936','-42.604303'],
            'GM' => ['13.443182','-15.310139'],
            'GN' => ['9.945587','-9.696645'],
            'GP' => ['16.995971','-62.067641'],
            'GQ' => ['1.650801','10.267895'],
            'GR' => ['39.074208','21.824312'],
            'GS' => ['-54.429579','-36.587909'],
            'GT' => ['15.783471','-90.230759'],
            'GU' => ['13.444304','144.793731'],
            'GW' => ['11.803749','-15.180413'],
            'GY' => ['4.860416','-58.93018'],
            'GZ' => ['31.354676','34.308825'],
            'HK' => ['22.396428','114.109497'],
            'HM' => ['-53.08181','73.504158'],
            'HN' => ['15.199999','-86.241905'],
            'HR' => ['45.1','15.2'],
            'HT' => ['18.971187','-72.285215'],
            'HU' => ['47.162494','19.503304'],
            'ID' => ['-0.789275','113.921327'],
            'IE' => ['53.41291','-8.24389'],
            'IL' => ['31.046051','34.851612'],
            'IM' => ['54.236107','-4.548056'],
            'IN' => ['20.593684','78.96288'],
            'IO' => ['-6.343194','71.876519'],
            'IQ' => ['33.223191','43.679291'],
            'IR' => ['32.427908','53.688046'],
            'IS' => ['64.963051','-19.020835'],
            'IT' => ['41.87194','12.56738'],
            'JE' => ['49.214439','-2.13125'],
            'JM' => ['18.109581','-77.297508'],
            'JO' => ['30.585164','36.238414'],
            'JP' => ['36.204824','138.252924'],
            'KE' => ['-0.023559','37.906193'],
            'KG' => ['41.20438','74.766098'],
            'KH' => ['12.565679','104.990963'],
            'KI' => ['-3.370417','-168.734039'],
            'KM' => ['-11.875001','43.872219'],
            'KN' => ['17.357822','-62.782998'],
            'KP' => ['40.339852','127.510093'],
            'KR' => ['35.907757','127.766922'],
            'KW' => ['29.31166','47.481766'],
            'KY' => ['19.513469','-80.566956'],
            'KZ' => ['48.019573','66.923684'],
            'LA' => ['19.85627','102.495496'],
            'LB' => ['33.854721','35.862285'],
            'LC' => ['13.909444','-60.978893'],
            'LI' => ['47.166','9.555373'],
            'LK' => ['7.873054','80.771797'],
            'LR' => ['6.428055','-9.429499'],
            'LS' => ['-29.609988','28.233608'],
            'LT' => ['55.169438','23.881275'],
            'LU' => ['49.815273','6.129583'],
            'LV' => ['56.879635','24.603189'],
            'LY' => ['26.3351','17.228331'],
            'MA' => ['31.791702','-7.09262'],
            'MC' => ['43.750298','7.412841'],
            'MD' => ['47.411631','28.369885'],
            'ME' => ['42.708678','19.37439'],
            'MG' => ['-18.766947','46.869107'],
            'MH' => ['7.131474','171.184478'],
            'MK' => ['41.608635','21.745275'],
            'ML' => ['17.570692','-3.996166'],
            'MM' => ['21.913965','95.956223'],
            'MN' => ['46.862496','103.846656'],
            'MO' => ['22.198745','113.543873'],
            'MP' => ['17.33083','145.38469'],
            'MQ' => ['14.641528','-61.024174'],
            'MR' => ['21.00789','-10.940835'],
            'MS' => ['16.742498','-62.187366'],
            'MT' => ['35.937496','14.375416'],
            'MU' => ['-20.348404','57.552152'],
            'MV' => ['3.202778','73.22068'],
            'MW' => ['-13.254308','34.301525'],
            'MX' => ['23.634501','-102.552784'],
            'MY' => ['4.210484','101.975766'],
            'MZ' => ['-18.665695','35.529562'],
            'NA' => ['-22.95764','18.49041'],
            'NC' => ['-20.904305','165.618042'],
            'NE' => ['17.607789','8.081666'],
            'NF' => ['-29.040835','167.954712'],
            'NG' => ['9.081999','8.675277'],
            'NI' => ['12.865416','-85.207229'],
            'NL' => ['52.132633','5.291266'],
            'NO' => ['60.472024','8.468946'],
            'NP' => ['28.394857','84.124008'],
            'NR' => ['-0.522778','166.931503'],
            'NU' => ['-19.054445','-169.867233'],
            'NZ' => ['-40.900557','174.885971'],
            'OM' => ['21.512583','55.923255'],
            'PA' => ['8.537981','-80.782127'],
            'PE' => ['-9.189967','-75.015152'],
            'PF' => ['-17.679742','-149.406843'],
            'PG' => ['-6.314993','143.95555'],
            'PH' => ['12.879721','121.774017'],
            'PK' => ['30.375321','69.345116'],
            'PL' => ['51.919438','19.145136'],
            'PM' => ['46.941936','-56.27111'],
            'PN' => ['-24.703615','-127.439308'],
            'PR' => ['18.220833','-66.590149'],
            'PS' => ['31.952162','35.233154'],
            'PT' => ['39.399872','-8.224454'],
            'PW' => ['7.51498','134.58252'],
            'PY' => ['-23.442503','-58.443832'],
            'QA' => ['25.354826','51.183884'],
            'RE' => ['-21.115141','55.536384'],
            'RO' => ['45.943161','24.96676'],
            'RS' => ['44.016521','21.005859'],
            'RU' => ['61.52401','105.318756'],
            'RW' => ['-1.940278','29.873888'],
            'SA' => ['23.885942','45.079162'],
            'SB' => ['-9.64571','160.156194'],
            'SC' => ['-4.679574','55.491977'],
            'SD' => ['12.862807','30.217636'],
            'SE' => ['60.128161','18.643501'],
            'SG' => ['1.352083','103.819836'],
            'SH' => ['-24.143474','-10.030696'],
            'SI' => ['46.151241','14.995463'],
            'SJ' => ['77.553604','23.670272'],
            'SK' => ['48.669026','19.699024'],
            'SL' => ['8.460555','-11.779889'],
            'SM' => ['43.94236','12.457777'],
            'SN' => ['14.497401','-14.452362'],
            'SO' => ['5.152149','46.199616'],
            'SR' => ['3.919305','-56.027783'],
            'ST' => ['0.18636','6.613081'],
            'SV' => ['13.794185','-88.89653'],
            'SY' => ['34.802075','38.996815'],
            'SZ' => ['-26.522503','31.465866'],
            'TC' => ['21.694025','-71.797928'],
            'TD' => ['15.454166','18.732207'],
            'TF' => ['-49.280366','69.348557'],
            'TG' => ['8.619543','0.824782'],
            'TH' => ['15.870032','100.992541'],
            'TJ' => ['38.861034','71.276093'],
            'TK' => ['-8.967363','-171.855881'],
            'TL' => ['-8.874217','125.727539'],
            'TM' => ['38.969719','59.556278'],
            'TN' => ['33.886917','9.537499'],
            'TO' => ['-21.178986','-175.198242'],
            'TR' => ['38.963745','35.243322'],
            'TT' => ['10.691803','-61.222503'],
            'TV' => ['-7.109535','177.64933'],
            'TW' => ['23.69781','120.960515'],
            'TZ' => ['-6.369028','34.888822'],
            'UA' => ['48.379433','31.16558'],
            'UG' => ['1.373333','32.290275'],
            'UK' => ['55.378051','-3.435973'],
            'US' => ['37.09024','-95.712891'],
            'UY' => ['-32.522779','-55.765835'],
            'UZ' => ['41.377491','64.585262'],
            'VA' => ['41.902916','12.453389'],
            'VC' => ['12.984305','-61.287228'],
            'VE' => ['6.42375','-66.58973'],
            'VG' => ['18.420695','-64.639968'],
            'VI' => ['18.335765','-64.896335'],
            'VN' => ['14.058324','108.277199'],
            'VU' => ['-15.376706','166.959158'],
            'WF' => ['-13.768752','-177.156097'],
            'WS' => ['-13.759029','-172.104629'],
            'XK' => ['42.602636','20.902977'],
            'YE' => ['15.552727','48.516388'],
            'YT' => ['-12.8275','45.166244'],
            'ZA' => ['-30.559482','22.937506'],
            'ZM' => ['-13.133897','27.849332'],
            'ZW' => ['-19.015438','29.154857'],
        ];

        // If the user country isn't in our country
        // list above.. default to US
        if(!isset($country_locs[$user_country])) {
            $user_country = 'US';
        }
        if(isset($active_feeds) && count($active_feeds)>0) {
            foreach($active_feeds as $feed) {
                $feed_check = strtoupper($feed);
                if(isset($country_locs[$feed_check])) {
                    $compare[$feed_check] = haversine_distance(
                        $country_locs[$user_country][0],
                        $country_locs[$user_country][1],
                        $country_locs[$feed_check][0], // latitude
                        $country_locs[$feed_check][1], // longitude
                        true);
                }
            }
        }
        asort($compare);

        if(count($compare) > 0) {
            $return = key($compare);
        } else {
            $return = $user_country;
        }
       
        if($uppercase) {
            return strtoupper($return);
        }
        return strtolower($return);
   }
}

if(!function_exists('country2to3')) {
    function country2to3($code2)
    {
        //@formatter:off
        $data = array('AD'=>'AND','AE'=>'ARE','AF'=>'AFG','AG'=>'ATG','AI'=>'AIA','AL'=>'ALB','AM'=>'ARM','AN'=>'ANT','AO'=>'AGO','AQ'=>'ATA','AR'=>'ARG','AS'=>'ASM','AT'=>'AUT','AU'=>'AUS','AW'=>'ABW','AX'=>'ALA','AZ'=>'AZE','BA'=>'BIH','BB'=>'BRB','BD'=>'BGD','BE'=>'BEL','BF'=>'BFA','BG'=>'BGR','BH'=>'BHR','BI'=>'BDI','BJ'=>'BEN','BL'=>'BLM','BM'=>'BMU','BN'=>'BRN','BO'=>'BOL','BR'=>'BRA','BS'=>'BHS','BT'=>'BTN','BV'=>'BVT','BW'=>'BWA','BY'=>'BLR','BZ'=>'BLZ','CA'=>'CAN','CC'=>'CCK','CD'=>'COD','CF'=>'CAF','CG'=>'COG','CH'=>'CHE','CI'=>'CIV','CK'=>'COK','CL'=>'CHL','CM'=>'CMR','CN'=>'CHN','CO'=>'COL','CR'=>'CRI','CU'=>'CUB','CV'=>'CPV','CX'=>'CXR','CY'=>'CYP','CZ'=>'CZE','DE'=>'DEU','DJ'=>'DJI','DK'=>'DNK','DM'=>'DMA','DO'=>'DOM','DZ'=>'DZA','EC'=>'ECU','EE'=>'EST','EG'=>'EGY','EH'=>'ESH','ER'=>'ERI','ES'=>'ESP','ET'=>'ETH','FI'=>'FIN','FJ'=>'FJI','FK'=>'FLK','FM'=>'FSM','FO'=>'FRO','FR'=>'FRA','GA'=>'GAB','GB'=>'GBR','GD'=>'GRD','GE'=>'GEO','GF'=>'GUF','GG'=>'GGY','GH'=>'GHA','GI'=>'GIB','GL'=>'GRL','GM'=>'GMB','GN'=>'GIN','GP'=>'GLP','GQ'=>'GNQ','GR'=>'GRC','GS'=>'SGS','GT'=>'GTM','GU'=>'GUM','GW'=>'GNB','GY'=>'GUY','HK'=>'HKG','HM'=>'HMD','HN'=>'HND','HR'=>'HRV','HT'=>'HTI','HU'=>'HUN','ID'=>'IDN','IE'=>'IRL','IL'=>'ISR','IM'=>'IMN','IN'=>'IND','IO'=>'IOT','IQ'=>'IRQ','IR'=>'IRN','IS'=>'ISL','IT'=>'ITA','JE'=>'JEY','JM'=>'JAM','JO'=>'JOR','JP'=>'JPN','KE'=>'KEN','KG'=>'KGZ','KH'=>'KHM','KI'=>'KIR','KM'=>'COM','KN'=>'KNA','KP'=>'PRK','KR'=>'KOR','KW'=>'KWT','KY'=>'CYM','KZ'=>'KAZ','LA'=>'LAO','LB'=>'LBN','LC'=>'LCA','LI'=>'LIE','LK'=>'LKA','LR'=>'LBR','LS'=>'LSO','LT'=>'LTU','LU'=>'LUX','LV'=>'LVA','LY'=>'LBY','MA'=>'MAR','MC'=>'MCO','MD'=>'MDA','ME'=>'MNE','MF'=>'MAF','MG'=>'MDG','MH'=>'MHL','MK'=>'MKD','ML'=>'MLI','MM'=>'MMR','MN'=>'MNG','MO'=>'MAC','MP'=>'MNP','MQ'=>'MTQ','MR'=>'MRT','MS'=>'MSR','MT'=>'MLT','MU'=>'MUS','MV'=>'MDV','MW'=>'MWI','MX'=>'MEX','MY'=>'MYS','MZ'=>'MOZ','NA'=>'NAM','NC'=>'NCL','NE'=>'NER','NF'=>'NFK','NG'=>'NGA','NI'=>'NIC','NL'=>'NLD','NO'=>'NOR','NP'=>'NPL','NR'=>'NRU','NU'=>'NIU','NZ'=>'NZL','OM'=>'OMN','PA'=>'PAN','PE'=>'PER','PF'=>'PYF','PG'=>'PNG','PH'=>'PHL','PK'=>'PAK','PL'=>'POL','PM'=>'SPM','PN'=>'PCN','PR'=>'PRI','PS'=>'PSE','PT'=>'PRT','PW'=>'PLW','PY'=>'PRY','QA'=>'QAT','RE'=>'REU','RO'=>'ROU','RS'=>'SRB','RU'=>'RUS','RW'=>'RWA','SA'=>'SAU','SB'=>'SLB','SC'=>'SYC','SD'=>'SDN','SE'=>'SWE','SG'=>'SGP','SH'=>'SHN','SI'=>'SVN','SJ'=>'SJM','SK'=>'SVK','SL'=>'SLE','SM'=>'SMR','SN'=>'SEN','SO'=>'SOM','SR'=>'SUR','SS'=>'SSD','ST'=>'STP','SV'=>'SLV','SY'=>'SYR','SZ'=>'SWZ','TC'=>'TCA','TD'=>'TCD','TF'=>'ATF','TG'=>'TGO','TH'=>'THA','TJ'=>'TJK','TK'=>'TKL','TL'=>'TLS','TM'=>'TKM','TN'=>'TUN','TO'=>'TON','TR'=>'TUR','TT'=>'TTO','TV'=>'TUV','TW'=>'TWN','TZ'=>'TZA','UA'=>'UKR','UK'=>'GBR','UG'=>'UGA','UM'=>'UMI','US'=>'USA','UY'=>'URY','UZ'=>'UZB','VA'=>'VAT','VC'=>'VCT','VE'=>'VEN','VG'=>'VGB','VI'=>'VIR','VN'=>'VNM','VU'=>'VUT','WF'=>'WLF','WS'=>'WSM','YE'=>'YEM','YT'=>'MYT','ZA'=>'ZAF','ZM'=>'ZMB','ZW'=>'ZWE');
        //@formatter:on

        $code2 = strtoupper($code2);

        if (isset($data[$code2]))
            return $data[$code2];

        return '';
    }
}

if(!function_exists('unsubscribeMailer')) {
	function unsubscribeMailer($email, $mailer=''){
		global $db;
		
		if(empty($email)) {
			return false;
		}
		
		if(!empty($mailer)) {
			
			$sent_stmt = $db->prepare("UPDATE {$mailer} SET subscribed='0' where email=?)");
			$sent_stmt->execute([$email]);
		}
		
		if(!empty($email)) {
			$sent_stmt = $db->prepare("UPDATE `winmo` SET subscribed='0' where email=?)");
			$sent_stmt->execute([$email]);
		}
	}
}

if (!function_exists('generateRequestId')) {
    function generateRequestId($ip = '0.0.0.0') {
        // Convert IP to numeric hash (IPv4 + IPv6 safe)
        $ipNum = sprintf('%u', crc32($ip));

        // Microtime (microseconds, always increasing, no dots)
        $time = (int)(microtime(true) * 1000000);

        // 4-digit random safety
        $rand = mt_rand(1000, 9999);

        // Concatenate numeric parts into a single BIG number (string)
        return $ipNum . $time . $rand;
    }
}

if (!function_exists('logRequestEventData')) {
    function logRequestEventData($requestId, $eventType, $data = []) {
        // Prepare event object
        $event = [
            'requestId' => $requestId,
            'type' => $eventType,
            'ts' => microtime(true),
            'data' => $data
        ];

        // Redis connection
        $redis = new Redis();
        $redis->connect('127.0.0.1', 22130);
//        $redis->connect('44.230.167.202', 6391);

        // Redis list key
        $key = "request_logs";

        // Push JSON to list
        $redis->rPush($key, json_encode($event));

        // Close connection
        $redis->close();

        return true;
    }
}

if(!function_exists('get_cleartrust_score')) {
	function get_cleartrust_score($ip, $referrer,$ua,$pubid,$client) {
        global $uRequestId;
        $referrer = urlencode($referrer);
		$cid = time().'_'.rand(100000,999999);
		$url = "https://api.botman.ninja/ic3.php?m=AF&src=s2s&b=20679&s=20679&cid=$cid".
			"&ip=$ip&s1=$client&s2=$pubid&s3=$referrer&s6=".urlencode($ua);

		if (!empty($_GET['debug'])){
			echo "URL: ".$url."<br>";

		}

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 2 );
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

		$result = curl_exec($ch);
		$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
		curl_close ($ch);

		if (!empty($_GET['debug'])){
			echo "Cleartrust status code is: ".$status_code."<br>";
			print_r($result);
			echo '<br>------------------------<br>';
		}

        if ($uRequestId) {
            logRequestEventData($uRequestId, 'cleartrust_api_data', [
                'url' => $url,
                'result' => $result
            ]);
        }

        if(!$result || $status_code != 200){

			return false;
		} else {

			return $result;
		}
	}
}


if(!function_exists('get_escalated_score')) {
	
	function get_escalated_score($ip, $referrer,$ua,$pubid,$client) {
		$referrer = urlencode($referrer);
		$ua = urlencode($ua);
        $ip = isset($_GET['ip']) ? $_GET['ip'] : $_SERVER['HTTP_X_FORWARDED_FOR'];

        $url = "https://api.escalated.io/v2/?i=zTENIKFmX4vu&ip=$ip&ua=$ua&r=$referrer&type=click&sid=$pubid&d=$client";

		if (!empty($_GET['debug'])){
			echo "URL: ".$url."<br>";

		}

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 2 );
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

		$result = curl_exec($ch);
		$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
		curl_close ($ch);

		if (!empty($_GET['debug'])){
			echo "Escalated status code is: ".$status_code."<br>";
			print_r($result);
			echo '<br>------------------------<br>';
		}

		if(!$result || $status_code != 200){

			return false;
		} else {

			return $result;
		}

	}
}

if(!function_exists('get_pokuw_score')) {
    function get_pokuw_score($ip, $referrer, $ua, $pubid, $client){
        global $uRequestId;
        $data = array(
            'key'=>'63Jd536f',
            'ip'=> $ip,
            'ua'=> $ua,
            's1'=> $client,
            's2'=> $pubid,
        );
        $url = 'https://pokuw.com/ip/?'. http_build_query($data);
        $ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 2 );
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
		$result = curl_exec($ch);
		$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
		curl_close ($ch);

        if ($uRequestId) {
            logRequestEventData($uRequestId, 'pokuw_api_data', [
                'url' => $url,
                'result' => $result
            ]);
        }

        if (!empty($_GET['debug'])){
            echo "URL: ".$url."<br>";
            echo "Pokuw status code is: ".$status_code."<br>";
			print_r($result);
			echo '<br>------------------------<br>';
		}
        return (!$result || $status_code != 200) ? false : json_decode($result,true);
    }
}

if(!function_exists('get_trueaudience_score')) {
	function get_trueaudience_score($ip, $referrer,$ua,$pubid,$client) {
        global $keyword, $true_audience_conf;

        if(!array_key_exists($pubid, $true_audience_conf)){
            return false;
        }

		$referrer = urlencode($referrer);
		$data = array(
            'ip'=> $ip,
            'user_agent'=> $ua,
            'keyword'=> $keyword,
            'source'=> '',
            'source_type'=> '',
            'session_id'=> session_id(),
            'client_id'=> $true_audience_conf[$pubid]['client_id'],
        );
        $headers = [
            'X-API-KEY: '.$true_audience_conf[$pubid]['api_key'],
            'CheckIpQuality: true',
            'Accept: application/json',
            'Content-Type: application/json',            
        ];
        
        $url = 'http://api.trueaudience.io/api/v1/check';
        $ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 2 );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
		$result = curl_exec($ch);
		$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code
		curl_close ($ch);

        if (!empty($_GET['debug'])){
            echo "URL: ".$url."<br>";
            //print_r($headers);
            print_r(json_encode($data));
            echo "<br> trueaudience status code is: ".$status_code."<br>";
            print_r($result);
			echo '<br>------------------------<br>';
		}
        return (!$result || $status_code != 200) ? false : json_decode($result,true);
	}
}

if(!function_exists('get_traffic_result')) {
    function get_traffic_result($pubid, $client, $domain=null, $log_ivt_data = true, $is_log_raw_data = false){
	    global $tra_fail, $true_audience_conf, $ivt_info;
                $raw_data = array();
		$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
		$ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        if (empty($ivt_info['ip_address'])) {
            $ip = isset($_GET['ip']) ? $_GET['ip'] : $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $ivt_info['ip_address'];
        }
		$ct_final_score = -1;
		$ct_fail = $es_fail = $pk_fail = $block_traffic = $tra_fail = 0;
		$cleartrust_score = get_cleartrust_score($ip,$referrer,$ua,$pubid,$client);
		$ct_score = json_decode($cleartrust_score);
		if(!empty($ct_score)){
			if(isset($ct_score->tqs->score)){
				$ct_final_score = $ct_score->tqs->score;
                                $ct_reason = $ct_score->tqs->reason;
                                $raw_data['cleartrust'] = array('score' => $ct_final_score, 'result' => $ct_reason, 'response' => $cleartrust_score);
			}
		}
		
		/*$escalated_score = get_escalated_score($ip,$referrer,$ua,$pubid,$client);
		$es_score = json_decode($escalated_score);
		if(!empty($es_score)){
			if(isset($es_score->result) && isset($es_score->risk)){
				$es_final_score = $es_score->risk;
				$es_final_result = $es_score->result;
			}
		}*/

		$pokuw_score = get_pokuw_score($ip, $referrer, $ua, $pubid, $client);
		//$pk_final_score = isset($pokuw_score['ipqs']['fraud']) ? $pokuw_score['ipqs']['fraud'] : null;
		//$pk_final_result = !empty($pokuw_score['an']['result']) ? $pokuw_score['an']['result'] : false;
		$pk_final_score = isset($pokuw_score['s']) ? $pokuw_score['s'] : null;
		$raw_data['pokuw'] = array('score' => $pk_final_score, 'response' => $pokuw_score);
		$pk_reason = $pk_final_result = false;

       if (is_array($true_audience_conf) && array_key_exists($pubid, $true_audience_conf)) {
            $true_audience_result = get_trueaudience_score($ip, $referrer,$ua,$pubid,$client);
	    $true_audience_score = isset($true_audience_result['status']) ? $true_audience_result['status'] : false;            
	    $raw_data['trueaudience'] = array('score' => $true_audience_score, 'response' => $true_audience_result);
            $tra_fail = ($true_audience_score !== false && $true_audience_score <= 4) ? 1 : 0;            
        }
        
		if($pk_final_result=='suspect' ){
			$pk_fail = 1;
		}
		
		if($ct_final_score < 3 && $ct_final_score > 0){
			$ct_fail = 1;
		}
		
		/*if(isset($es_final_result) && isset($es_final_score) && ($es_final_result > 100 || $es_final_score > 14)){
			$es_fail = 1;
		}*/
		
		if($es_fail || $pk_fail || $tra_fail){
			$block_traffic = 1;
		}
		
		if (!empty($_GET['unblock']) && $_GET['unblock']=='adm1234'){
			$block_traffic = 0;
		}

        $channel = isset($_GET['channel']) ? $_GET['channel'] : 1;

        $ivt_info['pubid'] = $pubid;
        $ivt_info['client'] = $client;
        $ivt_info['channel_id'] = $channel;
        $ivt_info['pokuw_result'] = $pk_fail;
        $ivt_info['cleartrust_result'] = $ct_fail;
        $ivt_info['escalated_result'] = $es_fail;
        $ivt_info['is_blocked_ip'] = is_blocked_ip($ip,$domain);
        $ivt_info['blocked_ip_reason'] = $ivt_info['is_blocked_ip'] == 0 ? '' : get_blocked_ip_reason($ip, $domain);
        $ivt_info['cleartrust_reason'] = isset($ct_reason) ? $ct_reason : '';
        $ivt_info['pokuw_reason'] = $pk_reason;
        $ivt_info['raw_data'] = $raw_data;
        $req_id = "";
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            $req_id = ip2long_v6($ip);
        } else {
            $req_id = ip2long($ip);
        }
        $req_id .= time();
        $ivt_info['req_id'] = $req_id;

        if ($log_ivt_data) {
            log_ivt_data($ivt_info);
        }

        if ($is_log_raw_data) {
            $ivt_info['server_data'] = json_encode($_SERVER);
            $ivt_info['u_name'] = php_uname();
            $ivt_info['host'] = gethostbyname(gethostname());
            $ivt_info['hostname'] = '';
            log_ivt_data($ivt_info, null, true);
        }
        return $block_traffic;
	}

    if(!function_exists('log_ivt_data')) {
        function log_ivt_data($ivt_info, $domain = null, $is_req_raw_data = false){
            try {

                $redis = new Redis();
                
                $ivt_info['date'] = date('Y-m-d H:i:s');

                if($domain=='rsoc.technoratimedia.com') {
                    $redisHost = "127.0.0.1";
                    $redisPort = "22137";
                } else {
                    $redisHost = "127.0.0.1";
                    $redisPort = "22130";
                }

                /*$redisHost = "192.168."."30.39";
                $redisPort = "6383";*/

                if (!empty($_GET['debug']) && $_GET['debug']=='1'){
                    echo 'get_traffic_result redis connection <br>';
                    echo 'Host: '.$redisHost.'<br>';
                    echo 'Port: '.$redisPort.'<br>';
                }
    
                $key = 'traffic_result';
                $redis->connect($redisHost, $redisPort);
                $redis->rpush($key, json_encode($ivt_info));
                if ($is_req_raw_data || !empty($ivt_info['req_id'])) {
                    $key = 'traffic_raw_data';
                     $redis->rpush($key, json_encode($ivt_info));
                }
				$redis->close();
                return true;
    
            } catch( Exception $ex ) {
                return false;
               
            }
        }
    }

    if(!function_exists('is_blocked_ip')) {
        function is_blocked_ip($ip_address,$domain){

            try {
                global $uRequestId;

                $redis = new Redis();

                if( filter_var( $ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
                    $ip2long = ip2long_v6( $ip_address );
                } else {
                    $ip2long = ip2long( $ip_address );
                }

                if($domain=='rsoc.technoratimedia.com') {
                    $redisHost = "127.0.0.1";
                    $redisPort = "22137";
                } else if($domain=='portal.technorati.com') {
                    $redisHost = "127.0.0.1";
                    $redisPort = "22133";
                } else {
                    $redisHost = "127.0.0.1";
                    $redisPort = "22135";
                }

                if (!empty($_GET['debug']) && $_GET['debug']=='1'){
                    echo 'is_blocked_ip redis connection <br>'; 
                    echo 'Host: '.$redisHost.'<br>'; 
                    echo 'Port: '.$redisPort.'<br>';
                }

                /*$redisHost = "192.168."."30.39";
                $redisPort = "6383";*/

                $redis->pconnect($redisHost, $redisPort);
                
                $redis_key = "block_ips_{$ip2long}";
                $is_blocked_ip = 0;
                $blocked = $redis->get( $redis_key );
                
                if($blocked) {
                   $is_blocked_ip = 1;
                }

                if ($uRequestId) {
                    logRequestEventData($uRequestId, 'block_ips_2', [
                        'redis_key' => $redis_key,
                        'is_blocked_ip' => $is_blocked_ip,
                        'response' => $blocked,
                    ]);
                }

            } catch( Exception $ex ) {
                $is_blocked_ip = 0;
            }

            return $is_blocked_ip;
        }
    }

    if (!function_exists('get_blocked_ip_reason')) {
        function get_blocked_ip_reason($ip_address, $domain) {
            global $uRequestId;

            try {

                $redis = new Redis();

                if (filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
                    $ip2long = ip2long_v6($ip_address);
                } else {
                    $ip2long = ip2long($ip_address);
                }

                if ($domain == 'portal.technorati.com') {
                    $redisHost = "127.0.0.1";
                    $redisPort = "22133";
                } else {
                    $redisHost = "127.0.0.1";
                    $redisPort = "22135";
                }

                if (!empty($_GET['debug']) && $_GET['debug'] == '1') {
                    echo 'is_blocked_ip redis connection <br>';
                    echo 'Host: ' . $redisHost . '<br>';
                    echo 'Port: ' . $redisPort . '<br>';
                }

                /*$redisHost = "192.168."."30.39";
                $redisPort = "6383";*/

                $redis->pconnect($redisHost, $redisPort);

                $redis_key = "block_ips_{$ip2long}";

                $blocked = $redis->get($redis_key);

                if ($uRequestId) {
                    logRequestEventData($uRequestId, 'block_ips_2_reason', [
                        'redis_key' => $redis_key,
                        'response' => $blocked,
                    ]);
                }

                return $blocked;
            } catch (Exception $ex) {

            }

            return "";
        }
    }

}

if(!function_exists('getPixelDataFromRedis')){
    function getPixelDataFromRedis($pubid){
        global $pixel_data;
        if(!empty($pixel_data)){
            return $pixel_data;
        }
        $key = 'affiliates_pixel_detail';
        try{
            $redis = new Redis();
            $redis->pconnect('127.0.0.1', '22135');
            //$redis->pconnect('192.168.'.'30.'.'106', '6378');
            $data = $redis->hGet($key, 'key_'.$pubid); 
            $redis->close();      
        }catch(Exception $e){
            $data = array();
        }
        
        // $data = '{"facebook":{"pixel_id":"1417082162390960","landing_page_load":["PageView"],"landing_click":[],"rsoc_serp_page_load":["PageView"],"rsoc_serp_click":["Lead"]},"bing":{"pixel_id":"34235334","landing_page_load":[{"event":"pageView","label":"click_conversion","category":"outbound_click"}],"landing_click":[{"event":"Lead","label":"click_conversion","category":"outbound_click"}],"rsoc_serp_page_load":[{"event":"viewContent","label":"click_conversion","category":"outbound_click"}],"rsoc_serp_click":[{"event":"Click","label":"click_conversion","category":"outbound_click"},{"event":"Purchase","label":"click_conversion","category":"outbound_click"}]},"taboola":{"pixel_id":"34235321","landing_page_load":["pageView"],"landing_click":["Lead"],"rsoc_serp_page_load":["viewContent"],"rsoc_serp_click":["Purchase"]},"outbrain":{"pixel_id":"34235678","landing_page_load":["pageView"],"landing_click":["Lead"],"rsoc_serp_page_load":["viewContent"],"rsoc_serp_click":["Purchase"]},"tiktok":{"pixel_id":"34235678","landing_page_load":["pageView"],"landing_click":["Lead"],"rsoc_serp_page_load":["viewContent"],"rsoc_serp_click":["Purchase"]},"google":{"gtag_id":"AW-16693544920","landing_page_load":[],"landing_click":[],"rsoc_serp_page_load":[{"conversion":"AW-16693544920/ORSiCPHmptIZENiPjZg-"}],"rsoc_serp_click":[{"conversion":"AW-16693544920/Rt7zCPukgdIZENiPjZg-"}]},"gtm":"GTM-KJTWRDZ","ga":"G-MQYH5E8WLM"}';
        $pixel_data = !empty( $data) ? json_decode($data, true) : array();
        if(!empty($_GET['debug'])){
            print_r($data);
        }        
        return $pixel_data;
    }
}

if(!function_exists('getTagDataFromRedis')){
    function getTagDataFromRedis($domain){
        global $tag_data;
        if(!empty($tag_data)){
            return $tag_data;
        }
        $key = 'affiliates_tag_detail';
        $data = array();
        try{
            $redis = new Redis();
            $conn = $redis->pconnect('127.0.0.1', '22135');//prod server
            //$conn  = $redis->pconnect('127.0.0.1', '6378');//dev server
            if(!empty($_GET['debug'])){
                echo "<!-- "; var_dump($conn); echo "::: key_$domain -->";
            }
            $data = $redis->hGet($key, 'key_'.$domain);   
            $redis->close();    
        }catch(Exception $e){
            if(!empty($_GET['debug'])){
                echo "<!-- rserr ---";
                print_r($e->getMessage());
                echo "-->";
            } 
            $data = array();
        }
        
        // $data = '{"ga":"G-MQYH5E8WLB","google-site-verification":"KtAorcWVzsjFtg0qefe9KJPHGBSoSaBlOOZIaanfwwgfrg"}';
        $tag_data = !empty( $data) ? json_decode($data, true) : array();
        if(!empty($_GET['debug'])){
            var_dump($data);
        }        
        return $tag_data;
    }
}

if(!function_exists('getEncryptDecryptMessage')){
    function getEncryptDecryptMessage($msg, $action='encrypt'){
        $ciphering = "AES-128-CTR";
        $options = 0;
        $iv = '1943534537133434';
        $key = "rsoc_click_time_validation";
        $encrypted_str = $decrypted_str = '';

        if($action == 'encrypt'){
            $encrypted_str = openssl_encrypt($msg, $ciphering, $key, $options, $iv);
        }else if($action == 'decrypt'){
            $decrypted_str =openssl_decrypt ($msg, $ciphering, $key, $options, $iv);
        }

        return !empty($encrypted_str) ? $encrypted_str : (!empty($decrypted_str) ? $decrypted_str : '' );

    }
}

if(!function_exists('authenticateInternalUsers')){
    function authenticateInternalUsers(){
        $host = $_SERVER['HTTP_HOST'];
		if (strpos($host, '192') === false) {
			if (!isset($_COOKIE['is_valid_oauth'])) {
				// Split host by dots
				$parts = explode('.', $host);

				// If there are at least 2 parts (e.g., x.abc.com), get the second to last part
				if (count($parts) >= 2) {
					$domain =  $parts[count($parts) - 2];
				} else {
					// fallback, return the full host if unexpected
					$domain = $host;
				}
				$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://";
				$host = $_SERVER['HTTP_HOST'];
				$requestUri = $_SERVER['REQUEST_URI'];
				$domain_path = $protocol . $host . $requestUri;
				$redirectUrl = 'https://oauth.' . $domain . '.com/internalauth/index.php?redirect='.$domain_path;
				header('Location: ' . $redirectUrl);
				exit; // always call exit after header redirects!
			}
		} 
    }
}

