processor.php 15.6 KB
<?php
/**
 * 黄河分销模块处理程序
 *
 * @author 黄河分销
 * @url http://fx.dsyk.net
 */
defined('IN_IA') or exit('Access Denied');
define('WWX_FXXT_BASE', '/addons/wwx_fxxt');

	class wwx_fxxtModuleProcessor extends WeModuleProcessor
	{ 
		private $reply_table = 'wwx_fxxt_reply';
 


///P1.海报生成之二维码
	private function getURLQR($mid,$from_user,$homeurl)
	{ 
		include IA_ROOT . WWX_FXXT_BASE . '/class/phpqrcode.php';
		$value = $homeurl . '&mid=' . $mid; 
		$errorCorrectionLevel = 'L'; 
		$matrixPointSize = '4'; 
		$rand_file = $from_user . '.png'; 
		$att_target_file = 'qr-' . $rand_file; 
		$target_file = IA_ROOT . WWX_FXXT_BASE . '/tmppic/' . $att_target_file;
		QRcode::png($value, $target_file, $errorCorrectionLevel, $matrixPointSize); 
		return $target_file;
	} 

///P2.生成海报之海报与头像
	private function genImage($bg,$qr_file,$uniacid,$from_user)
	{
		$express = pdo_fetch("select * from " . tablename('wwx_fxxt_channel') . " WHERE uniacid=:uniacid and isdel=0 and active=1 limit 1", array(':uniacid' => $uniacid)); 
		if(!empty($express['channel'])) { 
			$rand_file = $from_user . '.jpg'; 
			$att_target_file = 'qr-image-' .$rand_file; 
			$att_head_cache_file = 'head-image-' . $rand_file;
			$target_file = IA_ROOT . '/addons/wwx_fxxt/tmppic/' . $att_target_file;
			$head_cache_file = IA_ROOT . '/addons/wwx_fxxt/tmppic/' . $att_head_cache_file; 
			$bg_file=IA_ROOT . "/attachment/".$bg; 
			$ch = pdo_fetch("SELECT * FROM " . tablename('wwx_fxxt_channel') . " WHERE channel=:channel", array(":channel"=>$express['channel'])); 
			$ch = $this->decode_channel_param($ch, $ch['bgparam']);///P5.生成二维码位置信息等等
			$this->mergeImage($bg_file, $qr_file, $target_file, array('left'=>$ch['qrleft'], 'top'=>$ch['qrtop'], 'width'=>$ch['qrwidth'], 'height'=>$ch['qrheight']));///P6.生成二维码系列
			$enableHead = $ch['avatarenable']; 
			$enableName = $ch['nameenable']; 
			$myheadimg = pdo_fetch("SELECT member.avatar,member.nickname FROM " . tablename('mc_mapping_fans') . " fans, " . tablename('mc_members') . " member WHERE fans.uniacid = :uniacid AND fans.uid=member.uid AND fans.openid = :from_user LIMIT 1", array(':uniacid' => $uniacid, ':from_user' => $from_user));
				if (!empty($myheadimg)) {
					if ($enableName) {
						if (strlen($myheadimg['nickname']) > 0) {
							$this->writeText($target_file, $target_file, '我是'.$myheadimg['nickname'], array('size'=>$ch['namesize'], 'left'=>$ch['nameleft'], 'top'=>$ch['nametop']));///P7.往海报文件中写入文本信息
						}
					} 
					if ($enableHead) { 
						$head_file = $myheadimg['avatar'];
						if(false===strpos(strtolower($myheadimg['avatar']), 'http://')){$head_file = $_W['siteroot'] . 'attachment/'.$myheadimg['avatar'];}
						if(strlen($myheadimg['avatar']) < 15) {$head_file = $_W['siteroot'] . '/addons/wwx_fxxt/images/notoo.png';}
						$bild=$head_cache_file; 
						$urlName = $_W['siteroot'] . '/addons/wwx_fxxt/images/notoo.png';
						$ws = false;
						for ($a = 0; $a < 3; $a++) {
							$url = $this->curl_file_get_contents($head_file);///P8.获取远程图片
							if (empty($url)) {
								$url = file_get_contents($urlName);
							}
							$fp = fopen($bild, 'w');
							$ws = fwrite($fp, $url);
							fclose($fp);
							if (!empty($ws) && $ws != false) {
								$a = 4;
							}
						}

						$this->mergeImage($target_file, $head_cache_file, $target_file, array('left'=>$ch['avatarleft'], 'top'=>$ch['avatartop'], 'width'=>$ch['avatarwidth'], 'height'=>$ch['avatarheight']));///P6.生成二维码系列
					}
				} 
				return '/addons/wwx_fxxt/tmppic/' . $att_target_file;
			}
		return '';
	}


///P3.根据公众号信息和用户OPENID发送微信消息
	public function sendcustomMsg($account,$from_user,$msg)
	{ 
		$access_token=$this->get_weixin_token($account);///P4.根据公众号信息解析微信公众号授权token
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
		$post = '{"touser":"' . $from_user . '","msgtype":"text","text":{"content":"' . $msg . '"}}'; 
		$this->curlPost($url,$post);
	}

///P4.根据公众号信息解析微信公众号授权token
	public function get_weixin_token($account)
	{
		load()->func('communication');//调用http通信文件
		if (is_array($account['access_token']) && !empty($account['access_token']['token']) && !empty($account['access_token']['expire']) && $account['access_token']['expire'] > TIMESTAMP) {
			return $account['access_token']['token'];
		} else {
			if (empty($account['uniacid'])) {
				return '';
			}
			$appid = $account['key'];
			$secret = $account['secret'];
			if (empty($appid) || empty($secret)) {
				return '';
			}
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
			$content = ihttp_get($url);
			if (empty($content)) {
				return '';
			}
			$token = @json_decode($content['content'], true);
			if (empty($token) || !is_array($token)) {
				return '';
			}
			if (empty($token['access_token']) || empty($token['expires_in'])) {
				return '';
			}
			$record = array();
			$record['token'] = $token['access_token'];
			$record['expire'] = TIMESTAMP + $token['expires_in'];
			$row = array();
			$row['access_token'] = iserializer($record);
			pdo_update('account_wechats', $row, array('uniacid' => $account['uniacid']));
			return $record['token'];
		}
	}


///P5.生成二维码位置信息等等
	public static function decode_channel_param($item, $p)
	{
		$gpc = unserialize($p); 
		$item['qrleft'] = intval($gpc['qrleft']) ? intval($gpc['qrleft']) : 145; 
		$item['qrtop'] = intval($gpc['qrtop']) ? intval($gpc['qrtop']): 475; 
		$item['qrwidth'] = intval($gpc['qrwidth']) ? intval($gpc['qrwidth']): 240; 
		$item['qrheight'] = intval($gpc['qrheight']) ? intval($gpc['qrheight']): 240; 
		$item['avatarleft'] = intval($gpc['avatarleft']) ? intval($gpc['avatarleft']): 111; 
		$item['avatartop'] = intval($gpc['avatartop']) ? intval($gpc['avatartop']) : 10; 
		$item['avatarwidth'] = intval($gpc['avatarwidth']) ? intval($gpc['avatarwidth']): 86; 
		$item['avatarheight'] = intval($gpc['avatarheight']) ?intval($gpc['avatarheight']) : 86; 
		$item['avatarenable'] = intval($gpc['avatarenable']); 
		$item['nameleft'] = intval($gpc['nameleft']) ? intval($gpc['nameleft']): 211; 
		$item['nametop'] = intval($gpc['nametop']) ?intval($gpc['nametop']) : 68; 
		$item['namesize'] = intval($gpc['namesize']) ? intval($gpc['namesize']) : 16; 
		$item['namecolor'] = $gpc['namecolor']; 
		$item['nameenable'] = intval($gpc['nameenable']); 
		return $item;
	} 


///P6.生成二维码系列
	private function mergeImage($bg, $qr, $out, $param)
	{
		list($bgWidth, $bgHeight) = getimagesize($bg);
		list($qrWidth, $qrHeight) = getimagesize($qr);
		extract($param);
		$bgImg = $this->imagecreate($bg);///P14.由文件或 URL 创建一个新图象
		$qrImg = $this->imagecreate($qr);///P14.由文件或 URL 创建一个新图象
		imagecopyresized($bgImg, $qrImg, $left, $top, 0, 0, $width, $height, $qrWidth, $qrHeight); 
		ob_start();
		imagejpeg($bgImg, NULL, 100); 
		$contents = ob_get_contents(); 
		ob_end_clean(); 
		imagedestroy($bgImg); 
		imagedestroy($qrImg); 
		$fh = fopen($out, "w+" ); 
		fwrite( $fh, $contents ); 
		fclose( $fh );
	} 


///P7.往海报文件中写入文本信息
	private function writeText($bg, $out, $text, $param = array())
	{
		list($bgWidth, $bgHeight) = getimagesize($bg); 
		extract($param); 
		$im = imagecreatefromjpeg($bg);///P14.由文件或 URL 创建一个新图象
		$black = imagecolorallocate($im, 0, 0, 0); 
		$font = IA_ROOT . '/addons/wwx_fxxt/style/css/msyhbd.ttf'; 
		$white = imagecolorallocate($im, 255, 255, 255); 
		imagettftext($im, $size, 0, $left, $top+$size/2, $white, $font, $text); 
		ob_start(); 
		imagejpeg($im, NULL, 100); 
		$contents = ob_get_contents(); 
		ob_end_clean(); imagedestroy($im); $fh = fopen($out, "w+" ); 
		fwrite( $fh, $contents ); 
		fclose( $fh );
	} 

///P8.获取远程图片
	public function curl_file_get_contents($durl)
	{
		$r = null;
			if(function_exists('curl_init') && function_exists('curl_exec'))
			{ 
				$ch = curl_init(); 
				curl_setopt($ch, CURLOPT_URL, $durl); 
				curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
				curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1'); 
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
				$r = curl_exec($ch); curl_close($ch);
			} 
		return $r;
	} 



///P9.分销专属二维码回复
	public function respond()
	{ 
		global $_W, $_GPC;
		$cfg = $this->module['config'];//获取模块设置信息
		$rid = $this->rule;
		$row = pdo_fetch("SELECT * FROM ".tablename($this->reply_table)." WHERE uniacid = :uniacid AND rid = :rid", array(':uniacid' => $_W['uniacid'], ':rid' => $rid));
		if(!empty($row)) { 
			return $this->respNews(
				array(
					'title' => $row['title'],
					'description' => $row['description'],
					'picurl'      => $row['avatar'],
					'url' => $this->createMobileUrl('Index')
				)
			);
		}

		if ($this->message['content']=='二维码') { 
			if ($this->message['msgtype'] == 'text' ||($this->message['msgtype'] == 'event' and $this->message['event'] == 'CLICK')) { 
				$account = $GLOBALS['_W']['account']; 
				$express = pdo_fetch("select * from " . tablename('wwx_fxxt_channel') . " WHERE uniacid=:uniacid and active=1 and isdel=0 limit 1", array(':uniacid' => $GLOBALS['_W']['uniacid'])); 
				$profile = pdo_fetch('SELECT * FROM '.tablename('wwx_fxxt_member')." WHERE  uniacid = :uniacid  AND from_user = :from_user " , array(':uniacid' =>$GLOBALS['_W']['uniacid'],':from_user' => $this->message['from'])); 
				if(empty($profile['id'])) { 
					$regurl=$GLOBALS['_W']['siteroot']."app/index.php?c=entry&m=wwx_fxxt&do=fansIndex&i=".$GLOBALS['_W']['uniacid']; 
					return $this->respText("请先注册成代理! <a href='".$regurl."'>马上注册成为分销员</a>");
				} 
				
				if ($profile['flag'] == 0 && $cfg['dimensionalcode'] == 0) {
					return $this->respText("您还不是代理,不能使用专属二维码功能!");
				}
				
				if(!empty($express['channel'])) { 
					$homeurl=$GLOBALS['_W']['siteroot']."app/index.php?c=entry&m=wwx_fxxt&do=list&i=".$GLOBALS['_W']['uniacid'].'&mid='.$profile['id']; 
					$theone = pdo_fetch('SELECT ischeck FROM ' . tablename('wwx_fxxt_rules') . ' WHERE  uniacid = :uniacid', array(':uniacid' => $GLOBALS['_W']['uniacid']));
					if ($profile['dzdflag'] == 1 && $profile['flag'] == 1 && $theone['ischeck'] == 2) {
						$homeurl = $homeurl . '&dzdid=' . $profile['id'];
					}
					$follow = pdo_fetch("select * from " . tablename('wwx_fxxt_follow') . " WHERE uniacid=:uniacid and follower=:from_user limit 1", array(':uniacid' => $GLOBALS['_W']['uniacid'],':from_user'=>$this->message['from'])); 
					if(!empty($follow['follower'])) { 
						if($follow['createtime'] > TIMESTAMP) { 
							exit;
						}else{
							pdo_update('wwx_fxxt_follow', array( 'createtime' => TIMESTAMP+(3)), array('uniacid'=> $GLOBALS['_W']['uniacid'],'follower'=> $this->message['from']));
						}
					}else{
						$insert = array( 'uniacid' => $GLOBALS['_W']['uniacid'], 'follower' => $this->message['from'], 'leader' => $this->message['from'], 'channel' => '', 'credit' => 0, 'createtime' => TIMESTAMP+(3));
						pdo_insert('wwx_fxxt_follow', $insert);
					} 
						
					$qmjf_qr = pdo_fetch("select * from " . tablename('wwx_fxxt_qr') . " WHERE uniacid=:uniacid and from_user=:from_user and channel=:channel  limit 1", array(':uniacid' => $GLOBALS['_W']['uniacid'],':from_user'=>$this->message['from'],':channel'=>$express['channel'])); 
			
					if((empty($qmjf_qr['id'])||empty($qmjf_qr['qr_url'])||empty($qmjf_qr['media_id'])||empty($qmjf_qr['id'])) || (!empty($qmjf_qr['expiretime']) && $qmjf_qr['expiretime'] < TIMESTAMP)) { 
						pdo_update('wwx_fxxt_follow', array( 'createtime' => TIMESTAMP+(6)), array('uniacid'=> $GLOBALS['_W']['uniacid'],'follower'=> $this->message['from']));
						if(!empty($express['notice'])) { 
							$this->sendcustomMsg($account,$this->message['from'],$express['notice']);///P3.根据公众号信息和用户OPENID发送微信消息
						}

						if(empty($qmjf_qr['id'])) { 
							$insert = array( 'uniacid' => $GLOBALS['_W']['uniacid'], 'from_user' => $this->message['from'], 'channel' => $express['channel'], 'qr_url' => '', 'media_id' => 0, 'expiretime' => TIMESTAMP+(60*24*6), 'createtime' => TIMESTAMP);
							pdo_insert('wwx_fxxt_qr', $insert);
						} 
						$tqmjf_qr = pdo_fetch("select * from " . tablename('wwx_fxxt_qr') . " WHERE uniacid=:uniacid and from_user=:from_user and channel=:channel  limit 1", array(':uniacid' => $GLOBALS['_W']['uniacid'],':from_user'=>$this->message['from'],':channel'=>$express['channel']));
						$newid = $tqmjf_qr['id']; 
						if(!empty($profile['id'])){
							$qrfile=$this->getURLQR($profile['id'],$this->message['from'],$homeurl);///P1.海报生成之二维码
						}else{ 
							$qrfile=$this->getURLQR(0,$this->message['from'],$homeurl);///P1.海报生成之二维码
						}
						for($a=0;$a<3;$a++) { 
							$qrpic=$this->genImage($express['bg'],$qrfile,$GLOBALS['_W']['uniacid'],$this->message['from']);///P2.生成海报之海报与头像
							if(!empty($qrpic)) { 
								$a=4;
							}
						}
						$media_id = $this->uploadImage($account,IA_ROOT .$qrpic); ///P10.上传下载多媒体文件
						$content = @json_decode($media_id, true);
						pdo_update('wwx_fxxt_qr', array( 'expiretime' => TIMESTAMP+(86400*2), 'media_id' => $content['media_id'],'qr_url' => $qrpic), array('id'=> $newid)); 
						$this->sendcustomIMG($account,$this->message['from'],$content['media_id']);///P13.发送客服消息
						exit(); 
					}else { 
						return $this->respImage($qmjf_qr['media_id']);
					}
				}else { 
					return $this->respText('商家未设置二维码生成');
				}
			}
		}
	} 

///P10.上传下载多媒体文件
	public function uploadImage($account,$img)
	{
		return $this->uploadRes($this->get_weixin_token($account), $img, 'image');///P4.根据公众号信息解析微信公众号授权token///P11.上传下载多媒体文件
	}
	
///P11.上传下载多媒体文件
	private function uploadRes($access_token, $img, $type)
	{
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type={$type}"; 
		$post = array( 'media' => '@' . $img ); 
		$ret =$this->curlPost($url,$post);///P12.CURL方式访问网络
		return $ret;
	} 
	
///P12.CURL方式访问网络
	public function curlPost($url,$data)
	{ 
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url); 
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); 
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
		$info = curl_exec($ch);
		curl_close($ch); 
		return $info;
	} 

///P13.发送客服消息
	public function sendcustomIMG($account,$from_user,$msg)
	{ 
		$access_token=$this->get_weixin_token($account);///P4.根据公众号信息解析微信公众号授权token
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}"; 
		$msg = str_replace('"', '\\"', $msg);
		$post='{"touser":"'.$from_user.'","msgtype":"image","image":{"media_id":"'.$msg.'"}}'; 
		$this->curlPost($url,$post);///P12.CURL方式访问网络
	} 

///P14.由文件或 URL 创建一个新图象
	private function imagecreate($bg)
	{ 
		$bgImg = @imagecreatefromjpeg($bg); 
			if (FALSE == $bgImg)
			{ $bgImg = @imagecreatefrompng($bg); } 
			if (FALSE == $bgImg)
			{ $bgImg = @imagecreatefromgif($bg); } 
		return $bgImg;
	} 

}
 ?>