<?php
require_once(__DIR__ . "/config.php");
require_once(__DIR__ . "/util/Log.php");
require_once(__DIR__ . "/util/Cache.php");
require_once(__DIR__ . "/api/ISVService.php");
require_once(__DIR__ . "/api/Activate.php");
require_once(__DIR__ . "/crypto/DingtalkCrypt.php");
require_once(__DIR__ . "/crypto/pkcs7Encoder.php");
/*
$postdata = '{"encrypt":"T/w3yVimyokxqoZa8owceuX5TobMBKu3zfRZfY452ExV7C3vH1Z24ir+BorG+ZOUQ0wuE0RuY/80cqWyhW5wLwpxeVbbREAnx9GrD6pZJ6Fw933ucw4BbNHIOg4LODMG"}';
$postList = json_decode($postdata,true);
$encrypt = $postList['encrypt'];
$aes_key = 'abcdefgABCDEFG0123456789hHiIjJKkLlMmnNOpQrs';
$decrypt = new Prpcrypt($aes_key);
$corpid = 'ding48bce8fd3957c96b';
$result = $decrypt->decrypt($encrypt, $corpid);

print_r($result);
die();
*/
$signature = $_GET["signature"];
$timeStamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$postdata = file_get_contents("php://input");
/*$signature = '36e154f3bbaf043a6110b2025dca684967d67784';
$timeStamp = '1578453834041';
$nonce = 'bpmnoUjO';
$postdata = '{"encrypt":"mh8kSwUzMKYr4VyvH+6Ay5UJdz41rgPqhjniHqdq3euo2P0XLZqu2fhQxgQBs5ZLNv7W8hjuQgmpf+ZVNElAhNv9SVT39ZdBmXY/e1481qOsZoLw9SP9HE6Q/Uma9feA"}';*/
$postList = json_decode($postdata,true);
$encrypt = $postList['encrypt'];
$crypt = new DingtalkCrypt(TOKEN, ENCODING_AES_KEY, SUITE_KEY);

$msg = "";
$errCode = $crypt->DecryptMsg($signature, $timeStamp, $nonce, $encrypt, $msg);

if ($errCode != 0)
{
    Log::e(json_encode($_GET) . "  ERR:" . $errCode);
    
    /**
     * 创建套件时检测回调地址有效性，使用CREATE_SUITE_KEY作为SuiteKey
     */
    $crypt = new DingtalkCrypt(TOKEN, ENCODING_AES_KEY, CREATE_SUITE_KEY);
    $errCode = $crypt->DecryptMsg($signature, $timeStamp, $nonce, $encrypt, $msg);
    if ($errCode == 0)
    {
        Log::i("DECRYPT CREATE SUITE MSG SUCCESS " . json_encode($_GET) . "  " . $msg);
        $eventMsg = json_decode($msg);
        $eventType = $eventMsg->EventType;
        if ("check_create_suite_url" === $eventType)
        {
            $random = $eventMsg->Random;
            $testSuiteKey = $eventMsg->TestSuiteKey;
            
            $encryptMsg = "";
            $errCode = $crypt->EncryptMsg($random, $timeStamp, $nonce, $encryptMsg);
            if ($errCode == 0) 
            {
                Log::i("CREATE SUITE URL RESPONSE: " . $encryptMsg);
                echo $encryptMsg;
            } 
            else 
            {
                Log::e("CREATE SUITE URL RESPONSE ERR: " . $errCode);
            }
        }
        else
        {
            //should never happened
        }
    }
    else 
    {
        Log::e(json_encode($_GET) . "CREATE SUITE ERR:" . $errCode);
    }
    return;
}
else
{
    /**
     * 套件创建成功后的回调推送
     */
    Log::i("DECRYPT MSG SUCCESS " . json_encode($_GET) . "  " . $msg);
	GetPost_http('http://www.mycht.cn/webht.php/apps/dingtools/index/recivecallback',$msg,'POST');
    $eventMsg = json_decode($msg);
    $eventType = $eventMsg->EventType;
    /**
     * 套件ticket
     */
    if ("suite_ticket" === $eventType)
    {
        Cache::setSuiteTicket($eventMsg->SuiteTicket);
    }
    /**
     * 临时授权码
     */
    else if ("tmp_auth_code" === $eventType)
    {
        $tmpAuthCode = $eventMsg->AuthCode;
        Activate::autoActivateSuite($tmpAuthCode);
    }
    /**
     * 授权变更事件
     */

    /*user_add_org : 通讯录用户增加
    user_modify_org : 通讯录用户更改
    user_leave_org : 通讯录用户离职
    org_admin_add ：通讯录用户被设为管理员
    org_admin_remove ：通讯录用户被取消设置管理员
    org_dept_create ： 通讯录企业部门创建
    org_dept_modify ： 通讯录企业部门修改
    org_dept_remove ： 通讯录企业部门删除
    org_remove ： 企业被解散
    */

    else if ("user_add_org" === $eventType)
    {
        Log::e(json_encode($_GET) . "  ERR:user_add_org");
        //handle auth change event
    }

    else if ("user_modify_org" === $eventType)
    {
        Log::e(json_encode($_GET) . "  ERR:user_modify_org");
        //handle auth change event
    }

    else if ("user_leave_org" === $eventType)
    {
        Log::e(json_encode($_GET) . "  ERR:user_leave_org");
        //handle auth change event
    }
    /**
     * 应用被解除授权的时候，需要删除相应企业的存储信息
     */
    else if ("suite_relieve" === $eventType)
    {
        $corpid = $eventMsg->AuthCorpId;
        ISVService::removeCorpInfo($corpid);
        //handle auth change event
    }else if ("change_auth" === $eventType)
     {
         //handle auth change event
     }

    /**
     * 回调地址更新
     */
    else if ("check_update_suite_url" === $eventType)
    {
        $random = $eventMsg->Random;
        $testSuiteKey = $eventMsg->TestSuiteKey;
        
        $encryptMsg = "";
        $errCode = $crypt->EncryptMsg($random, $timeStamp, $nonce, $encryptMsg);
        if ($errCode == 0) 
        {
            Log::i("UPDATE SUITE URL RESPONSE: " . $encryptMsg);
            echo $encryptMsg;
            return;
        } 
        else 
        {
            Log::e("UPDATE SUITE URL RESPONSE ERR: " . $errCode);
        }
    }
    else
    {
        //should never happen
    }
    
    $res = "success";
    $encryptMsg = "";
    $errCode = $crypt->EncryptMsg($res, $timeStamp, $nonce, $encryptMsg);
    if ($errCode == 0) 
    {
        echo $encryptMsg;
        Log::i("RESPONSE: " . $encryptMsg);
    } 
    else 
    {
        Log::e("RESPONSE ERR: " . $errCode);
    }
}
function GetPost_http($url, $data = '', $method = 'GET') {
	$curl = curl_init(); // 启动一个CURL会话  
	curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址  
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查  
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在  
	curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器  
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转  
	curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer  
	if ($method == 'POST' && !empty($data)) {
		curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求  
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
	}
	curl_setopt($curl, CURLOPT_TIMEOUT, 40); // 设置超时限制防止死循环  
	curl_setopt($curl, CURLOPT_TIMEOUT_MS, 40000); // 设置超时限制防止死循环  
	curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容  
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回  
	$tmpInfo = curl_exec($curl); // 执行操作  
	$errno = curl_errno($curl);
	if ($errno !== 0) {
		log_message('error', 'ctripost'.$errno.curl_error($curl));
	}
	curl_close($curl); //关闭CURL会话  
	return $tmpInfo; //返回数据
}