<?php

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

require_once($GLOBALS['PROJECT_ROOT_PATH'].'/settings/settings.php');
require_once($GLOBALS['PROJECT_ROOT_PATH'].'/include/Adodb/adodb.inc.php');
require_once($GLOBALS['PROJECT_ROOT_PATH'].'/include/Affiliate/API/Bl/Token.class.php');

class Affiliate_API_Bl_AffClientRelationship {

public $db;
public $params;
public $lock = false;

/**
 * Array $params
 * $params['affid']     推广员ID
 * $params['outuserid'] 客户ID(对方网站的会员)
 */

function Affiliate_API_Bl_AffClientRelationship($params) {
    $this->params['action'] = $params['action'];
    $this->params['method'] = $params['method'];
    $this->params['affid'] = $params['affid'];
    $this->params['outuserid'] = $params['outuserid'];
    $this->params['outusername'] = $params['outusername'];
    $this->params['token'] = $params['token'];
    $this->params['cookie'] = $params['cookie'];

    $this->conndb();

    //未知方法
    if(!in_array($this->params['action'],array('bind','unbind','getaffiliate'))) {
        $this->lock = true;
        echo '<!-- //0 -->';
        return;
    }

    //检查系统是否开启绑定
    $query = 'select * from `wd_g_settings` where `rtype`=3 and `code`="Aff_bindcust" and `value`="enable" and `accountid`="default1"';
    $rs = $this->db->Query($query);
    if(!$rs || $rs->EOF) {
        $this->lock = true;
        if($this->params['action']=='getaffiliate') {
            if($this->params['method']=='js') {
                echo ' var mt_aff_cover = false;';
            }else {
                echo '';
            }
        }else {
            echo '<!-- //1 -->';
        }
        return;
    }

    //绑定时推广员参数错误
    if($this->params['action']=='bind') {
        /*if(strlen($this->params['affid'])!=8 || $this->params['outuserid']=='') {
            $this->lock = true;
            echo '<!-- //2 -->';
            return;
        }*/

        //推广员不存在
        $query = 'select * from `wd_g_users` where `deleted`=0 and `rtype`=4 and `userid`="'.$this->params['affid'].'" or `refid`="'.$this->params['affid'].'" or `username`="'.$this->params['affid'].'"';
        $rs = $this->db->Query($query);
        if(!$rs || $rs->EOF) {
            $this->lock = true;
            echo '<!-- //3 -->';
            return;
        }
        $this->params['affid'] = $rs->fields['userid'];

        //检查该客户是否已经绑定到某个推广员
        $query = 'select * from `wd_g_affclientrelationship` where `affid`="'.$this->params['affid'].'" and `outuserid`="'.$this->params['outuserid'].'"';
        $rs = $this->db->Query($query);
        if($rs && !$rs->EOF) {
            $this->lock = true;
            echo '<!-- //4 -->';
            return;
        }
    }

    //检查TOKEN是否正确
    $token = new Affiliate_API_Bl_Token();
    if(!$token->check($this->params['token'])) {
        $this->lock = true;
        echo '<!-- //5 -->';
        return;
    }
}

function process() {
    if(!$this->lock) {
        switch($this->params['action']) {
            case 'bind': $this->bind(); break;
            case 'unbind': $this->unbind(); break;
            case 'getaffiliate': $this->getaffiliate(); break;
            default: echo '<!-- //0 -->';
        }
    }
}

//将推广员与客户绑定
function bind() {
    $query = 'INSERT INTO `wd_g_affclientrelationship` (`ID`, `affid`, `outuserid`, `outusername`, `dateinserted`) VALUES (NULL,"%s","%s","%s",CURRENT_TIMESTAMP)';
    $query = sprintf($query,$this->params['affid'],$this->params['outuserid'],$this->params['outusername']);
    if($this->db->Execute($query)===false) {
        echo '<!-- //6 -->';
    }else {
        echo '<!-- //7 -->';
    }
}

//解除绑定，可单个，批量
function unbind() {
    $this->params['outuserid'] = explode(',',$this->params['outuserid']);
    $query = 'delete from `wd_g_affclientrelationship` where `outuserid` in ("'.join('","',$this->params['outuserid']).'")';
    $this->db->Execute($query);
    echo '<!-- //8 -->';
}

//获取推广员ID
//需要覆盖时返回 推广员ID_默认项目ID，否则返回false/0
function getaffiliate() {
    //获取关联的AFFID
    $query = 'select * from `wd_g_affclientrelationship` where `outuserid`="'.$this->params['outuserid'].'"';
    $rs = $this->db->Query($query);
    if(!$rs || $rs->EOF) {
        $bindaffiliate = '';
    }else {
        $bindaffiliate = $rs->fields['affid'];
    }

    //获取默认项目ID
    if(!empty($bindaffiliate)) {
        $query = 'select * from `wd_g_settings` where `code`="Aff_default_campaign" and `rtype`=3 and `accountid`="default1"';
        $rs = $this->db->Query($query);
        if(!$rs || $rs->EOF) {
            $campaignid = '';
        }else {
            $campaignid = $rs->fields['value']; //仍可能为空
        }
    }
    $newcookie = !empty($campaignid)?$bindaffiliate.'_'.$campaignid:0;

    //读取系统设置是否覆盖
    $query = 'select * from `wd_g_settings` where `code`="Aff_overwrite_cookie" and `rtype`=3 and `accountid`="default1" and value="1"';
    $rs = $this->db->Query($query);
    if(!$rs || $rs->EOF) {  //不覆盖，则需要读取关联，在上两步已读取，这里无操作

    }elseif(!empty($this->params['cookie'])) { //系统设置为覆盖且目标服务器没有任何COOKEI，则不读取关联，返回空，让目标服务器无任何变动
        $newcookie = '';
    }

    //如果对方网站没有MT COOKIE 或 有COOKIE但是系统设置为覆盖
    if($this->params['method']=='js') {
        //header('Content-Type: application/x-javascript');
        echo ' var mt_aff_cover = "'.$newcookie.'";';
    }elseif($this->params['method']=='socket') {
        echo $newcookie;
    }
}

//创建数据库链接对象
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
}

}//end of class...
?>