<?php

/**
 * MARKETOOLS 令牌机制程序
 * ============================================================================
 * 版权所有 2007-2010 海南推广易科技有限公司，并保留所有权利。
 * 网站地址: http://www.marketools.cn；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: easelify $
 * $Id: track.php 2010/6/21 easelify $
 */

define('ACCESS_DENY','Access Deny!');

require_once($GLOBALS['PROJECT_ROOT_PATH'].'/settings/settings.php');
require_once($GLOBALS['PROJECT_ROOT_PATH'].'/include/Adodb/adodb.inc.php');

class Affiliate_API_Bl_Token {

private $key;
private $lock;
private $timeout = 30;
private $prefix = 'token_marketools_affiliate_';
private $securitycode = API_SECURITYCODE;

public  $db;

function Affiliate_API_Bl_Token($securitycode='') {
    $this->lock = $securitycode==$this->securitycode?false:true;
    $this->conndb();
}

//创建一个TOKEN
function create() {
    if($this->lock) return;
    $this->key = md5($this->prefix.$this->getmicrotime());
    $this->save();
}

function save() {
    if($this->lock) return;
    $query = 'insert into `wd_pa_tokens` values (NULL,%d,"%s","")';
    $query = sprintf($query,time(),$this->key);
    $this->db->Execute($query);
}

//第二步
function update() {
    $_GET['securitycode'] = preg_replace('/[\'\"]/','',$_GET['securitycode']);
    if($_GET['securitycode']==ACCESS_DENY)
        return false;
    $query = sprintf('select * from `wd_pa_tokens` where `securitycode1`="%s"',$_GET['securitycode']);
    $rs = $this->db->Query($query);
    if(!$rs || $rs->EOF)
        return false;

    $this->key = md5($this->getmicrotime().$this->prefix);
    $query = sprintf('update `wd_pa_tokens` set `securitycode2`="%s" where `securitycode1`="%s"',
        $this->key,
        $_GET['securitycode']
    );
    $this->db->Execute($query);
    return true;
}

function autoclear() {
    $this->db->Execute(sprintf('delete from `wd_pa_tokens` where %d-`insertime`>%d',time(),$this->timeout));
}

//最终检查安全码的正确性
function check($key) {
    $this->autoclear();
    $query = sprintf('select * from `wd_pa_tokens` where `securitycode1`="%s"',$key);
    $rs = $this->db->Query($query);
    if(!$rs || $rs->EOF)
        return false;
    else {
        //不能删除，因为有多级下线制度，只能采用超时自动删除
        //$this->db->Execute(sprintf('delete from `wd_pa_tokens` where `ID`=%d',$rs->fields['ID']));
        return true;
    }
}

//获取第一步安全码，用于js调用获取第二步安全码
function get1() {
    if($this->lock) return ACCESS_DENY;
    $this->create();
    return $this->key;
}

//获取第二步安全码，用于传输到统计数据，作比对用
function get2() {
    if($this->update())
        return $this->key;
    else
        return ACCESS_DENY;
}

//创建数据库链接对象
function conndb() {
    $this->db = NewADOConnection(DB_TYPE);
    $this->db->Connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    $this->db->Execute("SET NAMES 'utf8'");
    $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;  //or ADODB_FETCH_NUM
}

//创建DBTOKEN表
function createTokenTable() {
    $query = 'CREATE TABLE IF NOT EXISTS `wd_pa_tokens` ('
        .' `ID` bigint(20) NOT NULL AUTO_INCREMENT,'
        .' `insertime` int(10) unsigned NOT NULL,'
        .' `securitycode1` char(32) COLLATE utf8_unicode_ci NOT NULL,'
        .' `securitycode2` char(32) COLLATE utf8_unicode_ci NOT NULL,'
        .' PRIMARY KEY (`ID`),'
        .' KEY `insertime` (`insertime`)'
        .' ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1';
    $this->db->Execute($query);
}

//获取当前微秒
function getmicrotime() {
   list($usec, $sec) = explode(" ",microtime());
   return ((float) $usec + (float) $sec);
}

}//end of class...
?>