+
+EOF;
+ echo $script;
+ }
+
+ /**
+ * 微信端已上传图片下载到服务器
+ *
+ * @access static public
+ * @name uploadImageInWeixin
+ * @param $resp 传入地址
+ * @return json
+ */
+ static function uploadImageInWeixin($media_id) {
+ global $_W;
+ load()->func('communication');
+ load()->model('account');
+ load()->model('attachment');
+ load()->func('file');
+
+ $uniacccount = WeAccount::create($_W['acid']);
+ $access_token = $uniacccount->fetch_available_token();
+ $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' . $access_token . '&media_id=' . $media_id;
+ $resp = ihttp_get($url);
+ $setting = $_W['setting']['upload']['image'];
+ $setting['folder'] = "images/" . MODULE_NAME . '/' . date('Y/m/d', time());
+
+ if (is_error($resp)) {
+ $result['message'] = '提取文件失败, 错误信息: ' . $resp['message'];
+ return json_encode($result);
+ }
+ if (intval($resp['code']) != 200) {
+ $result['message'] = '提取文件失败: 未找到该资源文件.';
+ return json_encode($result);
+ }
+ if (!self::mkDirs(PATH_ATTACHMENT . $setting['folder'])) {
+ $result['message'] = '提取文件失败: 未找到服务器存放文件夹.';
+ return json_encode($result);
+ }
+
+ $ext = '';
+ switch ($resp['headers']['Content-Type']) {
+ case 'application/x-jpg' :
+ case 'image/jpeg' :
+ $ext = 'jpg';
+ break;
+ case 'image/png' :
+ $ext = 'png';
+ break;
+ case 'image/gif' :
+ $ext = 'gif';
+ break;
+ default :
+ $result['message'] = '提取资源失败, 资源文件类型错误.';
+ return json_encode($result);
+ break;
+ }
+
+ if (intval($resp['headers']['Content-Length']) > $setting['limit'] * 1024) {
+ $result['message'] = '上传的媒体文件过大(' . sizecount($size) . ' > ' . sizecount($setting['limit'] * 1024);
+ return json_encode($result);
+ }
+
+ $originname = pathinfo($url, PATHINFO_BASENAME);
+ $filename = file_random_name(PATH_ATTACHMENT . $setting['folder'], $ext);
+ $pathname = $setting['folder'] . "/" . $filename;
+ $fullname = PATH_ATTACHMENT . $pathname;
+ if (file_put_contents($fullname, $resp['content']) == false) {
+ $result['message'] = '提取失败.';
+ return json_encode($result);
+ }
+ //上传到远程附件
+ $_W['attachurl'] = attachment_set_attach_url();
+ if (!empty($_W['setting']['remote']['type']) && !empty($pathname)) {
+ $remotestatus = file_remote_upload($pathname);
+ if (is_error($remotestatus)) {
+ $result['message'] = '远程附件上传失败,请检查配置并重新上传';
+ return json_encode($result);
+ }
+ }
+
+ $info = array('name' => $originname, 'ext' => $ext, 'filename' => $pathname, 'attachment' => $pathname, 'url' => tomedia($pathname), 'is_image' => $type == 'image' ? 1 : 0, 'filesize' => filesize($fullname));
+ return json_encode($info);
+ }
+
+ /**
+ * 二维数组转一维数组
+ *
+ * @access static public
+ * @name i_array_column
+ * @param $input $columnKey $indexKey
+ * @return json
+ */
+ static function i_array_column($input, $columnKey, $indexKey = null) {
+ if (!function_exists('array_column')) {
+ $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
+ $indexKeyIsNull = (is_null($indexKey)) ? true : false;
+ $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
+ $result = array();
+ foreach ((array)$input as $key => $row) {
+ if ($columnKeyIsNumber) {
+ $tmp = array_slice($row, $columnKey, 1);
+ $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
+ } else {
+ $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
+ }
+ if (!$indexKeyIsNull) {
+ if ($indexKeyIsNumber) {
+ $key = array_slice($row, $indexKey, 1);
+ $key = (is_array($key) && !empty($key)) ? current($key) : null;
+ $key = is_null($key) ? 0 : $key;
+ } else {
+ $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
+ }
+ }
+ $result[$key] = $tmp;
+ }
+ return $result;
+ } else {
+ return array_column($input, $columnKey, $indexKey);
+ }
+ }
+
+ /**
+ * id转换
+ *
+ * @access public
+ * @name idSwitch
+ * @param 根据 $beforeType 获得 $afterType
+ * @return $id 具体值
+ */
+ static function idSwitch($beforeType, $afterType, $id) {
+ global $_W;
+ $returnid = 0;
+ $types = array('sid', 'sName', 'areaid', 'areaName', 'aid', 'aName', 'cateParentId', 'cateParentName', 'cateChildId', 'cateChildName');
+ if (!in_array($beforeType, $types) || !in_array($afterType, $types))
+ return FALSE;
+ switch ($beforeType) {
+ case 'sid' :
+ switch ($afterType) {
+ case 'areaid' :
+ $data = pdo_get(PDO_NAME . 'merchantuser', array('id' => $id), array('areaid'));
+ if ($data['areaid'])
+ $returnid = $data['areaid'];
+ break;
+ case 'aid' :
+ $data = pdo_get(PDO_NAME . 'merchantuser', array('id' => $id), array('areaid'));
+ if ($data['areaid'])
+ $data2 = pdo_get(PDO_NAME . 'oparea', array('areaid' => $data['areaid']), array('aid'));
+ if ($data2['aid'])
+ $returnid = $data2['aid'];
+ break;
+ case 'sName' :
+ $data = pdo_get(PDO_NAME . 'merchantdata', array('id' => $id), array('storename'));
+ $returnid = $data['storename'];
+ break;
+ };
+ break;
+ case 'areaid' :
+ switch ($afterType) {
+ case 'sid' :
+ $data = pdo_getall(PDO_NAME . 'merchantuser', array('areaid' => $id), array('id'));
+ if ($data)
+ $returnid = $data;
+ break;
+ case 'aid' :
+ $data2 = pdo_get(PDO_NAME . 'oparea', array('areaid' => $id), array('aid'));
+ if ($data2['aid'])
+ $returnid = $data2['aid'];
+ break;
+ case 'areaName' :
+ $data2 = pdo_get(PDO_NAME . 'area', array('id' => $id), array('name'));
+ $returnid = $data2['name'];
+ break;
+ };
+ break;
+ case 'aid' :
+ switch ($afterType) {
+ case 'sid' :
+ $data = pdo_getall(PDO_NAME . 'oparea', array('aid' => $id), array('areaid'));
+ if ($data) {
+ foreach ($data as $key => $value) {
+ $re[] = pdo_get(PDO_NAME . 'merchantuser', array('areaid' => $value['areaid']), array('id'));
+ }
+ }
+ $returnid = $re;
+ break;
+ case 'areaid' :
+ $returnid = pdo_getall(PDO_NAME . 'oparea', array('aid' => $id), array('areaid'));
+ break;
+ case 'aName' :
+ $returnid = pdo_get(PDO_NAME . 'agentusers', array('id' => $id), array('agentname'));
+ $returnid = $returnid['agentname'];
+ break;
+ };
+ break;
+ case 'cateParentId' :
+ switch ($afterType) {
+ case 'cateParentName' :
+ $data = pdo_get(PDO_NAME . 'category_store', array('id' => $id), array('name'));
+ $returnid = $data['name'];
+ break;
+ case 'cateChildName' :
+ $returnid = pdo_getall(PDO_NAME . 'category_store', array('parentid' => $id), array('name'));
+ break;
+ case 'cateChildId' :
+ $returnid = pdo_getall(PDO_NAME . 'category_store', array('parentid' => $id), array('id'));
+ break;
+ };
+ break;
+ case 'cateChildId' :
+ switch ($afterType) {
+ case 'cateParentId' :
+ $data = pdo_get(PDO_NAME . 'category_store', array('id' => $id), array('parentid'));
+ $returnid = $data['parentid'];
+ break;
+ case 'cateChildName' :
+ $returnid2 = pdo_get(PDO_NAME . 'category_store', array('id' => $id), array('name'));
+ $returnid = $returnid2['name'];
+ break;
+ case 'cateParentName' :
+ $returnid2 = pdo_get(PDO_NAME . 'category_store', array('id' => $id), array('parentid'));
+ $returnid1 = pdo_get(PDO_NAME . 'category_store', array('id' => $returnid2['parentid']), array('name'));
+ $returnid = $returnid1['name'];
+ break;
+ };
+ break;
+ }
+ return $returnid;
+ }
+
+ /**
+ * 查询单条数据
+ *
+ * @access static
+ * @name getSingelData($tablename,$array,$select='*')
+ * @param $tablename 表名 'tg_member'
+ * @param $where 查询条件 array('name'=>'qidada')
+ * @param $select 查询字段 " id,name "
+ * @return array
+ */
+ static function getSingelData($select, $tablename, $where) {
+ $data = self::createStandardWhereString($where);
+ return pdo_fetch("SELECT $select FROM " . tablename($tablename) . " WHERE $data[0] ", $data[1]);
+ }
+
+ /**
+ * 查询多条数据
+ *
+ * @access static
+ * @name getNumData($tablename,$where,$page,$num,$order='id DESC',$isNeadPager = true,$select = '*')
+ * @param $tablename 表名 'tg_member'
+ * @param $where 查询条件 array('name'=>'qidada')
+ * @param $select 查询字段 " id,name "
+ * @param $pindex 分页查询页码
+ * @param $psize 分页查询每页数量
+ * @param $order 排序查询
+ * @return $res array($data,$pager,$total) $data:查询的数据 $pager:分页结果 $total :数据总条数
+ */
+ static function getNumData($select, $tablename, $where, $order = 'id DESC', $pindex = 0, $psize = 0, $ifpage = 0) {
+ global $_W;
+ $data = self::createStandardWhereString($where);
+ $countStr = "SELECT COUNT(*) FROM " . tablename($tablename) . " WHERE $data[0] ";
+ $selectStr = "SELECT $select FROM " . tablename($tablename) . " WHERE $data[0] ";
+ $res = self::getDataIfPage($countStr, $selectStr, $data[1], $pindex, $psize, $order, $ifpage);
+ return $res;
+ }
+
+ /**
+ * 查询数据共用方法
+ *
+ * @access static
+ * @name getDataIfPage
+ * @param $tablename 表名 'tg_member'
+ * @param $where 查询条件 array('name'=>'qidada')
+ * @param $select 查询字段 " id,name "
+ * @param $pindex 分页查询页码
+ * @param $psize 分页查询每页数量
+ * @param $order 排序查询
+ * @return $res array($data,$pager,$total) $data:查询的数据 $pager:分页结果 $total :数据总条数
+ */
+ static function getDataIfPage($countStr, $selectStr, $params, $pindex = 0, $psize = 0, $order = 'id DESC', $ifpage = 0) {
+ $pindex = max(1, intval($pindex));
+ $total = $ifpage ? pdo_fetchcolumn($countStr, $params) : '';
+ if ($psize > 0 && $ifpage) {
+ $data = pdo_fetchall($selectStr . " ORDER BY $order " . " LIMIT " . ($pindex - 1) * $psize . ',' . $psize, $params);
+ } else {
+ $data = pdo_fetchall($selectStr . " ORDER BY $order", $params);
+ }
+ $pager = wl_pagination($total, $pindex, $psize);
+ return array($data, $pager, $total);
+ }
+
+ /**
+ * 创建标准查询条件字符串
+ *
+ * @access static
+ * @name createStandardWhereString($where)
+ * @param $where 查询条件 array('name'=>'qidada')
+ * 注:= ,>= ,<= <,>,@(模糊查询),#(in),^(or)必须紧挨字符 例:
+ * $where = array('id'=>1,'createtime<'=>time(),'@name'=>'qidada','#status'=>(1,2,3),'name^mobile^address'=>'15756361007');
+ * @return array
+ */
+ static function createStandardWhereString($where = array()) {
+ global $_W;
+ if (!is_array($where))
+ return false;
+ $where['uniacid'] = $where['uniacid'] > 0 ? $where['uniacid'] : $_W['uniacid'];
+ $sql = '';
+ foreach ($where as $k => $v) {
+ $i = 0;
+ if (isset($k) && $v === '')
+ wl_message('存在异常参数' . $k);
+ if (strpos($k, '>') !== false) {
+ $k = trim(trim($k), '>');
+ $eq = ' >= ';
+ } elseif (strpos($k, '<') !== false) {
+ $k = trim(trim($k), '<');
+ $eq = ' <= ';
+ } elseif (strpos($k, '@') !== false) {
+ $eq = ' LIKE ';
+ $k = trim(trim($k), '@');
+ $v = "%" . $v . "%";
+ } elseif (strpos($k, '#') !== false) {
+ $i = 1;
+ $eq = ' IN ';
+ $k = trim(trim($k), '#');
+ } elseif (strpos($k, '!=') !== false) {
+ $i = 1;
+ $eq = ' != ';
+ $k = trim(trim($k), '!=');
+ } elseif (strpos($k, '^') !== false) {
+ $i = 2;
+ $arr = explode("^", $k);
+ $num = count($arr);
+ $str = '(';
+ for ($j = 0; $j < $num; $j++) {
+ if ($num - $j == 1) {
+ $str .= $arr[$j] . " LIKE '%" . $v . "%'";
+ } else {
+ $str .= $arr[$j] . " LIKE '%" . $v . "%'" . " or ";
+ }
+ }
+ $str .= ')';
+ } elseif (strpos($k, '*') !== false) {
+ $i = 2;
+ $str = $v;
+ } else {
+ $eq = ' = ';
+ }
+ if ($i == 1) {
+ if (strpos($eq,'IN') !== false) {
+ if (strpos($v,'(') !== false) {
+ $sql .= 'AND `' . $k . '`' . $eq . $v . ' ';
+ } else {
+ $sql .= 'AND `' . $k . '`' . $eq . '(' . $v . ') ';
+ }
+ } else {
+ $sql .= 'AND `' . $k . '`' . $eq . $v . ' ';
+ }
+ } elseif ($i == 2) {
+ $sql .= 'AND ' . $str;
+ } else {
+ if ($params[':' . $k]) {
+ $sql .= 'AND `' . $k . '`' . $eq . ':2' . $k . ' ';
+ $params[':2' . $k] = $v;
+ } else {
+ $sql .= 'AND `' . $k . '`' . $eq . ':' . $k . ' ';
+ $params[':' . $k] = $v;
+ }
+ }
+
+ }
+ $sql = trim($sql, 'AND');
+ return array($sql, $params);
+ }
+
+ /**
+ * 将地区数组转化为标准地区数组
+ *
+ * @access static
+ * @name changeAreaArray
+ * @param $arr 带转化数组
+ * @return array
+ */
+ static function changeAreaArray($arr) {
+ $newarr = array();
+ foreach ($arr as $key => $value) {
+ $newarr[$value['id']]['title'] = $value['name'];
+ $newarr[$value['id']]['cities'] = array();
+ foreach ($value['children'] as $k => $v) {
+ $newarr[$value['id']]['cities'][$v['id']]['title'] = $v['name'];
+ }
+ }
+ return $newarr;
+ }
+
+ static function multi_array_sort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC) {
+ if (is_array($arrays)) {
+ foreach ($arrays as $array) {
+ if (is_array($array)) {
+ $key_arrays[] = $array[$sort_key];
+ } else {
+ return false;
+ }
+ }
+ } else {
+ return false;
+ }
+ array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
+ return $arrays;
+ }
+
+ /**
+ * Comment: 写入日志
+ * @param string $filename 文件名称
+ * @param string $path 日志路径
+ * @param string|array|int $filedata 日志内容
+ * @param string $name 日志标题名称
+ * @param bool $state 是否使用默认名称
+ * @return string
+ */
+ static function wl_log($filename, $path, $filedata,$name = '',$state = true) {
+ if($state){
+ $url_log = $path . "log/" . date('Y-m-d', time()) . "/" . $filename . ".log";
+ $url_dir = $path . "log/" . date('Y-m-d', time());
+ }else{
+ $url_log = $path.$filename . "/" . date('Y-m-d', time()) . "/" . $filename . ".log";
+ $url_dir = $path.$filename . "/" . date('Y-m-d', time());
+ }
+ if (!is_dir($url_dir)) {
+ mkdir($url_dir, 0777, true);
+ }
+ //写入日志
+ if($name){
+ $title = "/======= {$name} =====================================================================";
+ }else{
+ $title = '/=====================================================================================';
+ }
+ file_put_contents($url_log, var_export($title. date('Y-m-d H:i:s', time()) . '/', true) . PHP_EOL, FILE_APPEND);
+ file_put_contents($url_log, var_export($filedata, true) . PHP_EOL, FILE_APPEND);
+ return 'log_success';
+ }
+
+ /// 中国正常坐标系GCJ02协议的坐标,转到 百度地图对应的 BD09 协议坐标
+ /// 维度
+ /// 经度
+ static function Convert_GCJ02_To_BD09($lat, $lng) {
+ $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
+ $x = $lng;
+ $y = $lat;
+ $z = sqrt($x * $x + $y * $y) + 0.00002 * sin($y * $x_pi);
+ $theta = atan2($y, $x) + 0.000003 * cos($x * $x_pi);
+ $lng = $z * cos($theta) + 0.0065;
+ $lat = $z * sin($theta) + 0.006;
+ return array('lat' => $lat, 'lng' => $lng);
+ }
+
+ /// 百度地图对应的 BD09 协议坐标,转到 中国正常坐标系GCJ02协议的坐标
+ /// 维度
+ /// 经度
+ static function Convert_BD09_To_GCJ02($lat, $lng) {
+ $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
+ $x = $lng - 0.0065;
+ $y = $lat - 0.006;
+ $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
+ $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
+ $lng = $z * cos($theta);
+ $lat = $z * sin($theta);
+ return array('lat' => sprintf("%.6f", $lat), 'lng' => sprintf("%.6f", $lng));
+ }
+
+ //删除文件夹下所有文件
+ static function deleteAll($path, $delall = '') {
+ $op = dir($path);
+ while (false != ($item = $op->read())) {
+ if ($item == '.' || $item == '..') {
+ continue;
+ }
+ if (is_dir($op->path . '/' . $item)) {
+ self::deleteAll($op->path . '/' . $item);
+ rmdir($op->path . '/' . $item);
+ } else {
+ unlink($op->path . '/' . $item);
+ }
+ }
+ if ($delall == 1) {
+ rmdir($path);
+ }
+ }
+
+ //长链转短链
+ static function long2short($url = '') {
+ global $_W;
+ if (empty($url)) {
+ return FALSE;
+ }
+ if (!empty($_W['acid'])) {
+ $account = WeAccount::create($_W['acid']);
+ } else {
+ $acid = pdo_fetchcolumn("SELECT acid FROM " . tablename('account_wechats') . " WHERE `uniacid`=:uniacid LIMIT 1", array(':uniacid' => $_W['uniacid']));
+ $account = WeAccount::create($acid);
+ }
+ $result = $account->long2short($url);
+ return $result;
+ }
+
+ /**
+ * 表连接 分页
+ * @param $tatal int 总页数
+ * @param $pageIndex int 当前页
+ * @param $pageSize int 一页多少条数据
+ * */
+
+ static function pagination($total, $pageIndex, $pageSize = 15, $url = '', $context = array('before' => 5, 'after' => 4, 'ajaxcallback' => '', 'callbackfuncname' => '')) {
+ return 23;
+// $pdata = array('tcount' => 0, 'tpage' => 0, 'cindex' => 0, 'findex' => 0, 'pindex' => 0, 'nindex' => 0, 'lindex' => 0, 'options' => '');
+// if ($context['ajaxcallback']) {
+// $context['isajax'] = true;
+// }
+//
+// if ($context['callbackfuncname']) {
+// $callbackfunc = $context['callbackfuncname'];
+// }
+//
+// $pdata['tcount'] = $total;
+// $pdata['tpage'] = (empty($pageSize) || $pageSize < 0) ? 1 : ceil($total / $pageSize);
+// if ($pdata['tpage'] <= 1) {
+// return '';
+// }
+// $cindex = $pageIndex;
+// $cindex = min($cindex, $pdata['tpage']);
+// $cindex = max($cindex, 1);
+// $pdata['cindex'] = $cindex;
+// $pdata['findex'] = 1;
+// $pdata['pindex'] = $cindex > 1 ? $cindex - 1 : 1;
+// $pdata['nindex'] = $cindex < $pdata['tpage'] ? $cindex + 1 : $pdata['tpage'];
+// $pdata['lindex'] = $pdata['tpage'];
+//
+// if ($context['isajax']) {
+//
+// $pdata['faa'] = 'href="javascript:;" page="' . $pdata['findex'] . '" ' . ($callbackfunc ? 'onclick="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['findex'] . '\', this);return false;"' : '');
+// $pdata['paa'] = 'href="javascript:;" page="' . $pdata['pindex'] . '" ' . ($callbackfunc ? 'onclick="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['pindex'] . '\', this);return false;"' : '');
+// $pdata['naa'] = 'href="javascript:;" page="' . $pdata['nindex'] . '" ' . ($callbackfunc ? 'onclick="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['nindex'] . '\', this);return false;"' : '');
+// $pdata['laa'] = 'href="javascript:;" page="' . $pdata['lindex'] . '" ' . ($callbackfunc ? 'onclick="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['lindex'] . '\', this);return false;"' : '');
+// } else {
+// if ($url) {
+// $pdata['faa'] = 'href="?' . str_replace('*', $pdata['findex'], $url) . '"';
+// $pdata['paa'] = 'href="?' . str_replace('*', $pdata['pindex'], $url) . '"';
+// $pdata['naa'] = 'href="?' . str_replace('*', $pdata['nindex'], $url) . '"';
+// $pdata['laa'] = 'href="?' . str_replace('*', $pdata['lindex'], $url) . '"';
+// }
+// }
+//
+// $html = '';
+// return $html;
+ }
+
+ /**
+ * Comment: 数据分页
+ * Author: zzw
+ * @param String $table 表的名称
+ * @param number $page 当前页数 默认1
+ * @param number $pageNum 每页的数量 默认10
+ * @param array $where 查询条件
+ * @param array $field 要查询的字段 默认全部字段
+ * @param array $orderBy 要进行排序的字段
+ * @return array 返回当前页的所有内容
+ */
+ static function paging($table, $page, $pageNum, $where = array(), $field = array(), $orderBy = array()) {
+ global $_W;
+ $count = implode(pdo_get(PDO_NAME . $table, $where, array('count(id)')));
+ $pindex = max(1, intval($page));//页数
+ $psize = $pageNum ? $pageNum : 10;//每页的数量
+ $list = pdo_getslice(PDO_NAME . $table,
+ $where, array(($pindex - 1) * $psize, $psize), $count, $field, '', $orderBy);
+ return $list;
+ }
+
+ /**
+ * Comment: 将本地图片提交到远程服务器端
+ * Author: zzw
+ */
+ static function uploadImgServer($images) {
+ global $_W, $_GPC;
+ if ($_W['setting']['remote']['type'] > 0) {
+ $attachurl = attachment_set_attach_url();
+ foreach ($images as $k => $v) {
+ WeliamWeChat::file_remote_upload($v);
+ $images[$k] = $attachurl . $v;
+ }
+ }
+ }
+
+ /**
+ * Comment: 将url地址转为path路径 格式:model/controller/function
+ * Author: zzw
+ * @param $url
+ * @return string
+ */
+ static function urlRestore($url) {
+ $p = self::cut("p=", '&ac', $url);
+ $ac = self::cut("&ac=", '&do', $url);
+ $doStr = explode('&do', $url);
+ $do = self::cut("=", '&', $doStr[1]);
+ //$urlRestore = $p . '/' . $ac . '/' . $do;
+ $urlRestore = $p . '/' . $ac;
+ return $urlRestore;
+ }
+
+ /**
+ * Comment: 截取两个字符之间的字符
+ * Author: zzw
+ * @param $begin
+ * @param $end
+ * @param $str
+ * @return string
+ */
+ static public function cut($begin, $end, $str) {
+ $b = mb_strpos($str, $begin) + mb_strlen($begin);
+ $e = mb_strpos($str, $end) - $b;
+ return mb_substr($str, $b, $e);
+ }
+
+
+}
diff --git a/addons/weliam_smartcity/core/class/WeApp.class.php b/addons/weliam_smartcity/core/class/WeApp.class.php
new file mode 100644
index 0000000..58ca9ea
--- /dev/null
+++ b/addons/weliam_smartcity/core/class/WeApp.class.php
@@ -0,0 +1,190 @@
+ 0,"g" => 0,"b" => 0]。
+ $qrCode = $app->app_code->get($path, $optional);
+ //判断返回内容为数组 则为错误抛出 正常返回内容应该为对象
+ if(is_array($qrCode)) throw new Exception($qrCode['message']);
+ //储存太阳码信息
+ $filePath = 'addons/' . MODULE_NAME . '/data/qrcode/'.$_W['uniacid'].'/'.date("Y-m-d", time()) . '/';//保存路径
+ $savePath = IA_ROOT . '/' . $filePath;//保存完整路径
+ if (!file_exists($savePath . $name)) {
+ if (empty($name)) $name = md5(uniqid(microtime(true), true));
+ $qrCode->saveAs($savePath, $name);
+ }
+ return $filePath . $name;
+ } catch (Exception $e) {
+ //错误抛出
+ $error = $e->getMessage();
+ return error(0, $error);
+ }
+ }
+ /**
+ * Comment: 发送客服信息
+ * Author: zzw
+ * Date: 2019/11/18 18:55
+ * @param $input
+ * @throws \GuzzleHttp\Exception\GuzzleException
+ */
+ public static function CustomerService($input) {
+ global $_W;
+ #1、获取参数信息
+ $openid = $input['FromUserName'];//发送者的openid
+ $content = $input['Content'];//用户发送的内容
+ #1、获取社群信息
+ $communityInfo = pdo_get(PDO_NAME . "community", ['id' => $content,'uniacid' => $_W['uniacid']], ['communqrcode', 'media_id', 'reply', 'media_endtime']);
+ #1、获取小程序配置信息
+ $app = self::getFactoryConfig();
+ #2、小程序客服操作
+ try {
+ #2、判断图片id是否存在 不存在则上传图片换取图片id
+ if (empty($communityInfo['media_id']) || ($communityInfo['media_endtime'] < time())) {
+ #1、保证图片存在本地
+ $imgPath = PATH_ATTACHMENT.'/' . $communityInfo['communqrcode'];//文件在本地服务器暂存地址
+ wl_uploadImages($imgPath, tomedia($communityInfo['communqrcode']));
+ #1、保证图片存在本地
+ $updateImg = $app->media->uploadImage($imgPath); // $path 为本地文件路径
+ if ($updateImg['media_id']) {
+ $communityInfo['media_id'] = $updateImg['media_id'];
+ pdo_update(PDO_NAME . "community", ['media_id' => $updateImg['media_id'], 'media_endtime' => time() + 48*3600], ['id' => $content]);
+ }
+ }
+ #2、发送二维码图片
+ $message = new Raw(self::dataEncoding([
+ "touser" => $openid,
+ "msgtype" => 'image',
+ "image" => [
+ "media_id" => $communityInfo['media_id']
+ ]
+ ]));
+ $app->customer_service->message($message)->to($openid)->send();
+ #2、发送回复内容
+ $messagess = new Raw(self::dataEncoding([
+ "touser" => $openid,
+ "msgtype" => 'text',
+ "text" => [
+ "content" => $communityInfo['reply']
+ ]
+ ]));
+ $app->customer_service->message($messagess)->to($openid)->send();
+ } catch (Exception $e) {
+ //错误抛出
+ $error = $e->getMessage();
+ Util::wl_log('customerService', PATH_MODULE . "log/", ['error' => $error, 'input' => $input], '微信小程序客服 —— 错误信息', false); //写入日志记录
+ }
+ }
+ /**
+ * Comment: 微信小程序客服接口请求验证(配置接口时微信官方验证接口是否可用)
+ * Author: zzw
+ * Date: 2019/11/18 11:01
+ * @param $info
+ * @return bool|mixed
+ */
+ public static function pleaseVerification($info) {
+ $signature = $info["signature"];
+ $timestamp = $info["timestamp"];
+ $nonce = $info["nonce"];
+ $echostr = $info["echostr"];
+ if ($signature && $timestamp && $nonce && $echostr) {
+ $set = Setting::wlsetting_read('wxapp_config');
+ $token = $set['token'];
+ $tmpArr = array($token, $timestamp, $nonce);
+ sort($tmpArr, SORT_STRING);
+ $tmpStr = implode($tmpArr);
+ $tmpStr = sha1($tmpStr);
+ if ($tmpStr == $signature) {
+ return $echostr;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ }
+ /**
+ * Comment: 数据编码(json)
+ * Author: zzw
+ * Date: 2019/11/18 11:29
+ * @param $array
+ * @return false|mixed|string|string[]|null
+ */
+ public static function dataEncoding($array) {
+ if (version_compare(PHP_VERSION, '5.4.0', '<')) {
+ $str = json_encode($array);
+ $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i", function ($matchs) {
+ return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
+ }, $str);
+ return $str;
+ } else {
+ return json_encode($array, JSON_UNESCAPED_UNICODE);
+ }
+ }
+ /**
+ * Comment: 获取 EasyWeChat 的配置信息
+ * Author: zzw
+ * Date: 2019/11/7 15:41
+ * @return \EasyWeChat\MiniProgram\Application
+ */
+ protected static function getFactoryConfig() {
+ #1、生成配置信息
+ $set = Setting::wlsetting_read('wxapp_config');
+ $config = [
+ 'app_id' => trim($set['appid']),
+ 'secret' => trim($set['secret']),
+ 'response_type' => 'array',
+ ];
+ $object = Factory::miniProgram($config);
+ return $object;
+ }
+ /**
+ * Comment: 小程序手机号解密
+ * Author: zzw
+ * Date: 2020/9/8 9:22
+ * @param $session_key
+ * @param $iv
+ * @param $data
+ * @return array
+ * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
+ */
+ public static function decryptedMobile($session_key , $iv , $data){
+ $app = self::getFactoryConfig();
+ return $app->encryptor->decryptData($session_key, $iv, $data);
+ }
+
+
+
+
+
+
+
+}
+
+
+
diff --git a/addons/weliam_smartcity/core/class/WeChatPay.class.php b/addons/weliam_smartcity/core/class/WeChatPay.class.php
new file mode 100644
index 0000000..6b71ff0
--- /dev/null
+++ b/addons/weliam_smartcity/core/class/WeChatPay.class.php
@@ -0,0 +1,249 @@
+getCode($mid, $orderNum, $goodDescribe, $fee);
+ //开始支付数据的操作
+ $return = $pay->weixinapp();
+
+ return $return;
+ }
+
+ /**
+ * Comment: 更新数据
+ * Author: zzw
+ * @param $mid 用户id
+ * @param $orderNum 订单号
+ * @param $goodDescribe 商品描述
+ * @param $fee 实际支付金额
+ */
+ private function getCode($mid, $orderNum, $goodDescribe, $fee) {
+ $set = unserialize(pdo_getcolumn(PDO_NAME . "setting", array('key' => 'city_selection_set'), 'value'));
+ $this->appid = $set['appid'];//appid
+ $this->openid = pdo_getcolumn(PDO_NAME . "member", array('id' => $mid), array('wechat_openid')); //openid
+ $this->mch_id = $set['mch_id'];//mch_id 商户id
+ $this->key = $set['pay_key'];//key 支付key
+ $this->out_trade_no = $orderNum; //out_trade_no 订单号
+ $this->body = $goodDescribe; //body 商品描述
+ $this->total_fee = $fee; //total_fee 实际支付总金额
+ }
+
+ /**
+ * Comment: 微信小程序接口
+ * Author: zzw
+ * @return array
+ */
+ private function weixinapp() {
+ //统一下单接口
+ $unifiedorder = $this->unifiedorder();
+ $parameters = array(
+ 'appId' => $this->appid, //小程序ID
+ 'timeStamp' => '' . time() . '', //时间戳
+ 'nonceStr' => $this->createNoncestr(), //随机串
+ 'package' => 'prepay_id=' . $unifiedorder['prepay_id'], //数据包
+ 'signType' => 'MD5'//签名方式
+ );
+ //签名
+ $parameters['paySign'] = $this->getSign($parameters);
+ return $parameters;
+ }
+
+ /**
+ * Comment: 统一下单接口
+ * Author: zzw
+ * @return mixed
+ */
+ private function unifiedorder() {
+ $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
+ $parameters = array(
+ 'appid' => $this->appid, //小程序ID
+ 'mch_id' => $this->mch_id, //商户号
+ 'nonce_str' => $this->createNoncestr(), //随机字符串
+ 'body' => $this->body,//商品描述
+ 'out_trade_no' => $this->out_trade_no,//商户订单号
+ 'total_fee' => $this->total_fee * 100,//总金额 单位 分
+ 'notify_url' => 'http://www.weixin.qq.com/wxpay/pay.php',//通知地址 确保外网能正常访问
+ 'openid' => $this->openid, //用户id
+ 'trade_type' => 'JSAPI'//交易类型
+ );
+
+ //统一下单签名
+ $parameters['sign'] = $this->getSign($parameters);
+ $xmlData = $this->arrayToXml($parameters);
+ $return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
+
+ return $return;
+ }
+
+ /**
+ * Comment: 请求获取支付数据
+ * Author: zzw
+ * @param $xml
+ * @param $url
+ * @param int $second
+ * @return mixed
+ */
+ private static function postXmlCurl($xml, $url, $second = 30) {
+ $ch = curl_init();
+ //设置超时
+ curl_setopt($ch, CURLOPT_TIMEOUT, $second);
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //严格校验
+ //设置header
+ curl_setopt($ch, CURLOPT_HEADER, FALSE);
+ //要求结果为字符串且输出到屏幕上
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
+ //post提交方式
+ curl_setopt($ch, CURLOPT_POST, TRUE);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
+
+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
+ curl_setopt($ch, CURLOPT_TIMEOUT, 40);
+ set_time_limit(0);
+
+ //运行curl
+ $data = curl_exec($ch);
+ //返回结果
+ if ($data) {
+ curl_close($ch);
+ return $data;
+ } else {
+ $error = curl_errno($ch);
+ curl_close($ch);
+ return "curl出错,错误码:$error";
+ }
+ }
+
+ /**
+ * Comment: 数组转换成xml
+ * Author: zzw
+ * @param $arr
+ * @return string
+ */
+ private function arrayToXml($arr) {
+ $xml = "";
+ foreach ($arr as $key => $val) {
+ if (is_array($val)) {
+ $xml .= "<" . $key . ">" . arrayToXml($val) . "" . $key . ">";
+ } else {
+ $xml .= "<" . $key . ">" . $val . "" . $key . ">";
+ }
+ }
+ $xml .= "";
+ return $xml;
+ }
+
+ /**
+ * Comment: xml转换成数组
+ * Author: zzw
+ * @param $xml
+ * @return mixed
+ */
+ private function xmlToArray($xml) {
+
+
+ //禁止引用外部xml实体
+
+
+ libxml_disable_entity_loader(true);
+
+
+ $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
+
+
+ $val = json_decode(json_encode($xmlstring), true);
+
+
+ return $val;
+ }
+
+ /**
+ * Comment: 产生随机字符串,不长于32位
+ * Author: zzw
+ * @param int $length
+ * @return string
+ */
+ private function createNoncestr($length = 32) {
+ $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
+ $str = "";
+ for ($i = 0; $i < $length; $i++) {
+ $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
+ }
+ return $str;
+ }
+
+ /**
+ * Comment: 生成签名
+ * Author: zzw
+ * @param $Obj
+ * @return string
+ */
+ private function getSign($Obj) {
+ foreach ($Obj as $k => $v) {
+ $Parameters[$k] = $v;
+ }
+ //签名步骤一:按字典序排序参数
+ ksort($Parameters);
+ $String = $this->formatBizQueryParaMap($Parameters, false);
+ //签名步骤二:在string后加入KEY
+ $String = $String . "&key=" . $this->key;
+ //签名步骤三:MD5加密
+ $String = md5($String);
+ //签名步骤四:所有字符转为大写
+ $result_ = strtoupper($String);
+ return $result_;
+ }
+
+ /**
+ * Comment: 格式化参数,签名过程需要使用
+ * Author: zzw
+ * @param $paraMap
+ * @param $urlencode
+ * @return bool|string
+ */
+ private function formatBizQueryParaMap($paraMap, $urlencode) {
+ $buff = "";
+ ksort($paraMap);
+ foreach ($paraMap as $k => $v) {
+ if ($urlencode) {
+ $v = urlencode($v);
+ }
+ $buff .= $k . "=" . $v . "&";
+ }
+ if (strlen($buff) > 0) {
+ $reqPar = substr($buff, 0, strlen($buff) - 1);
+ }
+ return $reqPar;
+ }
+
+}
+
+
+
diff --git a/addons/weliam_smartcity/core/class/WeixinPay.class.php b/addons/weliam_smartcity/core/class/WeixinPay.class.php
new file mode 100644
index 0000000..c0e1102
--- /dev/null
+++ b/addons/weliam_smartcity/core/class/WeixinPay.class.php
@@ -0,0 +1,915 @@
+createNoncestr();
+
+ $data['sign'] = $this->getSign($data);
+
+ if (empty($data['appid']) || empty($data['mch_id'])) {
+ $rearr['return_msg'] = '请先在微擎的功能选项-支付参数内设置微信商户号和秘钥';
+ return $rearr;
+ }
+ if ($data['total_fee'] > $data['refund_fee']) {
+ $rearr['return_msg'] = '退款金额不能大于实际支付金额';
+ return $rearr;
+ }
+ $xml = $this->arrayToXml($data);
+ $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
+ $re = $this->wxHttpsRequestPem($xml, $url);
+ $rearr = $this->xmlToArray($re);
+
+ return $rearr;
+ }
+
+ //查询退款
+ public function checkRefund($transid) {
+ global $_W;
+ $setting = uni_setting($_W['uniacid'], array('payment'));
+ $data['appid'] = $_W['account']['key'];
+ $data['mch_id'] = $setting['payment']['wechat']['mchid'];
+ $data['transaction_id'] = $transid;
+ $data['nonce_str'] = $this->createNoncestr();
+ $data['sign'] = $this->getSign($data);
+
+ if (empty($data['appid']) || empty($data['mch_id'])) {
+ $rearr['return_msg'] = '请先在微擎的功能选项-支付参数内设置微信商户号和秘钥';
+ return $rearr;
+ }
+ $xml = $this->arrayToXml($data);
+ $url = "https://api.mch.weixin.qq.com/pay/refundquery";
+ $re = $this->wxHttpsRequestPem($xml, $url);
+ $rearr = $this->xmlToArray($re);
+
+ return $rearr;
+ }
+
+ //企业付款
+ public function finance($openid = '', $money = 0, $desc = '', $realname, $trade_no) {
+ global $_W;
+ $setting = uni_setting($_W['uniacid'], array('payment'));
+
+ $refund_setting = $setting['payment']['wechat_refund'];
+ if ($refund_setting['switch'] != 1) {
+ return error(1, '未开启微信退款功能!');
+ }
+ if (empty($refund_setting['key']) || empty($refund_setting['cert'])) {
+ return error(1, '缺少微信证书!');
+ }
+ $cert = authcode($refund_setting['cert'], 'DECODE');
+ $key = authcode($refund_setting['key'], 'DECODE');
+ file_put_contents(ATTACHMENT_ROOT . $_W['uniacid'] . '_wechat_refund_all.pem', $cert . $key);
+
+ $data = array();
+ $data['mch_appid'] = $_W['account']['key'];
+ $data['mchid'] = $setting['payment']['wechat']['mchid'];
+ $data['nonce_str'] = $this->createNoncestr();;
+ $data['partner_trade_no'] = $trade_no;
+ $data['openid'] = $openid;
+ if (!empty($realname)) {
+ $data['re_user_name'] = $realname;
+ }
+ $data['check_name'] = 'NO_CHECK';
+ $data['amount'] = $money * 100;
+ $data['desc'] = empty($desc) ? '商家佣金提现' : $desc;
+ $data['spbill_create_ip'] = gethostbyname($_SERVER["HTTP_HOST"]);
+ $data['sign'] = $this->getSign($data);
+ if (empty($data['mch_appid'])) {
+ $rearr['return_msg'] = '请先在微擎的功能选项-支付参数内设置微信商户号和秘钥';
+ return $rearr;
+ }
+ $xml = $this->arrayToXml($data);
+ $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
+ $re = $this->wxHttpsRequestPem($xml, $url);
+ $rearr = $this->xmlToArray($re);
+ return $rearr;
+ }
+
+ public function createNoncestr($length = 32) {
+ $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
+ $str = "";
+ for ($i = 0; $i < $length; $i++) {
+ $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
+ }
+ return $str;
+ }
+
+ function formatBizQueryParaMap($paraMap, $urlencode) {
+ $buff = "";
+ ksort($paraMap);
+ foreach ($paraMap as $k => $v) {
+ if ($urlencode) {
+ $v = urlencode($v);
+ }
+ $buff .= $k . "=" . $v . "&";
+ }
+ $reqPar;
+ if (strlen($buff) > 0) {
+ $reqPar = substr($buff, 0, strlen($buff) - 1);
+ }
+ return $reqPar;
+ }
+
+ public function getSign($Obj) {
+ global $_W;
+ $setting = uni_setting($_W['uniacid'], array('payment'));
+ foreach ($Obj as $k => $v) {
+ $Parameters[$k] = $v;
+ }
+ ksort($Parameters);
+ $String = $this->formatBizQueryParaMap($Parameters, false);
+ $String = $String . "&key=" . $setting['payment']['wechat']['apikey'];
+ $String = md5($String);
+ $result_ = strtoupper($String);
+ return $result_;
+ }
+
+ public function arrayToXml($arr) {
+ $xml = "";
+ foreach ($arr as $key => $val) {
+ if (is_numeric($val)) {
+ $xml .= "<" . $key . ">" . $val . "" . $key . ">";
+ } else {
+ $xml .= "<" . $key . ">" . $key . ">";
+ }
+ }
+ $xml .= "";
+ return $xml;
+ }
+
+ public function xmlToArray($xml) {
+ $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
+ return $array_data;
+ }
+
+
+ public function wxHttpsRequestPem($vars, $url, $second = 30, $aHeader = array()) {
+ global $_W;
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_TIMEOUT, $second);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+ curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
+ curl_setopt($ch, CURLOPT_SSLCERT, ATTACHMENT_ROOT . $_W['uniacid'] . '_wechat_refund_all.pem');
+ // curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
+ // curl_setopt($ch,CURLOPT_SSLKEY, PATH_DATA."cert/".$_W['uniacid']."/wechat/apiclient_key.pem");
+// curl_setopt($ch,CURLOPT_CAINFO,'PEM');
+// curl_setopt($ch,CURLOPT_CAINFO,IA_ROOT . '/attachment/feng_fightgroups/cert/' . $_W['uniacid'] . '/rootca.pem');
+ if (count($aHeader) >= 1) {
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
+ }
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
+ $data = curl_exec($ch);
+ unlink(ATTACHMENT_ROOT . $_W['uniacid'] . '_wechat_refund_all.pem');
+ if ($data) {
+ curl_close($ch);
+ return $data;
+ } else {
+ $error = curl_errno($ch);
+ echo "call faild, errorCode:$error\n";
+ curl_close($ch);
+ return false;
+ }
+ }
+
+ /**
+ * Comment: 发送微信红包
+ * Author: zzw
+ */
+ static public function sendingRedPackets($info) {
+ global $_W;
+ #1、验证签名证书
+ $setting = uni_setting($_W['uniacid'], array('payment'));
+ $refund_setting = $setting['payment']['wechat_refund'];
+ if ($refund_setting['switch'] != 1) {
+ return error(1, '未开启微信付款功能!');
+ }
+ if (empty($refund_setting['key']) || empty($refund_setting['cert'])) {
+ return error(1, '缺少微信证书!');
+ }
+ $cert = authcode($refund_setting['cert'], 'DECODE');
+ $key = authcode($refund_setting['key'], 'DECODE');
+ file_put_contents(ATTACHMENT_ROOT . $_W['uniacid'] . '_wechat_refund_all.pem', $cert . $key);
+ #2、基本信息
+ $payment = $setting['payment'];
+ $cloud = Cloud::wl_syssetting_read('auth');
+ $info = array(
+ 'nonce_str' => random(32),//随机码
+ 'mch_billno' => $info['mch_billno'],//订单号
+ 'mch_id' => $payment['wechat']['mchid'],//商户id
+ 'wxappid' => $_W['account']['key'],//appid
+ 'send_name' => $_W['wlsetting']['base']['name'],//平台名称
+ 're_openid' => $info['re_openid'],//收款人openid
+ 'total_amount' => $info['total_amount'],//发送金额 单位:分
+ 'total_num' => 1,//发送数量
+ 'wishing' => '恭喜发财,大吉大利',//留言
+ 'client_ip' => $cloud['ip'],//发送主机ip
+ 'act_name' => '红包提现',//$info['act_name'],//活动名称/商品名称
+ 'remark' => $info['remark'],//备注信息
+ 'scene_id' => 'PRODUCT_5'//使用场景 这里是渠道分润
+ );
+ #3、获取签名信息
+ ksort($info);
+ $sign = '';
+ foreach ($info as $k => $v) {
+ if (!empty($v)) {
+ $sign .= $k . '=' . $v . '&';
+ }
+ }
+ $sign .= "key=" . $setting['payment']['wechat']['apikey'];
+ $info['sign'] = strtoupper(md5($sign));
+ $pay = new WeixinPay();
+ $xml = $pay->arrayToXml($info);
+ $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
+ $re = $pay->wxHttpsRequestPem($xml, $url);
+ $rearr = $pay->xmlToArray($re);
+ return $rearr;
+ }
+
+ /**
+ * Comment: 红包打款 查询接口
+ * Author: zzw
+ * @return array|mixed
+ */
+ static public function getRedPacketsInfo($info) {
+ global $_W;
+ #1、验证签名证书
+ $setting = uni_setting($_W['uniacid'], array('payment'));
+ $refund_setting = $setting['payment']['wechat_refund'];
+ if ($refund_setting['switch'] != 1) {
+ return error(1, '未开启微信付款功能!');
+ }
+ if (empty($refund_setting['key']) || empty($refund_setting['cert'])) {
+ return error(1, '缺少微信证书!');
+ }
+ $cert = authcode($refund_setting['cert'], 'DECODE');
+ $key = authcode($refund_setting['key'], 'DECODE');
+ file_put_contents(ATTACHMENT_ROOT . $_W['uniacid'] . '_wechat_refund_all.pem', $cert . $key);
+ #2、基本信息
+ $payment = $setting['payment'];
+ $info = array(
+ 'nonce_str' => random(32),
+ 'mch_billno' => $info['mch_billno'],
+ 'mch_id' => $payment['wechat']['mchid'],
+ 'appid' => $_W['account']['key'],
+ 'bill_type' => 'MCHT',
+ );
+ #3、获取签名信息
+ ksort($info);
+ $sign = '';
+ foreach ($info as $k => $v) {
+ if (!empty($v)) {
+ $sign .= $k . '=' . $v . '&';
+ }
+ }
+ $sign .= "key=" . $setting['payment']['wechat']['apikey'];
+ $info['sign'] = strtoupper(md5($sign));
+ $pay = new WeixinPay();
+ $xml = $pay->arrayToXml($info);
+ $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo';
+ $re = $pay->wxHttpsRequestPem($xml, $url);
+ $rearr = $pay->xmlToArray($re);
+ return $rearr;
+ }
+
+ /**
+ * Comment: 获取平台分账信息
+ * Author: wlf
+ * Date: 2020/09/04 11:24
+ */
+ public function getSysAllInfo($price,$source,$set,$uniacid){
+ global $_W;
+ $_W['uniacid'] = $uniacid;
+ $cashset = Setting::wlsetting_read('cashset');
+ $payment_set = Setting::wlsetting_read('payment_set');
+ if($source != 3 && $cashset['wxsyspercent'] > 0){
+ $sysmoney = $price * $cashset['wxsyspercent'];
+ if($sysmoney > 0){
+ $paysetid = $payment_set['wechat']['wechat'];
+// if($_W['wlsetting']['cashset']['wxsysalltype'] == 1){
+// //添加关系
+// $res = self::addReceiver('MERCHANT_ID',$_W['wlsetting']['cashset']['wxmerchantid'],'SERVICE_PROVIDER',$_W['wlsetting']['cashset']['wxmerchantname'],$set);
+// if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
+// $data = [
+// 'type' => 'MERCHANT_ID',
+// 'account' => $_W['wlsetting']['cashset']['wxmerchantid'],
+// 'amount' => $sysmoney,
+// 'description' => '平台抽佣',
+// ];
+// }else{
+// file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+// }
+// }else if($_W['wlsetting']['cashset']['wxsysalltype'] == 2){
+// $cashopenid = pdo_getcolumn(PDO_NAME.'member',array('id'=>$_W['wlsetting']['cashset']['wxallmid']),'openid');
+// $res = self::addReceiver('PERSONAL_OPENID',$cashopenid,'SERVICE_PROVIDER','',$set);
+// if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
+// $data = [
+// 'type' => 'PERSONAL_OPENID',
+// 'account' => $cashopenid,
+// 'amount' => $sysmoney,
+// 'description' => '平台抽佣',
+// ];
+// }else{
+// file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+// }
+// }
+ }
+ }else if($source == 3 && $cashset['appsyspercent'] > 0){
+ $sysmoney = $price * $cashset['appsyspercent'];
+ if($sysmoney > 0){
+ $paysetid = $payment_set['wxapp']['wechat'];
+// if($_W['wlsetting']['cashset']['appsysalltype'] == 1){
+// $res = self::addReceiver('MERCHANT_ID',$_W['wlsetting']['cashset']['appmerchantid'],'SERVICE_PROVIDER',$_W['wlsetting']['cashset']['appmerchantname'],$set);
+// if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
+// $data = [
+// 'type' => 'MERCHANT_ID',
+// 'account' => $_W['wlsetting']['cashset']['appmerchantid'],
+// 'amount' => $sysmoney,
+// 'description' => '平台抽佣',
+// ];
+// }else{
+// file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+// }
+// }else if($_W['wlsetting']['cashset']['appsysalltype'] == 2){
+// $cashopenid = pdo_getcolumn(PDO_NAME.'member',array('id'=>$_W['wlsetting']['cashset']['appallmid']),'wechat_openid');
+// $res = self::addReceiver('PERSONAL_OPENID',$cashopenid,'SERVICE_PROVIDER','',$set);
+// if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
+// $data = [
+// 'type' => 'PERSONAL_OPENID',
+// 'account' => $cashopenid,
+// 'amount' => $sysmoney,
+// 'description' => '平台抽佣',
+// ];
+// }else{
+// file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+// }
+// }
+ }
+ }
+ if($paysetid > 0){
+ $info = pdo_get(PDO_NAME."payment",['id'=>$paysetid]);
+ $Setinfo = json_decode($info['param'],true);
+ $res = self::addReceiver('MERCHANT_ID',$Setinfo['sub_shop_number'],'SERVICE_PROVIDER',$Setinfo['merchantname'],$set);
+ if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
+ $data = [
+ 'type' => 'MERCHANT_ID',
+ 'account' => $Setinfo['sub_shop_number'],
+ 'amount' => $sysmoney,
+ 'description' => '平台抽佣',
+ ];
+ }else{
+ file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+ }
+ }
+ return !empty($data) ? $data : 0;
+ }
+
+ /**
+ * Comment: 获取分销分账信息
+ * Author: wlf
+ * Date: 2020/09/04 14:15
+ */
+ public function getDisAllInfo($disid,$disprice,$source,$set){
+ global $_W;
+ if($source == 1){
+ $openid = pdo_getcolumn(PDO_NAME.'member',array('distributorid'=>$disid),'openid');
+ }else{
+ $openid = pdo_getcolumn(PDO_NAME.'member',array('distributorid'=>$disid),'wechat_openid');
+ }
+ if(!empty($openid)){
+ $res = self::addReceiver('PERSONAL_OPENID',$openid,'DISTRIBUTOR','',$set);
+ if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
+ $data = [
+ 'type' => 'PERSONAL_OPENID',
+ 'account' => $openid,
+ 'amount' => $disprice * 100,
+ 'description' => '分佣',
+ ];
+ }else{
+ file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+ }
+ }
+ return !empty($data) ? $data : 0;
+ }
+
+ /**
+ * Comment: 获取业务员分账信息
+ * Author: wlf
+ * Date: 2020/09/04 15:53
+ */
+ public function getSaleAllInfo($mid,$salesprice,$source,$set){
+ global $_W;
+ if($source == 1){
+ $openid = pdo_getcolumn(PDO_NAME.'member',array('mid'=>$mid),'openid');
+ }else{
+ $openid = pdo_getcolumn(PDO_NAME.'member',array('mid'=>$mid),'wechat_openid');
+ }
+ if(!empty($openid)){
+ $res = self::addReceiver('PERSONAL_OPENID',$openid,'STAFF','',$set);
+ if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
+ $data = [
+ 'type' => 'PERSONAL_OPENID',
+ 'account' => $openid,
+ 'amount' => $salesprice * 100,
+ 'description' => '业务员',
+ ];
+ }else{
+ file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+ }
+ }
+ return !empty($data) ? $data : 0;
+ }
+
+ /**
+ * Comment: 获取代理分账信息
+ * Author: wlf
+ * Date: 2020/09/04 16:09
+ */
+ public function getAgentAllInfo($aid,$agentprice,$source,$set){
+ global $_W;
+ $agentset = pdo_get('wlmerchant_agentusers',array('id' => $aid),array('wxpaysetid','apppaysetid'));
+ if($source == 1 || $source == 2){
+ $paysetid = $agentset['wxpaysetid'];
+// if($agentset['wxsysalltype'] == 1){
+// //添加关系
+// $res = self::addReceiver('MERCHANT_ID',$agentset['wxmerchantid'],'PARTNER',$agentset['wxmerchantname'],$set);
+// if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
+// $data = [
+// 'type' => 'MERCHANT_ID',
+// 'account' => $agentset['wxmerchantid'],
+// 'amount' => $agentprice * 100,
+// 'description' => '代理抽佣',
+// ];
+// }else{
+// file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+// }
+// }else{
+// //添加关系
+// $cashopenid = pdo_getcolumn(PDO_NAME.'member',array('id'=>$agentset['wxallmid']),'openid');
+// $res = self::addReceiver('PERSONAL_OPENID',$cashopenid,'PARTNER','',$set);
+// if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
+// $data = [
+// 'type' => 'PERSONAL_OPENID',
+// 'account' => $cashopenid,
+// 'amount' => $agentprice * 100,
+// 'description' => '代理抽佣',
+// ];
+// }else{
+// file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+// }
+// }
+ }else if($source == 3){
+ $paysetid = $agentset['apppaysetid'];
+// if($agentset['appsysalltype'] == 1){
+// //添加关系
+// $res = self::addReceiver('MERCHANT_ID',$agentset['appmerchantid'],'PARTNER',$agentset['appmerchantname'],$set);
+// if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
+// $data = [
+// 'type' => 'MERCHANT_ID',
+// 'account' => $agentset['appmerchantid'],
+// 'amount' => $agentprice * 100,
+// 'description' => '代理抽佣',
+// ];
+// }else{
+// file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+// }
+// }else{
+// //添加关系
+// $cashopenid = pdo_getcolumn(PDO_NAME.'member',array('id'=>$agentset['appallmid']),'wechat_openid');
+// $res = self::addReceiver('PERSONAL_OPENID',$cashopenid,'PARTNER','',$set);
+// if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
+// $data = [
+// 'type' => 'PERSONAL_OPENID',
+// 'account' => $cashopenid,
+// 'amount' => $agentprice * 100,
+// 'description' => '代理抽佣',
+// ];
+// }else{
+// file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+// }
+// }
+ }
+ if($paysetid > 0){
+ $info = pdo_get(PDO_NAME."payment",['id'=>$paysetid]);
+ $Setinfo = json_decode($info['param'],true);
+ $res = self::addReceiver('MERCHANT_ID',$Setinfo['sub_shop_number'],'SERVICE_PROVIDER',$Setinfo['merchantname'],$set);
+ if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
+ $data = [
+ 'type' => 'MERCHANT_ID',
+ 'account' => $Setinfo['sub_shop_number'],
+ 'amount' => $agentprice * 100,
+ 'description' => '代理抽佣',
+ ];
+ }else{
+ file_put_contents(PATH_DATA . "allocation_error.log", var_export($res, true) . PHP_EOL, FILE_APPEND);
+ }
+ }
+ return !empty($data) ? $data : 0;
+ }
+
+ /**
+ * Comment: 服务商订单结算分账借口
+ * Author: wlf
+ * Date: 2020/09/08 14:10
+ */
+ public function allocationPro($orderid,$type,$source,$salesinfo = [],$salesmoney = 0){
+ global $_W;
+ $receivers = [];
+ $sysmoney = $disonemoney = $distwomoney = $storemoney = 0;
+ //获取订单数据
+ switch ($type){
+ case '1':
+ $order = pdo_get(PDO_NAME.'rush_order',array('id'=>$orderid),array('sid','uniacid','settlementmoney','transid','aid','paysetid','orderno','actualprice','disorderid'));
+ $price = $order['actualprice'];
+ $storemoney = $order['settlementmoney'];
+ break;
+ case '4':
+ $order = pdo_get(PDO_NAME.'halfcard_record',array('id'=>$orderid),array('transid','uniacid','aid','paysetid','orderno','price','disorderid'));
+ $price = $order['price'];
+ break;
+ default :
+ $order = pdo_get(PDO_NAME.'order',array('id'=>$orderid),array('sid','settlementmoney','transid','uniacid','plugin','aid','paysetid','orderno','price','disorderid'));
+ $price = $order['price'];
+ $plugin = $order['plugin'];
+ $storemoney = $order['settlementmoney'];
+ break;
+ }
+ if(empty($order['transid'])) {
+ $order['transid'] = pdo_getcolumn(PDO_NAME . 'paylogvfour', array('tid' => $order['orderno']), 'transaction_id');
+ }
+ //基础信息
+ $getUrl = "https://api.mch.weixin.qq.com/secapi/pay/profitsharing";
+ $filePath = PATH_ATTACHMENT . "public_file/" . MODULE_NAME . "/";
+ $id = $order['paysetid'];
+ $info = pdo_get(PDO_NAME."payment",['id'=>$id]);
+ $setting = json_decode($info['param'],true);
+ //获取平台分账信息
+ $sysinfo = self::getSysAllInfo($price,$source,$setting,$order['uniacid']);
+ if(!empty($sysinfo)){
+ $receivers[] = $sysinfo;
+ $sysmoney = sprintf("%.2f",$sysinfo['amount'] / 100);
+ }
+ //获取分销分账信息
+ if($order['disorderid'] > 0){
+ $disorder = pdo_get('wlmerchant_disorder',array('id' => $order['disorderid']),array('oneleadid','twoleadid','leadmoney'));
+ $leadmoney = unserialize($disorder['leadmoney']);
+ if($disorder['oneleadid'] > 0 && $leadmoney['one'] > 0){
+ $onedisinfo = self::getDisAllInfo($disorder['oneleadid'],$leadmoney['one'],$source,$setting);
+ if(!empty($sysinfo)){
+ $receivers[] = $onedisinfo;
+ }
+ $disonemoney = $leadmoney['one'];
+ }
+ if($disorder['twoleadid'] > 0 && $leadmoney['two'] > 0){
+ $onedisinfo = self::getDisAllInfo($disorder['twoleadid'],$leadmoney['two'],$source,$setting);
+ if(!empty($sysinfo)){
+ $receivers[] = $onedisinfo;
+ }
+ $distwomoney = $leadmoney['two'];
+ }
+ }
+ //获取业务员信息
+ if(!empty($salesinfo) && $salesmoney > 0){
+ foreach($salesinfo as $sinfo){
+ $saleallinfo = self::getSaleAllInfo($sinfo['mid'],$sinfo['reportmoney'],$source,$setting);
+ if(!empty($saleallinfo)){
+ $receivers[] = $saleallinfo;
+ }
+ }
+ }
+ //获取代理分账信息
+ if(!empty($order['sid']) || $plugin == 'store'){
+ $agentmoney = sprintf("%.2f",$price - $sysmoney - $disonemoney - $storemoney - $distwomoney - $salesmoney);
+ if($agentmoney > 0 && $order['aid'] > 0){
+ $agentallinfo = self::getAgentAllInfo($order['aid'],$agentmoney,$source,$setting);
+ if(!empty($agentallinfo)){
+ $receivers[] = $agentallinfo;
+ }
+ }
+ }
+
+ //生成分账方面
+ if(count($receivers)>0){
+ $receivers = json_encode($receivers);
+ $data = [
+ 'mch_id' => $setting['shop_number'],
+ 'sub_mch_id' => $setting['sub_shop_number'],
+ 'appid' => $setting['sub_up_app_id'],
+ 'nonce_str' => $this -> createNoncestr(),
+ 'transaction_id' => $order['transid'],
+ 'out_order_no' => 'PP'.date('YmdHis').random(4,1),
+ 'receivers' => $receivers,
+ ];
+ $data['sign'] = $this->getWlfSign($data,$setting['secret_key']);
+
+ $cert = trim($filePath . $setting['cert_certificate']);
+ $key = trim($filePath . $setting['key_certificate']);
+
+ $xml = $this->arrayToXml($data);
+ $re = $this->wxWlfHttpsRequestPem($xml,$getUrl,30,[],$cert,$key);
+ $rearr = $this->xmlToArray($re);
+ if($rearr['return_code'] == 'SUCCESS' && $rearr['result_code'] == 'SUCCESS'){
+ $result = [
+ 'status' => 1,
+ 'agentmoney' => $agentmoney > 0 ? $agentmoney : 0,
+ 'sysmoney' => $sysmoney
+ ];
+ return $result;
+ }else{
+ file_put_contents(PATH_DATA . "allocation_error.log", var_export($rearr, true) . PHP_EOL, FILE_APPEND);
+ return 0;
+ }
+ }else{
+ //完成结算
+ $data = [
+ 'mch_id' => $setting['shop_number'],
+ 'sub_mch_id' => $setting['sub_shop_number'],
+ 'appid' => $setting['sub_up_app_id'],
+ 'nonce_str' => $this -> createNoncestr(),
+ 'transaction_id' => $order['transid'],
+ 'out_order_no' => 'PP'.date('YmdHis').random(4,1),
+ 'description' => '分账已完成',
+ ];
+ $data['sign'] = $this->getWlfSign($data,$setting['secret_key']);
+ $cert = trim($filePath . $setting['cert_certificate']);
+ $key = trim($filePath . $setting['key_certificate']);
+
+ $getUrl = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharingfinish';
+ $xml = $this->arrayToXml($data);
+ $re = $this->wxWlfHttpsRequestPem($xml,$getUrl,30,[],$cert,$key);
+ $rearr = $this->xmlToArray($re);
+ if($rearr['return_code'] == 'SUCCESS' && $rearr['result_code'] == 'SUCCESS'){
+ $result = [
+ 'status' => 1,
+ 'agentmoney' => $agentmoney > 0 ? $agentmoney : 0,
+ 'sysmoney' => $sysmoney > 0 ? : 0
+ ];
+ return $result;
+ }else{
+ file_put_contents(PATH_DATA . "allocation_error.log", var_export($rearr, true) . PHP_EOL, FILE_APPEND);
+ return 0;
+ }
+ }
+ }
+
+ /**
+ * Comment: 服务商核销码分账借口
+ * Author: wlf
+ * Date: 2020/08/31 10:46
+ */
+ public function allocationMulti($orderid,$source,$salesinfo = [],$salesmoney = 0){ // $source = 1公众号 3小程序
+ global $_W;
+ //获取订单数据
+ $receivers = [];
+ $sysmoney = 0;
+ $smallorder = pdo_get('wlmerchant_smallorder',array('id' => $orderid),array('aid','orderprice','plugin','orderid','settlemoney','sid','oneleadid','twoleadid','onedismoney','twodismoney'));
+ $price = $smallorder['orderprice'];
+ if($smallorder['plugin'] == 'rush'){
+ $order = pdo_get('wlmerchant_rush_order',array('id' => $smallorder['orderid']),array('transid','uniacid','paysetid','orderno','allocationtype'));
+ }else{
+ $order = pdo_get('wlmerchant_order',array('id' => $smallorder['orderid']),array('transid','uniacid','paysetid','orderno','allocationtype'));
+ }
+ if(empty($order['transid'])) {
+ $order['transid'] = pdo_getcolumn(PDO_NAME . 'paylogvfour', array('tid' => $order['orderno']), 'transaction_id');
+ }
+ //基础信息
+ $getUrl = "https://api.mch.weixin.qq.com/secapi/pay/multiprofitsharing";
+ $filePath = PATH_ATTACHMENT . "public_file/" . MODULE_NAME . "/";
+ $id = $order['paysetid'];
+ $info = pdo_get(PDO_NAME."payment",['id'=>$id]);
+ $setting = json_decode($info['param'],true);
+
+ //获取平台分账信息
+ $sysinfo = self::getSysAllInfo($price,$source,$setting,$order['uniacid']);
+
+ if(!empty($sysinfo)){
+ $receivers[] = $sysinfo;
+ $sysmoney = sprintf("%.2f",$sysinfo['amount'] / 100);
+ }
+ //获取分销分账信息
+ if($smallorder['oneleadid'] > 0 && $smallorder['onedismoney'] > 0){
+ $onedisinfo = self::getDisAllInfo($smallorder['oneleadid'],$smallorder['onedismoney'],$source,$setting);
+ if(!empty($sysinfo)){
+ $receivers[] = $onedisinfo;
+ }
+ }
+ if($smallorder['twoleadid'] > 0 && $smallorder['twodismoney'] > 0){
+ $onedisinfo = self::getDisAllInfo($smallorder['twoleadid'],$smallorder['twodismoney'],$source,$setting);
+ if(!empty($sysinfo)){
+ $receivers[] = $onedisinfo;
+ }
+ }
+ //获取业务员信息
+ if(!empty($salesinfo) && $salesmoney > 0){
+ foreach($salesinfo as $sinfo){
+ $saleallinfo = self::getSaleAllInfo($sinfo['mid'],$sinfo['reportmoney'],$source,$setting);
+ if(!empty($saleallinfo)){
+ $receivers[] = $saleallinfo;
+ }
+ }
+ }
+ //获取代理分账信息
+ $agentmoney = sprintf("%.2f",$price - $sysmoney - $smallorder['settlemoney'] - $smallorder['onedismoney'] - $smallorder['twodismoney'] - $salesmoney);
+ if($agentmoney > 0 && $smallorder['aid'] > 0){
+ $agentallinfo = self::getAgentAllInfo($smallorder['aid'],$agentmoney,$source,$setting);
+ if(!empty($agentallinfo)){
+ $receivers[] = $agentallinfo;
+ }
+ }
+ //生成分账方面
+ if(count($receivers)>0){
+ $receivers = json_encode($receivers);
+ $data = [
+ 'mch_id' => $setting['shop_number'],
+ 'sub_mch_id' => $setting['sub_shop_number'],
+ 'appid' => $setting['sub_up_app_id'],
+ 'nonce_str' => $this -> createNoncestr(),
+ 'transaction_id' => $order['transid'],
+ 'out_order_no' => 'PP'.date('YmdHis').random(4,1),
+ 'receivers' => $receivers,
+ ];
+ $data['sign'] = $this->getWlfSign($data,$setting['secret_key']);
+
+ $cert = trim($filePath . $setting['cert_certificate']);
+ $key = trim($filePath . $setting['key_certificate']);
+
+ $xml = $this->arrayToXml($data);
+ $re = $this->wxWlfHttpsRequestPem($xml,$getUrl,30,[],$cert,$key);
+ $rearr = $this->xmlToArray($re);
+ if($rearr['return_code'] == 'SUCCESS' && $rearr['result_code'] == 'SUCCESS'){
+ $result = [
+ 'status' => 1,
+ 'agentmoney' => $agentmoney > 0 ? $agentmoney : 0,
+ 'sysmoney' => $sysmoney
+ ];
+ return $result;
+ }else{
+ file_put_contents(PATH_DATA . "allocation_error.log", var_export($rearr, true) . PHP_EOL, FILE_APPEND);
+ return 0;
+ }
+ }else{
+ $result = [
+ 'status' => 1,
+ 'agentmoney' => $agentmoney > 0 ? $agentmoney : 0,
+ 'sysmoney' => $sysmoney > 0 ? : 0
+ ];
+ return $result;
+ }
+ }
+
+ /**
+ * Comment: 添加分账方接口
+ * Author: wlf
+ * Date: 2020/08/31 15:27
+ */
+ public function addReceiver($type,$account,$relation_type,$name = '',$setting){
+ global $_W;
+ $getUrl = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";
+ //生成分账方面
+ $receiver = [
+ 'type' => $type,
+ 'account' => $account,
+ 'relation_type' => $relation_type,
+ ];
+ if($type == 'MERCHANT_ID'){
+ $receiver['name'] = $name;
+ }
+ $receiver = json_encode($receiver);
+ $data = [
+ 'mch_id' => $setting['shop_number'],
+ 'sub_mch_id' => $setting['sub_shop_number'],
+ 'appid' => $setting['sub_up_app_id'],
+ 'nonce_str' => $this -> createNoncestr(),
+ 'receiver' => $receiver,
+ ];
+ $data['sign'] = $this->getWlfSign($data,$setting['secret_key']);
+ $xml = $this->arrayToXml($data);
+ $re = $this->wxWlfHttpsRequestPem($xml,$getUrl);
+ $rearr = $this->xmlToArray($re);
+
+ return $rearr;
+ }
+
+ /**
+ * Comment: 完结分账接口
+ * Author: wlf
+ * Date: 2020/09/04 18:10
+ */
+ public function allocationFinish($orderid){
+ global $_W;
+ $smallorder = pdo_get('wlmerchant_smallorder',array('id' => $orderid),array('aid','orderprice','plugin','orderid','settlemoney','sid','oneleadid','twoleadid','onedismoney','twodismoney'));
+ $price = $smallorder['orderprice'];
+ if($smallorder['plugin'] == 'rush'){
+ $order = pdo_get('wlmerchant_rush_order',array('id' => $smallorder['orderid']),array('transid','paysetid','orderno','allocationtype'));
+ }else{
+ $order = pdo_get('wlmerchant_order',array('id' => $smallorder['orderid']),array('transid','paysetid','orderno','allocationtype'));
+ }
+ if(empty($order['transid'])) {
+ $order['transid'] = pdo_getcolumn(PDO_NAME . 'paylogvfour', array('tid' => $order['orderno']), 'transaction_id');
+ }
+ //基础信息
+ $getUrl = "https://api.mch.weixin.qq.com/secapi/pay/profitsharingfinish";
+ $filePath = PATH_ATTACHMENT . "public_file/" . MODULE_NAME . "/";
+ $id = $order['paysetid'];
+ $info = pdo_get(PDO_NAME."payment",['id'=>$id]);
+ $setting = json_decode($info['param'],true);
+
+ $data = [
+ 'mch_id' => $setting['shop_number'],
+ 'sub_mch_id' => $setting['sub_shop_number'],
+ 'appid' => $setting['sub_up_app_id'],
+ 'nonce_str' => $this -> createNoncestr(),
+ 'transaction_id' => $order['transid'],
+ 'out_order_no' => 'PP'.date('YmdHis').random(4,1),
+ 'description' => '订单已完成',
+ ];
+ $data['sign'] = $this->getWlfSign($data,$setting['secret_key']);
+
+ $cert = trim($filePath . $setting['cert_certificate']);
+ $key = trim($filePath . $setting['key_certificate']);
+
+ $xml = $this->arrayToXml($data);
+ $re = $this->wxWlfHttpsRequestPem($xml,$getUrl,30,[],$cert,$key);
+ $rearr = $this->xmlToArray($re);
+ if($rearr['return_code'] == 'SUCCESS' && $rearr['result_code'] == 'SUCCESS'){
+ return 1;
+ }else{
+ file_put_contents(PATH_DATA . "allocation_error.log", var_export($rearr, true) . PHP_EOL, FILE_APPEND);
+ return 0;
+ }
+
+ }
+
+
+ public function wxWlfHttpsRequestPem($vars, $url, $second = 30, $aHeader = array(),$cert = '',$key = '') {
+ global $_W;
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_TIMEOUT, $second);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+ if(!empty($cert)){
+ curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
+ curl_setopt($ch, CURLOPT_SSLCERT,$cert);
+ }
+ if(!empty($key)){
+ curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
+ curl_setopt($ch, CURLOPT_SSLKEY,$key);
+ }
+ // curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
+ // curl_setopt($ch,CURLOPT_SSLKEY, PATH_DATA."cert/".$_W['uniacid']."/wechat/apiclient_key.pem");
+// curl_setopt($ch,CURLOPT_CAINFO,'PEM');
+// curl_setopt($ch,CURLOPT_CAINFO,IA_ROOT . '/attachment/feng_fightgroups/cert/' . $_W['uniacid'] . '/rootca.pem');
+ if (count($aHeader) >= 1) {
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
+ }
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
+ $data = curl_exec($ch);
+ if ($data) {
+ curl_close($ch);
+ return $data;
+ } else {
+ $error = curl_errno($ch);
+ echo "call faild, errorCode:$error\n";
+ curl_close($ch);
+ return false;
+ }
+ }
+
+ public function getWlfSign($Obj,$key) {
+ global $_W;
+ foreach ($Obj as $k => $v) {
+ $Parameters[$k] = $v;
+ }
+ ksort($Parameters);
+ $String = $this->formatBizQueryParaMap($Parameters, false);
+ $String = $String . "&key=" . $key;
+ $String = hash_hmac("sha256",$String,$key);
+ $result_ = strtoupper($String);
+ return $result_;
+ }
+
+
+}
+
+?>
\ No newline at end of file
diff --git a/addons/weliam_smartcity/core/class/Weixinqrcode.class.php b/addons/weliam_smartcity/core/class/Weixinqrcode.class.php
new file mode 100644
index 0000000..d3cd2e8
--- /dev/null
+++ b/addons/weliam_smartcity/core/class/Weixinqrcode.class.php
@@ -0,0 +1,328 @@
+func('communication');
+ $barcode = array(
+ 'expire_seconds' => '',
+ 'action_name' => '',
+ 'action_info' => array(
+ 'scene' => array(),
+ ),
+ );
+
+ $scene_str = date('YmdHis') . rand(1000, 9999);
+ $uniacccount = WeAccount::create($_W['acid']);
+
+ if ($qrctype == 1) {
+ $qrcid = pdo_fetchcolumn("SELECT qrcid FROM " . tablename('qrcode') . " WHERE acid = :acid AND model = '1' AND type = 'scene' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $_W['acid']));
+ $barcode['action_info']['scene']['scene_id'] = !empty($qrcid) ? ($qrcid + 1) : 100001;
+ $barcode['expire_seconds'] = 2592000;
+ $barcode['action_name'] = 'QR_SCENE';
+ $result = $uniacccount->barCodeCreateDisposable($barcode);
+ } else if ($qrctype == 2) {
+ $is_exist = pdo_fetchcolumn('SELECT id FROM ' . tablename('qrcode') . ' WHERE uniacid = :uniacid AND scene_str = :scene_str AND model = 2', array(':uniacid' => $_W['uniacid'], ':scene_str' => $scene_str));
+ if (!empty($is_exist)) {
+ $scene_str = date('YmdHis') . rand(1000, 9999);
+ }
+ $barcode['action_info']['scene']['scene_str'] = $scene_str;
+ $barcode['action_name'] = 'QR_LIMIT_STR_SCENE';
+ $result = $uniacccount->barCodeCreateFixed($barcode);
+ }
+
+ if (!is_error($result)) {
+ $insert = array(
+ 'uniacid' => $_W['uniacid'],
+ 'acid' => $_W['acid'],
+ 'qrcid' => $barcode['action_info']['scene']['scene_id'],
+ 'scene_str' => $barcode['action_info']['scene']['scene_str'],
+ 'keyword' => $keyword,
+ 'name' => $name,
+ 'model' => $qrctype,
+ 'ticket' => $result['ticket'],
+ 'url' => $result['url'],
+ 'expire' => $result['expire_seconds'],
+ 'createtime' => TIMESTAMP,
+ 'status' => '1',
+ 'type' => 'scene',
+ );
+ pdo_insert('qrcode', $insert);
+ $qrid = pdo_insertid();
+ $qrinsert = array(
+ 'uniacid' => $_W['uniacid'],
+ 'aid' => $agentid,
+ 'qrid' => $qrid,
+ 'type' => $ptype,
+ 'model' => $qrctype,
+ 'cardsn' => $scene_str,
+ 'salt' => random(8),
+ 'createtime' => TIMESTAMP,
+ 'status' => '1',
+ 'remark' => $remark
+ );
+ pdo_insert(PDO_NAME . 'qrcode', $qrinsert);
+ return $qrid;
+ }
+ return $result;
+ }
+
+ static function get_qrid($message)
+ {
+ global $_W;
+ if (!empty($message['ticket'])) {
+ if (is_numeric($message['scene']) && mb_strlen($message['scene']) != 18) {
+ $qrid = pdo_fetchcolumn('select id from ' . tablename('qrcode') . ' where uniacid=:uniacid and qrcid=:qrcid', array(':uniacid' => $_W['uniacid'], ':qrcid' => $message['scene']));
+ } else {
+ $qrid = pdo_fetchcolumn('select id from ' . tablename('qrcode') . ' where uniacid=:uniacid and scene_str=:scene_str', array(':uniacid' => $_W['uniacid'], ':scene_str' => $message['scene']));
+ }
+ if ($message['event'] == 'subscribe') {
+ self::qr_log($qrid, $message['from'], 1);
+ } else {
+ self::qr_log($qrid, $message['from'], 2);
+ }
+ } else {
+ self::send_text('欢迎关注我们!', $message);
+ }
+ return $qrid;
+ }
+
+ static function qr_log($qrid, $openid, $type)
+ {
+ global $_W;
+ if (empty($qrid) || empty($openid)) {
+ return;
+ }
+ $qrcode = pdo_get('qrcode', array('id' => $qrid), array('scene_str', 'name'));
+ $log = array('uniacid' => $_W['uniacid'], 'acid' => $_W['acid'], 'qid' => $qrid, 'openid' => $openid, 'type' => $type, 'scene_str' => $qrcode['scene_str'], 'name' => $qrcode['name'], 'createtime' => time());
+ pdo_insert('qrcode_stat', $log);
+ }
+
+ static function createkeywords($name, $keyword)
+ {
+ global $_W;
+ if (empty($name) || empty($keyword)) {
+ return error('-1', '二维码关键字和名称不能为空');
+ }
+ $rid = pdo_fetchcolumn("select id from " . tablename('rule') . 'where uniacid=:uniacid and module=:module and name=:name', array(
+ ':uniacid' => $_W['uniacid'],
+ ':module' => 'weliam_smartcity',
+ ':name' => $name
+ ));
+ if (empty($rid)) {
+ $rule_data = array(
+ 'uniacid' => $_W['uniacid'],
+ 'name' => $name,
+ 'module' => 'weliam_smartcity',
+ 'displayorder' => 0,
+ 'status' => 1
+ );
+ pdo_insert('rule', $rule_data);
+ $rid = pdo_insertid();
+ }
+
+ $content = pdo_getcolumn('rule_keyword', array('rid' => $rid, 'module' => 'weliam_smartcity', 'content' => $keyword), 'content');
+ if (empty($content)) {
+ $keyword_data = array(
+ 'uniacid' => $_W['uniacid'],
+ 'rid' => $rid,
+ 'module' => 'weliam_smartcity',
+ 'content' => $keyword,
+ 'type' => 1,
+ 'displayorder' => 0,
+ 'status' => 1
+ );
+ pdo_insert('rule_keyword', $keyword_data);
+ }
+
+ return $rid;
+ }
+
+ static function send_news($returnmess, $message, $end = 1)
+ {
+ global $_W;
+ if (count($returnmess) > 1) {
+ $returnmess = array_slice($returnmess, 0, 1);
+ }
+ $send['touser'] = $message['from'];
+ $send['msgtype'] = 'news';
+ $send['news']['articles'] = $returnmess;
+ $acc = WeAccount::create($_W['acid']);
+ $data = $acc->sendCustomNotice($send);
+ if (is_error($data)) {
+ self::salerEmpty();
+ } else {
+ if ($end == 1) {
+ self::salerEmpty();
+ }
+ }
+ }
+
+ static function send_image($image, $message, $end = 1)
+ {
+ global $_W;
+ $media = self::image_to_media($image, $message);
+ $send['touser'] = $message['from'];
+ $send['msgtype'] = 'image';
+ $send['image'] = array('media_id' => $media['media_id']);
+
+ $acc = WeAccount::create($_W['acid']);
+ $data = $acc->sendCustomNotice($send);
+ if (is_error($data)) {
+ self::salerEmpty();
+ } else {
+ if ($end == 1) {
+ self::salerEmpty();
+ }
+ }
+ }
+
+ static function send_text($mess, $message, $end = 1)
+ {
+ global $_W;
+ $send['touser'] = $message['from'];
+ $send['msgtype'] = 'text';
+ $send['text'] = array('content' => urlencode($mess));
+ $acc = WeAccount::create($_W['acid']);
+ $data = $acc->sendCustomNotice($send);
+ if (is_error($data)) {
+ self::salerEmpty();
+ } else {
+ if ($end == 1) {
+ self::salerEmpty();
+ }
+ }
+ }
+
+ static function send_wxapp($mess, $message, $end = 1)
+ {
+ global $_W;
+ if(empty($mess['path'])){
+ $mess['path'] = tomedia($_W['wlsetting']['base']['logo']);
+ }
+ if(!empty($mess['path'])){
+ $acc = WeAccount::create($_W['acid']);
+ $media = self::image_to_media($mess['path'], $message);
+ $mess['thumb_media_id'] = $media['media_id'];
+ unset($mess['path']);
+ $send['touser'] = $message['from'];
+ $send['msgtype'] = 'miniprogrampage';
+ $send['miniprogrampage'] = $mess;
+ $data = $acc->sendCustomNotice($send);
+ if (is_error($data)) {
+ self::salerEmpty();
+ } else {
+ if ($end == 1) {
+ self::salerEmpty();
+ }
+ }
+ }
+ }
+
+ private static function image_to_media($image, $message)
+ {
+ global $_W;
+ $caCheName = md5($image);//当前图片缓存信息 防止同一张图片多次提交
+ //获取缓存信息
+ $media = Cache::getCache('wxappSend',$caCheName);
+ if(empty($media)){
+ $acc = WeAccount::create($_W['acid']);
+ //文件在远程需要下载到本地
+ $path = "images" . DIRECTORY_SEPARATOR . $_W['uniacid'] . DIRECTORY_SEPARATOR . "media.upload" . DIRECTORY_SEPARATOR . md5($image) . substr($image, -4);
+ $allpath = ATTACHMENT_ROOT . $path;
+ if (!file_exists($allpath)) {
+ $imgcontent = self::getImage($image);
+ $res = FilesHandle::file_mkdirs(dirname($allpath));
+ if($res){
+ //保存图片信息
+ $res = file_put_contents($allpath, $imgcontent);
+ if(!$res){
+ //获取图片类型
+ $imageInfo = getimagesize($image);
+ $mime = explode('/',$imageInfo['mime'])['1'];
+ $imageType = $mime ? '.'.$mime : '.jpg';
+ //再次写入图片信息
+ ob_start();//打开输出
+ readfile($image);//输出图片文件
+ $img = ob_get_contents();//得到浏览器输出
+ ob_end_clean();//清除输出并关闭
+ $fp2 = @fopen($allpath.$imageType, "a");
+ $res = fwrite($fp2, $img);//向当前目录写入图片文件,并重新命名
+ fclose($fp2);
+ //从新定义path
+ $path = $path.$imageType;
+ }
+ }else{
+ self::send_text('目录创建失败', $message);
+ return false;
+ }
+ }
+ $media = $acc->uploadMedia($path);
+ if (is_error($media)) {
+ self::send_text($media['message'], $message);
+ } else {
+ Cache::setCache('wxappSend',$caCheName,$media);
+ return $media;
+ }
+ }
+ return $media;
+ }
+
+ private static function salerEmpty()
+ {
+// ob_clean();
+// ob_start();
+// echo '';
+// ob_flush();
+// ob_end_flush();
+// exit(0);
+ return true;
+ }
+
+
+ protected static function getImage($imgurl){
+ load()->func('communication');
+ $resp = ihttp_request($imgurl);
+
+ if ($resp['code'] == 200 && !empty($resp['content'])) {
+ return imagecreatefromstring($resp['content']);
+ }
+ if ($resp['errno'] == 35) {
+ $imgurl = str_replace(array('https://'), 'http://', $imgurl);
+ }
+
+ $i = 0;
+ while ($i < 3) {
+ $resp = ihttp_request($imgurl);
+ if ($resp['code'] == 200 && !empty($resp['content'])) {
+ return imagecreatefromstring($resp['content']);
+ }
+ ++$i;
+ }
+
+ //以上方法都未获取图片资源
+ $resp = file_get_contents($imgurl);
+ return imagecreatefromstring($resp);
+ }
+
+
+
+
+}
\ No newline at end of file
diff --git a/addons/weliam_smartcity/core/class/WeliamDb.class.php b/addons/weliam_smartcity/core/class/WeliamDb.class.php
new file mode 100644
index 0000000..6c45572
--- /dev/null
+++ b/addons/weliam_smartcity/core/class/WeliamDb.class.php
@@ -0,0 +1,270 @@
+ $field) {
+ if (empty($oldtable['fields'][$fk])) {
+ //字段不存在,增加字段
+ $sqlarr[] = ($field['increment'] == 1) ? self::table_field_edit($table['table'], $field, 1, $table['indexes']['PRIMARY']) : self::table_field_edit($table['table'], $field, 1);
+ } elseif (array_diff_assoc($table['fields'][$fk], $oldtable['fields'][$fk]) || array_diff_assoc($oldtable['fields'][$fk], $table['fields'][$fk])) {
+ //字段有变化,修改字段
+ $sqlarr[] = self::table_field_edit($table['table'], $field, 2);
+ }
+ }
+ //对比索引
+ foreach ($table['indexes'] as $idx => $index) {
+ if ($idx == 'PRIMARY') {
+ continue;
+ }
+ if (empty($oldtable['indexes'][$idx])) {
+ //索引不存在,增加索引
+ $sqlarr[] = self::table_index_edit($table['table'], $index, 1);
+ } elseif (array_diff_assoc($table['indexes'][$idx], $oldtable['indexes'][$idx]) || array_diff_assoc($oldtable['indexes'][$idx]['fields'], $table['indexes'][$idx]['fields']) || array_diff_assoc($table['indexes'][$idx]['fields'], $oldtable['indexes'][$idx]['fields'])) {
+ //索引有变化,删除索引,新建索引
+ $sqlarr[] = self::table_index_edit($table['table'], $index, 2);
+ $sqlarr[] = self::table_index_edit($table['table'], $index, 1);
+ }
+ }
+ //多余索引,需要删除
+ foreach ($oldtable['indexes'] as $oidx => $oindex) {
+ if (empty($table['indexes'][$oidx])) {
+ $sqlarr[] = self::table_index_edit($table['table'], $oindex, 2);
+ }
+ }
+ //对比存储引擎
+ if ($table['engine'] != $oldtable['engine']) {
+ $sqlarr[] = "ALTER TABLE " . self::tablename($table['table']) . " ENGINE=" . $table['engine'] . ", ROW_FORMAT=DEFAULT;";
+ }
+ }
+ }
+ return $sqlarr;
+ }
+
+ /**
+ * 根据条件查找表名
+ * @param $table
+ * @param string $tablepre
+ * @param bool $haspre
+ * @return array
+ */
+ static function get_tables_name($table, $tablepre = 'ims_', $haspre = false) {
+ $tablenames = pdo_fetchall("SHOW TABLES LIKE :tablename", array(":tablename" => "%" . $table . "%"));
+ if (!empty($tablenames)) {
+ $tables = [];
+ foreach ($tablenames as $item) {
+ $table = end($item);
+ $tables[] = $haspre ? $table : substr($table, strlen($tablepre));
+ }
+ return $tables;
+ }
+ return [];
+ }
+
+ /**
+ * 根据表名生成数据库插入语句
+ * @param $tablename
+ * @param $uniacid
+ * @param $start
+ * @param $size
+ * @return array|bool
+ */
+ static function get_table_insert_sql($tablename, $uniacid, $start, $size) {
+ $data = '';
+ $tmp = '';
+ $sql = "SELECT * FROM {$tablename} WHERE `uniacid` = {$uniacid} LIMIT {$start}, {$size}";
+ $result = pdo_fetchall($sql);
+ if (!empty($result)) {
+ foreach ($result as $row) {
+ $tmp .= '(';
+ foreach ($row as $k => $v) {
+ $value = str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $v);
+ $tmp .= "'" . $value . "',";
+ }
+ $tmp = rtrim($tmp, ',');
+ $tmp .= "),\n";
+ }
+ $tmp = rtrim($tmp, ",\n");
+ $data .= "INSERT INTO {$tablename} VALUES \n{$tmp};\n";
+ $datas = array(
+ 'data' => $data,
+ 'result' => $result,
+ );
+
+ return $datas;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * 根据表名返回表的数据
+ * @param string $tablename
+ * @return array
+ */
+ static function get_table_schema($tablename = '') {
+ $result = self::pdo()->fetch("SHOW TABLE STATUS LIKE '" . trim(self::tablename($tablename), "`") . "'");
+ if (empty($result) || empty($result['Create_time'])) {
+ return array();
+ }
+ $ret["table"] = $tablename;
+ $ret["tablename"] = $result["Name"];
+ $ret["charset"] = $result["Collation"];
+ $ret["engine"] = $result["Engine"];
+ $ret["increment"] = $result["Auto_increment"];
+ $result = self::pdo()->fetchall("SHOW FULL COLUMNS FROM " . self::tablename($tablename));
+ foreach ($result as $value) {
+ $temp = array();
+ $type = explode(" ", $value["Type"], 2);
+ $temp["name"] = $value["Field"];
+ $pieces = explode("(", $type[0], 2);
+ $temp["type"] = $pieces[0];
+ $temp["length"] = rtrim($pieces[1], ")");
+ $temp["null"] = !($value["Null"] == "NO");
+ $temp["signed"] = empty($type[1]);
+ $temp["increment"] = $value["Extra"] == "auto_increment";
+ if (!empty($value['Comment'])) {
+ $temp["comment"] = $value["Comment"];
+ }
+ if ($value["Default"] != NULL) {
+ $temp["default"] = $value["Default"];
+ }
+ $ret["fields"][$value["Field"]] = $temp;
+ }
+ $result = self::pdo()->fetchall("SHOW INDEX FROM " . self::tablename($tablename));
+ foreach ($result as $value) {
+ $ret["indexes"][$value["Key_name"]]["name"] = $value["Key_name"];
+ $ret["indexes"][$value["Key_name"]]["type"] = $value["Key_name"] == "PRIMARY" ? "primary" : ($value["Non_unique"] == 0 ? "unique" : "index");
+ $ret["indexes"][$value["Key_name"]]["fields"][] = $value["Column_name"];
+ }
+ return $ret;
+ }
+
+ /**
+ * 返回完整表名
+ * @param $table
+ * @return string
+ */
+ private static function tablename($table) {
+ return self::pdo()->tablename($table);
+ }
+
+ /**
+ * 数据库操作类
+ * @return DB|SlaveDb
+ */
+ private static function pdo() {
+ return pdo();
+ }
+
+ /**
+ * 生成创建表的SQL
+ * @param $schema
+ * @return string
+ */
+ private static function create_table($schema) {
+ if (empty($schema)) {
+ return '';
+ }
+ $sql = "CREATE TABLE IF NOT EXISTS " . self::tablename($schema['table']) . " (";
+ //生成表的字段
+ foreach ($schema['fields'] as $field) {
+ $sql .= self::create_table_field($field);
+ $sql .= ",";
+ }
+ //生成表的索引
+ foreach ($schema['indexes'] as $index) {
+ $sql .= self::create_table_index($index);
+ $sql .= ",";
+ }
+ $sql = rtrim($sql, ",");
+
+ $charset = substr($schema['charset'], 0, stripos($schema['charset'], "_"));
+ $sql .= ") ENGINE={$schema['engine']} DEFAULT CHARSET={$charset};";
+
+ return $sql;
+ }
+
+ /**
+ * 生成操作字段的SQL段
+ * @param $field
+ * @return string
+ */
+ private static function create_table_field($field) {
+ if (empty($field)) {
+ return "";
+ }
+ $sql = "";
+ $sql .= " `{$field['name']}` {$field['type']}";
+ $sql .= !empty($field['length']) ? "({$field['length']})" : "";
+ $sql .= !empty($field['signed']) ? "" : " UNSIGNED";
+ $sql .= !empty($field['null']) ? (array_key_exists("default", $field) ? "" : " DEFAULT NULL") : " NOT NULL";
+ $sql .= array_key_exists("default", $field) ? " DEFAULT '{$field['default']}'" : "";
+ $sql .= !empty($field['increment']) ? " AUTO_INCREMENT" : "";
+ $sql .= !empty($field['comment']) ? " COMMENT '{$field['comment']}'" : "";
+ return $sql;
+ }
+
+ /**
+ * 生成操作索引的SQL段
+ * @param $index
+ * @param string $type
+ * @return string
+ */
+ private static function create_table_index($index, $type = 'ADD') {
+ if (empty($index)) {
+ return "";
+ }
+ $sql = "";
+ $sql .= $index['type'] == 'primary' ? "PRIMARY KEY" : "KEY `{$index['name']}`";
+ if ($type == 'ADD') {
+ $sql .= " (`" . implode("`,`", $index['fields']) . "`)";
+ }
+ return $sql;
+ }
+
+ /**
+ * 生成操作字段的SQL
+ * @param string $tablename
+ * @param $field
+ * @param int $type
+ * @return string
+ */
+ private static function table_field_edit($tablename = '', $field, $type = 1, $idx_field = []) {
+ $sqlstr = ($type == 1) ? " ADD " : " MODIFY COLUMN ";
+ $sql = "ALTER TABLE " . self::tablename($tablename) . $sqlstr . self::create_table_field($field);
+ //特殊情况,增加主键字段时
+ if ($type == 1 && $field['increment'] == 1) {
+ $sql .= ", ADD " . self::create_table_index($idx_field, 'ADD');
+ }
+ $sql .= ";";
+ return $sql;
+ }
+
+ /**
+ * 生成操作索引的SQL
+ * @param string $tablename
+ * @param $field
+ * @param int $type
+ * @return string
+ */
+ private static function table_index_edit($tablename = '', $field, $type = 1) {
+ $sqlstr = ($type == 1) ? " ADD " : " DROP ";
+ $sql = "ALTER TABLE " . self::tablename($tablename) . $sqlstr . self::create_table_index($field, trim($sqlstr)) . ";";
+ return $sql;
+ }
+}
\ No newline at end of file
diff --git a/addons/weliam_smartcity/core/class/WeliamWeChat.class.php b/addons/weliam_smartcity/core/class/WeliamWeChat.class.php
new file mode 100644
index 0000000..03d108a
--- /dev/null
+++ b/addons/weliam_smartcity/core/class/WeliamWeChat.class.php
@@ -0,0 +1,2131 @@
+ $_W['uniacid'], 'key' => 'halfcard'));
+ $wlsetting['value'] = unserialize($wlsetting['value']);
+ $now = time();
+ if ($wlsetting['value']['halfcardtype'] == 2) {
+ $halfcardflag = pdo_fetch("SELECT * FROM " . tablename('wlmerchant_halfcardmember') . "WHERE uniacid = {$_W['uniacid']} AND mid = {$mid} AND aid = {$_W['aid']} AND expiretime > {$now} AND disable != 1");
+ } else {
+ $halfcardflag = pdo_fetch("SELECT * FROM " . tablename('wlmerchant_halfcardmember') . "WHERE uniacid = {$_W['uniacid']} AND mid = {$mid} AND expiretime > {$now} AND disable != 1");
+ }
+ //判断state返回内容
+ if($state) return is_array($halfcardflag) && count($halfcardflag) > 0 && $halfcardflag['id'] > 0 ? $halfcardflag['id'] : 0 ;
+ return $halfcardflag;
+ }
+ /**
+ * Comment: 获取头条信息列表
+ * Author: zzw
+ * Date: 2019/8/29 17:11
+ * @param bool $shop_id
+ * @param int $page
+ * @param int $pageNum
+ * @return array
+ */
+ static function getHeadline($shop_id = false, $page = 1, $pageNum = 10,$one_id = 0,$two_id = 0,$sort = 0){
+ global $_W;
+ #1、条件生成
+ $where = " WHERE uniacid = {$_W['uniacid']} AND aid = {$_W['aid']} ";
+ if ($shop_id) $where .= " AND sid = {$shop_id} ";
+ if($one_id > 0){
+ $where .= " AND one_id = {$one_id} ";
+ }
+ if($two_id > 0){
+ $where .= " AND two_id = {$two_id} ";
+ }
+ if($sort == 1){
+ $order = " ORDER BY browse DESC ";
+ }else{
+ $order = " ORDER BY release_time DESC ";
+ }
+ $pageStart = $page * $pageNum - $pageNum;
+ #2、信息获取
+ $list = pdo_fetchall("SELECT id,title,summary,display_img,author,author_img,browse,one_id,two_id,release_time FROM "
+ .tablename(PDO_NAME."headline_content") .$where.$order." LIMIT {$pageStart},{$pageNum}");
+ foreach ($list as $k => &$v) {
+ $v['display_img'] = tomedia($v['display_img']);
+ $v['author_img'] = tomedia($v['author_img']);
+ $v['one_name'] = implode(pdo_get(PDO_NAME . 'headline_class' , ['id' => $v['one_id']] , ['name']));
+ $v['two_name'] = implode(pdo_get(PDO_NAME . 'headline_class' , ['id' => $v['two_id']] , ['name']));
+ $v['release_time'] = date("H:i",$v['release_time']);
+ unset($v['one_id']);
+ unset($v['two_id']);
+ }
+ return $list;
+ }
+ /**
+ * Comment: 获取某个店铺销量最好的商品
+ * Author: zzw
+ * Date: 2019/8/29 17:12
+ * @param $Atable string 商品表
+ * @param $Btable string 订单表
+ * @param $field string 查询的字段信息
+ * @param $where string 查询条件
+ * @param $group string 分组信息
+ * @param $relation string 两表之间的关联信息
+ * @param $SpareW string 备用条件,如果没有销量最好的商品时 查询任意一条本店铺的商品
+ * @param $SpareF string 备用查询字段
+ * @return string
+ */
+ static function getSalesChampion($Atable, $Btable, $field, $where, $group, $relation, $SpareW, $SpareF) {
+ $info = pdo_fetchall("SELECT {$field} FROM "
+ . tablename(PDO_NAME . $Atable)
+ . " a LEFT JOIN "
+ . tablename(PDO_NAME . $Btable)
+ . " b ON {$relation} "
+ . " WHERE {$where} GROUP BY {$group}");
+ $num = array_column($info, 'num');
+ array_multisort($num, SORT_DESC, $info);
+ $info = $info[0];
+ //$info 不存在,则当前店铺当前种类商品暂时没有销售 直接获取一个商品
+ if (!$info) {
+ $info = pdo_fetchall("SELECT {$SpareF} FROM "
+ . tablename(PDO_NAME . $Atable)
+ . " WHERE {$SpareW}");
+ $info = $info[0];
+ }
+ return $info ? $info : '';
+ }
+ /**
+ * Comment: 通过店铺列表 获取店铺每种类型的商品中销量最好的一个
+ * Author: zzw
+ * Date: 2019/8/29 17:13
+ * @param $shopList
+ * @return mixed
+ */
+ static function getStoreList($shopList) {
+ global $_W, $_GPC;
+ foreach ($shopList as $k => &$v) {
+ $id = $v['id'];
+ //获取店铺的头条信息
+ $headline = WeliamWeChat::getHeadline($id, 1, 1);
+ $headline = $headline[0] ? $headline[0] : '';
+ if ($headline) {
+ unset($headline['summary']);
+ unset($headline['display_img']);
+ unset($headline['author']);
+ unset($headline['author_img']);
+ unset($headline['browse']);
+ unset($headline['one_name']);
+ unset($headline['two_name']);
+ $headline['jump_link'] = h5_url('pages/mainPages/headline/headlineDetail',['headline_id'=>$headline['id']]);
+ }
+ $v['headline'] = $headline;
+ //获取店铺每种商品中销量最好的一件商品的详细信息
+ #1、抢购信息
+ $goods['active'] = self::getSalesChampion('rush_activity', 'rush_order', 'a.id,a.name,count(b.activityid) as num', "a.sid = {$id} AND a.status IN (1,2) ", 'b.activityid', "a.id = b.activityid", " sid = {$id} AND status IN (1,2) ", "id,name");//status IN (1,2)
+ $goods['active']['jump_link'] = h5_url('pages/subPages/goods/index',['type'=>1,'id'=>$goods['active']['id']]);
+ #2、团购信息
+ $goods['groupon'] = self::getSalesChampion('groupon_activity', 'order', 'a.id,a.name,count(b.fkid) as num', "a.sid = {$id} AND a.status IN (1,2) AND b.plugin = 'groupon' ", 'b.fkid', "a.id = b.fkid", " sid = {$id} AND status IN (1,2) ", "id,name");
+ $goods['groupon']['jump_link'] = h5_url('pages/subPages/goods/index',['type'=>2,'id'=>$goods['groupon']['id']]);
+ #3、折扣信息
+ $goods['halfcard'] = self::getSalesChampion('halfcardlist', 'timecardrecord', 'a.id,a.title as name,count(b.activeid) as num ', "a.uniacid = {$_W['uniacid']} AND a.aid = {$_W['aid']} AND a.status = 1 AND b.type = 1 AND b.merchantid = {$id}", 'b.activeid', "a.id = b.activeid", " uniacid = {$_W['uniacid']} AND aid = {$_W['aid']} AND status = 1 AND merchantid = {$id} ", "id,title as name");
+ $goods['halfcard']['jump_link'] = h5_url('pages/subPages2/newBuyOrder/buyOrder', array('id' => $id));
+ #4、礼包信息
+ $goods['packages'] = self::getSalesChampion('package', 'timecardrecord', 'a.id,a.title as name,count(b.activeid) as num ', "a.uniacid = {$_W['uniacid']} AND a.aid = {$_W['aid']} AND a.status = 1 AND b.type = 2 AND b.merchantid = {$id}", 'b.activeid', "a.id = b.activeid", " uniacid = {$_W['uniacid']} AND aid = {$_W['aid']} AND status = 1 AND merchantid = {$id} ", "id,title as name");
+ $goods['packages']['jump_link'] = h5_url('pages/mainPages/memberCard/memberCard');
+ #5、超级券信息
+ $goods['coupon'] = self::getSalesChampion('couponlist', 'order', 'a.id,a.title as name,count(b.fkid) as num ', "a.uniacid = {$_W['uniacid']} AND a.aid = {$_W['aid']} AND a.merchantid = {$id} AND a.status IN (1,2) AND b.plugin = 'coupon' AND a.is_show = 0 ", 'b.fkid', "a.id = b.fkid", " uniacid = {$_W['uniacid']} AND aid = {$_W['aid']} AND merchantid = {$id} AND status IN (1,2) AND is_show = 0 ", "id,title as name");
+ $goods['coupon']['jump_link'] = h5_url('pages/subPages/goods/index',['type'=>5,'id'=>$goods['coupon']['id']]);
+ #6、拼团信息
+ $goods['fightgroup'] = self::getSalesChampion('fightgroup_goods', 'order', 'a.id,a.name,count(b.fkid) as num ', "a.uniacid = {$_W['uniacid']} AND a.aid = {$_W['aid']} AND a.merchantid = {$id} AND a.status IN (1,2) AND b.plugin = 'wlfightgroup'", 'b.fkid', "a.id = b.fkid", " uniacid = {$_W['uniacid']} AND aid = {$_W['aid']} AND merchantid = {$id} AND status IN (1,2) ", "id,name");
+ $goods['fightgroup']['jump_link'] = h5_url('pages/subPages/goods/index',['type'=>3,'id'=>$goods['fightgroup']['id']]);
+ #7、砍价信息
+ $goods['bargain'] = self::getSalesChampion('bargain_activity', 'order', 'a.id,a.name,count(b.fkid) as num ', " a.uniacid = {$_W['uniacid']} AND a.aid = {$_W['aid']} AND a.sid = {$id} AND a.status IN (1,2) AND b.plugin = 'bargain'", 'b.fkid', "a.id = b.fkid", " uniacid = {$_W['uniacid']} AND aid = {$_W['aid']} AND sid = {$id} AND status IN (1,2) ", "id,name");
+ $goods['bargain']['jump_link'] = h5_url('pages/subPages/goods/index',['type'=>7,'id'=>$goods['bargain']['id']]);
+ //删除多余的数据
+ unset($v['location']);
+ unset($v['url']);
+ unset($v['cate']);
+ if (!is_array($goods['active'])) unset($goods['active']);
+ if (!is_array($goods['groupon'])) unset($goods['groupon']);
+ if (!is_array($goods['halfcard'])) unset($goods['halfcard']);
+ if (!is_array($goods['packages'])) unset($goods['packages']);
+ if (!is_array($goods['coupon'])) unset($goods['coupon']);
+ if (!is_array($goods['fightgroup'])) unset($goods['fightgroup']);
+ if (!is_array($goods['bargain'])) unset($goods['bargain']);
+
+
+
+
+
+ $v['goods'] = $goods;
+ }
+ return $shopList;
+ }
+ /**
+ * Comment: 图片上传到远程服务器
+ * Author: zzw
+ * Date: 2019/8/29 17:14
+ * @param $filename
+ * @param bool $auto_delete_local
+ * @return bool|string
+ * @throws Exception
+ */
+ static function file_remote_upload($filename, $auto_delete_local = true) {
+ global $_W;
+ //本公众号设置信息
+ if($_W['wlsetting']['enclosure']['service'] == 2){
+ $_W['setting']['remote']['type'] = 2;
+ $_W['setting']['remote']['alioss'] = $_W['wlsetting']['enclosure']['alioss'];
+ }else if($_W['wlsetting']['enclosure']['service'] == 3){
+ $_W['setting']['remote']['type'] = 3;
+ $_W['setting']['remote']['qiniu'] = $_W['wlsetting']['enclosure']['qiniu'];
+ }else if($_W['wlsetting']['enclosure']['service'] == 4){
+ $_W['setting']['remote']['type'] = 4;
+ $_W['setting']['remote']['cos'] = $_W['wlsetting']['enclosure']['tengxun'];
+ }
+ if (empty($_W['setting']['remote']['type'])) {
+ return false;
+ }
+ if ($_W['setting']['remote']['type'] == '1') {
+ load()->library('ftp');
+ $ftp_config = array(
+ 'hostname' => $_W['setting']['remote']['ftp']['hostname'],
+ 'username' => $_W['setting']['remote']['ftp']['username'],
+ 'password' => $_W['setting']['remote']['ftp']['password'],
+ 'port' => $_W['setting']['remote']['ftp']['port'],
+ 'ssl' => $_W['setting']['remote']['ftp']['ssl'],
+ 'passive' => $_W['setting']['remote']['ftp']['passive'],
+ 'timeout' => $_W['setting']['remote']['ftp']['timeout'],
+ 'rootdir' => $_W['setting']['remote']['ftp']['rootdir'],
+ );
+ $ftp = new Ftp($ftp_config);
+ if (true === $ftp->connect()) {
+ $response = $ftp->upload(ATTACHMENT_ROOT . '/' . $filename, $filename);
+ if ($auto_delete_local) {
+ self::file_delete($filename);
+ }
+ if (!empty($response)) {
+ //return true;
+ } else {
+ return '远程附件上传失败,请检查配置并重新上传';
+ }
+ } else {
+ return '远程附件上传失败,请检查配置并重新上传';
+ }
+ } elseif ($_W['setting']['remote']['type'] == '2') {
+ load()->library('oss');
+ load()->model('attachment');
+ $buckets = attachment_alioss_buctkets($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret']);
+ $endpoint = 'http://' . $buckets[$_W['setting']['remote']['alioss']['bucket']]['location'] . '.aliyuncs.com';
+ try {
+ $ossClient = new \OSS\OssClient($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret'], $endpoint);
+ $ossClient->uploadFile($_W['setting']['remote']['alioss']['bucket'], $filename, ATTACHMENT_ROOT . $filename);
+ } catch (\OSS\Core\OssException $e) {
+ return $e->getMessage();
+ }
+ if ($auto_delete_local) self::file_delete($filename);
+ } elseif ($_W['setting']['remote']['type'] == '3') {
+ load()->library('qiniu');
+ $auth = new Qiniu\Auth($_W['setting']['remote']['qiniu']['accesskey'], $_W['setting']['remote']['qiniu']['secretkey']);
+ $config = new Qiniu\Config();
+ $uploadmgr = new Qiniu\Storage\UploadManager($config);
+ $putpolicy = Qiniu\base64_urlSafeEncode(json_encode(array(
+ 'scope' => $_W['setting']['remote']['qiniu']['bucket'] . ':' . $filename,
+ )));
+ $uploadtoken = $auth->uploadToken($_W['setting']['remote']['qiniu']['bucket'], $filename, 3600, $putpolicy);
+ [$ret, $err] = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . '/' . $filename);
+ if ($auto_delete_local) {
+ self::file_delete($filename);
+ }
+ if ($err !== null) {
+ return '远程附件上传失败,请检查配置并重新上传';
+ }
+ } elseif ($_W['setting']['remote']['type'] == '4') {
+ //使用腾讯4.2版本上传
+ //include IA_ROOT . "/framework/library/cosv4.2/include.php";//微擎5.0有问题 强制使用4.2
+ load()->library('cos');
+ if(in_array('qcloudcos\Cosapi',get_declared_classes())){
+ //使用腾讯4.2版本上传
+ $bucket = trim($_W['setting']['remote']['cos']['bucket']);
+ qcloudcos\Cosapi::setRegion(trim($_W['setting']['remote']['cos']['local']));
+ $uploadRet = qcloudcos\Cosapi::upload($bucket, ATTACHMENT_ROOT . $filename, '/' . $filename, '', 3 * 1024 * 1024, 0);
+ if ($uploadRet['code'] != 0) {
+ switch ($uploadRet['code']) {
+ case -62:
+ $message = '输入的appid有误';
+ break;
+ case -79:
+ $message = '输入的SecretID有误';
+ break;
+ case -97:
+ $message = '输入的SecretKEY有误';
+ break;
+ case -166:
+ $message = '输入的bucket有误';
+ break;
+ }
+ return $message ? : $uploadRet['message'];
+ }
+ if ($auto_delete_local) self::file_delete($filename);
+ }else {
+ //使用腾讯5版本上传
+ load()->library('cosv5');
+ try {
+ $bucket = $_W['setting']['remote']['cos']['bucket'] . '-' . $_W['setting']['remote']['cos']['appid'];
+ $params = [
+ 'region' => $_W['setting']['remote']['cos']['local'] ,
+ 'credentials' => [
+ 'secretId' => $_W['setting']['remote']['cos']['secretid'] ,
+ 'secretKey' => $_W['setting']['remote']['cos']['secretkey']
+ ]
+ ];
+ $cosClient = new Qcloud\Cos\Client($params);
+ $cosClient->Upload($bucket, $filename, fopen(ATTACHMENT_ROOT . $filename, 'rb'));
+ if ($auto_delete_local) self::file_delete($filename);
+ } catch (\Exception $e) {
+ return $e->getMessage();
+ }
+ }
+ }
+ }
+ /**
+ * Comment: 图片上传后删除本地图片
+ * Author: zzw
+ * Date: 2019/8/29 17:14
+ * @param $file
+ * @return bool
+ */
+ static function file_delete($file) {
+ if (empty($file)) {
+ return false;
+ }
+ if (file_exists($file)) {
+ @unlink($file);
+ }
+ if (file_exists(ATTACHMENT_ROOT . '/' . $file)) {
+ @unlink(ATTACHMENT_ROOT . '/' . $file);
+ }
+ return true;
+ }
+ /**
+ * Comment: 获取已购买当前商品的用户信息 已参与的人数
+ * Author: zzw
+ * Date: 2019/8/29 17:15
+ * @param $state int 状态:代表商品类型 1=抢购商品 2=团购商品 3=拼团商品 5=优惠券
+ * @param $id int 商品id
+ * @return mixed
+ */
+ static function PurchaseUser($state, $id) {
+ global $_W, $_GPC;
+ $limit = 5;
+ //条件拼装
+ $where = "uniacid = {$_W['uniacid']} AND aid = {$_W['aid']}";//条件
+ $table = 'order';//表
+ switch ($state) {
+ case 1:
+ $table = 'rush_order';
+ $where .= " AND `activityid` = {$id} ";
+ break;//抢购商品
+ case 2:
+ $where .= " AND plugin = 'groupon' AND fkid = {$id} ";
+ break;//团购商品
+ case 3:
+ $where .= " AND plugin = 'wlfightgroup' AND fkid = {$id} ";
+ break;//拼团商品
+ case 5:
+ $where .= " AND plugin = 'coupon' AND fkid = {$id} ";
+ break;//优惠券
+ case 7:
+ $where .= " AND plugin = 'bargain' AND fkid = {$id} ";
+ break;//砍价商品
+ }
+ //获取内容
+ $info = pdo_fetchall("SELECT id,mid FROM " . tablename(PDO_NAME . $table)."WHERE {$where} ORDER BY id DESC LIMIT {$limit} ");
+ if(!empty($info)){
+ foreach($info as &$in){
+ $member = pdo_get('wlmerchant_member',array('id' => $in['mid']),array('nickname','avatar'));
+ $in['nickname'] = $member['nickname'];
+ $in['avatar'] = tomedia($member['avatar']);
+ }
+ }
+ $count = pdo_fetchall("SELECT id FROM " . tablename(PDO_NAME . $table)."WHERE {$where}");
+ //信息拼装
+ $data['info'] = $info;
+ $data['count'] = count($count);
+
+ return $data;
+ }
+ /**
+ * Comment: 获取商品多规格信息列表
+ * Author: zzw
+ * Date: 2019/8/29 17:16
+ * @param $id
+ * @param $type
+ * @return array
+ */
+ static function getSpec($id, $type,$vipstatus = 0) {
+ global $_W;
+ #1、根据商品类型判断获取条件
+ # 商品type:1=抢购 2=团购 3=拼团 4=大礼包(无佣金) 5=优惠券 6=折扣卡(无佣金) 7=砍价商品
+ # 规格type:1抢购 2拼团 3团购
+ $where = " WHERE uniacid = {$_W['uniacid']} AND goodsid = {$id} ";
+ switch ($type){
+ case 1:$where .= " AND type = 1";break;//抢购
+ case 2:$where .= " AND type = 3";break;//团购
+ case 3:$where .= " AND type = 2";break;//拼团
+ default:return [];break;//当前商品不支持多规格
+ }
+ #2、获取规格信息
+ $list = pdo_fetchall("SELECT title,content FROM ".tablename(PDO_NAME."goods_spec").$where." ORDER BY displayorder ASC ");
+ foreach($list as $key => &$val){
+ //生成规格参数查询条件
+ $idList = unserialize($val['content']);
+ if(is_array($idList) && count($idList) > 1){
+ $ids = implode($idList,',');
+ $itemWhere = " WHERE id in ({$ids}) AND `show` = 1 ";
+ }else{
+ $itemWhere = " WHERE id = {$idList[0]} AND `show` = 1 ";
+ }
+ //获取规格参数信息
+ $val['item'] = pdo_fetchall(" SELECT id,title FROM ".tablename(PDO_NAME."goods_spec_item").$itemWhere." ORDER BY displayorder ASC ");
+
+ unset($val['content']);
+ }
+ #3、获取规格组合后的销售信息
+ $info = pdo_fetchall("SELECT id,specs,stock,price,thumb,viparray,onedismoney,vipprice as aloneprice FROM ".tablename(PDO_NAME."goods_option").$where." ORDER BY id ASC ");
+ #5、数据拼装
+ $data['list'] = $list;//规格信息列表
+ $data['info'] = $info;//规格参数列表
+
+ return $data;
+ }
+ /**
+ * Comment: 获取同城活动的多规格信息列表
+ * Author: wlf
+ * Date: 2020/10/30 09:22
+ * @param $id
+ * @return array
+ */
+ static function getActivitySpec($id){
+ global $_W;
+ $where = " WHERE uniacid = {$_W['uniacid']} AND activityid = {$id} ";
+ $info = pdo_fetchall("SELECT id,name,maxnum,price,viparray FROM ".tablename(PDO_NAME."activity_spec").$where." ORDER BY id ASC ");
+ foreach($info as $infoK => &$infoV){
+ $stopBuyNum = WeliamWeChat::getSalesNum(6,$id,$infoV['id'],1);
+ $infoV['stock'] = $infoV['maxnum'] - intval($stopBuyNum);
+ }
+ //统计
+ $prices = array_column($info,'price');
+ $data['minprice'] = min($prices);
+ $data['maxprice'] = max($prices);
+ $stkList = array_column($info,'stock');
+ $data['stk'] = array_sum($stkList);
+ $data['info'] = $info;
+
+ return $data;
+ }
+ /**
+ * Comment: 新的首页商品信息查询
+ * Author: wlf
+ * Date: 2020/09/16 15:28
+ * @param $plugin
+ * @param $id
+ * @return bool
+ */
+ static function getNewHomeGoods($plugin,$id) {
+ global $_W;
+ $mid = $_W['mid'];
+ $usercard = WeliamWeChat::VipVerification($mid);
+ if($usercard['id'] > 0){
+ $usercardlevel = $usercard['levelid'];
+ }else{
+ $usercardlevel = -1;
+ }
+ switch ($plugin) {
+ case 1:
+ $goods = pdo_fetch("SELECT a.optionstatus,IFNULL(a.pv,0) as pv,a.thumbs as adv,a.appointment,a.allowapplyre,a.communityid,'1' as type,b.logo as shop_logo,a.op_one_limit as buy_limit,a.status,a.id,a.thumb as logo,a.name as goods_name,a.price,a.oldprice,a.num as totalnum,b.storename,b.id as sid,a.starttime,a.endtime,a.viparray,a.vipstatus,a.allsalenum,b.address FROM "
+ . tablename(PDO_NAME . "rush_activity")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.sid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = 'rush';
+ $goods['postertype'] = '3';
+ break;//抢购商品
+ case 2:
+ $goods = pdo_fetch("SELECT IFNULL(a.pv,0) as pv,a.optionstatus,a.thumbs as adv,a.appointment,a.allowapplyre,a.communityid,'2' as type,b.logo as shop_logo,a.op_one_limit as buy_limit,b.address,a.status,a.id,a.thumb as logo,a.name as goods_name,a.price,a.oldprice,a.num as totalnum,b.storename,b.id as sid,a.starttime,a.endtime,a.viparray,a.vipstatus,a.allsalenum FROM "
+ . tablename(PDO_NAME . "groupon_activity")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.sid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = $pluginType = 'groupon';
+ $goods['postertype'] = '4';
+ break;//团购商品
+ case 3:
+ $goods = pdo_fetch("SELECT a.specstatus as optionstatus,a.pv,a.adv,a.communityid,'3' as type,a.is_pool,a.allowapplyre,a.appointment,b.logo as shop_logo,a.buylimit as buy_limit,b.address,a.status,a.id,a.logo,a.name as goods_name,a.price,a.aloneprice as oldprice,stock as totalnum,a.peoplenum,b.storename,b.id as sid,a.viparray,a.realsalenum,a.falsesalenum as allsalenum FROM "
+ . tablename(PDO_NAME . "fightgroup_goods")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.merchantid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = $pluginType = 'wlfightgroup';
+ $goods['postertype'] = '6';
+ break;//拼团商品
+ }
+ $goods['logo'] = tomedia($goods['logo']);
+ $goods['shop_logo'] = tomedia($goods['shop_logo']);
+ $advs = unserialize($goods['adv']);
+ $goods['long_logo'] = tomedia($advs[0]);
+ if ($plugin == 1) {
+ //抢购商品的销量
+ $stopBuyNum = WeliamWeChat::getSalesNum(1,$id,0,1);
+ } else if ($plugin == 2) {
+ $stopBuyNum = WeliamWeChat::getSalesNum(2,$id,0,1);
+ } else if ($plugin == 3) {
+ $stopBuyNum = WeliamWeChat::getSalesNum(3,$id,0,1);
+ }
+ #3、加上虚拟销量
+ if ($goods['allsalenum'] && empty($storeflag)) {
+ $stopBuyNum = intval($stopBuyNum) + intval($goods['allsalenum']);
+ $goods['totalnum'] = $goods['totalnum'] + $goods['allsalenum'];
+ }
+ $purchaseUser = WeliamWeChat::PurchaseUser($plugin, $goods['id']);
+ $goods['user_list'] = array_column($purchaseUser['info'], 'avatar');//购买当前商品的用户的头像
+ $goods['user_num'] = $stopBuyNum;//$purchaseUser['count'];//已参与人数
+ $goods['buy_num'] = $stopBuyNum ? $stopBuyNum : 0;//获取已售数量
+ //获取当前商品的浏览记录
+ //$browseRecord = array_column(self::getBrowseRecord($plugin, $goods['id']), 'avatar');
+ //$goods['user_list'] = is_array($browseRecord) ? $browseRecord :[];
+ //$goods['user_list'] = is_array($browseRecord) ? $browseRecord :[];
+ #4、已销售数量的百分比
+ if($goods['buy_num'] > 0 && $goods['totalnum'] > 0){
+ $goods['buy_percentage'] = sprintf("%.2f", ($goods['buy_num'] / $goods['totalnum']) * 100);
+ if($goods['buy_percentage']>100){
+ $goods['buy_percentage'] = 100.00;
+ }
+ }else{
+ $goods['buy_percentage'] = 0.00;
+ }
+ $goods['stk'] = $goods['totalnum'] - $stopBuyNum;
+ if($goods['stk']<0){$goods['stk'] = 0;}
+ #7、商品为抢购商品时 并且状态为未开始时 判断用户是否关注当前抢购商品 0=未关注,1=已关注
+ $goods['is_follow'] = 0;
+ if($plugin == 1 && $goods['status'] == 1){
+ $isFollow = pdo_getcolumn(PDO_NAME.'rush_follows',['mid'=>$mid,'actid'=>$id],'id');
+ if($isFollow) $goods['is_follow'] = 1;
+ }
+ #9、获取商品的优惠金额 Discount
+ if($goods['vipstatus'] == 1){
+ $goods['discount_price'] = self::getVipDiscount($goods['viparray'],$usercardlevel);
+ }else{
+ $goods['discount_price'] = 0;
+ }
+ if($goods['vipstatus'] != 1){
+ $goods['discount_price'] = 0;
+ }
+
+ if($goods['optionstatus'] > 0){
+ if($plugin == 9){
+ $specinfo = WeliamWeChat::getActivitySpec($id);
+ $goods['spec'] = $specinfo['info'];
+ if($goods['vipstatus'] == 1){
+ foreach($goods['spec'] as &$spb){
+ $spb['discount_price'] = self::getVipDiscount($spb['viparray'],$usercardlevel);
+ if($spb['discount_price'] < 0.01){
+ $spb['discount_price'] = $goods['discount_price'];
+ }
+ }
+ }
+ $goods['minprice'] = $specinfo['minprice'];
+ $goods['maxprice'] = $specinfo['maxprice'];
+ $goods['stk'] = $specinfo['stk'];
+ }else{
+ $goods['spec'] = WeliamWeChat::getSpec($id, $plugin,$goods['vipstatus']);
+ //从新获取库存信息
+ foreach ($goods['spec']['info'] as &$sp){
+ if ($plugin == 1) {
+ //抢购商品的销量
+ $stopBuyNum = WeliamWeChat::getSalesNum(1,$goods['id'],$sp['id'],1);
+ $sp['stock'] = $sp['stock'] - intval($stopBuyNum);
+ }else if($plugin == 2 || $plugin == 3){
+ $stopBuyNum = WeliamWeChat::getSalesNum($plugin,$goods['id'],$sp['id'],1);
+ $sp['stock'] = $sp['stock'] - intval($stopBuyNum);
+ }
+ $sp['thumb'] = tomedia($sp['thumb']);
+ if($goods['vipstatus'] == 1){
+ $sp['discount_price'] = self::getVipDiscount($sp['viparray'],$usercardlevel);
+ if($sp['discount_price'] < 0.01 ){
+ $sp['discount_price'] = $goods['discount_price'];
+ }
+ }
+ }
+ $stkList = array_column($goods['spec']['info'],'stock');
+ $goods['stk'] = array_sum($stkList);
+ }
+ }
+
+ return $goods;
+
+ }
+ /**
+ * Comment: 首页商品信息查询
+ * Author: zzw
+ * Date: 2019/8/29 17:17
+ * @param $plugin
+ * @param $id
+ * @return bool
+ */
+ static function getHomeGoods($plugin, $id,$storeflag = 0,$mid = 0,$time = 0) {
+ global $_W;
+ if(empty($mid)){
+ $mid = $_W['mid'];
+ }
+ if(empty($time)){
+ $time = time();
+ }
+ #商品类型:1=抢购 2=团购 3=拼团 4=大礼包 5=优惠券 6=折扣卡 7=砍价商品 8=积分商品 9 = 同城活动
+ #1、获取商品信息
+ switch ($plugin) {
+ case 1:
+ $goods = pdo_fetch("SELECT a.id,a.optionstatus,IFNULL(a.pv,0) as pv,a.thumbs as adv,a.appointment,a.appointstatus,a.allowapplyre,a.communityid,'1' as type,b.logo as shop_logo,a.op_one_limit as buy_limit,a.status,a.id,a.thumb as logo,a.name as goods_name,a.price,a.oldprice,a.num as totalnum,b.storename,b.id as sid,a.starttime,a.endtime,a.viparray,a.vipstatus,a.allsalenum,b.address,a.pftid,a.cc_id FROM "
+ . tablename(PDO_NAME . "rush_activity")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.sid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = 'rush';
+ $goods['postertype'] = '3';
+ break;//抢购商品
+ case 2:
+ $goods = pdo_fetch("SELECT a.id,IFNULL(a.pv,0) as pv,a.optionstatus,a.thumbs as adv,a.appointment,a.appointstatus,a.allowapplyre,a.communityid,'2' as type,b.logo as shop_logo,a.op_one_limit as buy_limit,b.address,a.status,a.id,a.thumb as logo,a.name as goods_name,a.price,a.oldprice,a.num as totalnum,b.storename,b.id as sid,a.starttime,a.endtime,a.viparray,a.vipstatus,a.allsalenum,a.pftid FROM "
+ . tablename(PDO_NAME . "groupon_activity")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.sid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = $pluginType = 'groupon';
+ $goods['postertype'] = '4';
+ break;//团购商品
+ case 3:
+ $goods = pdo_fetch("SELECT a.id,a.specstatus as optionstatus,a.pv,a.adv,a.communityid,'3' as type,a.is_pool,a.allowapplyre,a.appointment,a.appointstatus,b.logo as shop_logo,a.buylimit as buy_limit,b.address,a.status,a.id,a.logo,a.name as goods_name,a.price,a.oldprice,a.stock as totalnum,a.peoplenum,b.storename,b.id as sid,a.vipstatus,a.viparray,a.realsalenum,a.falsesalenum as allsalenum,a.aloneprice_switch FROM "
+ . tablename(PDO_NAME . "fightgroup_goods")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.merchantid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = $pluginType = 'wlfightgroup';
+ $goods['postertype'] = '6';
+ break;//拼团商品
+ case 4:
+ //获取礼包信息
+ $goods = pdo_fetch("SELECT a.id,'1' as is_link,a.type as exttype,a.storemoney,a.extlink,a.extinfo,'4' as type,b.logo as shop_logo,
+a.id,a.limit,a.datestatus,a.title as `name`,a.timeslimit,a.timestatus,a.starttime,a.endtime,a.packtimestatus,a.datestarttime,a.dateendtime,a.oplimit,a.weeklimit,a.monthlimit,a.price,a.usetimes,a.usetimes as surplus,b.storename,
+b.logo,b.lat,b.lng,b.address,b.id as sid,REPLACE('table','table','package') as `plugin`,a.datestatus,a.usedatestatus,a.week,a.day,allnum,resetswitch,`level` FROM "
+ . tablename(PDO_NAME . "package")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . "b ON a.merchantid = b.id WHERE a.id = {$id} ");
+ $goods['logo'] = tomedia($goods['logo']);
+ $goods['shop_logo'] = tomedia($goods['shop_logo']);
+ //获取已被使用的数量礼包库存
+ $hasUsed = pdo_fetchcolumn("SELECT COUNT(*) as stk FROM " . tablename(PDO_NAME . "timecardrecord") . " WHERE `type` = 2 AND activeid = {$id}");
+ $goods['stk'] = $goods['allnum'];
+ if ($goods['allnum'] > 0) {
+ $goods['stk'] = $goods['allnum'] - $hasUsed;
+ }
+ $userCardInfo = WeliamWeChat::VipVerification($mid);
+ //查看用户剩余次数
+ switch ($goods['datestatus']) {
+ case 2:
+ $startTime = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
+ $goods['newlimit'] = '每周';
+ break;//每周
+ case 3:
+ $startTime = mktime(0, 0, 0, date('m'), 1, date('Y'));
+ $goods['newlimit'] = '每月';
+ break;//每月
+ case 4:
+ $startTime = mktime(0, 0, 0, 1, 1, date('Y'));
+ $goods['newlimit'] = '每年';
+ break;//每年
+ default:
+ $goods['newlimit'] = '可用';
+ break;
+ }
+ $goods['newlimit'] .= $goods['usetimes'].'次';
+ if ($mid) {
+ //获取查询条件及可以使用的总次数
+ $where = " WHERE `type` = 2 AND activeid = {$id} AND mid = {$mid} ";
+ //判断是否开启周期使用
+ $goods['datestatus'] = $goods['datestatus'] ? : 1;
+ //判断是否开启续卡重置功能
+ if ($goods['resetswitch'] == 1) {
+ //获取用户最近续卡时间
+ $time1 = pdo_fetchcolumn("SELECT paytime FROM " . tablename(PDO_NAME . "halfcard_record")
+ . " WHERE uniacid = {$_W['uniacid']} AND aid = {$_W['aid']} AND mid = {$mid} AND cardid > 0 ORDER BY paytime DESC");
+ $time2 = pdo_getcolumn(PDO_NAME.'halfcardmember',array('id'=>$userCardInfo['id']),'createtime');
+ $time1 = intval($time1);
+ $time2 = intval($time2);
+ $time = $time1 > $time2 ? $time1 : $time2;
+ if ($startTime < $time) $startTime = $time;//续卡重置礼包使用时间
+ }
+ if($startTime > 0) {
+ $where .= " AND usetime >= " . $startTime;
+ }
+ //获取已使用数量
+ $surplus = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename(PDO_NAME . "timecardrecord") . $where);
+ $goods['surplus'] = ($goods['usetimes'] - $surplus) > 0 ? ($goods['usetimes'] - $surplus) : 0;
+ //判断用户是否为一卡通会员 并且获取一卡通的id
+ $goods['card'] = self::VipVerification($mid,true);
+ }
+ //外链礼包的信息处理
+ if ($goods['exttype'] == 1) {
+ $setInfo = unserialize($goods['extinfo']);
+ $goods['url'] = $goods['extlink'];
+ $goods['storename'] = $setInfo['storename'];
+ $goods['shop_logo'] = tomedia($setInfo['storelogo']);
+ $goods['is_link'] = intval(0);//0=外链礼包
+ }
+ //判断当前用户是否可用该礼包
+ $lvInfo = unserialize($goods['level']);//会员限制列表
+ $goods['use_where'] = intval(1);
+ if($userCardInfo['id'] > 0){
+ //明确会员等级限制 只能是当前等级的会员可以使用
+ if($lvInfo && !in_array($userCardInfo['levelid'],$lvInfo)){
+ $goods['use_where'] = intval(0);
+ }
+ }else{
+ $goods['use_where'] = intval(0);
+ }
+
+ unset($goods['extinfo']);
+ unset($goods['extlink']);
+ unset($goods['storelogo']);
+
+ return $goods;
+ break;//大礼包
+ case 5:
+ $goods = pdo_fetch("SELECT a.id,IFNULL(a.pv,0) as pv,a.indexorder,a.extflag,a.extlink,a.extinfo,'5' as type,b.logo as shop_logo,a.get_limit as buy_limit,a.status,a.id,a.logo,a.title as goods_name,a.price,a.vipstatus,a.viparray,quantity as totalnum,b.storename,b.id as sid,a.surplus,a.is_charge,a.adv FROM "
+ . tablename(PDO_NAME . "couponlist")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.merchantid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = $pluginType = 'coupon';
+ //外链卡券的信息处理
+ if($goods['extflag'] == 1){
+ $extInfo = unserialize($goods['extinfo']);
+ $goods['storename'] = $extInfo['storename'];
+ }
+ $goods['postertype'] = '5';
+ break;//优惠券
+ case 6:
+ $goods = pdo_fetch("SELECT a.id,'1' as is_link,a.type as exttype,a.extlink,a.extinfo,'6' as type,a.describe,
+b.logo as shop_logo,a.timeslimit as buy_limit,a.levelstatus,a.activearray,a.dayactarray,a.id,a.title as `name`,a.limit,a.datestatus,a.week,a.day,a.activediscount,
+a.discount,a.daily,b.id as sid,b.storename,a.pv,a.sort,b.logo,a.level,b.payonline,b.panorama_discount FROM "
+ . tablename(PDO_NAME . "halfcardlist")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.merchantid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = $pluginType = 'halfcard';
+ $goods['logo'] = tomedia($goods['logo']);
+ $goods['shop_logo'] = tomedia($goods['shop_logo']);
+ if($goods['datestatus'] == 3 && $goods['daily'] > 0 ){
+ $goods['activediscount'] = $goods['discount'];
+ }
+ //判断用户是否为一卡通会员 并且获取一卡通的id
+ if ($mid){
+ $vipInfo = self::VipVerification($mid);
+ $goods['card'] = $vipInfo['id'];
+ }
+ //判断等级限制 获取折扣信息
+ $lvevl = unserialize($goods['level']);
+ //分级折扣
+ if($goods['levelstatus'] > 0){
+ $le_ac_array = unserialize($goods['activearray']);
+ $le_day_array = unserialize($goods['dayactarray']);
+ if(empty($vipInfo)){
+ $goods['activediscount'] = min($le_ac_array);
+ $goods['discount'] = min($le_day_array);
+ $goods['lowtip'] = 1;
+ }else{
+ $goods['activediscount'] = $le_ac_array[$vipInfo['levelid']];
+ $goods['discount'] = $le_day_array[$vipInfo['levelid']];
+ }
+ $lvevl = [];
+ }
+ if(!empty($vipInfo) && !in_array($vipInfo['levelid'],$lvevl) && count($lvevl) > 0){
+ //获取当前折扣卡今天的折扣情况
+ $weekflag = date('w', $time);//星期
+ $dayflag2 = date('j', $time);//日期
+ switch ($goods['datestatus']) {
+ case 1:
+ //日期格式:星期
+ if($weekflag == 0){
+ $weekflag = 7;
+ }
+ $goods['week'] = unserialize($goods['week']);
+ if(!in_array($weekflag, $goods['week']) && $goods['daily'] > 0){
+ $goods['activediscount'] = $goods['discount'];
+ }
+ break;
+ case 2:
+ //日期格式:日期
+ $goods['day'] = unserialize($goods['day']);
+ if(!in_array($dayflag2, $goods['day']) && $goods['daily'] > 0){
+ $goods['activediscount'] = $goods['discount'];
+ }
+ break;
+ }
+ $goods['discount'] = $goods['panorama_discount'];
+ }else if( (!empty($vipInfo) && Customized::init('customized336') ) || !Customized::init('customized336') ){
+ if(empty($goods['daily'])){
+ $goods['discount'] = $goods['panorama_discount'];
+ }
+ //获取当前折扣卡今天的折扣情况
+ $weekflag = date('w', $time);//星期
+ $dayflag2 = date('j', $time);//日期
+ switch ($goods['datestatus']) {
+ case 1:
+ //日期格式:星期
+ if($weekflag == 0){
+ $weekflag = 7;
+ }
+ $goods['week'] = unserialize($goods['week']);
+ if (in_array($weekflag, $goods['week'])) {
+ $goods['discount'] = $goods['activediscount'];
+ }else if($goods['daily'] > 0){
+ $goods['activediscount'] = $goods['discount'];
+ }
+ break;
+ case 2:
+ //日期格式:日期
+ $goods['day'] = unserialize($goods['day']);
+ if (in_array($dayflag2, $goods['day'])) {
+ $goods['discount'] = $goods['activediscount'];
+ }else if($goods['daily'] > 0){
+ $goods['activediscount'] = $goods['discount'];
+ }
+ break;
+ }
+ }else{
+ $goods['discount'] = $goods['panorama_discount'];
+ }
+
+ //外链折扣卡的信息处理
+ if ($goods['exttype'] == 1) {
+ $setInfo = unserialize($goods['extinfo']);
+ $goods['storename'] = $setInfo['storename'];
+ $goods['logo'] = tomedia($setInfo['storelogo']);
+ $goods['url'] = $goods['extlink'];
+ $goods['is_link'] = intval(0);//0=外链折扣卡
+ $goods['discount'] = $goods['activediscount'];
+ $goods['exdetail'] = htmlspecialchars_decode($goods['describe']);
+ }
+ #3、判断当前用户是否可用该折扣卡
+ $userCardInfo = WeliamWeChat::VipVerification($mid);
+ $lvInfo = unserialize($goods['level']);//会员限制列表
+ $goods['use_where'] = intval(1);
+ if($userCardInfo['id'] > 0){
+ //明确会员等级限制 只能是当前等级的会员可以使用
+ if($lvInfo && !in_array($userCardInfo['levelid'],$lvInfo)){
+ $goods['use_where'] = intval(0);
+ }
+ }else{
+ $goods['use_where'] = intval(0);
+ }
+
+ unset($goods['extinfo']);
+ unset($goods['extlink']);
+ unset($goods['exttype']);
+ unset($goods['week']);
+ unset($goods['day']);
+ unset($goods['daily']);
+ unset($goods['datestatus']);
+
+ return $goods;
+ break;//折扣卡
+ case 7:
+ $goods = pdo_fetch("SELECT a.id,IFNULL(a.pv,0) as pv,a.tag,a.thumbs as adv,a.communityid,'7' as type,b.logo as shop_logo,b.address,a.allowapplyre,a.appointment,a.appointstatus,a.status,a.id,a.thumb as logo,a.name as goods_name,stock as totalnum,b.storename,b.id as sid,a.starttime,a.endtime,a.viparray,a.vipstatus,a.oldprice,a.price FROM "
+ . tablename(PDO_NAME . "bargain_activity")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.sid = b.id WHERE a.id = {$id} ");
+ $goods['plugin'] = 'bargain';
+ $goods['postertype'] = '7';
+ break;//砍价商品
+ case 8:
+ #2、判断用户是否为会员
+ $cardid = WeliamWeChat::VipVerification($mid,true);
+ #3、获取商品详细信息
+ $field = " id,advs,title,thumb,old_price,description,IFNULL(pv,0) as pv,stock,community_id,`describe`,isdistri,
+ CASE WHEN {$cardid} > 0 AND vipstatus = 1 THEN vipcredit1
+ ELSE use_credit1
+ END as use_credit1,
+ CASE WHEN {$cardid} > 0 AND vipstatus = 1 THEN vipcredit2
+ ELSE use_credit2
+ END as price ";
+ $info = pdo_fetch("SELECT {$field} FROM " . tablename(PDO_NAME . "consumption_goods") . " WHERE id = {$id} ");
+ if (!$info) Commons::sRenderError('商品不存在!');
+ $info['thumb'] = tomedia($info['thumb']);
+ $info['description'] = htmlspecialchars_decode($info['description']);
+ $info['is_vip'] = $cardid;
+ #4、幻灯片处理
+ $info['advs'] = unserialize($info['advs']);
+ if (is_array($info['advs']) && count($info['advs']) > 0) {
+ foreach ($info['advs'] as $key => &$val) {
+ $val = tomedia($val);
+ }
+ }else{
+ $info['advs'] = [];
+ }
+ #5、浏览量添加
+ $pv = $info['pv'] + 1;
+ pdo_update(PDO_NAME . "consumption_goods" , [ 'pv' => $pv ] , [ 'id' => $id ]);
+ #6、获取销量
+ $info['total'] = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename(PDO_NAME . "order") . " WHERE plugin = 'consumption' AND fkid = {$id} ");
+ #7、获取社群设置
+ if ($info['community_id'] > 0) {
+ $info['community'] = Commons::getCommunity($info['community_id']);
+ }
+ if(!$info['community']) unset($info['community']);
+ #8、获取购买人头像信息
+ $member = pdo_fetchall("SELECT b.avatar FROM " . tablename(PDO_NAME . "order")
+ . " as a LEFT JOIN " . tablename(PDO_NAME . "member")
+ . " as b ON a.mid = b.id WHERE a.plugin = 'consumption' AND a.fkid = {$id} GROUP BY b.id LIMIT 5");
+ $info['avatar_list'] = is_array($member) && count($member) > 0 ? array_column($member , 'avatar') : [];
+ #9、一卡通文本信息获取
+ $info['halfcard_text'] = !empty($_W['wlsetting']['trade']['halfcardtext']) ? $_W['wlsetting']['trade']['halfcardtext'] : '一卡通';
+ #10、分销助手,获取当前用户分享最高可以获得的佣金
+ $info['dis_assistant'] = WeliamWeChat::getDisInfo($plugin,$id);
+ #10、修改商品的人气(浏览量)信息
+ $pv = intval($info['pv']) + 1;
+ pdo_update(PDO_NAME."consumption_goods",['pv'=>$pv],['id'=>$id]);
+ $info['postertype'] = '10';
+ $info['plugin'] = 'integral';
+ //价格处理
+ $trade = Setting::wlsetting_read('trade');
+ $creditText = $trade['credittext'];
+ $info['price_text'] = "{$info['use_credit1']}{$creditText} + {$info['price']}元";
+ //获取轮播图第一张
+ $info['long_logo'] = $info['advs'][0];
+
+ if(empty($info['stock'])){
+ $info['stock'] = 999;
+ }
+ return $info;
+ break;//积分商品
+ case 9:
+ $goods = pdo_fetch("SELECT a.id,a.vipprice,a.optionstatus,a.threeurl,IFNULL(a.pv,0) as pv,a.advs as adv,'9' as type,b.logo as shop_logo,a.status,a.id,a.thumb as logo,a.title as goods_name,a.price,a.maxpeoplenum as totalnum,b.storename,b.id as sid,a.activestarttime,a.activeendtime,a.viparray,a.vipstatus,a.addresstype,a.address as acaddress,b.address,c.name as catename FROM "
+ . tablename(PDO_NAME . "activitylist")
+ . " a LEFT JOIN " . tablename(PDO_NAME . "merchantdata")
+ . " b ON a.sid = b.id LEFT JOIN ". tablename(PDO_NAME . "activity_category")
+ . " c ON a.cateid = c.id WHERE a.id = {$id} ");
+ $goods['plugin'] = 'activity';
+ $goods['postertype'] = '9';
+ if($goods['addresstype'] > 0){
+ $goods['address'] = $goods['acaddress'];
+ }
+ if($goods['optionstatus'] > 0 ){
+ $Aoptions = pdo_getall('wlmerchant_activity_spec',array('activityid' => $goods['id']),array('price'));
+ $Parray = array_column($Aoptions,'price');
+ $goods['price'] = min($Parray).'-'.max($Parray);
+ }
+ break;//同城活动
+ case 10:
+ //获取信息
+ $field = "id,name as goods_name,price,thumb as logo,thumbs as adv,fictitiousnum,status,allstock";
+ $goods = pdo_fetch("SELECT {$field} FROM "
+ . tablename(PDO_NAME . "delivery_activity")
+ ." WHERE id = {$id} ");
+ //处理信息
+ $goods['logo'] = tomedia($goods['logo']);
+ $goods['long_logo'] = tomedia(unserialize($goods['adv'])[0]);
+ $goods['plugin'] = 'citydelivery';
+ //获取销量
+ $stopBuyNum = pdo_fetchcolumn("SELECT sum(num) FROM "
+ . tablename(PDO_NAME . "delivery_order")
+ . " WHERE gid = {$goods['id']} AND uniacid = {$_W['uniacid']} AND status IN (1,2)");
+ $goods['buy_num'] = $stopBuyNum ? $stopBuyNum : 0;//获取已售数量
+ $goods['buy_num'] = $goods['buy_num'] + $goods['fictitiousnum'];//添加虚拟销量
+ //获取库存
+ $goods['stk'] = $goods['allstock'] > 0 ? $goods['allstock'] - $goods['buy_num'] : 0;//-1则代表不限量
+ unset($goods['adv'],$goods['fictitiousnum']);
+
+ return $goods;
+ break;//配送商品
+ }
+ #2、获取商品销量
+ $goods['logo'] = tomedia($goods['logo']);
+ $goods['shop_logo'] = tomedia($goods['shop_logo']);
+ $advs = unserialize($goods['adv']);
+ $goods['long_logo'] = tomedia($advs[0]);
+ if ($plugin == 1) {
+ //抢购商品的销量
+ $stopBuyNum = WeliamWeChat::getSalesNum(1,$id,0,1,0,0,0,$goods['pftid']);
+ } else if ($plugin == 5) {
+ $stopBuyNum = WeliamWeChat::getSalesNum(4,$id,0,1);
+ } else if ($plugin == 3) {
+ $stopBuyNum = WeliamWeChat::getSalesNum(3,$id,0,1);
+ } else if ($plugin == 7) {
+ $stopBuyNum = WeliamWeChat::getSalesNum(5,$id,0,1);
+ } else if ($plugin == 2) {
+ $stopBuyNum = WeliamWeChat::getSalesNum(2,$id,0,1,0,0,0,$goods['pftid']);
+ } else if ($plugin == 9) {
+ $stopBuyNum = WeliamWeChat::getSalesNum(6,$id,0,1);
+ } else {
+ $stopBuyNum = pdo_fetchcolumn("SELECT sum(num) FROM "
+ . tablename(PDO_NAME . "order")
+ . " WHERE fkid = {$goods['id']} AND plugin = '{$pluginType}' AND uniacid = {$_W['uniacid']} AND status IN (0,1,2,3,6,9,4,8)");
+ }
+ #3、加上虚拟销量
+ if ($goods['allsalenum'] && empty($storeflag)) {
+ $stopBuyNum = intval($stopBuyNum) + intval($goods['allsalenum']);
+ $goods['totalnum'] = $goods['totalnum'] + $goods['allsalenum'];
+ }
+ $purchaseUser = WeliamWeChat::PurchaseUser($plugin, $goods['id']);
+ $goods['user_list'] = array_column($purchaseUser['info'], 'avatar');//购买当前商品的用户的头像
+ $goods['user_num'] = $stopBuyNum;//$purchaseUser['count'];//已参与人数
+ $goods['buy_num'] = $stopBuyNum ? $stopBuyNum : 0;//获取已售数量
+ //获取当前商品的浏览记录
+ //$browseRecord = array_column(self::getBrowseRecord($plugin, $goods['id']), 'avatar');
+ //$goods['user_list'] = is_array($browseRecord) ? $browseRecord :[];
+ //$goods['user_list'] = is_array($browseRecord) ? $browseRecord :[];
+ #4、已销售数量的百分比
+ if($goods['buy_num'] > 0 && $goods['totalnum'] > 0){
+ $goods['buy_percentage'] = sprintf("%.2f", ($goods['buy_num'] / $goods['totalnum']) * 100);
+ if($goods['buy_percentage']>100){
+ $goods['buy_percentage'] = 100.00;
+ }
+ }else{
+ $goods['buy_percentage'] = 0.00;
+ }
+ $goods['stk'] = $goods['totalnum'] - $stopBuyNum;
+ if($goods['stk']<0){$goods['stk'] = 0;}
+ #5、判断用户会员信息 获取商品基础价格
+ $goods['pay_state'] = 0;//购买状态 0=可以购买
+ if($mid){
+ $usercard = WeliamWeChat::VipVerification($mid);
+ if($usercard['id'] > 0){
+ $goods['is_vip'] = $usercard['id'];//获取当前用户的会员卡id 等于0则不是会员
+ $usercardlevel = $usercard['levelid'];
+ if($usercardlevel > 0){
+ $levelinfo = pdo_get(PDO_NAME.'halflevel',array('id'=>$usercardlevel),['name','army']);
+ $goods['levelname'] = $levelinfo['name'];
+ $goods['levelarmy'] = $levelinfo['army'];
+ }else{
+ $goods['levelname'] = $_W['wlsetting']['halflevel']['name'];
+ $goods['levelarmy'] = 0;
+ }
+ }else{
+ $goods['is_vip'] = 0;
+ $usercardlevel = -1;
+ $goods['levelname'] = '会员最多';
+ $goods['levelarmy'] = 0;
+ }
+ if($goods['vipstatus'] > 0){
+ if($goods['vipstatus'] == 2 && ($goods['is_vip'] <= 0 || empty($goods['is_vip']))){
+ $goods['pay_state'] = 1;//购买状态 1=会员特供,用户不是会员,不可购买
+ }
+ }
+ }else{
+ $usercardlevel = -1;
+ $goods['levelname'] = '会员最多';
+ $goods['levelarmy'] = 0;
+ }
+ #7、商品为抢购商品时 并且状态为未开始时 判断用户是否关注当前抢购商品 0=未关注,1=已关注
+ $goods['is_follow'] = 0;
+ if($plugin == 1 && $goods['status'] == 1){
+ $isFollow = pdo_getcolumn(PDO_NAME.'rush_follows',['mid'=>$mid,'actid'=>$id],'id');
+ if($isFollow) $goods['is_follow'] = 1;
+ }
+ #9、获取商品的优惠金额 Discount
+ if($goods['vipstatus'] == 1){
+ if($plugin == 1 || $plugin == 2 || $plugin == 3 || $plugin == 5 || $plugin == 7 || $plugin == 9){
+ $goods['discount_price'] = self::getVipDiscount($goods['viparray'],$usercardlevel);
+ }else{
+ $goods['discount_price'] = sprintf("%.2f",$goods['price'] - $goods['vipprice']);
+ }
+ }else{
+ $goods['discount_price'] = 0;
+ }
+ #8、判断是否为多规格商品
+ if($goods['optionstatus'] > 0){
+ if($plugin == 9){
+ $specinfo = WeliamWeChat::getActivitySpec($id);
+ $goods['spec'] = $specinfo['info'];
+ if($goods['vipstatus'] == 1){
+ foreach($goods['spec'] as &$spb){
+ $spb['discount_price'] = self::getVipDiscount($spb['viparray'],$usercardlevel);
+ if($spb['discount_price'] < 0.01){
+ $spb['discount_price'] = $goods['discount_price'];
+ }
+ }
+ }
+ $goods['minprice'] = $specinfo['minprice'];
+ $goods['maxprice'] = $specinfo['maxprice'];
+ $goods['stk'] = $specinfo['stk'];
+ }else{
+ $goods['spec'] = WeliamWeChat::getSpec($id, $plugin,$goods['vipstatus']);
+ //从新获取库存信息
+ foreach ($goods['spec']['info'] as &$sp){
+ if ($plugin == 1) {
+ //抢购商品的销量
+ $stopBuyNum = WeliamWeChat::getSalesNum(1,$goods['id'],$sp['id'],1,0,0,0,$goods['pftid']);
+ $sp['stock'] = $sp['stock'] - intval($stopBuyNum);
+ }else if($plugin == 2 || $plugin == 3){
+ $stopBuyNum = WeliamWeChat::getSalesNum($plugin,$goods['id'],$sp['id'],1,0,0,0,$goods['pftid']);
+ $sp['stock'] = $sp['stock'] - intval($stopBuyNum);
+ }
+ $sp['thumb'] = tomedia($sp['thumb']);
+ if($goods['vipstatus'] == 1){
+ $sp['discount_price'] = self::getVipDiscount($sp['viparray'],$usercardlevel);
+ if($sp['discount_price'] < 0.01 ){
+ $sp['discount_price'] = $goods['discount_price'];
+ }
+ }
+ }
+ $stkList = array_column($goods['spec']['info'],'stock');
+ $goods['stk'] = array_sum($stkList);
+ }
+ }
+
+ unset($goods['viparray']);
+ return $goods;
+ }
+ /**
+ * Comment: 首页获取头条信息
+ * Author: zzw
+ * Date: 2019/8/29 17:18
+ * @param $id
+ * @return bool
+ */
+ static function getHomeLine($id) {
+ $line = pdo_fetch("SELECT id,title,summary,display_img,author,author_img,browse,one_id,two_id FROM "
+ . tablename(PDO_NAME . "headline_content")
+ . " WHERE id = {$id} ");
+ if(!$line) return '';
+ $line['display_img'] = tomedia($line['display_img']);
+ $line['author_img'] = tomedia($line['author_img']);
+ $line['one_name'] = pdo_getcolumn(PDO_NAME . 'headline_class', ['id' => $line['one_id']], 'name') ? : '';
+ $line['two_name'] = pdo_getcolumn(PDO_NAME . 'headline_class',['id' => $line['two_id']], 'name') ? : '';
+ unset($line['one_id']);
+ unset($line['two_id']);
+ return $line;
+ }
+ /**
+ * Comment: 根据信息获取页面信息,菜单信息,广告信息
+ * Author: zzw
+ * Date: 2019/8/29 17:21
+ * @param $pageInfo
+ * @param $menuid
+ * @param $advid
+ * @return mixed
+ */
+ static function getPageInfo($pageInfo, $menuid, $advid) {
+ global $_W, $_GPC;
+ $page['title'] = $pageInfo['title'];
+ $page['background'] = $pageInfo['background'];
+ $page['share_title'] = $pageInfo['share_title'];
+ $page['share_image'] = tomedia($pageInfo['share_image']);
+ if ($menuid > 0) {
+ $menudata = Diy::getMenu($menuid)['data'];
+ }
+ if ($advid > 0) {
+ $advdata = Diy::BeOverdue($advid, false)['data'];
+ }
+ //信息拼装
+ $data['page'] = $page;//本页面配置信息
+ $data['menu'] = $menudata;//菜单配置信息
+ $data['adv'] = $advdata;//广告配置信息
+ return $data;
+ }
+
+ /**
+ * Comment: 核销码发送
+ * Author: wlf
+ * Date: 2021/08/13 10:04
+ * @param $code
+ * @param $mobile
+ * @return array
+ */
+ static function smsHXM($code,$goodname,$num = 1,$time,$mobile,$mid,$nickname='',$storename = '') {
+ global $_W;
+ $smsset = unserialize(pdo_getcolumn(PDO_NAME . "setting", array('key' => 'smsset','uniacid'=>$_W['uniacid']), 'value'));
+ $baseset = unserialize(pdo_getcolumn(PDO_NAME . "setting", array('key' => 'base','uniacid'=>$_W['uniacid']), 'value'));
+ if($smsset['dy_hxm'] > 0){
+ $smses = pdo_get(PDO_NAME . "smstpl", array('uniacid' => $_W['uniacid'], 'id' => $smsset['dy_hxm']));
+ $param = unserialize($smses['data']);
+ $nickname = !empty($nickname) ? $nickname : pdo_getcolumn(PDO_NAME.'member',array('id'=>$mid),'nickname');
+
+ $datas = array(
+ array('name' => '系统名称', 'value' => $baseset['name']),
+ array('name' => '版权信息', 'value' => $baseset['copyright']),
+ array('name' => '核销码', 'value' => $code),
+ array('name' => '昵称', 'value' => $nickname),
+ array('name' => '商品名', 'value' => $goodname),
+ array('name' => '数量', 'value' => $num),
+ array('name' => '过期时间', 'value' => $time),
+ array('name' => '店铺名', 'value' => $storename)
+ );
+ foreach ($param as $d) {
+ $params[$d['data_temp']] = self::replaceTemplate($d['data_shop'], $datas);
+ }
+ return self::sendSms($smses, $params, $mobile,$mid);
+ }
+ }
+
+ /**
+ * Comment: 验证码发送组一
+ * Author: zzw
+ * Date: 2019/8/29 17:22
+ * @param $code
+ * @param $mobile
+ * @return array
+ */
+ static function smsSF($code, $mobile,$mid) {
+ global $_W;
+ $smsset = unserialize(pdo_getcolumn(PDO_NAME . "setting", array('key' => 'smsset','uniacid'=>$_W['uniacid']), 'value'));
+ $baseset = unserialize(pdo_getcolumn(PDO_NAME . "setting", array('key' => 'base','uniacid'=>$_W['uniacid']), 'value'));
+ $smses = pdo_get(PDO_NAME . "smstpl", array('uniacid' => $_W['uniacid'], 'id' => $smsset['dy_sf']));
+ $nickname = pdo_getcolumn(PDO_NAME.'member',array('id'=>$mid),'nickname');
+ $param = unserialize($smses['data']);
+ $datas = array(
+ array('name' => '系统名称', 'value' => $baseset['name']),
+ array('name' => '版权信息', 'value' => $baseset['copyright']),
+ array('name' => '验证码', 'value' => $code),
+ array('name' => '昵称', 'value' => $nickname)
+ );
+ foreach ($param as $d) {
+ $params[$d['data_temp']] = self::replaceTemplate($d['data_shop'], $datas);
+ }
+ return self::sendSms($smses, $params, $mobile,$mid);
+ }
+ /**
+ * Comment: 验证码发送组二
+ * Author: zzw
+ * Date: 2019/8/29 17:22
+ * @param $str
+ * @param array $datas
+ * @return mixed
+ */
+ static function replaceTemplate($str, $datas = array()) {
+ foreach ($datas as $d) {
+ $str = str_replace('【' . $d['name'] . '】', $d['value'], $str);
+ }
+ return $str;
+ }
+ /**
+ * Comment: 验证码发送组三
+ * Author: zzw
+ * Date: 2019/8/29 17:22
+ * @param $smstpl
+ * @param $param
+ * @param $mobile
+ * @param string $mid
+ * @return array
+ */
+ static function sendSms($smstpl, $param, $mobile, $mid = '') {
+ global $_W;
+ $smsset = unserialize(pdo_getcolumn(PDO_NAME . "setting", array('key' => 'sms','uniacid'=>$_W['uniacid']), 'value'));
+ if ($smstpl['type'] == 'aliyun') {
+ include PATH_CORE . 'library/aliyun/Config.php';
+ $profile = DefaultProfile::getProfile("cn-hangzhou", $smsset['note_appkey'], $smsset['note_secretKey']);
+ DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
+ $acsClient = new DefaultAcsClient($profile);
+ m('aliyun/sendsmsrequest')->setSignName($smsset['note_sign']);
+ m('aliyun/sendsmsrequest')->setTemplateParam(json_encode($param));
+ m('aliyun/sendsmsrequest')->setTemplateCode($smstpl['smstplid']);
+ m('aliyun/sendsmsrequest')->setPhoneNumbers($mobile);
+ $resp = $acsClient->getAcsResponse(m('aliyun/sendsmsrequest'));
+ $res = Util::object_array($resp);
+ if ($res['Code'] == 'OK') {
+ self::create_apirecord(-1, '', $mid, $mobile, 1, '阿里云身份验证');
+ $recode = array("result" => 1);
+ } else {
+ $recode = array("result" => 2, "msg" => $res['Message']);
+ }
+ } else {
+ m('alidayu/topclient')->appkey = $smsset['note_appkey'];
+ m('alidayu/topclient')->secretKey = $smsset['note_secretKey'];
+ m('alidayu/smsnum')->setSmsType("normal");
+ m('alidayu/smsnum')->setSmsFreeSignName($smsset['note_sign']);
+ m('alidayu/smsnum')->setSmsParam(json_encode($param));
+ m('alidayu/smsnum')->setRecNum($mobile);
+ m('alidayu/smsnum')->setSmsTemplateCode($smstpl['smstplid']);
+ $resp = m('alidayu/topclient')->execute(m('alidayu/smsnum'), '6100e23657fb0b2d0c78568e55a3031134be9a3a5d4b3a365753805');
+ $res = Util::object_array($resp);
+ if ($res['result']['success'] == 1) {
+ self::create_apirecord(-1, '', $mid, $mobile, 1, '阿里大于身份验证');
+ $recode = array("result" => 1);
+ } else {
+ $recode = array("result" => 2, "msg" => $res['sub_msg']);
+ }
+ }
+
+
+ return $recode;
+ }
+ /**
+ * Comment: 验证码发送组四
+ * Author: zzw
+ * Date: 2019/8/29 17:22
+ * @param $sendmid
+ * @param string $sendmobile
+ * @param $takemid
+ * @param $takemobile
+ * @param $type
+ * @param $remark
+ */
+ static function create_apirecord($sendmid, $sendmobile = '', $takemid, $takemobile, $type, $remark) {
+ global $_W;
+ $data = array(
+ 'uniacid' => $_W['uniacid'],
+ 'sendmid' => $sendmid,
+ 'sendmobile' => $sendmobile,
+ 'takemid' => $takemid,
+ 'takemobile' => $takemobile,
+ 'type' => $type,
+ 'remark' => $remark,
+ 'createtime' => time()
+ );
+ pdo_insert(PDO_NAME . 'apirecord', $data);
+ }
+ /**
+ * Comment: 获取推荐商品信息列表
+ * Author: zzw
+ * Date: 2019/8/13 17:11
+ * @param string $num 获取的数量
+ * @param int $type 当前商品类型:1=抢购 2=团购 3=拼团 4=大礼包 5=优惠券 6=折扣卡 7=砍价商品
+ * @param int $id 当前商品id,存在时不会获取该商品
+ * @return mixed
+ */
+ public static function getRecommendGoods($num,$type = 0,$id = 0){
+ global $_W,$_GPC;
+ //获取设置选项
+ $set = Setting::wlsetting_read('base');
+ $recommendType = $set['recommend_type'] ? : 0;//0=同商家同类型,1=同商家,2=同类型,3=随机
+ //获取商品列表
+ switch ($recommendType){
+ case 0: $list = self::sameStoreType($num,$type,$id);break;//同商家同类型
+ case 1: $list = self::sameStore($num,$type,$id);break;//同商家
+ case 2: $list = self::sameType($num,$type,$id);break;//同类型
+ case 3: $list = self::sameRandom($num,$type,$id);break;//随机
+ }
+ //处理list
+ if(is_array($list) && count($list) > 0){
+ if(count($list) > $num){
+ //总数量大于需要数量 随机获取
+ for($i=0;$i<$num;$i++){
+ if(count($list) > 0){
+ $key = array_rand($list);
+ $newList[$i] = self::getHomeGoods($list[$key]['type'], $list[$key]['id']);
+ //链接生成
+ $newList[$i]['url'] = h5_url('pages/subPages/goods/index',['id'=>$newList[$i]['id'],'type'=>$newList[$i]['type']]);
+ unset($list[$key]);
+ unset($newList[$i]['user_list']);
+ unset($newList[$i]['user_num']);
+ unset($newList[$i]['stk']);
+ unset($newList[$i]['buy_percentage']);
+ unset($newList[$i]['is_vip']);
+ unset($newList[$i]['address']);
+ unset($newList[$i]['status']);
+ unset($newList[$i]['totalnum']);
+ unset($newList[$i]['storename']);
+ unset($newList[$i]['sid']);
+ unset($newList[$i]['starttime']);
+ unset($newList[$i]['endtime']);
+ unset($newList[$i]['vipprice']);
+ unset($newList[$i]['vipstatus']);
+ unset($newList[$i]['buy_limit']);
+ unset($newList[$i]['peoplenum']);
+ unset($newList[$i]['realsalenum']);
+ unset($newList[$i]['allsalenum']);
+ unset($newList[$i]['buy_num']);
+ unset($newList[$i]['user_limit_num']);
+ }else{
+ continue;
+ }
+ }
+ }else{
+ //总数量小于或者等于需要数量 直接返回
+ foreach($list as $key => &$val){
+ $val = self::getHomeGoods($val['type'], $val['id']);
+ //链接生成
+ $val['url'] = h5_url('pages/subPages/goods/index',['id'=>$val['id'],'type'=>$val['type']]);
+ unset($val['user_list']);
+ unset($val['user_num']);
+ unset($val['stk']);
+ unset($val['buy_percentage']);
+ unset($val['is_vip']);
+ unset($val['address']);
+ unset($val['status']);
+ unset($val['totalnum']);
+ unset($val['storename']);
+ unset($val['sid']);
+ unset($val['starttime']);
+ unset($val['endtime']);
+ unset($val['vipprice']);
+ unset($val['vipstatus']);
+ unset($val['buy_limit']);
+ unset($val['peoplenum']);
+ unset($val['realsalenum']);
+ unset($val['allsalenum']);
+ unset($val['buy_num']);
+ unset($val['user_limit_num']);
+ }
+ $newList = $list;
+ }
+ }else{
+ $newList = [];
+ }
+
+ return $newList;
+ }
+ /**
+ * Comment: 推荐商品 —— 同商家同类型
+ * Author: zzw
+ * Date: 2021/1/4 10:32
+ * @param $num
+ * @param $type
+ * @param $id
+ * @return array|false|mixed
+ */
+ private static function sameStoreType($num,$type,$id){
+ global $_W,$_GPC;
+ //基本条件生成
+ $where = " WHERE aid = {$_W['aid']} AND uniacid = {$_W['uniacid']} AND id != {$id} ";
+ //获取商户id、表信息
+ switch ($type) {
+ case 1:
+ $sid = pdo_getcolumn(PDO_NAME."rush_activity",['id' => $id],'sid');
+ $table = tablename(PDO_NAME."rush_activity");
+ $where .= " AND sid = {$sid} AND status = 2";
+ $field = " id,'1' as type ";
+ break;//抢购商品表
+ case 2:
+ $sid = pdo_getcolumn(PDO_NAME."groupon_activity",['id' => $id],'sid');
+ $table = tablename(PDO_NAME."groupon_activity");
+ $where .= " AND sid = {$sid} AND status = 2";
+ $field = " id,'2' as type ";
+ break;//团购商品表
+ case 3:
+ $sid = pdo_getcolumn(PDO_NAME."fightgroup_goods",['id' => $id],'merchantid');
+ $table = tablename(PDO_NAME."fightgroup_goods");
+ $where .= " AND merchantid = {$sid} AND status = 2";
+ $field = " id,'3' as type ";
+ break;//拼团商品表
+ case 5:
+ $sid = pdo_getcolumn(PDO_NAME."couponlist",['id' => $id],'merchantid');
+ $table = tablename(PDO_NAME."couponlist");
+ $where .= " AND merchantid = {$sid} AND status = 2";
+ $field = " id,'5' as type ";
+ break;//拼团商品表
+ case 7:
+ $sid = pdo_getcolumn(PDO_NAME."bargain_activity",['id' => $id],'sid');
+ $table = tablename(PDO_NAME."bargain_activity");
+ $where .= " AND sid = {$sid} AND status = 2";
+ $field = " id,'7' as type ";
+ break;//砍价商品表
+ }
+ $list = pdo_fetchall("SELECT {$field} FROM ".$table.$where." LIMIT 100 ");
+
+ return $list ? : [];
+ }
+ /**
+ * Comment: 推荐商品 —— 同商家
+ * Author: zzw
+ * Date: 2021/1/4 11:17
+ * @param $num
+ * @param $type
+ * @param $id
+ * @return array
+ */
+ private static function sameStore($num,$type,$id){
+ global $_W,$_GPC;
+ //获取商户id
+ switch ($type) {
+ case 1:
+ $sid = pdo_getcolumn(PDO_NAME."rush_activity",['id' => $id],'sid');
+ break;//抢购商品表
+ case 2:
+ $sid = pdo_getcolumn(PDO_NAME."groupon_activity",['id' => $id],'sid');
+ break;//团购商品表
+ case 3:
+ $sid = pdo_getcolumn(PDO_NAME."fightgroup_goods",['id' => $id],'merchantid');
+ break;//拼团商品表
+ case 5:
+ $sid = pdo_getcolumn(PDO_NAME."couponlist",['id' => $id],'merchantid');
+ break;//拼团商品表
+ case 7:
+ $sid = pdo_getcolumn(PDO_NAME."bargain_activity",['id' => $id],'sid');
+ break;//砍价商品表
+ }
+ //商品信息获取
+ $rush = tablename(PDO_NAME."rush_activity");//抢购商品表 1
+ $group = tablename(PDO_NAME."groupon_activity");//团购商品表 2
+ $fight = tablename(PDO_NAME."fightgroup_goods");//拼团商品表 3
+ $coupon = tablename(PDO_NAME."couponlist");//卡卷商品表 5
+ $bargain = tablename(PDO_NAME."bargain_activity");//砍价商品表 7
+ $where = " WHERE aid ={$_W['aid']} AND uniacid = {$_W['uniacid']} ";
+ $noId = " AND id != {$id} ";
+ //抢购商品信息
+ if($type == 1) $rushList = pdo_fetchall("SELECT id,'1' as type FROM ".$rush.$where.$noId." AND status = 2 AND sid = {$sid} LIMIT 100");
+ else $rushList = pdo_fetchall("SELECT id,'1' as type FROM ".$rush.$where." AND status = 2 AND sid = {$sid} LIMIT 100");
+ //团购商品信息
+ if($type == 2) $groupList = pdo_fetchall("SELECT id,'2' as type FROM ".$group.$where.$noId." AND status = 2 AND sid = {$sid} LIMIT 100");
+ else $groupList = pdo_fetchall("SELECT id,'2' as type FROM ".$group.$where." AND status = 2 AND sid = {$sid} LIMIT 100");
+ //拼团商品信息
+ if($type == 3) $fightList = pdo_fetchall("SELECT id,'3' as type FROM ".$fight.$where.$noId." AND status = 2 AND merchantid = {$sid} LIMIT 100");
+ else $fightList = pdo_fetchall("SELECT id,'3' as type FROM ".$fight.$where." AND status = 2 AND merchantid = {$sid} LIMIT 100");
+ //卡卷商品信息
+ if($type == 5) $couponList = pdo_fetchall("SELECT id,'5' as type FROM ".$coupon.$where.$noId." AND status = 2 AND merchantid = {$sid} LIMIT 100");
+ else $couponList = pdo_fetchall("SELECT id,'5' as type FROM ".$coupon.$where." AND status = 2 AND merchantid = {$sid} LIMIT 100");
+ //砍价商品信息
+ if($type == 7) $bargainList = pdo_fetchall("SELECT id,'7' as type FROM ".$bargain.$where.$noId." AND status = 2 AND sid = {$sid} LIMIT 100");
+ else $bargainList = pdo_fetchall("SELECT id,'7' as type FROM ".$bargain.$where." AND status = 2 AND sid = {$sid} LIMIT 100");
+ #3、随机获取商品信息
+ $list = array_merge($rushList,$groupList,$fightList,$couponList,$bargainList);
+
+ return $list ? : [];
+ }
+ /**
+ * Comment: 推荐商品 —— 同类型
+ * Author: zzw
+ * Date: 2021/1/4 11:21
+ * @param $num
+ * @param $type
+ * @param $id
+ * @return array|false|mixed
+ */
+ private static function sameType($num,$type,$id){
+ global $_W,$_GPC;
+ //基本条件生成
+ $where = " WHERE aid = {$_W['aid']} AND uniacid = {$_W['uniacid']} AND id != {$id} ";
+ //获取商户id、表信息
+ switch ($type) {
+ case 1:
+ $table = tablename(PDO_NAME."rush_activity");
+ $where .= " AND status = 2";
+ $field = " id,'1' as type ";
+ break;//抢购商品表
+ case 2:
+ $table = tablename(PDO_NAME."groupon_activity");
+ $where .= " AND status = 2";
+ $field = " id,'2' as type ";
+ break;//团购商品表
+ case 3:
+ $table = tablename(PDO_NAME."fightgroup_goods");
+ $where .= " AND status = 2";
+ $field = " id,'3' as type ";
+ break;//拼团商品表
+ case 5:
+ $table = tablename(PDO_NAME."couponlist");
+ $where .= " AND status = 2";
+ $field = " id,'5' as type ";
+ break;//拼团商品表
+ case 7:
+ $table = tablename(PDO_NAME."bargain_activity");
+ $where .= " AND status = 2";
+ $field = " id,'7' as type ";
+ break;//砍价商品表
+ }
+ $list = pdo_fetchall("SELECT {$field} FROM ".$table.$where." LIMIT 100 ");
+
+ return $list ? : [];
+ }
+ /**
+ * Comment: 推荐商品 —— 随机
+ * Author: zzw
+ * Date: 2021/1/4 11:26
+ * @param $num
+ * @param $type
+ * @param $id
+ * @return array
+ */
+ private static function sameRandom($num,$type,$id){
+ global $_W,$_GPC;
+ //商品信息获取
+ $rush = tablename(PDO_NAME."rush_activity");//抢购商品表 1
+ $group = tablename(PDO_NAME."groupon_activity");//团购商品表 2
+ $fight = tablename(PDO_NAME."fightgroup_goods");//拼团商品表 3
+ $coupon = tablename(PDO_NAME."couponlist");//卡卷商品表 5
+ $bargain = tablename(PDO_NAME."bargain_activity");//砍价商品表 7
+ $where = " WHERE aid ={$_W['aid']} AND uniacid = {$_W['uniacid']} ";
+ $noId = " AND id != {$id} ";
+ //抢购商品信息
+ if($type == 1) $rushList = pdo_fetchall("SELECT id,'1' as type FROM ".$rush.$where.$noId." AND status = 2 LIMIT 100");
+ else $rushList = pdo_fetchall("SELECT id,'1' as type FROM ".$rush.$where." AND status = 2 LIMIT 100");
+ //团购商品信息
+ if($type == 2) $groupList = pdo_fetchall("SELECT id,'2' as type FROM ".$group.$where.$noId." AND status = 2 LIMIT 100");
+ else $groupList = pdo_fetchall("SELECT id,'2' as type FROM ".$group.$where." AND status = 2 LIMIT 100");
+ //拼团商品信息
+ if($type == 3) $fightList = pdo_fetchall("SELECT id,'3' as type FROM ".$fight.$where.$noId." AND status = 2 LIMIT 100");
+ else $fightList = pdo_fetchall("SELECT id,'3' as type FROM ".$fight.$where." AND status = 2 LIMIT 100");
+ //卡卷商品信息
+ if($type == 5) $couponList = pdo_fetchall("SELECT id,'5' as type FROM ".$coupon.$where.$noId." AND status = 2 LIMIT 100");
+ else $couponList = pdo_fetchall("SELECT id,'5' as type FROM ".$coupon.$where." AND status = 2 LIMIT 100");
+ //砍价商品信息
+ if($type == 7) $bargainList = pdo_fetchall("SELECT id,'7' as type FROM ".$bargain.$where.$noId." AND status = 2 LIMIT 100");
+ else $bargainList = pdo_fetchall("SELECT id,'7' as type FROM ".$bargain.$where." AND status = 2 LIMIT 100");
+ #3、随机获取商品信息
+ $list = array_merge($rushList,$groupList,$fightList,$couponList,$bargainList);
+
+ return $list ? : [];
+ }
+ /**
+ * Comment: 开启事务处理
+ * Author: zzw
+ * Date: 2019/8/15 11:47
+ * @return bool
+ */
+ public static function startTrans(){
+ return pdo_query(" BEGIN ");
+ }
+ /**
+ * Comment: 提交事务处理
+ * Author: zzw
+ * Date: 2019/8/15 11:47
+ * @return bool
+ */
+ public static function commit(){
+ return pdo_query(" COMMIT ");
+ }
+ /**
+ * Comment: 事务回滚
+ * Author: zzw
+ * Date: 2019/8/15 11:47
+ * @return bool
+ */
+ public static function rollback(){
+ return pdo_query(" ROLLBACK ");
+ }
+ /**
+ * Comment: 获取二维码图片base64格式
+ * Author: zzw
+ * Date: 2019/8/20 18:09
+ * @param $url
+ * @return string
+ */
+ public static function getQrCode($url){
+ global $_W,$_GPC;
+ #1、长链接转短连接
+ $result = Util::long2short($url);
+ if (!is_error($result)) $url = $result['short_url'];
+ #2、生成二维码
+ require_once '../library/qrcode/QRcode.lib.php';
+ ob_start();
+ QRcode::png($url, false, QR_ECLEVEL_L, 16, 1,false,true);
+ $image_data = base64_encode(ob_get_contents());
+ ob_end_clean();
+ $image_data = "data:image/png;base64," . $image_data;
+
+ return $image_data;
+ }
+ /**
+ * Comment: 获取对应渠道的access_token(默认:公众号)
+ * Author: zzw
+ * Date: 2019/10/24 10:55
+ * @param bool $new 是否获取最新的token,默认false
+ * @param int $source 渠道:1=公众号(默认);2=h5;3=小程序
+ * @return mixed
+ */
+ public static function getAccessToken($new = false,$source = 1){
+ global $_W;
+ $name = 'accesstoken_source'.$source;
+ session_start();
+ #1、判断是否存在accessToken 存在则直接获取,不存在则从新获取
+ $tokenCacheInfo = json_decode($_SESSION[$name],true);
+ if($tokenCacheInfo && time() < $tokenCacheInfo['end_time'] && !$new){
+ $accessToken = $tokenCacheInfo['access_token'];
+ }else{
+ //根据渠道获取配置信息 并且获取对应的信息
+ switch ($source){
+ case 1:case 2:
+ //获取配置信息 初始化EasyWeChat
+ $params = Util::object_array($_W['account']);
+ $config = [
+ 'app_id' => trim($params['key']),
+ 'secret' => trim($params['secret']),
+ 'token' => trim($params['token']),
+ 'response_type' => 'array',
+ ];
+ $app = Factory::officialAccount($config);
+ $tokenObj = $app->access_token;
+ $token = $tokenObj->getToken($new); // token 数组 token['access_token'] 字符串
+ break;
+ case 3:
+ //获取配置信息 初始化EasyWeChat
+ $params = Setting::wlsetting_read('wxapp_config');
+ $config = [
+ 'app_id' => trim($params['appid']),
+ 'secret' => trim($params['secret']),
+ 'response_type' => 'array',
+ ];
+ $app = Factory::miniProgram($config);
+ $tokenObj = $app->access_token;
+ $token = $tokenObj->getToken($new); // token 数组 token['access_token'] 字符串
+ break;
+ }
+ //获取token信息 判断有效时间
+ $accessToken = $token['access_token'];
+ $endTime = (time() + $token['expires_in']) - 100;
+ //记录进入session中
+ $_SESSION[$name] = json_encode(['access_token'=>$accessToken,'end_time'=>$endTime]);
+ }
+ #2、返回accessToken
+ return $accessToken;
+ }
+ /**
+ * Comment: 判断当前商品是否显示分销助手/获取当前商品的分销佣金
+ * Author: zzw
+ * Date: 2019/11/14 11:35
+ * @param $type int 商品类型:1=抢购 2=团购 3=拼团 5=优惠券 7=砍价商品 8=积分商品
+ * @param $id int 商品id
+ * @return mixed|array
+ */
+ public static function getDisInfo($type,$id){
+ global $_W;
+ #1、获取基本设置信息
+ $data['is_show'] = $data['tipflag'] = 0;//是否显示分销助手 0=不显示;1=显示
+ $disSet = $_W['wlsetting']['distribution'];
+ #1、判断是否开启分销商 判断当前商品是否参与分销
+ $disflag = pdo_getcolumn(PDO_NAME.'distributor',array('id'=>$_W['wlmember']['distributorid']),'disflag');
+ if($disSet['switch'] > 0) {
+ //获取分销商佣金比例
+ if($_W['wlmember']['distributorid'] > 0){
+ $lv_id = pdo_getcolumn(PDO_NAME."distributor",['id'=>$_W['wlmember']['distributorid']],'dislevel');
+ $rate = pdo_getcolumn(PDO_NAME."dislevel",['id'=>$lv_id,'uniacid'=>$_W['uniacid']],'onecommission');
+ }
+ //用户不是分销商 获取默认佣金比例
+ if(!$lv_id){
+ $defaleve = pdo_get(PDO_NAME."dislevel",['isdefault'=>1,'uniacid'=>$_W['uniacid']],['onecommission','id']);
+ $lv_id = $defaleve['id'];
+ $rate = $defaleve['onecommission'];
+ }
+ $rate = $rate ? $rate / 100 : 0;
+ //获取对应商品类型的佣金 商品类型:1=抢购 2=团购 3=拼团 5=优惠券 7=砍价商品 8=积分商品
+ switch ($type) {
+ case 1:
+ $goods = pdo_get('wlmerchant_rush_activity',array('id' => $id),array('disarray','isdistri','price','optionstatus','isdistristatus'));
+ if($goods['isdistri'] != 1){
+ if($goods['optionstatus'] > 0){
+ $options = pdo_getall('wlmerchant_goods_option',array('type' => 1,'goodsid' => $id),array('price','disarray'));
+ foreach($options as &$opp){
+ $disarray = self::mergeDisArray($opp['disarray'],$goods['disarray']);
+ $disarray = unserialize($disarray);
+ $opp['dismoney'] = self::getDismoney($disarray,$lv_id,$goods['isdistristatus'],$opp['price'],$rate);
+ }
+ $prices = array_column($options,'dismoney');
+ $goods['commission'] = max($prices);
+ }else{
+ $disarray = unserialize($goods['disarray']);
+ $goods['commission'] = self::getDismoney($disarray,$lv_id,$goods['isdistristatus'],$goods['price'],$rate);
+ }
+ }
+ break;//抢购
+ case 2:
+ $goods = pdo_get('wlmerchant_groupon_activity',array('id' => $id),array('disarray','isdistri','price','optionstatus','isdistristatus'));
+ if($goods['isdistri'] != 1){
+ if($goods['optionstatus'] > 0){
+ $options = pdo_getall('wlmerchant_goods_option',array('type' => 3,'goodsid' => $id),array('price','disarray'));
+ foreach($options as &$opp){
+ $disarray = self::mergeDisArray($opp['disarray'],$goods['disarray']);
+ $disarray = unserialize($disarray);
+ $opp['dismoney'] = self::getDismoney($disarray,$lv_id,$goods['isdistristatus'],$opp['price'],$rate);
+ }
+ $prices = array_column($options,'dismoney');
+ $goods['commission'] = max($prices);
+ }else{
+ $disarray = unserialize($goods['disarray']);
+ $goods['commission'] = self::getDismoney($disarray,$lv_id,$goods['isdistristatus'],$goods['price'],$rate);
+ }
+ }
+ break;//团购
+ case 3:
+ $goods = pdo_get('wlmerchant_fightgroup_goods',array('id' => $id),array('disarray','isdistri','price','specstatus','isdistristatus'));
+ if($goods['isdistri'] != 1){
+ if($goods['specstatus'] > 0){
+ $options = pdo_getall('wlmerchant_goods_option',array('type' => 2,'goodsid' => $id),array('price','disarray'));
+ foreach($options as &$opp){
+ $disarray = self::mergeDisArray($opp['disarray'],$goods['disarray']);
+ $disarray = unserialize($disarray);
+ $opp['dismoney'] = self::getDismoney($disarray,$lv_id,$goods['isdistristatus'],$opp['price'],$rate);
+ }
+ $prices = array_column($options,'dismoney');
+ $goods['commission'] = max($prices);
+ }else{
+ $disarray = unserialize($goods['disarray']);
+ $goods['commission'] = self::getDismoney($disarray,$lv_id,$goods['isdistristatus'],$goods['price'],$rate);
+ }
+ }
+ break;//拼团
+ case 5:
+ $goods = pdo_get('wlmerchant_fightgroup_goods',array('id' => $id),array('disarray','isdistri','price','isdistristatus'));
+ if($goods['isdistri'] != 1){
+ $disarray = unserialize($goods['disarray']);
+ $goods['commission'] = self::getDismoney($disarray,$lv_id,$goods['isdistristatus'],$goods['price'],$rate);
+ }
+ break;//优惠券
+ case 7:
+ $goods = pdo_get('wlmerchant_bargain_activity',array('id' => $id),array('disarray','isdistri','price','isdistristatus'));
+ if($goods['isdistri'] != 1){
+ $disarray = unserialize($goods['disarray']);
+ $goods['commission'] = self::getDismoney($disarray,$lv_id,$goods['isdistristatus'],$goods['price'],$rate);
+ }
+ break;//砍价商品
+ case 8:
+ $sql = "SELECT CASE WHEN onedismoney > 0 THEN onedismoney
+ ELSE (`use_credit2`*{$rate})
+ END as commission,isdistri FROM ".tablename(PDO_NAME.'consumption_goods')." WHERE id = {$id} ";
+ $goods = pdo_fetch($sql);
+ break;//积分商品
+ }
+ $data['max_commission'] = sprintf("%.2f" , $goods['commission']);
+ //商品参与分销
+ if($type == 8){
+ $goods['isdistri'] = $goods['isdistri'] ? 0:1;
+ }
+ if($goods['isdistri'] != 1 && $data['max_commission'] > 0){
+ $data['is_show'] = 1;
+ }
+ //判断用户
+ if($disflag == 0){
+ if($disSet['dishelp'] > 0){
+ $data['tipflag'] = 1;
+ }
+ $data['is_show'] = 0;
+ }
+ //定制
+ if(Customized::init('pocket140') > 0){
+ $data['korea'] = 1;
+ }else{
+ $data['korea'] = 0;
+ }
+ }
+
+ return $data;
+ }
+ /**
+ * Comment: 获取应该的分销佣金
+ * Author: wlf
+ * Date: 2020/11/25 18:48
+ */
+ public static function getDismoney($disarray,$lv_id,$isdistristatus,$price,$rate){
+ global $_W;
+ if($disarray[$lv_id]['onedismoney'] > 0){
+ if($isdistristatus > 0){
+ $dismoney = $disarray[$lv_id]['onedismoney'];
+ }else{
+ $dismoney = sprintf("%.2f" , $price * $disarray[$lv_id]['onedismoney'] /100);
+ }
+ }else{
+ $dismoney = sprintf("%.2f" , $price * $rate);
+ }
+ return $dismoney;
+ }
+ /**
+ * Comment: 记录用户浏览信息
+ * Author: zzw
+ * Date: 2019/11/14 14:34
+ * @param $type int 商品类型:1=抢购 2=团购 3=拼团 4=大礼包 5=优惠券 6=折扣卡 7=砍价商品 8=积分商品
+ * @param $id int 商品id
+ */
+ public static function browseRecord($type, $id){
+ global $_W;
+ #商品类型:1=抢购 2=团购 3=拼团 4=大礼包 5=优惠券 6=折扣卡 7=砍价商品 8=积分商品
+ if($_W['mid']){
+ $data = [
+ 'type' => $type ,
+ 'mid' => $_W['mid'] ,
+ 'goods_id' => $id ,
+ 'uniacid' => $_W['uniacid']
+ ];
+ #1、判断用户是否已经浏览当前商品
+ $isBrowse = pdo_get(PDO_NAME."browse_record",$data);
+ if($isBrowse){
+ //已经浏览 修改最近浏览时间
+ pdo_update(PDO_NAME."browse_record",['updade_time'=>time()],$data);
+ }else{
+ $data['create_time'] = time();
+ $data['updade_time'] = time();
+ pdo_insert(PDO_NAME."browse_record",$data);
+ }
+ }
+ }
+ /**
+ * Comment: 获取某个商品的浏览记录
+ * Author: zzw
+ * Date: 2019/11/14 14:50
+ * @param int $type 商品类型:1=抢购 2=团购 3=拼团 4=大礼包 5=优惠券 6=折扣卡 7=砍价商品 8=积分商品
+ * @param int $id 商品id
+ * @param int $limit 查询的最大数量
+ * @return array
+ */
+ public static function getBrowseRecord($type, $id,$limit = 5){
+ global $_W;
+ #1、条件生成
+ //$where = " a.type = {$type} AND a.goods_id = {$id} AND a.uniacid = {$_W['uniacid']} ";
+ // if($_W['mid']) $where .= " AND mid != {$_W['mid']} ";
+ #1、获取当前商品的浏览记录
+// $sql = "SELECT a.id,b.avatar,b.nickname FROM ".tablename(PDO_NAME."browse_record")
+// . " as a RIGHT JOIN ".tablename(PDO_NAME."member")
+// ." as b ON a.mid = b.id WHERE {$where} ORDER BY a.updade_time DESC LIMIT {$limit}";
+// $list = pdo_fetchall($sql);
+ if(empty($_W['mid'])) $_W['mid'] = 0;
+ $list = pdo_fetchall("SELECT distinct mid FROM ".tablename(PDO_NAME."browse_record")."WHERE uniacid = {$_W['uniacid']} AND mid != {$_W['mid']} AND type = {$type} AND goods_id = {$id} ORDER BY updade_time DESC LIMIT {$limit}");
+ if($list){
+ foreach ($list as &$li){
+ $member = pdo_get(PDO_NAME."member",array('id' => $li['mid']),array('avatar','nickname'));
+ $li['nickname'] = $member['nickname'];
+ $li['avatar'] = tomedia($member['avatar']);
+ }
+ }
+ return is_array($list) ? $list : [];
+ }
+ /**
+ * Comment: 获取某个商品或规格的销量
+ * Author: wlf
+ * Date: 2020/06/28 18:30
+ * @param int $plugin 商品类型:1=抢购 2=团购 3=拼团 4=卡券 5=砍价 6=活动
+ * @param int $id 商品id
+ * @param int $specid 规格id
+ * @param int $type 类型: 1=已下单 2=已支付 3=已完成
+ * @param int $mid 买家ID
+ * @param int $starttime 起始时间
+ * @param int $endtime 结束时间
+ * @param int $endtime 三方商品id
+ * @return array
+ */
+ public static function getSalesNum($plugin,$id,$specid = 0,$type = 1,$mid = 0,$starttime = 0,$endtime = 0,$threeid = 0){
+ global $_W;
+ if($threeid > 0){
+ $salesnum = Pftapimod::getThreeSalesNum($plugin,$id,$type,$mid,$starttime,$endtime);
+ }else{
+ if($plugin == 1){
+ $orderwhere = " activityid = {$id}";
+ $smallorderwhere = " gid = {$id} AND plugin = 'rush'";
+ if($specid > 0){
+ $orderwhere .= " AND optionid = {$specid}";
+ $smallorderwhere .= " AND specid = {$specid}";
+ }
+ if($mid > 0){
+ $orderwhere .= " AND mid = {$mid}";
+ $smallorderwhere .= " AND mid = {$mid}";
+ }
+ if($starttime > 0){
+ $orderwhere .= " AND createtime > {$starttime}";
+ $smallorderwhere .= " AND createtime > {$starttime}";
+ }
+ if($endtime > 0){
+ $orderwhere .= " AND createtime < {$endtime}";
+ $smallorderwhere .= " AND createtime < {$endtime}";
+ }
+ if($type == 1){
+ //未支付的
+ $nopayorderwhere = $orderwhere." AND status = 0";
+ $nopaynum = implode(pdo_fetch("SELECT sum(num) FROM " . tablename(PDO_NAME . "rush_order") . " WHERE {$nopayorderwhere}"));
+ //快递的
+ $expresswhere = $orderwhere." AND expressid > 0 AND status IN (2,3,6,4,8,9)";
+ $expressnum = implode(pdo_fetch("SELECT sum(num) FROM " . tablename(PDO_NAME . "rush_order") . " WHERE {$expresswhere}"));
+ //核销的
+ $smallorderwhere .= " AND status != 3";
+ $hexiaonum = pdo_fetchcolumn('SELECT count(id) FROM '.tablename('wlmerchant_smallorder')." WHERE {$smallorderwhere}");
+ $salesnum = $nopaynum + $expressnum + $hexiaonum;
+ }else if($type == 2){
+ //快递的
+ $expresswhere = $orderwhere." AND expressid > 0 AND status IN (2,3,6,4,8,9)";
+ $expressnum = implode(pdo_fetch("SELECT sum(num) FROM " . tablename(PDO_NAME . "rush_order") . " WHERE {$expresswhere}"));
+ //核销的
+ $smallorderwhere .= " AND status != 3";
+ $hexiaonum = pdo_fetchcolumn('SELECT count(id) FROM '.tablename('wlmerchant_smallorder')." WHERE {$smallorderwhere}");
+ $salesnum = $expressnum + $hexiaonum;
+ }else if($type == 3){
+ //快递的
+ $expresswhere = $orderwhere." AND expressid > 0 AND status IN (2,3)";
+ $expressnum = implode(pdo_fetch("SELECT sum(num) FROM " . tablename(PDO_NAME . "rush_order") . " WHERE {$expresswhere}"));
+ //核销的
+ $smallorderwhere .= " AND status = 2";
+ $hexiaonum = pdo_fetchcolumn('SELECT count(id) FROM '.tablename('wlmerchant_smallorder')." WHERE {$smallorderwhere}");
+ $salesnum = $expressnum + $hexiaonum;
+ }
+ }
+ else{
+ $orderwhere = " fkid = {$id}";
+ $smallorderwhere = " gid = {$id}";
+ switch($plugin){
+ case 2:
+ $orderwhere .= " AND plugin = 'groupon'";
+ $smallorderwhere .= " AND plugin = 'groupon'";
+ break;
+ case 3:
+ $orderwhere .= " AND plugin = 'wlfightgroup'";
+ $smallorderwhere .= " AND plugin = 'wlfightgroup'";
+ break;
+ case 4:
+ $orderwhere .= " AND plugin = 'coupon'";
+ $smallorderwhere .= " AND plugin = 'coupon'";
+ break;
+ case 5:
+ $orderwhere .= " AND plugin = 'bargain'";
+ $smallorderwhere .= " AND plugin = 'bargain'";
+ break;
+ case 6:
+ $orderwhere .= " AND plugin = 'activity'";
+ $smallorderwhere .= " AND plugin = 'activity'";
+ break;
+ }
+ if($specid > 0){
+ $orderwhere .= " AND specid = {$specid}";
+ $smallorderwhere .= " AND specid = {$specid}";
+ }
+ if($mid > 0){
+ $orderwhere .= " AND mid = {$mid}";
+ $smallorderwhere .= " AND mid = {$mid}";
+ }
+ if($starttime > 0){
+ $orderwhere .= " AND createtime > {$starttime}";
+ $smallorderwhere .= " AND createtime > {$starttime}";
+ }
+ if($endtime > 0){
+ $orderwhere .= " AND createtime < {$endtime}";
+ $smallorderwhere .= " AND createtime < {$endtime}";
+ }
+ if($type == 1){
+ //未支付的
+ $nopayorderwhere = $orderwhere." AND status = 0";
+ $nopaynum = implode(pdo_fetch("SELECT sum(num) FROM " . tablename(PDO_NAME . "order") . " WHERE {$nopayorderwhere}"));
+ $nopaynum = $nopaynum ? : 0;
+ //快递的
+ $expresswhere = $orderwhere." AND expressid > 0 AND status IN (2,3,6,4,8,9)";
+ $expressnum = implode(pdo_fetch("SELECT sum(num) FROM " . tablename(PDO_NAME."order") . " WHERE {$expresswhere}"));
+ $expressnum = $expressnum ? : 0;
+ //核销的
+ $smallorderwhere .= " AND status != 3";
+ $hexiaonum = pdo_fetchcolumn('SELECT count(id) FROM '.tablename('wlmerchant_smallorder')." WHERE {$smallorderwhere}");
+ $hexiaonum = $hexiaonum ? : 0;
+ $salesnum = $nopaynum + $expressnum + $hexiaonum;
+ //拼团的特殊处理(拼团中的订单)
+ if($plugin == 3){
+ $fightorderwhere = " a.fkid = {$id} AND a.fightstatus = 1 AND a.status = 1 AND b.status = 1";
+ if($mid > 0){
+ $fightorderwhere .= " AND a.mid = {$mid}";
+ }
+ if($specid > 0){
+ $fightorderwhere .= " AND a.specid = {$specid}";
+ }
+ $fightnum = implode(pdo_fetch("SELECT sum(a.num) FROM " . tablename(PDO_NAME . "order"). " as a LEFT JOIN ".tablename(PDO_NAME . "fightgroup_group") . " as b ON a.fightgroupid = b.id WHERE {$fightorderwhere}"));
+ $salesnum = $salesnum + $fightnum;
+ }
+ }else if($type == 2){
+ //快递的
+ $expresswhere = $orderwhere." AND expressid > 0 AND status IN (2,3,6,4,8,9)";
+ $expressnum = implode(pdo_fetch("SELECT sum(num) FROM " . tablename(PDO_NAME."order") . " WHERE {$expresswhere}"));
+ //核销的
+ $smallorderwhere .= " AND status != 3";
+ $hexiaonum = pdo_fetchcolumn('SELECT count(id) FROM '.tablename('wlmerchant_smallorder')." WHERE {$smallorderwhere}");
+ $salesnum = $expressnum + $hexiaonum;
+ //拼团的特殊处理(拼团中的订单)
+ if($plugin == 3){
+ $fightorderwhere = " a.fkid = {$id} AND a.fightstatus = 1 AND a.status = 1 AND b.status = 1";
+ if($mid > 0){
+ $fightorderwhere .= " AND a.mid = {$mid}";
+ }
+ if($specid > 0){
+ $fightorderwhere .= " AND a.specid = {$specid}";
+ }
+ $fightnum = implode(pdo_fetch("SELECT sum(a.num) FROM " . tablename(PDO_NAME . "order"). " as a LEFT JOIN ".tablename(PDO_NAME . "fightgroup_group") . " as b ON a.fightgroupid = b.id WHERE {$fightorderwhere}"));
+ $salesnum = $salesnum + $fightnum;
+ }
+ }else if($type == 3){
+ //快递的
+ $expresswhere = $orderwhere." AND expressid > 0 AND status IN (2,3)";
+ $expressnum = implode(pdo_fetch("SELECT sum(num) FROM " . tablename(PDO_NAME."order") . " WHERE {$expresswhere}"));
+ //核销的
+ $smallorderwhere .= " AND status = 2";
+ $hexiaonum = pdo_fetchcolumn('SELECT count(id) FROM '.tablename('wlmerchant_smallorder')." WHERE {$smallorderwhere}");
+ $salesnum = $expressnum + $hexiaonum;
+ }
+ }
+ }
+ return $salesnum;
+ }
+ /**
+ * Comment: 检查商品当天是否可以购买
+ * Author: wlf
+ * Date: 2020/09/21 17:48
+ */
+ public static function checkUseDateStatus($status = 0,$week = '',$day = ''){
+ global $_W;
+ $time = time();//时间筛选
+ $toWeek = date("w", $time);//当前时间的星期
+ if ($toWeek == 0) $toWeek = 7;//星期天时值的转换
+ $toDay = date("j", $time);//当前时间的日期
+ if($status == 1){
+ $week = unserialize($week);
+ if(in_array($toWeek,$week)){
+ return 1;
+ }
+ }else if($status == 2){
+ $day = unserialize($day);
+ if(in_array($toDay,$day)){
+ return 1;
+ }
+ }
+ return 0;
+ }
+ /**
+ * Comment: 获取当前会员等级的会员价
+ * Author: wlf
+ * Date: 2020/11/12 16:46
+ */
+ public static function getVipDiscount($viparray,$levelid = 0){
+ global $_W;
+ $viparray = unserialize($viparray);
+ if($levelid == -1){
+ $prices = array_column($viparray,'vipprice');
+ $discount = max($prices);
+ }else{
+ $discount = $viparray[$levelid]['vipprice'];
+ }
+ return $discount ? : 0;
+ }
+ /**
+ * Comment: 合并规格和商品会员减免数组
+ * Author: wlf
+ * Date: 2020/11/20 14:13
+ */
+ public static function mergeVipArray($optionviparray,$goodsviparray){
+ global $_W;
+ $optionviparray = unserialize($optionviparray);
+ $goodsviparray = unserialize($goodsviparray);
+ foreach($optionviparray as $optk => &$opvip){
+ if($opvip['vipprice'] < 0.01){
+ $opvip['vipprice'] = $goodsviparray[$optk]['vipprice'];
+ }
+ if($opvip['storeset'] < 0.01){
+ $opvip['storeset'] = $goodsviparray[$optk]['storeset'];
+ }
+ }
+ $viparray = serialize($optionviparray);
+ return $viparray ? : 0;
+ }
+ /**
+ * Comment: 合并规格和商品会员分销数组
+ * Author: wlf
+ * Date: 2020/11/25 11:48
+ */
+ public static function mergeDisArray($optiondisarray,$goodsdisarray){
+ global $_W;
+ $optiondisarray = unserialize($optiondisarray);
+ $goodsdisarray = unserialize($goodsdisarray);
+ foreach($optiondisarray as $optk => &$opvip){
+ if($opvip['onedismoney'] < 0.01){
+ $opvip['onedismoney'] = $goodsdisarray[$optk]['onedismoney'];
+ }
+ if($opvip['twodismoney'] < 0.01){
+ $opvip['twodismoney'] = $goodsdisarray[$optk]['twodismoney'];
+ }
+ }
+ $disarray = serialize($optiondisarray);
+ return $disarray ? : 0;
+ }
+
+}
+
+
+
diff --git a/addons/weliam_smartcity/core/class/util_csv.class.php b/addons/weliam_smartcity/core/class/util_csv.class.php
new file mode 100644
index 0000000..9d22ed8
--- /dev/null
+++ b/addons/weliam_smartcity/core/class/util_csv.class.php
@@ -0,0 +1,137 @@
+ $value) {
+ $output = array();
+ $output[] = $value['id'];
+ $output[] = $value['name'];
+ echo iconv('utf-8', 'gbk//TRANSLIT', '"' . implode('","', $output) . "\"\n");
+ }
+ }
+
+ /**
+ * 导出CSV文件
+ * @param array $data 数据
+ * @param array $header_data 首行数据
+ * @param string $file_name 文件名称
+ * @return string
+ */
+ static function export_csv_2($data = array(), $header_data = array(), $file_name = '') {
+ header('Content-Type: application/vnd.ms-excel');
+ header('Content-Disposition: attachment;filename=' . $file_name);
+ header('Cache-Control: max-age=0');
+ $fp = fopen('php://output', 'a');
+ if (!empty($header_data)) {
+ foreach ($header_data as $key => $value) {
+ $header_data[$key] = iconv('utf-8', 'gbk', $value);
+ }
+ fputcsv($fp, $header_data);
+ }
+ $num = 0;
+ //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
+ $limit = 100000;
+ //逐行取出数据,不浪费内存
+ $count = count($data);
+ if ($count > 0) {
+ for ($i = 0; $i < $count; $i++) {
+ $num++;
+ //刷新一下输出buffer,防止由于数据过多造成问题
+ if ($limit == $num) {
+ ob_flush();
+ flush();
+ $num = 0;
+ }
+ $row = $data[$i];
+ foreach ($row as $key => $value) {
+ $row[$key] = iconv('utf-8', 'gbk', $value);
+ }
+ fputcsv($fp, $row);
+ }
+ }
+ fclose($fp);
+ }
+
+ /**
+ * 保存CSV文件
+ * @param array $data 数据
+ * @param array $header_data 首行数据
+ * @param string $file_name 文件名称
+ * @return string
+ */
+ static function save_csv($data = array(), $header_data = array(), $file_name = '') {
+ header('Content-Type: application/vnd.ms-excel');
+ header('Content-Disposition: attachment;filename=' . $file_name);
+ header('Cache-Control: max-age=0');
+ $csv_filename = PATH_ATTACHMENT . "public_file/" . MODULE_NAME . "/".$file_name;
+ $fp = fopen($csv_filename, "w");
+ if (!empty($header_data)) {
+ foreach ($header_data as $key => $value) {
+ $header_data[$key] = iconv('utf-8', 'gbk', $value);
+ }
+ fputcsv($fp, $header_data);
+ }
+ $num = 0;
+ //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
+ $limit = 100000;
+ //逐行取出数据,不浪费内存
+ $count = count($data);
+ if ($count > 0) {
+ for ($i = 0; $i < $count; $i++) {
+ $num++;
+ //刷新一下输出buffer,防止由于数据过多造成问题
+ if ($limit == $num) {
+ ob_flush();
+ flush();
+ $num = 0;
+ }
+ $row = $data[$i];
+ foreach ($row as $key => $value) {
+ $row[$key] = iconv('utf-8', 'gbk', $value);
+ }
+ fputcsv($fp, $row);
+ }
+ }
+ fclose($fp);
+ }
+
+}
diff --git a/addons/weliam_smartcity/core/class/wlPay.class.php b/addons/weliam_smartcity/core/class/wlPay.class.php
new file mode 100644
index 0000000..62c6c85
--- /dev/null
+++ b/addons/weliam_smartcity/core/class/wlPay.class.php
@@ -0,0 +1,168 @@
+finance($openid, $money, $desc, $realname, $trade_no);
+ return $arr;
+ }
+ /**
+ * Comment: 退款操作
+ * Author: zzw
+ * Date: 2019/9/29 10:55
+ * @param $id int 订单ID
+ * @param $money float 退款金额
+ * @param $remark string 退款原因
+ * @param $plugin string 模块信息
+ * @param int $type int 1微信端2web端3计划任务退款
+ * @param $blendcredit float 退款到余额
+ * @return mixed
+ * @throws \Yansongda\Pay\Exceptions\GatewayException
+ * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
+ * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
+ * @throws \Yansongda\Pay\Exceptions\InvalidSignException
+ */
+ static function refundMoney ($id , $money , $remark , $plugin , $type = 3,$blendcredit = 0){
+ global $_W;
+ #1、初始申明
+ $refund = false;//默认退款失败
+ #2、基本订单信息获取
+ switch ($plugin) {
+ case 'rush' :
+ $order = pdo_get(PDO_NAME.'rush_order' ,[ 'id' => $id] ,['paytype','orderno','aid','sid']);
+ break;
+ case 'attestation' :
+ $order = pdo_get(PDO_NAME.'attestation_money' ,[ 'id' => $id] ,['paytype','orderno']);
+ break;
+ case 'mobilerecharge' :
+ $order = pdo_get(PDO_NAME.'mrecharge_order' ,[ 'id' => $id] ,['paytype','orderno']);
+ break;
+ default :
+ $order = pdo_get(PDO_NAME.'order' , [ 'id' => $id] ,['paytype','orderno','aid','sid','paylogid']);
+ break;
+ }
+ #3、获取支付信息
+ if(empty($order['orderno'])){
+ $res['status'] = false;
+ $res['message'] = '订单不存在';
+ }
+ if($plugin == 'citydelivery'){
+ $payInfo = pdo_get(PDO_NAME."paylogvfour",['tid'=>$order['orderno']] ,['tid','transaction_id','fee','blendcredit','mid','module','uniacid','type']);
+ if(empty($payInfo)){
+ $payInfo = pdo_get(PDO_NAME."paylogvfour",['plid'=>$order['paylogid']] ,['tid','transaction_id','fee','blendcredit','mid','module','uniacid','type']);
+ }
+ $order['orderno'] = $payInfo['tid'];
+ }else{
+ $payInfo = pdo_get(PDO_NAME."paylogvfour",['tid'=>$order['orderno']] ,['transaction_id','fee','mid','blendcredit','module','uniacid','type']);
+ if(empty($payInfo)){
+ $payInfo = pdo_get(PDO_NAME."paylog",['tid'=>$order['orderno']] ,['transaction_id','fee','mid','module','uniacid','type']);
+ }
+ }
+ if(empty($payInfo)){
+ $payInfo = ['fee' => 0];
+ }
+ $orderInfo = array_merge($order,$payInfo);//合并两个数组的信息
+ #4、退款金额判断
+ if ($money > $orderInfo['fee']) {
+ $errMsg = '退款金额大于实际支付金额,无法退款';
+ } else if ($money > 0) {
+ $orderInfo['refund_money'] = $money;//记录退款金额
+ } else if ($blendcredit < 0.01){
+ $money = $orderInfo['fee'];//退款金额为支付金额(全额退款)
+ if($orderInfo['blendcredit'] > 0){
+ $money = sprintf("%.2f",$money - $orderInfo['blendcredit']);
+ $blendcredit = $orderInfo['blendcredit'];
+ }
+ }
+ //支付返现判断
+ if(p('cashback')){
+ //判断当前订单是否存在返现订单
+ $cashOrderInfo = pdo_get(PDO_NAME."cashback",['order_id'=>$id,'plugin'=>$plugin,'status'=>1]);
+ if($cashOrderInfo){
+ //退款比例计算
+ $proportion = sprintf("%.2f",$money / $orderInfo['fee']);//比例
+ $cashRefund = sprintf("%.2f",$cashOrderInfo['money'] * $proportion);//取消的返现金额
+ //数据判断 余额是否大于当前取消返现金额
+ $member = Member::wl_member_get($cashOrderInfo['mid'],['id','uid','cash_back_money']);//用户当前余额获取
+ if($member['credit2'] < $cashRefund) return ['status'=>false,'message'=>'退款失败;余额不足,不能取消返现金额!'];
+ }
+ }
+ #5、插入退款记录信息
+ $refundRecord = [
+ 'sid' => $orderInfo['sid'] ,
+ 'orderno' => $orderInfo['orderno'] ,
+ 'mid' => $orderInfo['mid'] ,
+ 'aid' => $orderInfo['aid'] ,
+ 'paytype' => $orderInfo['type'] ,
+ 'transid' => $orderInfo['transaction_id'] ,
+ 'type' => $type ,
+ 'orderid' => $id ,
+ 'payfee' => $orderInfo['fee'] ,
+ 'refundfee' => sprintf("%.2f",$money + $blendcredit),
+ 'uniacid' => $orderInfo['uniacid'] ,
+ 'remark' => $remark ,
+ 'plugin' => $plugin
+ ];
+ $refundid = pdo_getcolumn(PDO_NAME.'refund_record',$refundRecord,'id');
+ if(empty($refundid)){
+ $refundRecord['createtime'] = TIMESTAMP;
+ $refundRecord['status'] = 0;
+ pdo_insert(PDO_NAME . 'refund_record' , $refundRecord);
+ $refundid = pdo_insertid();
+ }
+ #6、判断退款成功失败信息
+ $pluginArray = [ 'rush','housekeep' , 'vip' ,'mobilerecharge', 'citydelivery','yellowpage','coupon' ,'attestation','merchant' , 'wlfightgroup' , 'activity' , 'groupon' , 'bargain' ];
+ if (!in_array($plugin , $pluginArray)) {
+ pdo_update(PDO_NAME . 'refund_record' , [ 'errmsg' => '退款订单插件' . $plugin . '错误' ] , [ 'id' => $refundid]);
+ $errMsg = '退款订单插件' . $plugin . '错误';
+ }
+ if ($money <= 0 && $blendcredit <= 0 && $orderInfo['paytype'] != 6 ) {
+ pdo_update(PDO_NAME . 'refund_record' , ['errmsg' => '退款金额小于0'] , ['id' => $refundid]);
+ $errMsg = '退款金额小于0';
+ }
+ if (empty($orderInfo['transaction_id']) && $orderInfo['type'] == 'wechat') {
+ pdo_update(PDO_NAME . 'refund_record' ,['errmsg' => '无微信订单号'] , ['id' => $refundid]);
+ $errMsg = '微信订单无微信订单号';
+ }
+ if($orderInfo['module'] == 'weliam_merchant'){
+ $errMsg = '此订单为旧版系统支付订单,无法在V4版本进行退款,请前往旧版系统退款';
+ pdo_update(PDO_NAME . 'refund_record' ,['errmsg' => $errMsg] , ['id' => $refundid]);
+ }
+ #7、符合退款要求,开始退款操作
+ if (empty($errMsg)){
+ if($orderInfo['paytype'] == 6){
+ $result = ['error' => 1];
+ }else{
+ $result = Refund::refundInit($orderInfo['orderno'],$money,$blendcredit); //调用方法进行退款操作
+ }
+ }
+ #8、返回退款结果
+ if ($result['error']) {
+ pdo_update(PDO_NAME . 'refund_record' , [ 'status' => 1 ] , [ 'id' => $refundid ]);
+ $res['status'] = true;
+ $res['message'] = '退款成功';
+ //支付返现退款操作
+ if(p('cashback') && $cashOrderInfo){
+ //修改用户返现金额
+ pdo_update(PDO_NAME."member",['cash_back_money'=>sprintf("%.2f",$member['cash_back_money'] - $cashRefund)],['id'=>$cashOrderInfo['mid']]);
+ //修改用户余额信息
+ Member::credit_update_credit2($cashOrderInfo['mid'],-$cashRefund,'订单['.$order['orderno'].']退款取消返现金额');
+ //修改返现记录信息
+ pdo_update(PDO_NAME."cashback",['refund_money'=>sprintf("%.2f",$cashOrderInfo['refund_money'] + $cashRefund)],['id'=>$cashOrderInfo['id']]);
+ }
+ } else {
+ $errMsg = $result['msg'] ? : $errMsg;
+ if (empty($errMsg)) $errMsg = '未知错误,请联系管理员';
+ pdo_update(PDO_NAME . 'refund_record' ,['errmsg' => $errMsg] , ['id' => $refundid]);
+ $res['status'] = false;
+ $res['message'] = $errMsg;
+ }
+ return $res;
+ }
+
+
+
+}
diff --git a/addons/weliam_smartcity/core/common/Im.php b/addons/weliam_smartcity/core/common/Im.php
new file mode 100644
index 0000000..f15e850
--- /dev/null
+++ b/addons/weliam_smartcity/core/common/Im.php
@@ -0,0 +1,292 @@
+model('attachment');
+//获取基本设置信息
+$set = pdo_get(PDO_NAME.'setting',['key' => 'im_set'],['value']);
+if (is_array($set)) $set = iunserializer($set['value']);
+$port = $set['port'];
+$cert = $set['pem_path'];
+$key = $set['key_path'];
+//$cert = 'D:/Software/phpstudy_pro/Extensions/Nginx1.15.11/conf/ssl/www.locatiom.smartcity.com.pem';
+//$key = 'D:/Software/phpstudy_pro/Extensions/Nginx1.15.11/conf/ssl/www.locatiom.smartcity.com.key';
+
+//开始进行通讯处理
+use Workerman\Worker;
+require_once PATH_VENDOR.'workerman/workerman/Autoloader.php';
+//创建一个Worker监听端口,使用websocket协议通讯
+$context = [
+ // 更多ssl选项请参考手册 http://php.net/manual/zh/context.ssl.php
+ 'ssl' => [
+ 'local_cert' => $cert,
+ 'local_pk' => $key,
+ 'verify_peer' => false,
+ // 'allow_self_signed' => true, //如果是自签名证书需要开启此选项
+ ]
+];
+$socket = new Worker("websocket://0.0.0.0:{$port}",$context);
+$socket->transport = 'ssl';
+//$socket->count = 4;//启动x个进程对外提供服务
+$socket->onWorkerStart = function($worker) {
+ // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
+ global $db;
+ require '../../../../data/config.php';
+ $master = $config['db']['master'];
+ $db = new \Workerman\MySQL\Connection($master['host'],$master['port'], $master['username'], $master['password'],$master['database']);
+};
+//接收数据并且进行对应的处理
+$socket->onMessage = function ($connection,$data) {
+ //处理信息
+ (new handle($data,$connection))->handleData();
+};
+//当某个链接断开时触发
+$socket->onClose = function ($connection) {
+
+
+};
+//方法类
+class handle{
+ private $data,//当前接收的消息
+ $sendId,//发送方唯一id
+ $receiveId,//接收方唯一id
+ $idsFile = PATH_CORE."common/im_ids.php";
+
+ public function __construct($data,$connection){
+ global $_W;
+ //data信息处理
+ $data = json_decode($data,true);
+ $_W['uniacid'] = $data['i'] ? : $data['uniacid'];//公众号id
+ $_W['aid'] = $data['aid'];//代理商id
+ $_W['source'] = $data['source'];//渠道
+ //通讯信息获取
+ $data['send_id'] = intval($data['send_id']) ? : $_W['mid'];//当前发送信息的用户的id(商户id)
+ $data['receive_id'] = intval($data['receive_id']);//接受消息的用户id(商户id)
+ $data['page'] = intval($data['page']) ? : 1;//页码
+ $data['page_index'] = intval($data['page_index']) ? : 10;//每页的数量
+ $this->sendId = $data['send_id'].'_'.$data['receive_id'];
+ $this->receiveId = $data['receive_id'].'_'.$data['send_id'];
+ $this->data = $data;
+ //通讯节点处理
+ $this->setIds($this->sendId,$connection->id);
+ }
+ /**
+ * Comment: 处理接收的data信息
+ * Author: zzw
+ * Date: 2021/3/8 11:44
+ * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
+ * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
+ */
+ public function handleData(){
+ global $_W,$db;
+ //接受信息
+ $data = $this->data;
+ //判断是否给自己发送消息
+ if($data['send_id'] == $data['receive_id'] && $data['send_type'] == $data['receive_type']) $this->socketSend($this->sendId,"不能给自己发送信息哦",5);
+ //判断通讯类型,进行对应的操作。信息类型:1=系统信息,2=通信信息,3=断开链接,4=通讯记录,5=错误抛出
+ if($data['im_type'] == 2){
+ //记录信息到表
+ $newData['uniacid'] = $_W['uniacid'];
+ $newData['send_id'] = $data['send_id'];//发送方id
+ $newData['send_type'] = $data['send_type'];//发送方类型(1=用户;2=商户)
+ $newData['receive_id'] = $data['receive_id'];//接收人id
+ $newData['receive_type'] = $data['receive_type'];//接收人类型(1=用户;2=商户)
+ $newData['create_time'] = time();//发送时间(建立时间)
+ $newData['type'] = $data['type'];//内容类型:0=文本内容(可带表情),1=图片信息(不可带表情),2=视频信息(不可带表情),3=名片信息(不可带表情),4=简历信息(不可带表情),5=其他信息(不可带表情)
+ $newData['content'] = base64_encode($data['content']);//发送内容
+ $newData['plugin'] = $data['plugin'];//发送内容
+ $table = trim(tablename(PDO_NAME."im"),'`');
+ $db->insert($table)->cols($newData)->query();
+ //判断接收方是否在线 在线进行推送
+ $memberInfo = $db->select('nickname,avatar')
+ ->from(trim(tablename(PDO_NAME."member"),'`'))
+ ->where("id={$newData['send_id']}")
+ ->row();
+ $sendInfo = [
+ 'avatar' => tomedia($memberInfo['avatar']),
+ 'content' => $data['content'],
+ 'create_time' => $newData['create_time'],
+ 'date_time' => date('Y-m-d H:i:s',$newData['create_time']),
+ 'is_my' => 1,//0=自己发送的消息,1=对方发送的消息
+ 'nickname' => $memberInfo['nickname'],
+ 'receive_id' => $newData['receive_id'],
+ 'send_id' => $newData['send_id'],
+ 'type' => $newData['type']
+ ];
+
+ $this->socketSend($this->receiveId,'即时通讯信息',2,$data['type'],['list'=>[$sendInfo]]);
+ }else if ($data['im_type'] == 3){
+ //断开链接
+ //$this->log(['断开',$data]);
+ $this->deleteIds($this->sendId);
+ }else if($data['im_type'] == 4){
+ //获取通讯记录信息
+ $sendInfo['send_id'] = $data['send_id'] ;//发送方id
+ $sendInfo['send_type'] = $data['send_type'] ;//发送方类型(1=用户;2=商户)
+ $sendInfo['receive_id'] = $data['receive_id'] ;//接收人id
+ $sendInfo['receive_type'] = $data['receive_type'] ;//接收人类型(1=用户;2=商户)
+ //$list = Im::imRecord($data['page'],$data['page_index'],$sendInfo);
+ $pageStart = $data['page'] * $data['page_index'] - $data['page_index'];
+ //条件生成
+ $where = " as a WHERE a.uniacid = {$_W['uniacid']} AND
+ (
+ (a.send_id = {$sendInfo['send_id']} AND a.send_type = {$sendInfo['send_type']} AND a.receive_id = {$sendInfo['receive_id']} AND a.receive_type = {$sendInfo['receive_type']})
+ OR
+ (a.send_id = {$sendInfo['receive_id']} AND a.send_type = {$sendInfo['receive_type']} AND a.receive_id = {$sendInfo['send_id']} AND a.receive_type = {$sendInfo['send_type']})
+ )";
+ if($data['plugin']) $where .= " AND a.plugin = {$data['plugin']} ";
+ else $where .= " AND (a.plugin = '' OR a.plugin IS NULL)";
+ //要查询的字段生成
+ $field = " a.id,a.send_id,a.`receive_id`,a.content,a.create_time,a.type,FROM_UNIXTIME(create_time,'%Y-%m-%d %H:%i:%S') as date_time,
+ CASE {$sendInfo['receive_id']} WHEN a.send_id THEN 1
+ ELSE 0
+ END as is_my,
+ CASE a.`send_type`
+ WHEN 1 THEN (SELECT `nickname` FROM ".tablename(PDO_NAME."member")." WHERE `id` = a.`send_id`)
+ ELSE (SELECT storename FROM ".tablename(PDO_NAME."merchantdata")." WHERE `id` = a.`send_id` )
+ END as nickname,
+ CASE a.`send_type`
+ WHEN 1 THEN (SELECT `avatar` FROM ".tablename(PDO_NAME."member")." WHERE `id` = a.`send_id`)
+ ELSE (SELECT logo FROM ".tablename(PDO_NAME."merchantdata")." WHERE `id` = a.`send_id` )
+ END as avatar";
+ #4、获取总页数
+ $totalSql = "SELECT COUNT(*) as total FROM ".tablename(PDO_NAME."im").$where;
+ $total = $db->single($totalSql);
+ $list['total'] = ceil($total / $data['page_index']);
+ #5、获取当前页列表信息
+ $listSql = "SELECT {$field} FROM ".tablename(PDO_NAME."im").$where
+ ." ORDER BY a.create_time DESC LIMIT {$pageStart},{$data['page_index']} ";
+ $list['list'] = $db->query($listSql);
+ foreach($list['list'] as $key => &$val) {
+ $val['avatar'] = tomedia($val['avatar']);
+ if(is_base64($val['content'])) $val['content'] = base64_decode($val['content'],true);
+ }
+ //修改信息为已读
+ /*if(is_array($list['list']) && count($list['list']) > 0) {
+ //条件生成
+ $ids = array_column($list['list'],'id');
+ if(!empty($sendInfo['send_id'])) $where = " receive_id = {$sendInfo['send_id']} ";
+ else $where = " receive_id = {$_W['mid']} ";
+ if(count($ids) > 1){
+ $idStr = implode(',',$ids);
+ $where .= " AND id IN ({$idStr}) ";
+ }else{
+ $where .= " AND id = {$ids[0]} ";
+ }
+ #2、修改内容
+ $updateSql = "UPDATE ".tablename(PDO_NAME."im")." SET is_read = 1 WHERE ".$where;
+ $db->query($updateSql);
+ }*/
+ $where = " send_id = {$sendInfo['receive_id']} AND send_type = {$sendInfo['receive_type']} AND receive_id = {$sendInfo['send_id']} AND receive_type = {$sendInfo['send_type']} AND is_read = 0 ";
+ $sql = " UPDATE ".tablename(PDO_NAME."im")." SET is_read = 1 WHERE {$where} ";
+ $db->query($sql);
+ //信息排序
+ $sortArr = array_column($list['list'], 'create_time');
+ array_multisort($sortArr, SORT_ASC, $list['list']);
+ //获取聊天对象的昵称 1=用户;2=商户
+ if($sendInfo['receive_type'] == 1) {
+ $nicknameSql = "SELECT nickname FROM ".tablename(PDO_NAME."member")." WHERE id = {$sendInfo['receive_id']} ";
+ $list['receive_name'] = $db->single($nicknameSql);
+ } else {
+ $nicknameSql = "SELECT storename FROM ".tablename(PDO_NAME."merchantdata")." WHERE id = {$sendInfo['receive_id']} ";
+ $list['receive_name'] = $db->single($nicknameSql);
+ }
+ $this->socketSend($this->sendId,'通讯记录',4,5,$list);
+ }
+ }
+ /**
+ * Comment: 发送数据给移动端
+ * Author: zzw
+ * Date: 2021/3/8 11:44
+ * @param $id
+ * @param $content
+ * @param int $imType
+ * @param int $type
+ * @param array $other
+ */
+ public function socketSend($id,$content,$imType = 2,$type = 0,$other = []){
+ global $socket;
+ //生成需要发送的信息
+ $data = [
+ 'im_type' => $imType,//信息类型:1=系统信息,2=通信信息,3=断开链接,4=通讯记录,5=错误抛出
+ //具体通讯信息
+ 'type' => $type,//内容类型:0=文本内容(可带表情),1=图片信息(不可带表情),2=视频信息(不可带表情),3=名片信息(不可带表情),4=简历信息(不可带表情),5=其他信息(数组)
+ 'content' => $content,//文本内容
+ 'other' => $other,//其他信息(名片信息|简历信息)
+ ];
+ //发送信息
+ $connectionId = $this->getIds($id);
+ if($connectionId > 0){
+ $connection = $socket->connections[$connectionId];
+
+ if(is_object($connection)) $connection->send(json_encode($data,JSON_UNESCAPED_UNICODE));
+ }
+ }
+ /**
+ * Comment: 日志记录
+ * Author: zzw
+ * Date: 2021/3/8 11:44
+ * @param $content
+ * @param string $title
+ */
+ public function log($content,$title = '日志'){
+ Util::wl_log('socket',PATH_MODULE . "log/",$content,$title,false);
+ }
+ /**
+ * Comment: 获取ids数组信息
+ * Author: zzw
+ * Date: 2021/3/12 10:21
+ * @param int $key 发送者id
+ * @return array|bool|Memcache|mixed|Redis|string
+ */
+ public function getIds($id = 0){
+ //获取文件读写权限
+ if(!is_readable($this->idsFile)) chmod($this->idsFile,0755);
+ //获取文件内容
+ $data = file_get_contents($this->idsFile);
+ $data = json_decode($data,true);
+ if($id > 0) return $data[$id];
+ else return $data;
+ }
+ /**
+ * Comment: 设置id缓存
+ * Author: zzw
+ * Date: 2021/3/12 10:21
+ * @param int $key 发送者id
+ * @param int $val 通讯节点id
+ */
+ public function setIds($key,$val){
+ header('Content-Type:text/html;charset=utf-8');
+ //数组转字符串
+ $data = $this->getIds();
+ $data[$key] = $val;
+ $idStr = json_encode($data,JSON_UNESCAPED_UNICODE);
+ file_put_contents($this->idsFile, print_r($idStr, true));
+ }
+ /**
+ * Comment: 删除id缓存
+ * Author: zzw
+ * Date: 2021/3/18 11:13
+ * @param $id
+ */
+ public function deleteIds($id){
+ header('Content-Type:text/html;charset=utf-8');
+ //数组转字符串
+ $data = $this->getIds();
+ unset($data[$id]);
+ $idStr = json_encode($data,JSON_UNESCAPED_UNICODE);
+ file_put_contents($this->idsFile, print_r($idStr, true));
+ }
+
+
+
+
+}
+//运行
+Worker::runAll();
diff --git a/addons/weliam_smartcity/core/common/api.php b/addons/weliam_smartcity/core/common/api.php
new file mode 100644
index 0000000..86e900d
--- /dev/null
+++ b/addons/weliam_smartcity/core/common/api.php
@@ -0,0 +1,16 @@
+model('attachment');
+
+//判断公众号相关
+$_W['siteroot'] = str_replace(array('/addons/'.MODULE_NAME.'/core/common','/addons/weliam_smartcity/core/common'), '', $_W['siteroot']);
+$_W['method'] = $method = !empty($_GPC['do']) ? $_GPC['do'] : 'index';
+$_W['aid'] = intval($_GPC['aid']);
+$_W['uniacid'] = intval($_GPC['i']);
+$_W['apitoken'] = trim($_GPC['token']);
+if(empty($_W['uniacid'])) {
+ $_W['uniacid'] = intval($_GPC['weid']);
+}
+$_W['uniaccount'] = $_W['account'] = uni_fetch($_W['uniacid']);
+if(empty($_W['uniaccount'])) {
+ header('HTTP/1.1 404 Not Found');
+ header("status: 404 Not Found");
+ exit;
+}
+if (!empty($_W['uniaccount']['endtime']) && TIMESTAMP > $_W['uniaccount']['endtime']) {
+ exit('抱歉,您的公众号服务已过期,请及时联系管理员');
+}
+$_W['acid'] = $_W['uniaccount']['acid'];
+$isdel_account = pdo_get('account', array('isdeleted' => 1, 'acid' => $_W['acid']));
+if (!empty($isdel_account)) {
+ exit('指定公众号已被删除');
+}
+$_W['attachurl'] = attachment_set_attach_url();
+
+//寻找对应方法
+require IA_ROOT . "/addons/'.MODULE_NAME.'/plugin/openapi/openapi.php";
+$instance = new Weliam_smartcityModuleOpenapi();
+if (!method_exists($instance, $method)) {
+ $method = 'doPage' . ucfirst($method);
+}
+$instance -> $method();
+
+
+class Openapi {
+
+ public function __construct(){
+ global $_W;
+ $settings = Setting::wlsetting_read('apiset');
+ if ($_W['apitoken'] != $settings['token']) {
+ $this->result(-1, '无效Token');
+ }
+ }
+
+ public function result($errno, $message, $data = '') {
+ exit(json_encode(array(
+ 'errno' => $errno,
+ 'message' => $message,
+ 'data' => $data,
+ )));
+ }
+
+}
diff --git a/addons/weliam_smartcity/core/common/task.php b/addons/weliam_smartcity/core/common/task.php
new file mode 100644
index 0000000..e2233a4
--- /dev/null
+++ b/addons/weliam_smartcity/core/common/task.php
@@ -0,0 +1,23 @@
+ queueMain($on);
\ No newline at end of file
diff --git a/addons/weliam_smartcity/core/common/uniapp.php b/addons/weliam_smartcity/core/common/uniapp.php
new file mode 100644
index 0000000..ea5a1de
--- /dev/null
+++ b/addons/weliam_smartcity/core/common/uniapp.php
@@ -0,0 +1 @@
+model('attachment');
//判断公众号相关
$_W['siteroot'] = str_replace(array('/addons/'.MODULE_NAME.'/core/common','/addons/weliam_smartcity/core/common','/addons/weliam_smartcity','/addons/'.MODULE_NAME), '', $_W['siteroot']);
$_W['method'] = $method = !empty($_GPC['do']) ? $_GPC['do'] : 'index';
$_W['uniacid'] = intval($_GPC['i']);
if (empty($_W['uniacid'])) {
$_W['uniacid'] = intval($_GPC['weid']);
}
$_W['uniaccount'] = $_W['account'] = uni_fetch($_W['uniacid']);
if (empty($_W['uniaccount'])) {
header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
exit;
}
$_W['acid'] = $_W['uniaccount']['acid'];
$_W['attachurl'] = attachment_set_attach_url();
$_W['wlsetting'] = Setting::wlsetting_load();
$_W['source'] = $_GPC['source'] ? intval($_GPC['source']) : 1;//1=公众号(默认);2=h5;3=小程序
$_W['aid'] = intval($_GPC['aid'])?intval($_GPC['aid']):0;//代理id
//寻找对应方法
$plugin = trim($_GPC['p']);
if (empty($plugin)) {
require IA_ROOT . "/addons/".MODULE_NAME."/uniapp.php";
$instance = new Weliam_smartcityModuleUniapp();
if (!method_exists($instance, $method)) {
$instance->securityVerification($method);//调用方法进行安全验证
}
} else {
$uniapp = new Uniapp();
//判断文件是否存在
$filePath = IA_ROOT . "/addons/".MODULE_NAME."/plugin/" . $plugin . "/uniapp.php";
if (!file_exists($filePath)) $filePath = IA_ROOT . "/addons/".MODULE_NAME."/api/" . ucfirst($plugin) . ".php";
if (!file_exists($filePath)) $uniapp->renderError('错误的请求 - file does not exist! ');
require $filePath;
//判断类是否存在
$className = ucfirst($plugin) . 'ModuleUniapp';
if (class_exists($className)) {
$instance = new $className();
if (method_exists($instance, $method)) $instance->$method();
else $uniapp->renderError('错误的请求 - '.$instance.':'.$method.'Method does not exist! ');
} else {
$uniapp->renderError('错误的请求 - '.$className.'Non-existent classes! ');
}
}
class Uniapp {
public $disSetting;//分销设置信息
#0=操作成功;1=操作失败;2=需要登录;3=未开通地区;4=隐藏信息,仅开发者查看使用;5=小程序端必须登录才能访问的接口
public function __construct() {
global $_W, $_GPC;
//判断平台状态
$accinfo = Util::object_array($_W['account']);
if($accinfo['endtime'] > 0 && $accinfo['endtime'] < time() ){
$this->renderError('平台已过期,无法访问。');
}
//获取用户信息
$token = trim($_GPC['token']);
if (strlen($token) == 32) {
$res = Login::generateToken($token);
if($res['errno'] == '401' && $_W['source'] == 1){
file_put_contents(PATH_DATA . "login_error222.log", var_export($token, true) . PHP_EOL, FILE_APPEND);
$this->reLogin();
}else if($res['errno'] == '205'){
wl_setcookie('user_token',$res['code'],86400);
$res = Login::generateToken($res['message']);
$token = $res['message'];
}else{
$token = $res['message'];
}
if(!empty($token)){
$user = Member::wl_member_get(['tokey' => $token]);
if(!empty($user['encodename'])){
$user['nickname'] = base64_decode($user['encodename']);
}
if($user['blackflag']>0){
$tips = $_W['wlsetting']['userset']['black_desc'] ? $_W['wlsetting']['userset']['black_desc'] : '您被禁止访问,如有疑问请联系客服';
$this->renderError($tips);
}
if (is_array($user) && !empty($user)) {
$_W['wlmember'] = $user;
$_W['mid'] = $user['id'];
}
}
}
//目前默认 公共接口为不需要进行登录判断 仅判断各个模块下面的私有接口
if (!empty($_GPC['p'])) {
$api = $_GPC['p'] . '/' . $_GPC['do'];//将要请求的接口名称
$list = $this->noLoginApiList($_W['source']);//获取不需要登录的接口名称列表
#1、获取当前访问的接口信息
if (!in_array($api, $list) ) {
if(empty($_W['mid'])){
$this->reLogin();
}
}
}
if(empty($_W['mid']) && $_GPC['do'] == 'Poster'){
$this->reLogin();
}
//获取基本信息
$this->disSetting = $_W['wlsetting']['distribution'];
//分销商关系绑定
// $head_id = intval($_GPC['head_id']);
// if ($head_id > 0 && $_W['mid'] > 0 && p('distribution') && $_W['mid'] != $head_id) {
// Distribution::addJunior($head_id, $_W['mid']);
// }
}
/**
* Comment: 操作成功输出方法
* Author: zzw
* Date: 2019/7/16 9:35
* @param string $message
* @param array $data
*/
public function renderSuccess($message = '操作成功', $data = [],$nodo = 0) {
global $_W,$_GPC;
//JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
$content = json_encode(['errno' => 0, 'message' => $message, 'data' => $data]);
//if($_GPC['do'] != 'getGoodsExtensionInfo' && $_GPC['do'] != 'transferDetail'){
if(empty($nodo)){
//开启链接处理功能一 目前主要兼容未在#号前添加问号(?)的链接
//$content = str_replace('weliam_smartcity\/h5\/#\/', 'weliam_smartcity\/h5\/?#\/', $content);
$prefixPaths = explode('#/', h5_url('pages/mainPages/index/diypage'))[0] . '#/';
//处理富文本超链接一 带有href跳转的链接转换为指定字符串
$temporaryUrl = 'this_is_temporary_url_info';
$hrefPath = json_encode('href="'.$prefixPaths);
$content = str_replace(trim($hrefPath, '"'), $temporaryUrl, $content);
//开启链接处理功能二 目前主要兼容删除?#/前面的链接 只保留page路径信息及参数信息
$prefixPaths = explode('#/', h5_url('pages/mainPages/index/diypage'))[0] . '#/';
$jsonPath = json_encode($prefixPaths);
$content = str_replace(trim($jsonPath, '"'), '', $content);
//处理富文本超链接二 将字段字符串转为超链接前缀
$temporaryUrl = 'this_is_temporary_url_info';
$content = str_replace($temporaryUrl, trim($hrefPath, '"'), $content);
}
exit($content);
}
/**
* Comment: 操作失败返回内容
* Author: zzw
* Date: 2019/7/16 9:36
* @param string $message
* @param array $data
*/
public function renderError($message = '操作失败', $data = []) {
global $_W;
//JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
$content = json_encode(['errno' => 1, 'message' => $message, 'data' => $data]);
//是否开启链接处理功能一 目前主要兼容未在#号前添加问号(?)的链接
$state1 = $_REQUEST['debug'] ? true : true;
// if ($state1) {
// $content = str_replace('weliam_smartcity\/h5\/#\/', 'weliam_smartcity\/h5\/?#\/', $content);
// }
//是否开启链接处理功能二 目前主要兼容删除?#/前面的链接 只保留page路径信息及参数信息
$state2 = $_REQUEST['debug'] ? true : true;
if ($state2) {
$prefixPaths = explode('#/', h5_url('pages/mainPages/index/diypage'))[0] . '#/';
$jsonPath = json_encode($prefixPaths);
$content = str_replace(trim($jsonPath, '"'), '', $content);
}
exit($content);
}
/**
* Comment: 登录错误,重新登录
* Author: zzw
* Date: 2019/7/29 16:40
* @param string $message
*/
public function reLogin() {
global $_W;
$errno = ($_W['source'] == 3) ? 5 : 2;
exit(json_encode(array(
'errno' => $errno,//2
'message' => '请先登录',
'data' => [
'weChat_login' => $_W['siteroot'] . 'app/index.php?i=' . $_W['uniacid'] . '&c=entry&m=' . MODULE_NAME . '&do=wechatsign',
],
)));
}
/**
* Comment: 隐藏信息,仅开发者查看使用
* Author: zzw
* Date: 2019/11/1 10:07
* @param string $message
* @param array $data
*/
public function debugging($message = '维护中....', $data = []) {
exit(json_encode(array(
'errno' => 4,
'message' => $message,
'data' => $data,
)));
}
/**
* Comment: 不需要登录验证的接口列表
* Author: zzw
* Date: 2019/7/29 16:24
* @return array
*/
protected function noLoginApiList($source) {
$list = ['member/login', 'headline/HeadlineList','headline/HeadlineInfo','headline/getComment', 'distribution/getSetting', 'store/homeList', 'rush/homeList', 'rush/specialInfo', 'wlcoupon/homeList' ,
'halfcard/homeList', 'wlfightgroup/homeList', 'pocket/homeList', 'groupon/homeList', 'bargain/homeList', 'consumption/homeList', 'halfcard/packageList',
'member/getRegisterSet', 'member/register', 'member/userLogin', 'member/resetPassword','citycard/homeList','citycard/cardHome','citycard/cardInfo',
'redpack/newRedPackInfo','pocket/commentList','redpack/festivalRedPackDesc','citydelivery/finishOrder','goods/getGoodsCateList','recruit/homeList',
'dating/homeList','im/infoList','Im/getSetInfo','dating/homeList','dating/dynamicList','vehicle/homeList','recruit/enterpriseList'];
if($source == 3 || $source == 2){
//小程序不需要登录的接口
$newList = [
'store/chargeList','store/detail','store/getStoreGoods','store/getStoreComment','store/getStoreDynamic',
'store/cateList','goods/getGoodsDetail', 'member/memberInfo','helper/helpInfo','helper/helpInfo','helper/problemList', 'helper/detail',
'distribution/applyCondition', 'citycard/cardShare','halfcard/memberCardHome','halfcard/cardList', 'consumption/homeInfo', 'consumption/detail',
'pocket/homeInfo','pocket/classList','pocket/receivingRecords','pocket/getPocketStore','store/userShopList', 'pocket/infoList','pocket/detail','pocket/shareNum','pocket/getDisclaimer','wxapp/liveList','bargain/detail','housekeep/getStorelist',
'housekeep/getServicelist','housekeep/getArtificerlist','housekeep/getDemandlist','housekeep/getNewStorelist','recruit/recruitDesc','wlfightgroup/groupDetail','yellowpage/homeInfo','yellowpage/homeList',
'yellowpage/cateList','luckydraw/drawPageInfo','luckydraw/getShareCode'
];
$list = array_merge($newList,$list);
}
return $list;
}
}
\ No newline at end of file
diff --git a/addons/weliam_smartcity/core/common/yunAsyNotify.php b/addons/weliam_smartcity/core/common/yunAsyNotify.php
new file mode 100644
index 0000000..063837f
--- /dev/null
+++ b/addons/weliam_smartcity/core/common/yunAsyNotify.php
@@ -0,0 +1,31 @@
+ $transaction_id] , ['status','tid','uniacid','plugin' ,'plid','fee','payfor']);
+$_W['uniacid'] = $paylog['uniacid'];
+$tid = $paylog['tid'];
+if($paylog['status'] == 0){
+ $successInfo = [
+ 'type' => 2 ,//支付方式
+ 'tid' => $paylog['tid'],//订单号
+ 'transaction_id' => $transaction_id,
+ 'time' => $yunorderinfo['paidTime'],
+ ];
+ PayResult::main($successInfo);//调用方法处理订单
+ exit('SUCCESS');
+}else{
+ exit('SUCCESS');
+}
diff --git a/addons/weliam_smartcity/core/common/yunnotify.php b/addons/weliam_smartcity/core/common/yunnotify.php
new file mode 100644
index 0000000..bbbc258
--- /dev/null
+++ b/addons/weliam_smartcity/core/common/yunnotify.php
@@ -0,0 +1,113 @@
+ $transaction_id] , ['status','tid','uniacid','plugin' ,'plid','fee','payfor']);
+$_W['uniacid'] = $paylog['uniacid'];
+$tid = $paylog['tid'];
+//订单信息查询
+$type = strtolower($paylog['plugin']);
+$payfor = strtolower($paylog['payfor']);
+$data = [];
+$data['plugin'] = $type;
+if ($type == 'rush') {
+ $order = pdo_get('wlmerchant_rush_order' , ['orderno' => $tid] , ['id' ,'aid', 'num' , 'activityid' , 'actualprice']);
+ $data['price'] = $order['actualprice'];
+ $data['goodsname'] = pdo_getcolumn(PDO_NAME.'rush_activity',array('id'=>$order['activityid']),'name');
+ $detail_url = h5_url('pages/subPages/orderList/orderDetails/orderDetails',['orderid'=>$order['id'],'plugin'=>'rush']);
+}
+else if ($type == 'merchant' && $payfor == 'halfcard') {
+ $order = pdo_get('wlmerchant_halfcard_record' , ['orderno' => $tid] , ['id','aid', 'num' , 'price']);
+ $data['price'] = $order['price'];
+ $data['goodsname'] = '会员开通/续费';
+}
+else if ($type == 'attestation') {
+ $order = pdo_get('wlmerchant_attestation_money' , ['orderno' => $tid] , ['id' , 'num' , 'money' , 'type']);
+ $data['price'] = $order['money'];
+ $data['type'] = $order['type'];
+ $data['goodsname'] = '认证保证金缴纳';
+}else {
+ $order = pdo_get('wlmerchant_order' , ['orderno' => $tid] , ['id','aid' , 'recordid' , 'num' , 'fkid' , 'plugin' , 'fightstatus' , 'paidprid' , 'price' , 'vip_card_id' , 'expressid']);
+ $data['price'] = $order['price'];
+ if ($order['plugin'] == 'wlfightgroup') {
+ $data['goodsname'] = pdo_getcolumn(PDO_NAME.'fightgroup_goods',array('id'=>$order['fkid']),'name');
+ $detail_url = h5_url('pages/subPages/orderList/orderDetails/orderDetails',['orderid'=>$order['id'],'plugin'=>'wlfightgroup']);
+ }else if ($order['plugin'] == 'coupon') {
+ $data['goodsname'] = pdo_getcolumn(PDO_NAME.'couponlist',array('id'=>$order['fkid']),'title');
+ $detail_url = h5_url('pages/subPages/orderList/orderDetails/orderDetails',['orderid'=>$order['id'],'plugin'=>'coupon']);
+ }else if($data['plugin'] == 'citydelivery'){
+ $data['price'] = $paylog['fee'];
+ $order = pdo_get('wlmerchant_order' , ['paylogid' => $paylog['plid']] , ['id' , 'recordid' , 'num' , 'fkid' , 'plugin' , 'fightstatus' , 'paidprid' , 'price' , 'vip_card_id' , 'expressid']);
+ $detail_url = h5_url('pages/subPages/orderList/orderDetails/orderDetails',['orderid'=>$order['id'],'plugin'=>'citydelivery']);
+ $data['goodsname'] = '同城配送商品';
+ }else if ($order['plugin'] == 'groupon') {
+ $data['goodsname'] = pdo_getcolumn(PDO_NAME.'groupon_activity',array('id'=>$order['fkid']),'name');
+ $detail_url = h5_url('pages/subPages/orderList/orderDetails/orderDetails',['orderid'=>$order['id'],'plugin'=>'groupon']);
+ }else if ($order['plugin'] == 'bargain') {
+ $data['goodsname'] = pdo_getcolumn(PDO_NAME.'bargain_activity',array('id'=>$order['fkid']),'name');
+ $detail_url = h5_url('pages/subPages/orderList/orderDetails/orderDetails',['orderid'=>$order['id'],'plugin'=>'bargain']);
+ }else if ($order['plugin'] == 'pocket') {
+ $data['goodsname'] = '掌上信息付费';
+ }else if ($order['plugin'] == 'store') {
+ $data['goodsname'] = '商户入驻';
+ }else if ($order['plugin'] == 'distribution') {
+ $data['goodsname'] = '分销商申请';
+ }else if ($order['plugin'] == 'consumption') {
+ $data['goodsname'] = pdo_getcolumn(PDO_NAME.'consumption_goods',array('id'=>$order['fkid']),'title');
+ }else if ($order['plugin'] == 'member') {
+ $data['goodsname'] = '余额充值';
+ }else if ($order['plugin'] == 'halfcard') {
+ $data['goodsname'] = '在线买单';
+ }else if ($order['plugin'] == 'halfcard') {
+ $data['goodsname'] = '在线买单';
+ }else if ($order['plugin'] == 'citycard') {
+ $data['goodsname'] = '同城名片付费';
+ }else if ($order['plugin'] == 'yellowpage') {
+ $data['goodsname'] = '黄页114付费';
+ }else if ($order['plugin'] == 'recruit') {
+ $data['goodsname'] = '招聘求职付费';
+ }else if ($order['plugin'] == 'dating') {
+ $data['goodsname'] = '相亲交友付费';
+ }else if ($order['plugin'] == 'vehicle') {
+ $data['goodsname'] = '顺风车付费';
+ }else if ($order['plugin'] == 'housekeep') {
+ $data['goodsname'] = '家政服务付费';
+ }
+}
+$data['num'] = $order['num'] ? : 1;
+if(empty($data['goodsname'])){
+ $data['goodsname'] = '其他付费项目';
+}
+$_W['aid'] = $order['aid'] ? : 0;
+//系统信息查询
+$_W['attachurl_remote'] = attachment_set_attach_url();
+$base = Setting::wlsetting_read('base');
+$base['logo'] = tomedia($base['logo']);
+$home_url = h5_url('pages/mainPages/index/index');
+if(empty($detail_url)){
+ $detail_url = h5_url('pages/subPages/orderList/orderList',['type'=>10]);
+}
+//处理订单回调
+if($paylog['status'] == 0){
+ $successInfo = [
+ 'type' => 2 ,//支付方式
+ 'tid' => $paylog['tid'],//订单号
+ 'transaction_id' => $transaction_id,
+ 'time' => $_GPC['t'],
+ ];
+ PayResult::main($successInfo);//调用方法处理订单
+}
+
+
+include wl_template('utility/ahrcu');
\ No newline at end of file
diff --git a/addons/weliam_smartcity/core/function/global.func.php b/addons/weliam_smartcity/core/function/global.func.php
new file mode 100644
index 0000000..298fbef
--- /dev/null
+++ b/addons/weliam_smartcity/core/function/global.func.php
@@ -0,0 +1,1346 @@
+ MODULE_NAME), 'mid');
+ $moduleid = empty($moduleid) ? '000000' : sprintf("%06d", $moduleid);
+ $uniontid = date('YmdHis') . $moduleid . random(8, 1);
+ //生成商户订单号
+ return $uniontid;
+}
+
+/**
+ * model类实例函数
+ *
+ * @access public
+ * @name m
+ * @param $filename 文件夹/文件名
+ * @return 对象
+ */
+function m($filename = '') {
+ static $_modules = array();
+ if (strpos($filename, '/') > -1) {
+ [$file, $name] = explode('/', $filename);
+ } else {
+ die('文件结构不正确,正确结构(文件夹名/文件名)');
+ }
+ if (isset($_modules[$file][$name]))
+ return $_modules[$file][$name];
+ $model = PATH_CORE . "library/" . $file . "/" . $name . '.lib.php';
+ if (!is_file($model)) {
+ die('Library Class ' . $filename . ' Not Found!');
+ }
+ require $model;
+ $class_name = ucfirst($name);
+ //调用该类
+ $_modules[$file][$name] = new $class_name();
+ return $_modules[$file][$name];
+}
+/**
+ * Comment: 判断 当前模块权限
+ * Author: zzw
+ * Date: 2020/11/16 11:24
+ * @param string $name
+ * @return bool
+ */
+function p($name = '') {
+ global $_W;
+ //默认拥有当前模块权限
+ $status = true;
+ //判断文件是否存在 不存在则无权限
+ $model = PATH_PLUGIN . strtolower($name) . '/config.xml';
+ if (!is_file($model)) $status = false;
+
+
+ return $status;
+}
+
+/**
+ * Comment: 判断 当前公众号是否有此权限
+ * Author: wlf
+ * Date: 2021/09/26 14:36
+ * @param string $name
+ * @return bool
+ */
+function uniacid_p($name = '') {
+ global $_W;
+ $status = 1;
+ $pp = p($name);
+ if($pp){
+ $plugin = pdo_getcolumn(PDO_NAME.'perm_account',array('uniacid'=>$_W['uniacid']),'plugins');
+ $plugin = unserialize($plugin);
+ if(!empty($plugin)){
+ if(!in_array($name,$plugin)){
+ $status = 0;
+ }
+ }
+ }else{
+ $status = 0;
+ }
+ return $status;
+}
+
+/**
+ * Comment: 判断 当前代理是否有此权限
+ * Author: wlf
+ * Date: 2021/09/26 15:06
+ * @param string $name
+ * @return bool
+ */
+function agent_p($name = ''){
+ global $_W;
+ $status = 1;
+ $up = uniacid_p($name);
+ if($up > 0){
+ //获取代理分组权限信息
+ if($_W['aid'] > 0){
+ $groupid = pdo_getcolumn(PDO_NAME.'agentusers',array('id'=>$_W['aid']),'groupid');
+ if($groupid > 0){
+ $plugin = pdo_getcolumn(PDO_NAME.'agentusers_group',array('id'=>$groupid),'package');
+ $plugin = unserialize($plugin);
+ if(!empty($plugin)){
+ if(!in_array($name,$plugin)){
+ $status = 0;
+ }
+ }
+ }
+ }
+ }else{
+ $status = 0;
+ }
+ return $status;
+}
+
+/**
+ * Comment: 判断 当前商户是否有此权限
+ * Author: wlf
+ * Date: 2021/09/26 15:19
+ * @param string $name
+ * @return bool
+ */
+function store_p($name = '',$sid){
+ global $_W;
+ $status = 1;
+ $ap = agent_p($name);
+ if($ap > 0){
+ $groupid = pdo_getcolumn(PDO_NAME.'merchantdata',array('id'=>$sid),'groupid');
+ if($groupid > 0){
+ $plugin = pdo_getcolumn(PDO_NAME.'chargelist',array('id'=>$groupid),'authority');
+ $plugin = unserialize($plugin);
+ if(!empty($plugin)){
+ if(!in_array($name,$plugin)){
+ $status = 0;
+ }
+ }
+ }
+ }else{
+ $status = 0;
+ }
+ return $status;
+}
+
+
+/**
+ * Comment: 判断当前模块是否存在权限
+ * Author: zzw
+ * Date: 2020/11/16 19:45
+ * @param $name
+ * @return bool
+ */
+function j($name){
+ //TODO 当前权限判断功能需要优化 请求内容和判断内容过多 导致加载缓慢 当时为了方便直接使用的其他方法的返回结果在重新判断 可以重写判断不适用其他方法返回结果进行重新判断
+ //默认拥有当前模块权限
+ $status = true;
+ //判断是否存在权限
+ if(is_agent()) $wholePlugin = App::get_apps(0, 'agent');//全部插件
+ else if(is_store()) $wholePlugin = App::get_apps(0, 'store');//全部插件
+ else $wholePlugin = App::get_apps(0, 'account');//全部插件
+ $wholeIdents = array_column($wholePlugin,'ident');//插件昵称
+ $plugins = App::get_cate_plugins('agent');//当前代理商户拥有权限的插件
+ $channel = array_column($plugins['channel']['plugins'],'ident');
+ $market = array_column($plugins['market']['plugins'],'ident');
+ $interact = array_column($plugins['interact']['plugins'],'ident');
+ $expand = array_column($plugins['expand']['plugins'],'ident');
+ $help = array_column($plugins['help']['plugins'],'ident');
+ $idents = array_merge((array)$channel, (array)$market, (array)$interact, (array)$expand, (array)$help);
+ //当前插件存在权限处理 当前代理无当前权限
+ if(is_agent() || is_store()) {
+ if(!in_array($name,$wholeIdents) || !in_array($name,$idents)) $status = false;
+ }else{
+ if(!in_array($name,$wholeIdents)) $status = false;
+ }
+
+ return $status;
+}
+/**
+ * 权限检测函数
+ *
+ * @access public
+ * @name checkLimit
+ * @param $roleid 角色id
+ * @param $arr 检测位置
+ * @return false|true
+ */
+function checkLimit($roleid, $arr = array()) {
+ $allPerms = Perms::allParms();
+ if (empty($allPerms[$arr['p']][$arr['ac']][$arr['do']]))
+ return true;
+ $limits = Perms::getRolePerms($roleid);
+ if (empty($limits) || empty($arr))
+ return false;
+ if (empty($limits[$arr['p']][$arr['ac']][$arr['do']]))
+ return false;
+ return true;
+}
+
+if ((!function_exists('url') && defined('IN_UNIAPP')) || !function_exists('url') && defined('IS_INDEPENDENT')) {
+ function url($segment, $params = array(), $noredirect = false) {
+ return murl($segment, $params, $noredirect);
+ }
+}
+
+
+/**
+ * web地址生成
+ *
+ * @access public
+ * @name getUrlByWeb
+ * @param $segment do/ac/op
+ * @param $params 参数
+ * @return string
+ */
+function web_url($segment, $params = array()) {
+ global $_W;
+ [$p, $ac, $do] = explode('/', $segment);
+ if (is_store()) {
+ $url = $_W['siteroot'] . 'web/citystore.php?';
+ } else if (is_agent()) {
+ $url = $_W['siteroot'] . 'web/cityagent.php?';
+ } else if (is_staff()) {
+ $url = $_W['siteroot'] . 'web/citysys.php?';
+ } else {
+ $url = $_W['siteroot'] . 'web/index.php?c=site&a=entry&m=' . MODULE_NAME . '&';
+ }
+ if (!empty($p)) {
+ $url .= "p={$p}&";
+ }
+ if (!empty($ac)) {
+ $url .= "ac={$ac}&";
+ }
+ $do = !empty($do) ? $do : 'index';
+ if (!empty($do)) {
+ $url .= "do={$do}&";
+ }
+ if (!empty($params)) {
+ $queryString = http_build_query($params, '', '&');
+ $url .= $queryString;
+ }
+ return $url;
+}
+
+/**
+ * APP地址生成
+ *
+ * @access public
+ * @name app_url
+ * @param $segment do/ac/op
+ * @param $params 参数
+ * @return string
+ */
+function app_url($segment, $params = array(), $addhost = TRUE) {
+ global $_W;
+ [$p, $ac, $do] = explode('/', $segment);
+
+ if ($addhost == TRUE) {
+ $_W['siteroot'] = str_replace(array('/addons/' . MODULE_NAME,'/addons/weliam_smartcity','/core/common', '/addons/bm_payms'), '', $_W['siteroot']);
+ $url = $_W['siteroot'] . 'app/index.php?i=' . $_W['uniacid'] . '&c=entry&m=' . MODULE_NAME . '&';
+ } else {
+ $url = './index.php?i=' . $_W['uniacid'] . '&c=entry&m=' . MODULE_NAME . '&';
+ }
+
+ if (!empty($p)) {
+ $url .= "p={$p}&";
+ }
+ if (!empty($ac)) {
+ $url .= "ac={$ac}&";
+ }
+ $do = !empty($do) ? $do : 'index';
+ if (!empty($do)) {
+ $url .= "do={$do}&";
+ }
+ if (!empty($params)) {
+ $queryString = http_build_query($params, '', '&');
+ $url .= $queryString;
+ }
+ if (substr($url, -1) == '&') {
+ $url = substr($url, 0, strlen($url) - 1);
+ }
+
+ return $url;
+}
+
+/**
+ * Comment: H5链接地址生成 强制生成为https链接
+ * Author: zzw
+ * Date: 2019/7/2 16:37
+ * @param string $page
+ * @param array $params
+ * @param $addhost
+ * @return bool|string
+ */
+function h5_url($page, $params = array(), $catalog = 'h5',$aid=0) {
+ global $_W;
+ $_W['siteroot'] = str_replace(array('/addons/' . MODULE_NAME,'/addons/weliam_smartcity','/plugin/pftapimod','/core/common', '/addons/bm_payms','/addons/weliam_smartcity/payment','/addons/'.MODULE_NAME.'/payment','/payment'), '', $_W['siteroot']);
+ $_W['siteroot'] = str_replace(':19080','',$_W['siteroot']);
+ $is_have = strpos($page, '?');
+ if ($is_have) {
+ $info = explode('?', $page);
+ $page = $info[0];
+ $paramStr = $info[1];
+ //判断参数是否存在i 存在则删除
+ foreach (explode('&', $paramStr) as $key => $value) {
+ if ($value{0} == 'i' && $value{1} == '=') {
+ $paramStr = str_replace($value . '&', '', $paramStr);
+ break;
+ }
+ }
+ }
+ if(empty($aid)){
+ $aid = $_W['aid'];
+ }
+ if(empty($catalog)){
+ $catalog = 'h5';
+ }
+ $url = $_W['siteroot'] . 'addons/' . MODULE_NAME . '/' . $catalog . '/#/' . $page . "?i=" . $_W['uniacid'] . '&aid=' .$aid. '&' . $paramStr;
+ $url = trim($url, "&");
+ if (!empty($params)) {
+ $queryString = http_build_query($params, '', '&');
+ $url .= '&' . trim($queryString, "&");
+ }
+
+ $domain = Cloud::wl_syssetting_read('jumpadmin');
+ if(!empty($domain['targetDmain'])){
+ foreach($domain['targetDmain'] as $tar){
+ $url = str_replace($tar,$domain['endDmain'],$url);
+ }
+ }
+
+ return $url;
+}
+
+function is_store() {
+ if (defined('IN_STORE')) {
+ return true;
+ }
+ return false;
+}
+function is_agent() {
+ if (defined('IN_WEB')) {
+ return true;
+ }
+ return false;
+}
+function is_staff() {
+ if (defined('IN_STAFF')) {
+ return true;
+ }
+ return false;
+}
+if (!function_exists('is_wxapp')) {
+ function is_wxapp() {
+ global $_W;
+ if (!empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'miniProgram')) {
+ return true;
+ }
+
+ return false;
+ }
+
+}
+
+if (!function_exists('is_weixin')) {
+ function is_weixin() {
+ global $_W;
+
+ if (empty($_SERVER['HTTP_USER_AGENT']) || ((strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false) && (strpos($_SERVER['HTTP_USER_AGENT'], 'Windows Phone') === false))) {
+ return false;
+ }
+
+ return true;
+ }
+
+}
+
+if (!function_exists('is_h5app')) {
+ function is_h5app() {
+ if (!empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'CK 2.0')) {
+ return true;
+ }
+
+ return false;
+ }
+
+}
+
+if (!function_exists('is_ios')) {
+ function is_ios() {
+ if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
+ return true;
+ }
+
+ return false;
+ }
+
+}
+
+if (!function_exists('is_mobile')) {
+ function is_mobile() {
+ $useragent = $_SERVER['HTTP_USER_AGENT'];
+ if (preg_match('/(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $useragent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i', substr($useragent, 0, 4))) {
+ return true;
+ }
+
+ return false;
+ }
+
+}
+
+function ifilter_url($params) {
+ return wl_filter_url($params);
+}
+
+function wl_setcookie($key, $value, $expire = 0, $httponly = false) {
+ global $_W;
+ $expire = $expire != 0 ? (TIMESTAMP + $expire) : 0;
+ $secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
+ $value = is_array($value) ? base64_encode(json_encode($value)) : $value;
+ return setcookie('weliam_' . $key, $value, $expire, $_W['config']['cookie']['path'], $_W['config']['cookie']['domain'], $secure, $httponly);
+}
+
+function wl_getcookie($key) {
+ $sting = $_COOKIE['weliam_' . $key];
+ $data = json_decode(base64_decode($sting), true);
+ return is_array($data) ? $data : $sting;
+}
+
+//2019.9.4 默认:1=失败,0=成功
+function wl_json($errno = 0, $message = '', $data = '') {
+ exit(json_encode(array('errno' => $errno, 'message' => $message, 'data' => $data)));
+}
+
+function wl_new_method($plugin, $controller, $method, $catalog = 'app') {
+ global $_W;
+ $dir = IA_ROOT . '/addons/' . MODULE_NAME . '/';
+ $file = $dir . $catalog . '/controller/' . $plugin . '/' . $controller . '.ctrl.php';
+ if (!is_file($file)) {
+ $file = $dir . 'plugin/' . $plugin . '/' . $catalog . '/controller/' . $controller . '.ctrl.php';
+ }
+ if (($catalog == 'web' || $catalog == 'sys') && !is_file($file)) {
+ $_W['catalog'] = $catalog = ($catalog == 'web') ? 'sys' : 'web';
+ $file = $dir . $catalog . '/controller/' . $plugin . '/' . $controller . '.ctrl.php';
+ if (!is_file($file)) {
+ $file = $dir . 'plugin/' . $plugin . '/' . $catalog . '/controller/' . $controller . '.ctrl.php';
+ }
+ }
+ if (is_file($file)) {
+ require_once $file;
+ } else {
+ trigger_error("访问的模块 {$plugin} 不存在.", E_USER_WARNING);
+ }
+ $class = ucfirst($controller) . '_WeliamController';
+ if (class_exists($class, false)) {
+ $instance = new $class();
+ } else {
+ $instance = new $controller();
+ }
+ if ($catalog == 'app') {
+ $instance->inMobile = TRUE;
+ }
+ if (!method_exists($instance, $method)) {
+ trigger_error('控制器 ' . $controller . ' 方法 ' . $method . ' 未找到!');
+ }
+
+ $instance->$method();
+ exit();
+}
+
+/**
+ * html文件引入,生成缓存
+ *
+ * @access public
+ * @name wl_template
+ * @param $filename 文件
+ * @return string
+ */
+function wl_template($filename, $flag = '') {
+ global $_W;
+ $name = MODULE_NAME;
+ $catalog = strstr($filename, 'common/') ? 'web' : $_W['catalog'] ? : 'web';
+ $source = IA_ROOT . "/addons/{$name}/{$catalog}/view/default/{$filename}.html";
+ $compile = IA_ROOT . "/data/tpl/{$catalog}/{$name}/{$_W['plugin']}/{$catalog}/view/default/{$filename}.tpl.php";
+ if (!is_file($source)) $source = IA_ROOT . "/addons/{$name}/plugin/{$_W['plugin']}/{$catalog}/view/default/{$filename}.html";
+ if (!is_file($source)) exit("Error: template source '{$filename}' is not exist!!!");
+ if (!is_file($compile) || filemtime($source) > filemtime($compile)) Template::wl_template_compile($source, $compile, true);
+ if ($flag == TEMPLATE_FETCH) {
+ extract($GLOBALS, EXTR_SKIP);
+ ob_end_flush();
+ ob_clean();
+ ob_start();
+ include $compile;
+ $contents = ob_get_contents();
+ ob_clean();
+ return $contents;
+ } else if ($flag == 'template') {
+ extract($GLOBALS, EXTR_SKIP);
+ return $compile;
+ } else {
+ return $compile;
+ }
+
+/* $name = MODULE_NAME;
+ if (defined('IN_SYS') || defined('IN_WEB')) {
+ $catalog = strstr($filename, 'common/') ? 'web' : $_W['catalog'];
+ $source = IA_ROOT . "/addons/{$name}/{$catalog}/view/default/{$filename}.html";
+ $compile = IA_ROOT . "/data/tpl/{$catalog}/{$name}/{$catalog}/view/default/{$filename}.tpl.php";
+ if (!is_file($source)) {
+ $source = IA_ROOT . "/addons/{$name}/plugin/{$_W['plugin']}/{$catalog}/view/default/{$filename}.html";
+ }
+ }
+
+ if (defined('IN_APP')) {
+ $template = "default";
+ if (!empty($_W['wlsetting']['templat']['appview'])) {
+ $template = $_W['wlsetting']['templat']['appview'];
+ }
+ $source = IA_ROOT . "/addons/{$name}/app/view/{$template}/{$filename}.html";
+ $compile = IA_ROOT . "/data/tpl/app/{$name}/app/view/{$template}/{$filename}.tpl.php";
+ if (!is_file($source)) {
+ $source = IA_ROOT . "/addons/{$name}/app/view/default/{$filename}.html";
+ }
+ if (!is_file($source)) {
+ $source = IA_ROOT . "/addons/{$name}/plugin/{$_W['plugin']}/app/view/{$template}/{$filename}.html";
+ }
+ if (!is_file($source)) {
+ $source = IA_ROOT . "/addons/{$name}/plugin/{$_W['plugin']}/app/view/default/{$filename}.html";
+ }
+ if (!is_file($source)) {
+ $filenames = explode("/", $filename);
+ $source = IA_ROOT . "/addons/{$name}/plugin/{$filenames[0]}/app/view/default/{$filename}.html";
+ }
+ if (!empty($_W['wlsetting']['trade']['credittext']) || !empty($_W['wlsetting']['trade']['moneytext'])) {
+ $compile = IA_ROOT . "/data/tpl/app/{$name}/{$_W['uniacid']}/app/view/{$template}/{$filename}.tpl.php";
+ }
+ if (!empty($_W['wlsetting']['halfcard']['text']['halfcardtext']) || !empty($_W['wlsetting']['halfcard']['text']['privilege'])) {
+ $compile = IA_ROOT . "/data/tpl/app/{$name}/{$_W['uniacid']}/app/view/{$template}/{$filename}.tpl.php";
+ }
+ }
+ if (!is_file($source)) {
+ exit("Error: template source '{$filename}' is not exist!!!");
+ }
+ if (!is_file($compile) || filemtime($source) > filemtime($compile)) {
+ Template::wl_template_compile($source, $compile, true);
+ }
+ if ($flag == TEMPLATE_FETCH) {
+ extract($GLOBALS, EXTR_SKIP);
+ ob_end_flush();
+ ob_clean();
+ ob_start();
+ include $compile;
+ $contents = ob_get_contents();
+ ob_clean();
+ return $contents;
+ } else if ($flag == 'template') {
+ extract($GLOBALS, EXTR_SKIP);
+ return $compile;
+ } else {
+ return $compile;
+ }*/
+}
+
+function wl_message($msg, $redirect = '', $type = '') {
+ global $_W, $_GPC;
+ if ($redirect == 'refresh') {
+ $redirect = $_W['script_name'] . '?' . $_SERVER['QUERY_STRING'];
+ }
+ if ($redirect == 'referer') {
+ $redirect = referer();
+ }
+ if ($redirect == 'close') {
+ $redirect = 'wx.closeWindow()';
+ $close = 1;
+ }
+ if ($redirect == '') {
+ $type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql', 'fixed')) ? $type : 'info';
+ } else {
+ $type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql', 'fixed')) ? $type : 'success';
+ }
+ if (IN_WXAPP == 'wxapp') {
+ die(json_encode(array('errno' => $type == 'success' ? 0 : 1, 'message' => $msg, 'data' => $redirect)));
+ }
+ if ($_W['isajax'] || !empty($_GET['isajax']) || $type == 'ajax') {
+ if ($type != 'ajax' && !empty($_GPC['target'])) {
+ exit("
+");
+ } else {
+ //ajaxsubmit兼容方案
+ if ($_W['isajax'] && !empty($_GPC['token'])) {
+ $ret = array('status' => $type == 'success' ? 1 : 0, 'result' => $type == 'success' ? array('url' => $redirect ? $redirect : referer()) : array());
+ $ret['result']['message'] = $msg;
+ exit(json_encode($ret));
+ } else {
+ $vars = array();
+ if (is_array($msg)) {
+ $vars['errno'] = $msg['errno'];
+ $vars['message'] = $msg['message'];
+ die(json_encode($vars));
+ } else {
+ $vars['message'] = $msg;
+ }
+ $vars['redirect'] = $redirect;
+ $vars['type'] = $type;
+ die(json_encode($vars));
+ }
+ }
+ } elseif (is_array($msg)) {
+ $msg = $msg['message'];
+ }
+ if (empty($msg) && !empty($redirect)) {
+ header('location: ' . $redirect);
+ }
+ $label = $type;
+ if ($type == 'error') {
+ $label = 'danger';
+ }
+ if ($type == 'ajax' || $type == 'sql') {
+ $label = 'warning';
+ }
+
+ include wl_template('common/message', TEMPLATE_INCLUDEPATH);
+ exit();
+}
+
+/**
+ * debug打印
+ *
+ * @access public
+ * @name wl_debug
+ * @param $value 需要打印的参数
+ */
+function wl_debug($value) {
+ echo "
";
+ print_r($value);
+ echo "
";
+ exit;
+}
+
+/**
+ * Comment: 自有的debug模式 只有指定人员访问才会debug,其他人员访问不debug。
+ * Author: zzw
+ * Date: 2019/11/12 9:27
+ * @param array | string | int $value debug的内容
+ * @param int $mid 用户id
+ * @param bool $status 是否强制打印
+ */
+function private_debug($value,$mid = 0,$status = false){
+ global $_W;
+ if($status || ($_W['mid'] == $mid || $_REQUEST['debug'])){
+ echo "
";
+ print_r($value);
+ echo "
";
+ exit;
+ }
+}
+
+
+/**
+ * 日志文件打印
+ *
+ * @access public
+ * @name wl_log
+ * @param $filename 文件名
+ * @param $title 打印标题
+ * @param $data 需要打印内容
+ * @return array
+ */
+function wl_log($filename, $title, $data) {
+ global $_W;
+ if ($uniacid != '') {
+ $_W['uniacid'] = $uniacid;
+ }
+ $url_log = PATH_DATA . "log/" . date('Y-m-d', time()) . "/" . $filename . ".log";
+ $url_dir = PATH_DATA . "log/" . date('Y-m-d', time());
+ Util::mkDirs($url_dir);
+ file_put_contents($url_log, var_export('/=======' . date('Y-m-d H:i:s', time()) . '【' . $title . '】=======/', true) . PHP_EOL, FILE_APPEND);
+ file_put_contents($url_log, var_export($data, true) . PHP_EOL, FILE_APPEND);
+}
+
+function wl_filter_url($params) {
+ global $_W;
+ if (empty($params)) {
+ return '';
+ }
+ $query_arr = array();
+ $parse = parse_url($_W['siteurl']);
+ if (!empty($parse['query'])) {
+ $query = $parse['query'];
+ parse_str($query, $query_arr);
+ }
+ $params = explode(',', $params);
+ foreach ($params as $val) {
+ if (!empty($val)) {
+ $data = explode(':', $val);
+ $query_arr[$data[0]] = trim($data[1]);
+ }
+ }
+ $query_arr['page'] = 1;
+ $query = http_build_query($query_arr);
+ if(defined('IN_WEB')){
+ return './cityagent.php?' . $query;
+ }else if(defined('IN_STORE')){
+ return './citystore.php?' . $query;
+ }else if(defined('IN_STAFF')){
+ return './citysys.php?' . $query;
+ }else{
+ return './index.php?' . $query;
+ }
+}
+
+function wl_get_module_name(){
+ return MODULE_NAME;
+}
+
+function wl_tpl_form_field_member($value = array()) {
+ $s = '';
+ $s = '
+ ';
+ $s .= '
+
+ ';
+ return $s;
+}
+
+/**
+ * qr二维码生成
+ *
+ * @access public
+ * @name qr
+ * @param $url 需要生成二维码的链接
+ */
+function qr($url) {
+ global $_W;
+ if (empty($url))
+ return false;
+ m('qrcode/QRcode')->png($url, false, QR_ECLEVEL_H, 4);
+}
+
+/**
+ * puv浏览量统计
+ *
+ * @access public
+ * @name puv
+ * @param
+ */
+function puv() {
+ global $_W;
+ if ($_W['uniacid'] <= 0 || empty($_W['areaid'])) {
+ return;
+ }
+ $puv = pdo_getcolumn(PDO_NAME . 'puv', array('uniacid' => $_W['uniacid'], 'date' => date('Ymd'), 'areaid' => $_W['areaid']), 'id');
+ if (empty($puv)) {
+ pdo_insert(PDO_NAME . 'puv', array('areaid' => $_W['areaid'], 'uniacid' => $_W['uniacid'], 'pv' => 0, 'uv' => 0, 'date' => date('Ymd')));
+ $puv = pdo_insertid();
+ }
+ pdo_query('UPDATE ' . tablename(PDO_NAME . 'puv') . " SET `pv` = `pv` + 1 WHERE id = {$puv}");
+ if ($_W['mid']) {
+ $myp = pdo_getcolumn(PDO_NAME . 'puvrecord', array('uniacid' => $_W['uniacid'], 'date' => date('Ymd'), 'mid' => $_W['mid'], 'areaid' => $_W['areaid']), 'id');
+ if (empty($myp)) {
+ pdo_query('UPDATE ' . tablename(PDO_NAME . 'puv') . " SET `uv` = `uv` + 1 WHERE id = {$puv}");
+ pdo_insert(PDO_NAME . 'puvrecord', array('areaid' => $_W['areaid'], 'uniacid' => $_W['uniacid'], 'pv' => 0, 'mid' => $_W['mid'], 'date' => date('Ymd')));
+ $myp = pdo_insertid();
+ }
+ pdo_query('UPDATE ' . tablename(PDO_NAME . 'puvrecord') . " SET `pv` = `pv` + 1 WHERE id = {$myp}");
+ }
+}
+
+if (!function_exists('show_json')) {
+ function show_json($status = 1, $return = NULL) {
+ $ret = array('status' => $status, 'result' => $status == 1 ? array('url' => referer()) : array());
+
+ if (!is_array($return)) {
+ if ($return) {
+ $ret['result']['message'] = $return;
+ }
+
+ exit(json_encode($ret));
+ } else {
+ $ret['result'] = $return;
+ }
+
+ if (isset($return['url'])) {
+ $ret['result']['url'] = $return['url'];
+ } else {
+ if ($status == 1) {
+ $ret['result']['url'] = referer();
+ }
+ }
+
+ exit(json_encode($ret));
+ }
+
+}
+
+function checkshare() {//禁止分享
+ global $_W;
+ if ($_W['controller'] == 'supervise') {//商户管理
+ return 1;
+ } else if ($_W['method'] == 'orderlist') {//订单列表详情
+ return 1;
+ } else if ($_W['controller'] == 'home' && $_W['method'] == 'paySuccess') {//抢购订单详情
+ return 1;
+ } else if ($_W['controller'] == 'coupon_app' && $_W['method'] == 'couponDetail') {//卡券订单详情
+ return 1;
+ } else if ($_W['controller'] == 'fightapp' && $_W['method'] == 'expressorder') {//拼团订单详情
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+if (!function_exists('array_column')) {
+ function array_column($input, $column_key, $index_key = NULL) {
+ $arr = array();
+ foreach ($input as $d) {
+ if (!isset($d[$column_key])) {
+ return NULL;
+ }
+ if ($index_key !== NULL) {
+ return array($d[$index_key] => $d[$column_key]);
+ }
+ $arr[] = $d[$column_key];
+ }
+
+ if ($index_key !== NULL) {
+ $tmp = array();
+ foreach ($arr as $ar) {
+ $tmp[key($ar)] = current($ar);
+ }
+ $arr = $tmp;
+ }
+ return $arr;
+ }
+}
+
+/**
+ * $time 需要格式化的时间戳
+ * return 格式化时间
+ */
+function time_tran($time) {
+ $text = '';
+ if (!$time) {
+ return $text;
+ }
+ $current = time();
+ $t = $current - $time;
+ $retArr = array('刚刚', '秒前', '分钟前', '小时前', '天前', '月前', '年前');
+ switch ($t) {
+ case $t < 0://时间大于当前时间,返回格式化时间
+ $text = date('Y-m-d', $time);
+ break;
+ case $t == 0://刚刚
+ $text = $retArr[0];
+ break;
+ case $t < 60:// 几秒前
+ $text = $t . $retArr[1];
+ break;
+ case $t < 3600://几分钟前
+ $text = floor($t / 60) . $retArr[2];
+ break;
+ case $t < 86400://几小时前
+ $text = floor($t / 3600) . $retArr[3];
+ break;
+ case $t < 2592000: //几天前
+ $text = floor($t / 86400) . $retArr[4];
+ break;
+ case $t < 31536000: //几个月前
+ $text = floor($t / 2592000) . $retArr[5];
+ break;
+ default : //几年前
+ $text = floor($t / 31536000) . $retArr[6];
+
+ }
+ return $text;
+}
+
+/**
+ * Comment: http请求(post)
+ * Author: zzw
+ * Date: 2019/10/8 14:29
+ * @param $url
+ * @param $postData
+ * @param $header
+ * @return mixed
+ */
+function curlPostRequest($url, $postData, $header = '') {
+ $curl = curl_init();//初始化
+ curl_setopt($curl, CURLOPT_URL, $url);//设置抓取的url
+ if ($header) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//设置header信息
+ curl_setopt($curl, CURLOPT_HEADER, 1);//设置头文件的信息作为数据流输出
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以文件流的形式返回,而不是直接输出。
+ curl_setopt($curl, CURLOPT_POST, 1);//设置post方式提交
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
+ $data = curl_exec($curl); //执行命令
+// if (curl_errno($curl)) {
+// $error = 'Error:' . curl_error($curl);
+// wl_debug($error);
+// }
+ $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);// 获得响应结果里的:header头大小
+ $info = substr($data, $headerSize);//通过截取 获取body信息
+ curl_close($curl);//关闭URL请求
+ return json_decode($info, true);//返回获取的信息数据
+}
+/**
+ * Comment: Comment: http请求(get)
+ * Author: zzw
+ * Date: 2020/7/22 17:15
+ * @param string $url 请求地址
+ * @param string $header
+ * @return mixed
+ */
+function curlGetRequest($url, $header = '') {
+ $curl = curl_init();//初始化
+ curl_setopt($curl, CURLOPT_URL, $url);//设置抓取的url
+ if ($header) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//设置header信息
+ curl_setopt($curl, CURLOPT_HEADER, 1);//设置头文件的信息作为数据流输出
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以文件流的形式返回,而不是直接输出。
+ $data = curl_exec($curl); //执行命令
+ $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);// 获得响应结果里的:header头大小
+ $info = substr($data, $headerSize);//通过截取 获取body信息
+ curl_close($curl);//关闭URL请求
+ return json_decode($info, true);//返回获取的信息数据
+}
+/**
+ * Comment: 查看本地是否存在某张图片,不存在则下载到本地
+ * Author: zzw
+ * Date: 2019/11/18 18:37
+ * @param $imgPath
+ * @param $imgLink
+ */
+function wl_uploadImages($imgPath,$imgLink){
+ #1、判断是否已经存在本地
+ if(!file_exists($imgPath)){
+ $imgName = explode('/',$imgPath);
+ $dir = str_replace($imgName[count($imgName) - 1],'',$imgPath);
+ mkdir($dir,0777,true);
+ $img = $imgLink;
+ ob_clean();
+ ob_start();
+ readfile($img);//读取图片
+ $img = ob_get_contents();//得到缓冲区中保存的图片
+ ob_end_clean();//清空缓冲区
+ $fp = fopen($imgPath,'w'); //写入图片
+ if(fwrite($fp,$img)) {
+ fclose($fp);
+ }
+ }
+}
+/**
+ * Comment: 判断某个远程文件是否存在
+ * Author: zzw
+ * Date: 2020/1/17 11:17
+ * @param $url
+ * @return int
+ */
+function remoteFileExists($url){
+ if(file_get_contents($url,0,null,0,1)) return 1;
+ else return 0;
+}
+/**
+ * Comment: 汉字首字母 拼音获取
+ * Author: zzw
+ * Date: 2020/4/26 14:26
+ * @param $s0
+ * @return string|null
+ */
+function getFirstChar($s0){
+ $fchar = ord($s0{0});
+ if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
+ $s1 = iconv("UTF-8","gb2312", $s0);
+ $s2 = iconv("gb2312","UTF-8", $s1);
+ if($s2 == $s0){$s = $s1;}else{$s = $s0;}
+ $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
+ if($asc >= -20319 and $asc <= -20284) return "A";
+ if($asc >= -20283 and $asc <= -19776) return "B";
+ if($asc >= -19775 and $asc <= -19219) return "C";
+ if($asc >= -19218 and $asc <= -18711) return "D";
+ if($asc >= -18710 and $asc <= -18527) return "E";
+ if($asc >= -18526 and $asc <= -18240) return "F";
+ if($asc >= -18239 and $asc <= -17923) return "G";
+ if($asc >= -17922 and $asc <= -17418) return "H";
+ if($asc >= -17922 and $asc <= -17418) return "I";
+ if($asc >= -17417 and $asc <= -16475) return "J";
+ if($asc >= -16474 and $asc <= -16213) return "K";
+ if($asc >= -16212 and $asc <= -15641) return "L";
+ if($asc >= -15640 and $asc <= -15166) return "M";
+ if($asc >= -15165 and $asc <= -14923) return "N";
+ if($asc >= -14922 and $asc <= -14915) return "O";
+ if($asc >= -14914 and $asc <= -14631) return "P";
+ if($asc >= -14630 and $asc <= -14150) return "Q";
+ if($asc >= -14149 and $asc <= -14091) return "R";
+ if($asc >= -14090 and $asc <= -13319) return "S";
+ if($asc >= -13318 and $asc <= -12839) return "T";
+ if($asc >= -12838 and $asc <= -12557) return "W";
+ if($asc >= -12556 and $asc <= -11848) return "X";
+ if($asc >= -11847 and $asc <= -11056) return "Y";
+ if($asc >= -11055 and $asc <= -10247) return "Z";
+ return NULL;
+ //return $s0;
+}
+/**
+ * Comment: 腾讯云远程附件 丢失方法
+ * 由于自动加载路径问题,当前方法在微擎腾讯云远程附件中报错,所以在这里添加一个方法,强制成功
+ * Author: zzw
+ * Date: 2020/9/7 11:49
+ * @param $uri
+ * @param int $options
+ * @return mixed
+ */
+function _idn_uri_convert($uri, $options = 0)
+{
+ if ($uri->getHost()) {
+ $idnaVariant = defined('INTL_IDNA_VARIANT_UTS46') ? INTL_IDNA_VARIANT_UTS46 : 0;
+ $asciiHost = $idnaVariant === 0
+ ? idn_to_ascii($uri->getHost(), $options)
+ : idn_to_ascii($uri->getHost(), $options, $idnaVariant, $info);
+ if ($asciiHost === false) {
+ $errorBitSet = isset($info['errors']) ? $info['errors'] : 0;
+
+ $errorConstants = array_filter(array_keys(get_defined_constants()), function ($name) {
+ return substr($name, 0, 11) === 'IDNA_ERROR_';
+ });
+
+ $errors = [];
+ foreach ($errorConstants as $errorConstant) {
+ if ($errorBitSet & constant($errorConstant)) {
+ $errors[] = $errorConstant;
+ }
+ }
+
+ $errorMessage = 'IDN conversion failed';
+ if ($errors) {
+ $errorMessage .= ' (errors: ' . implode(', ', $errors) . ')';
+ }
+
+ throw new InvalidArgumentException($errorMessage);
+ } else {
+ if ($uri->getHost() !== $asciiHost) {
+ // Replace URI only if the ASCII version is different
+ $uri = $uri->withHost($asciiHost);
+ }
+ }
+ }
+
+ return $uri;
+}
+/**
+* Comment: 分页方法
+ * Author: zzw
+ * Date: 2020/12/29 9:49
+ * @param $total
+ * @param $pageIndex
+ * @param int $pageSize
+ * @param string $url
+ * @param array $context
+ * @return string
+ */
+function wl_pagination($total, $pageIndex, $pageSize = 15, $url = '', $context = array('before' => 5, 'after' => 4, 'ajaxcallback' => '', 'callbackfuncname' => '')) {
+ global $_W;
+ $pdata = array(
+ 'tcount' => 0,
+ 'tpage' => 0,
+ 'cindex' => 0,
+ 'findex' => 0,
+ 'pindex' => 0,
+ 'nindex' => 0,
+ 'lindex' => 0,
+ 'options' => '',
+ );
+ if (empty($context['before'])) {
+ $context['before'] = 5;
+ }
+ if (empty($context['after'])) {
+ $context['after'] = 4;
+ }
+
+ if ($context['ajaxcallback']) {
+ $context['isajax'] = true;
+ }
+
+ if ($context['callbackfuncname']) {
+ $callbackfunc = $context['callbackfuncname'];
+ }
+
+ $pdata['tcount'] = $total;
+ $pdata['tpage'] = (empty($pageSize) || $pageSize < 0) ? 1 : ceil($total / $pageSize);
+ if ($pdata['tpage'] <= 1) {
+ return '';
+ }
+ $cindex = $pageIndex;
+ $cindex = min($cindex, $pdata['tpage']);
+ $cindex = max($cindex, 1);
+ $pdata['cindex'] = $cindex;
+ $pdata['findex'] = 1;
+ $pdata['pindex'] = $cindex > 1 ? $cindex - 1 : 1;
+ $pdata['nindex'] = $cindex < $pdata['tpage'] ? $cindex + 1 : $pdata['tpage'];
+ $pdata['lindex'] = $pdata['tpage'];
+
+ if ($context['isajax']) {
+ if (empty($url)) {
+ $url = $_W['script_name'] . '?' . http_build_query($_GET);
+ }
+ $pdata['faa'] = 'href="javascript:;" page="' . $pdata['findex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['findex'] . '\', this);"' : '');
+ $pdata['paa'] = 'href="javascript:;" page="' . $pdata['pindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['pindex'] . '\', this);"' : '');
+ $pdata['naa'] = 'href="javascript:;" page="' . $pdata['nindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['nindex'] . '\', this);"' : '');
+ $pdata['laa'] = 'href="javascript:;" page="' . $pdata['lindex'] . '" ' . ($callbackfunc ? 'ng-click="' . $callbackfunc . '(\'' . $url . '\', \'' . $pdata['lindex'] . '\', this);"' : '');
+ } else {
+ if ($url) {
+ $pdata['faa'] = 'href="?' . str_replace('*', $pdata['findex'], $url) . '"';
+ $pdata['paa'] = 'href="?' . str_replace('*', $pdata['pindex'], $url) . '"';
+ $pdata['naa'] = 'href="?' . str_replace('*', $pdata['nindex'], $url) . '"';
+ $pdata['laa'] = 'href="?' . str_replace('*', $pdata['lindex'], $url) . '"';
+ } else {
+ $_GET['page'] = $pdata['findex'];
+ $pdata['faa'] = 'href="' . $_W['script_name'] . '?' . http_build_query($_GET) . '"';
+ $_GET['page'] = $pdata['pindex'];
+ $pdata['paa'] = 'href="' . $_W['script_name'] . '?' . http_build_query($_GET) . '"';
+ $_GET['page'] = $pdata['nindex'];
+ $pdata['naa'] = 'href="' . $_W['script_name'] . '?' . http_build_query($_GET) . '"';
+ $_GET['page'] = $pdata['lindex'];
+ $pdata['laa'] = 'href="' . $_W['script_name'] . '?' . http_build_query($_GET) . '"';
+ }
+ }
+ $html = '';
+
+ return $html;
+}
+/**
+ * Comment: 判断当前数组是否存在指定表中不存在的字段,存在则删除该字段
+ * Author: zzw
+ * Date: 2021/3/10 10:26
+ * @param array $data
+ * @param string $table
+ * @return mixed
+ */
+function fieldJudge($data,$table){
+ $sql = "SHOW COLUMNS FROM ".tablename(PDO_NAME.$table);
+ $fieldList = pdo_fetchall($sql);
+ $fields = array_column($fieldList,'Field');
+ foreach($data as $fieldName => $fieldVal){
+ //判断 数据库不存在该字段 删除信息
+ if(!in_array($fieldName, $fields)) unset($data[$fieldName]);
+ }
+
+ return $data;
+}
+/**
+ * Comment: 判断当前字符串是否包含html内容
+ * Author: zzw
+ * Date: 2021/4/27 9:47
+ * @param $str
+ * @return bool
+ */
+function isHtml($str){
+ if($str != strip_tags($str)) return true;
+ else return false;
+}
+/**
+ * Comment: 生成距离计算sql语句
+ * Author: zzw
+ * Date: 2021/5/6 11:30
+ * @param float|int $lat 纬度
+ * @param float|int $lng 经度
+ * @param string $latField 纬度在表中的字段
+ * @param string $lngField 经度在表中的字段
+ * @return string
+ */
+function getDistancesSql($lat,$lng,string $latField,string $lngField):string
+{
+ return "ROUND(CASE
+ WHEN {$lat} > 0 AND {$lng} > 0 THEN ROUND(6378.138 * 2 * ASIN(
+ SQRT(
+ POW(SIN(({$lat} * PI() / 180 - $latField * PI() / 180) / 2),2) +
+ COS({$lat} * PI() / 180) * COS($latField * PI() / 180) *
+ POW(SIN(({$lng} * PI() / 180 - $lngField * PI() / 180) / 2),2)
+ )
+ ) * 1000
+ )
+ ELSE 0
+END)";
+}
+
+
+function beautifyImgInfo($imgs)
+{
+ global $_W;
+ $imgs = unserialize($imgs);
+ if (empty($imgs)) {
+ $imgs = [];
+ } else {
+ foreach ($imgs as &$th) {
+ $th = tomedia($th);
+ }
+ }
+ return $imgs;
+}
+
+function add_aid($url){
+ global $_W;
+ if(strstr($url,'?')){
+ $url = $url.'&aid='.$_W['aid'];
+ }else{
+ $url = $url.'?aid='.$_W['aid'];
+ }
+ return $url;
+}
+
+/**
+ * 汉字截取
+ * @param $str
+ * @param $offset
+ * @param $length
+ * @return string
+ */
+function truncate_chinese_string($str,$offset = 0, $length = 10) {
+ global $_W;
+ $strlen = strlen('汉');
+ return substr($str,$offset,$strlen * $length);
+}
+
+
+
+
+
diff --git a/addons/weliam_smartcity/core/function/tpl.func.php b/addons/weliam_smartcity/core/function/tpl.func.php
new file mode 100644
index 0000000..22f9a84
--- /dev/null
+++ b/addons/weliam_smartcity/core/function/tpl.func.php
@@ -0,0 +1,1004 @@
+ $scene,
+ );
+ $option = json_encode($option);
+ $s = '
+ ';
+ define('TPL_INIT_TINY_FANS', true);
+ }
+
+ $s .= '
+
+
+
+
+
+
+
+
+
+ ';
+ return $s;
+}
+
+function itpl_form_field_daterange($name, $value = array(), $time = false) {
+ global $_GPC;
+ $placeholder = ((isset($value['placeholder']) ? $value['placeholder'] : ''));
+ $s = '';
+
+ if (empty($time) && !defined('TPL_INIT_TINY_DATERANGE_DATE')) {
+ $s = '
+';
+ define('TPL_INIT_TINY_DATERANGE_DATE', true);
+ }
+
+ if (!empty($time) && !defined('TPL_INIT_TINY_DATERANGE_TIME')) {
+ $s = '
+';
+ define('TPL_INIT_TINY_DATERANGE_TIME', true);
+ }
+
+ $str = $placeholder;
+ $value['starttime'] = ((isset($value['starttime']) ? $value['starttime'] : (($_GPC[$name]['start'] ? $_GPC[$name]['start'] : ''))));
+ $value['endtime'] = ((isset($value['endtime']) ? $value['endtime'] : (($_GPC[$name]['end'] ? $_GPC[$name]['end'] : ''))));
+ if ($value['starttime'] && $value['endtime']) {
+ if (empty($time)) {
+ $str = date('Y-m-d', strtotime($value['starttime'])) . '至 ' . date('Y-m-d', strtotime($value['endtime']));
+ } else {
+ $str = date('Y-m-d H:i', strtotime($value['starttime'])) . ' 至 ' . date('Y-m-d H:i', strtotime($value['endtime']));
+ }
+ }
+
+ $s .= '
+
+
+
+
+
+
+
+
';
+ return $s;
+}
+
+function tpl_form_field_tiny_link($name, $value = '', $options = array()) {
+ global $_GPC;
+ $s = '';
+ if (!defined('TPL_INIT_TINY_LINK')) {
+ $s = '
+ ';
+ define('TPL_INIT_TINY_LINK', true);
+ }
+ $s .= '
+
+
+
+
+
+
+ ';
+ return $s;
+}
+
+function tpl_form_field_tiny_wxapp_link($name, $value = '', $options = array()) {
+ global $_GPC;
+ $s = '';
+ if (!defined('TPL_INIT_TINY_WXAPP_LINK')) {
+ $s = '
+ ';
+ define('TPL_INIT_TINY_WXAPP_LINK', true);
+ }
+ $s .= '
+
+
+
+
+
+
+ ';
+ return $s;
+}
+
+function tpl_form_field_tiny_coordinate($field, $value = array(), $required = false) {
+ global $_W;
+ $s = '';
+ if (!defined('TPL_INIT_TINY_COORDINATE')) {
+ $s .= '';
+ define('TPL_INIT_TINY_COORDINATE', true);
+ }
+ $s .= '
+ ';
+ return $s;
+}
+
+function tpl_select2($name, $data, $value = 0, $filter = array('id', 'title'), $default = '请选择') {
+ $element_id = "select2-{$name}";
+ $json_data = array();
+ foreach ($data as $da) {
+ $json_data[] = array(
+ 'id' => $da[$filter[0]],
+ 'text' => $da[$filter[1]],
+ );
+ }
+ $json_data = json_encode($json_data);
+ $html = '';
+ $html .= '';
+ return $html;
+}
+
+function tpl_form_field_tiny_image($name, $value = '') {
+ global $_W;
+ $default = '';
+ $val = $default;
+ if (!empty($value)) {
+ $val = tomedia($value);
+ }
+ if (!empty($options['global'])) {
+ $options['global'] = true;
+ } else {
+ $options['global'] = false;
+ }
+ if (empty($options['class_extra'])) {
+ $options['class_extra'] = '';
+ }
+ if (isset($options['dest_dir']) && !empty($options['dest_dir'])) {
+ if (!preg_match('/^\w+([\/]\w+)?$/i', $options['dest_dir'])) {
+ exit('图片上传目录错误,只能指定最多两级目录,如: "we7_store","we7_store/d1"');
+ }
+ }
+ $options['direct'] = true;
+ $options['multiple'] = false;
+ if (isset($options['thumb'])) {
+ $options['thumb'] = !empty($options['thumb']);
+ }
+ $s = '';
+ if (!defined('TPL_INIT_TINY_IMAGE')) {
+ $s = '
+ ';
+ define('TPL_INIT_TINY_IMAGE', true);
+ }
+
+ $s .= '
+ ';
+ return $s;
+}
+
+function tpl_form_field_store($name, $value = '', $option = array('mutil' => 0)) {
+ global $_W;
+ if (empty($default)) {
+ $default = './resource/images/nopic.jpg';
+ }
+ if (!is_array($value)) {
+ $value = intval($value);
+ $value = array($value);
+ }
+ $value_ids = implode(',', $value);
+ $stores_temp = pdo_fetchall('select id, title, logo from ' . tablename('tiny_wmall_store') . " where uniacid = :uniacid and id in ({$value_ids})", array(':uniacid' => $_W['uniacid']));
+ $stores = array();
+ if (!empty($stores_temp)) {
+ foreach ($stores_temp as $row) {
+ $row['logo'] = tomedia($row['logo']);
+ $stores[] = $row;
+ }
+ }
+
+ $definevar = 'TPL_INIT_TINY_STORE';
+ $function = 'showStoreDialog';
+ if (!empty($option['mutil'])) {
+ $definevar = 'TPL_INIT_TINY_MUTIL_STORE';
+ $function = 'showMutilStoreDialog';
+ }
+ $s = '';
+ if (!defined($definevar)) {
+ $option_json = json_encode($option);
+ $s = '
+ ';
+ define($definevar, true);
+ }
+
+ $s .= '
+
+
+
+
+
+
';
+ if (empty($option['mutil'])) {
+ $s .= '
+ ';
+ } else {
+ $s .= '';
+ }
+ return $s;
+}
+
+function tpl_form_field_mutil_store($name, $value = '') {
+ return tpl_form_field_store($name, $value, $option = array('mutil' => 1));
+}
+
+function tpl_form_field_goods($name, $value = '', $option = array('mutil' => 0, 'sid' => 0, 'ignore' => array())) {
+ global $_W;
+ if (!isset($option['mutil'])) {
+ $option['mutil'] = 0;
+ }
+ if (empty($default)) {
+ $default = './resource/images/nopic.jpg';
+ }
+ if (!is_array($value)) {
+ $value = intval($value);
+ $value = array($value);
+ }
+ $condition = ' where uniacid = :uniacid';
+ $params = array(':uniacid' => $_W['uniacid']);
+ $value_ids = implode(',', $value);
+ $condition .= " and id in ({$value_ids})";
+ $goods_temp = pdo_fetchall('select id, title, thumb from ' . tablename('tiny_wmall_goods') . "{$condition}", $params);
+ $goods = array();
+ if (!empty($goods_temp)) {
+ foreach ($goods_temp as $row) {
+ $row['thumb'] = tomedia($row['thumb']);
+ $goods[] = $row;
+ }
+ }
+
+ $definevar = 'TPL_INIT_TINY_GOODS';
+ $function = 'showGoodsDialog';
+ if (!empty($option['mutil'])) {
+ $definevar = 'TPL_INIT_TINY_MUTIL_GOODS';
+ $function = 'showMutilGoodsDialog';
+ }
+ $s = '';
+ if (!defined($definevar)) {
+ $option_json = json_encode($option);
+ $s = '
+ ';
+ define($definevar, true);
+ }
+
+ $s .= '
+
+
+
+
+
+
';
+ if (empty($option['mutil'])) {
+ $s .= '
+ ';
+ } else {
+ $s .= '';
+ }
+ return $s;
+}
+
+function tpl_form_field_mutil_goods($name, $value = '', $option = array('sid' => 0, 'ignore' => array())) {
+ if (!isset($option['mutil'])) {
+ $option['mutil'] = 1;
+ }
+ return tpl_form_field_goods($name, $value, $option);
+}
+
+function tpl_form_filter_hidden($ctrls) {
+ global $_W;
+ if (is_agent()) {
+ $html = '';
+ } else {
+ $html = '
+
+
+
+ ';
+ }
+
+ [$p, $ac, $do] = explode('/', $ctrls);
+ if (!empty($p)) {
+ $html .= '';
+ if (!empty($ac)) {
+ $html .= '';
+ if (!empty($do)) {
+ $html .= '';
+ }
+ }
+ }
+ return $html;
+}
+
+function tpl_form_field_tiny_category_2level($name, $parents, $children, $parentid, $childid) {
+ $html = '
+ ';
+ if (!defined('TPL_INIT_TINY_CATEGORY')) {
+ $html .= '
+
+ ';
+ define('TPL_INIT_TINY_CATEGORY', true);
+ }
+
+ $html .=
+ '
+
+
+
+
+
+
+
+ ';
+ return $html;
+}
+
+function tpl_form_field_editor($params = array(), $callback = NULL) {
+ $html = '';
+ $html .= '';
+ $html .= '' . $params['value'] . '';
+ $html .= '修改';
+ $html .= '';
+ $html .= '';
+ $html .= '
+
+
+
+
+
+
+
+
+ ';
+
+ $html .= '';
+ return $html;
+
+}
+/**
+ * Comment: 状态改变控制器
+ * Author: zzw
+ * Date: 2019/9/18 14:30
+ * @param string $url 状态改变后提交的地址
+ * @param string $val 当前的值
+ * @param int $open 开启的值
+ * @param int $close 关闭的值
+ * @return string
+ */
+function tpl_change_status($url, $val, $open = 1, $close = 0) {
+ $url = web_url($url);
+ #1、生成基础内容
+ if ($val == $open) $html = '';
+ else $html = '';
+ return $html;
+}
+/**
+ * Comment: 用户选择器
+ * Author: zzw
+ * Date: 2019/11/29 18:17
+ * @param string|int $mid 用户id名称
+ * @param string|int $midVal 用户id值
+ * @return string
+ */
+function tpl_select_user($mid, $midVal,$title = '选择用户') {
+ $default = './resource/images/nopic.jpg';
+ if(!empty($midVal)) $member = Member::wl_member_get($midVal);
+ $html = '
+
+
+ '.$title.'
+
+ ';
+ return $html;
+}
+/**
+ * Comment: 时间选择器 tpl_form_field_daterange的重构版本
+ * Author: zzw
+ * Date: 2020/4/9 11:53
+ * @param $name
+ * @param array $value
+ * @param bool $time
+ * @return string
+ */
+function tpl_select_time_info($name, $value = array(), $time = false) {
+ $s = '
+
+ ';
+ define('TPL_INIT_DATERANGE_DATE' , true);
+ if ($value['starttime'] !== false && $value['start'] !== false) {
+ if($value['start']) {
+ $value['starttime'] = empty($time) ? date('Y-m-d',strtotime($value['start'])) : date('Y-m-d H:i',strtotime($value['start']));
+ }
+ $value['starttime'] = empty($value['starttime']) ? (empty($time) ? date('Y-m-d') : date('Y-m-d H:i') ): $value['starttime'];
+ } else {
+ $value['starttime'] = '请选择';
+ }
+
+ if ($value['endtime'] !== false && $value['end'] !== false) {
+ if($value['end']) {
+ $value['endtime'] = empty($time) ? date('Y-m-d',strtotime($value['end'])) : date('Y-m-d H:i',strtotime($value['end']));
+ }
+ $value['endtime'] = empty($value['endtime']) ? $value['starttime'] : $value['endtime'];
+ } else {
+ $value['endtime'] = '请选择';
+ }
+
+
+ $s .= '
+
+
+
+ ';
+ return $s;
+}
+/**
+ * Comment: 图片选择模型 —— 单选
+ * Author: zzw
+ * Date: 2020/8/31 18:50
+ * @param $name
+ * @param string $default_img
+ * @return string
+ */
+function attachment_select($name,$default_img = '',$ordernum = 0){
+ //名称处理
+ $idName = str_replace(['[',']'],'_',$name);
+ $http_url = $default_img;
+ if($http_url) $http_url = tomedia($http_url);
+ //生成html信息
+ $html = '
+
+
+
+
+
+ ';
+
+ return $html;
+}
+
+function attachment_select2W($name,$default_img = '',$ordernum = 0){
+ //名称处理
+ $idName = str_replace(['[',']'],'_',$name);
+ $http_url = $default_img;
+ if($http_url) $http_url = tomedia($http_url);
+ //生成html信息
+ $html = '
+
+
+
+
+
+ ';
+
+ return $html;
+}
+
+/**
+ * Comment: 图片选择模型 —— 多选
+ * Author: zzw
+ * Date: 2020/8/31 19:35
+ * @param $name
+ * @param string $default_img
+ * @return string
+ */
+function attachment_select_multi($name,$default_img = ''){
+ //名称处理
+ $idName = str_replace(['[',']'],'_',$name);
+ //默认图片信息处理
+ $html = '';
+ if(is_array($default_img) && count($default_img) > 0){
+ foreach($default_img as $attKey => $attVal){
+ //图片信息处理
+ $httpUrl = tomedia($attVal);
+ //生成html信息
+ $html .= '
+

+
+
×
+
';
+ }
+ }
+ //生成html信息
+ $html = '
+
+
+
+
+
+ '.$html.'
';
+
+
+ return $html;
+}
+/**
+ * Comment: 生成百度富文本编辑器
+ * Author: zzw
+ * Date: 2020/9/3 14:38
+ * @param $name
+ * @param string $value
+ * @return string
+ */
+function tpl_diy_editor_create($name,$value = ''){
+ $html = '';
+
+ return $html;
+}
+/**
+ * Comment: 地图定位
+ * Author: zzw
+ * Date: 2020/9/8 16:02
+ * @param $addressName
+ * @param $lngName
+ * @param $latName
+ * @param $address
+ * @param $lng
+ * @param $lat
+ * @return string
+ */
+function tpl_select_address($addressName,$lngName,$latName,$address,$lng,$lat){
+ //名称处理
+ $idAddressName = str_replace(['[',']'],'_',$addressName);
+ $idLngName = str_replace(['[',']'],'_',$lngName);
+ $idLatName = str_replace(['[',']'],'_',$latName);
+ //生成html信息
+ $html = '
+
+
+
+ 地图定位
+
';
+
+ return $html;
+}
+/**
+ * Comment: 红包选择器
+ * Author: zzw
+ * Date: 2020/9/14 15:22
+ * @param string $name
+ * @param string $id
+ * @return string
+ */
+function tpl_select_redPack($name = '',$id = ''){
+ $html = '
+
+
+
+
+
+
';
+ return $html;
+}
+/**
+ * Comment: 音频选择器
+ * Author: zzw
+ * Date: 2021/2/1 10:12
+ * @param $name
+ * @param string $defaultUrl
+ * @return string
+ */
+function attachment_select_audio($name,$defaultUrl = ''){
+ //名称处理
+ $idName = str_replace(['[',']'],'_',$name);
+ //生成html信息
+ $html = '
+
+
+
+
+
';
+ return $html;
+}
+/**
+ * Comment: 视频选择器
+ * Author: zzw
+ * Date: 2021/2/26 17:39
+ * @param $name
+ * @param string $defaultUrl
+ * @return string
+ */
+function attachment_select_video($name,$defaultUrl = ''){
+ //名称处理
+ $idName = str_replace(['[',']'],'_',$name);
+ $http_url = $defaultUrl;
+ if($http_url) $http_url = tomedia($http_url);
+ //生成html信息
+ $html = '
+
+
+
+
+
+
+
+ ×
+
';
+
+ return $html;
+}
+
+
diff --git a/addons/weliam_smartcity/core/table/agentarea.table.php b/addons/weliam_smartcity/core/table/agentarea.table.php
new file mode 100644
index 0000000..8e098d9
--- /dev/null
+++ b/addons/weliam_smartcity/core/table/agentarea.table.php
@@ -0,0 +1,38 @@
+classs('table');
+
+class AgentareaTable extends We7Table {
+
+ protected $tableName = 'wlmerchant_oparea';
+
+ public function getAreaList() {
+ return $this->query->from($this->tableName)->orderby('sort', 'DESC')->getall();
+ }
+
+ public function selectFields($select) {
+ $this->query->select($select);
+ return $this;
+ }
+
+ public function searchWithLevel($level) {
+ $this->query->where('level', $level);
+ return $this;
+ }
+
+ public function searchWithHot() {
+ $this->query->where('ishot', 1);
+ return $this;
+ }
+
+ public function searchWithOpen() {
+ $this->query->where('status', 1);
+ return $this;
+ }
+
+ public function searchWithUniacid($uniacid) {
+ $this->query->where('uniacid', $uniacid);
+ return $this;
+ }
+
+}
\ No newline at end of file
diff --git a/addons/weliam_smartcity/core/table/area.table.php b/addons/weliam_smartcity/core/table/area.table.php
new file mode 100644
index 0000000..039351a
--- /dev/null
+++ b/addons/weliam_smartcity/core/table/area.table.php
@@ -0,0 +1,45 @@
+classs('table');
+
+class AreaTable extends We7Table {
+
+ protected $area_table = 'wlmerchant_area';
+ protected $oparea_table = 'wlmerchant_oparea';
+
+ public function getAreaList() {
+ return $this->query->from($this->area_table)->getall();
+ }
+
+ public function getAreaById($id) {
+ return $this->query->from($this->area_table)->where('id', $id)->get();
+ }
+
+ public function selectFields($select) {
+ $this->query->select($select);
+ return $this;
+ }
+
+ public function searchWithLevel($level) {
+ $this->query->where('level', $level);
+ return $this;
+ }
+
+ public function searchWithOpen() {
+ $this->query->where('visible', 2);
+ return $this;
+ }
+
+ public function searchWithUniacid($uniacid) {
+ $value = !empty($uniacid) ? [0, $uniacid] : 0;
+ $this->query->where('displayorder', $value);
+ return $this;
+ }
+
+ public function searchWithKeyword($keyword) {
+ if (!empty($keyword)) {
+ $this->query->where('name LIKE', "%{$keyword}%")->whereor('pinyin LIKE', "%{$keyword}%");
+ return $this;
+ }
+ }
+}
\ No newline at end of file
diff --git a/addons/weliam_smartcity/core/table/distribution.table.php b/addons/weliam_smartcity/core/table/distribution.table.php
new file mode 100644
index 0000000..8523699
--- /dev/null
+++ b/addons/weliam_smartcity/core/table/distribution.table.php
@@ -0,0 +1,17 @@
+classs('table');
+
+class DistributionTable extends We7Table {
+
+ protected $distributor_table = 'wlmerchant_distributor';
+
+ public function getDisNumById($id, $level = 1) {
+ if ($level == 1) {
+
+ }
+ $onenum = pdo_fetchcolumn('SELECT count(id) FROM ' . tablename('wlmerchant_distributor') . " WHERE leadid = {$_W['wlmember']['id']}");
+ $twonum = pdo_fetchcolumn('SELECT count(id) FROM ' . tablename('wlmerchant_distributor') . " WHERE leadid in (select mid from " . tablename('wlmerchant_distributor') . " where `leadid` = {$_W['wlmember']['id']})");
+ return $this->query->from($this->area_table)->where('id', $id)->get();
+ }
+}
\ No newline at end of file