<?php
/*
 * 联众验证码识别集（修改加强特别版）
 *  最后修改：AnYueKeJi 2014-5-31
 *
 * 调用方式：Code_get ('验证码地址','帐号','密码');
 * 返回数据：验证码文字
 */

function Code_get($image,$user,$pass){
	//本地验证码保存路径
	$img_path = dirname (__FILE__) . DIRECTORY_SEPARATOR . md5(uniqid(rand())) . '.jpg';
	//下载远程验证码
	getImg($image, $img_path);
	return getValidInfo($img_path, $user, $pass);
}

function getHost(){
	return 'bbb4.hyslt.com';
}

function getId($img, $USER, $PASS, $host) {
    $ch = curl_init(sprintf('http://%s/index.php/demo', $host));
    $fields = array();
    $fields['imagepath'] = '@' . $img;
    $fields['info[lz_user]'] = $USER;
    $fields['info[lz_pass]'] = $PASS;
    $fields['pesubmit'] = '';

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    $ret = curl_exec($ch);
	if($ret === false){
		return curl_errno($ch);
	}
    curl_close($ch);
    if ($ret !== false && preg_match("/\/(\d+)'/", $ret, $id)){
        return $id[1];
    } else {
        return NULL;
    }
}

function getValidInfo($img, $USER, $PASS){
    $delay = 100000;
	$host = getHost();
    $j = 0;
    while ($j++ < 50) {
        $id = getId($img, $USER, $PASS, $host);
        if ($id != NULL){
            Code_end($img);
			break;
        }
        usleep ($delay);
    }

	Code_end($img);

    if ($id == NULL){
		Code_end($img);
        return NULL;
    }

	Code_end($img);
    $i = 0;
    while (true){
        if ($i++ > 150) {
			Code_end($img);
            return NULL; //如果超过15秒还没有识别出来,则认为失败
        }
        $ret = @file_get_contents(sprintf('http://%s/index.php?mod=demo&act=result&id=' . $id, $host));
        if ($ret == '' || $ret == NULL){
            usleep($delay);
            continue;
        }
        if ($ret !== '' && substr($ret, 0, 3) === "\xEF\xBB\xBF") {
            $ret = substr($ret, 3);
        }
        $ret = json_decode($ret);
        if ($ret != NULL && $ret->result != NULL) {
            Code_end($img);
			return $ret->result;
        }
        usleep($delay);
    }
}

//获取保存图片
function getImg($url = "", $filename = ""){
	//去除URL连接上面可能的引号
	$hander = curl_init();
	$fp = fopen($filename,'wb');
	curl_setopt($hander,CURLOPT_URL,$url);
	curl_setopt($hander,CURLOPT_FILE,$fp);
	curl_setopt($hander,CURLOPT_HEADER,0);
	curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
	curl_setopt($hander,CURLOPT_TIMEOUT,60);
	curl_exec($hander);
	curl_close($hander);
	fclose($fp);
	Return true;
}

//占用资源处理
function Code_end($urd){
	@unlink ($urd);  //删除临时验证码文件
}

?>