Beispiel #1
0
 function show()
 {
     //输出头内容
     Header("Content-type:image/png");
     //建立图象
     $image = Imagecreatefromjpeg($this->背景图片);
     //加入汉字
     $授权软件使用单位 = $this->createText($this->授权软件使用单位);
     imagettftext($image, 30, $this->angle, 235, 248, $white, $this->font, $授权软件使用单位);
     //加入汉字
     $授权软件名称 = $this->createText($this->授权软件名称);
     imagettftext($image, 24, $this->angle, 305, 418, $white, $this->font, $授权软件名称);
     //加入汉字
     $授权软件版本 = $this->createText($this->授权软件版本);
     imagettftext($image, 24, $this->angle, 305, 460, $white, $this->font, $授权软件版本);
     //加入汉字
     $内部软件版本 = $this->createText($this->内部软件版本);
     imagettftext($image, 24, $this->angle, 305, 505, $white, $this->font, $内部软件版本);
     //加入汉字
     $软件机器码 = $this->createText($this->软件机器码);
     imagettftext($image, 24, $this->angle, 305, 550, $white, $this->font, $软件机器码);
     //加入汉字
     $软件注册码 = $this->createText($this->软件注册码);
     imagettftext($image, 24, $this->angle, 305, 595, $white, $this->font, $软件注册码);
     //加入汉字
     $授权使用域名 = $this->createText($this->授权使用域名);
     imagettftext($image, 24, $this->angle, 305, 635, $white, $this->font, $授权使用域名);
     //加入汉字
     $授权使用学校 = $this->createText($this->授权使用学校);
     imagettftext($image, 24, $this->angle, 305, 680, $white, $this->font, $授权使用学校);
     //加入汉字
     $授权时间 = $this->createText($this->授权时间);
     imagettftext($image, 22, $this->angle, 235, 875, $white, $this->font, $授权时间);
     imagejpeg($image);
     ImageDestroy($image);
 }
Beispiel #2
0
function Map()
{
    global $debug, $link, $locsep, $vallbl, $sholbl, $sumlbl, $imas, $fmt, $lit, $fsz, $pos;
    global $xm, $ym, $xo, $yo, $rot, $cro, $bro, $len, $lsf, $mde, $in, $op, $st, $co, $lev, $loo, $loa, $loi, $ipi, $ifa;
    global $mapbg, $mapitems, $maplinks, $mapinfo, $imgmap, $reg, $cty, $bld, $flr, $dev, $nod, $nlnk, $jnod, $cud;
    $rlnk = array();
    $clnk = array();
    $blnk = array();
    $dlnk = array();
    $acol = '';
    $join = '';
    if ($pos == 'a') {
        $acol = ',status';
        $join .= 'LEFT JOIN monitoring USING (device) ';
    }
    if (in_array('vlanid', $in) or in_array('vlanname', $in)) {
        $join .= 'LEFT JOIN vlans USING (device) ';
    }
    if (in_array('mac', $in) or in_array('nodip', $in) or in_array('name', $in) or in_array('oui', $in)) {
        $join .= 'LEFT JOIN nodes USING (device) ';
    }
    if (in_array('ifip', $in) or in_array('vrfname', $in)) {
        $join .= 'LEFT JOIN networks USING (device) ';
    }
    if (in_array('neighbor', $in)) {
        $join .= 'LEFT JOIN links USING (device) ';
    }
    $query .= GenQuery('devices', 's', "distinct device,devip,type,location,contact,devmode,icon,cpu,temp,devopts,size,stack{$acol},snmpversion", '', '', $in, $op, $st, $co, $join);
    # Postgres requires ordercolumn (snmpversion)!
    if ($lev < 5) {
        if (strpos($query, 'WHERE')) {
            $query .= ' AND snmpversion != 0';
        } else {
            $query .= ' WHERE snmpversion != 0';
        }
    }
    $query .= ' order by snmpversion desc';
    $res = DbQuery($query, $link);
    if ($res) {
        while ($d = DbFetchRow($res)) {
            $l = explode($locsep, $d[3]);
            $reg[$l[0]]['ndv']++;
            $cty[$l[0]][$l[1]]['ndv']++;
            $dev[$d[0]]['reg'] = $l[0];
            if ($d[6] and $ipi) {
                # Get IP info for interfaces on snmpdevs
                $nquery = GenQuery('networks', 's', 'ifname,ifip,ifip6,vrfname', '', '', array('device'), array('='), array($d[0]));
                $nres = DbQuery($nquery, $link);
                if ($nres) {
                    while ($n = DbFetchRow($nres)) {
                        if ($n[1]) {
                            $dev[$d[0]]['ifip'][$n[0]] .= " " . long2ip($n[1]) . ($n[3] ? " ({$n['3']})" : "");
                        } else {
                            $dev[$d[0]]['ifip'][$n[0]] .= " " . DbIPv6($n[2]) . ($n[3] ? " ({$n['3']})" : "");
                        }
                    }
                } else {
                    echo DbError($nlink);
                }
                DbFreeResult($nres);
            }
            if ($d[6] and ($ifa or $lit == 'l')) {
                # Get IF alias TODO use iftype to determine links?
                $nquery = GenQuery('interfaces', 's', 'ifname,ifidx,iftype,alias,dinoct,doutoct', '', '', array('device'), array('='), array($d[0]));
                $nres = DbQuery($nquery, $link);
                if ($nres) {
                    while ($n = DbFetchRow($nres)) {
                        $dev[$d[0]]['ifty'][$n[0]] = $n[1];
                        $dev[$d[0]]['ifix'][$n[0]] = $n[2];
                        $dev[$d[0]]['ifal'][$n[0]] = $n[3];
                        $dev[$d[0]]['ifin'][$n[0]] = $n[4];
                        $dev[$d[0]]['ifout'][$n[0]] = $n[5];
                    }
                } else {
                    echo DbError($nlink);
                }
                DbFreeResult($nres);
            }
            if ($lev > 1) {
                $dev[$d[0]]['cty'] = $l[1];
            }
            if ($lev > 2) {
                $bld[$l[0]][$l[1]][$l[2]]['ndv']++;
                $dev[$d[0]]['bld'] = $l[2];
            }
            if ($lev > 3) {
                if ($mde == "r") {
                    $flr[$l[0]][$l[1]][$l[2]][$d[0]]['ndv']++;
                } else {
                    $flr[$l[0]][$l[1]][$l[2]][$l[3]][] = $d[0];
                }
                $dev[$d[0]]['ip'] = long2ip($d[1]);
                $dev[$d[0]]['rom'] = $l[4];
                $dev[$d[0]]['rak'] = $l[5] ? $l[5] : "";
                $dev[$d[0]]['typ'] = $d[2];
                $dev[$d[0]]['con'] = $d[4];
                $dev[$d[0]]['mod'] = Devmode($d[5]);
                $dev[$d[0]]['ico'] = $d[6];
                if (substr($d[9], 1, 1) == "C") {
                    $dev[$d[0]]['cpu'] = $d[7];
                } else {
                    $dev[$d[0]]['cpu'] = "-";
                }
                $dev[$d[0]]['tmp'] = $d[8];
                if ($d[8] != 0) {
                    $dev[$d[0]]['tlb'] = $_SESSION['far'] ? intval($dev[$d[0]]['tmp'] * 1.8 + 32) . "F" : $dev[$d[0]]['tmp'] . "C";
                } else {
                    $dev[$d[0]]['tlb'] = "-";
                }
                $dev[$d[0]]['stk'] = $d[11] > 1 ? $d[11] : 1;
                $dev[$d[0]]['siz'] = $d[10] * $dev[$d[0]]['stk'];
                if ($pos == 'a') {
                    $dev[$d[0]]['sta'] = $d[12];
                }
            }
        }
        DbFreeResult($res);
    } else {
        echo DbError($link);
    }
    # Precalculate Links
    foreach (array_keys($dev) as $d) {
        # Devs sorted by snmpversion creates links with stats first!
        $lquery = GenQuery('links', 's', '*', '', '', array('device'), array('='), array($d));
        $lres = DbQuery($lquery, $link);
        while ($k = DbFetchRow($lres)) {
            if (isset($dev[$k[3]]['reg'])) {
                # Only use, if we have complete devs
                $rlquery = GenQuery('links', 's', '*', '', '', array('device', 'neighbor'), array('=', '='), array($k[3], $k[1]), array('AND'));
                $rlres = DbQuery($rlquery, $link);
                $rlnum = DbNumRows($rlres);
                if ($debug) {
                    echo "<div class=\"textpad good\">LINK:{$k['1']} to {$k['3']} with BW of {$k['5']}</div>\n";
                }
                if (array_key_exists("{$k['3']};;{$k['1']}", $dlnk)) {
                    $dlnk["{$k['3']};;{$k['1']}"]['rbw'] += $k[5];
                    $dlnk["{$k['3']};;{$k['1']}"]['rtr'] += $dev[$k[3]]['ifin'][$k[4]];
                    $dlnk["{$k['3']};;{$k['1']}"]['rif'][] = "{$k['1']};;{$k['2']}";
                    $dlnk["{$k['3']};;{$k['1']}"]['rty']["{$k['6']}:" . date('j.M', $k[10])]++;
                } elseif (isset($dev[$k[3]]['ico'])) {
                    if (!$rlnum) {
                        if ($debug) {
                            echo "<div class=\"textpad alrm\">LNK: Fixing missing link from {$k['3']} to {$k['1']}</div>\n";
                        }
                        $dlnk["{$k['1']};;{$k['3']}"]['rbw'] += $k[5];
                        $dlnk["{$k['1']};;{$k['3']}"]['rtr'] += $dev[$k[1]]['ifin'][$k[2]];
                        $dlnk["{$k['1']};;{$k['3']}"]['rif'][] = "{$k['3']};;{$k['4']}";
                        $dlnk["{$k['1']};;{$k['3']}"]['fty']["{$k['6']}:" . date('j.M', $k[10])]++;
                    }
                    $dlnk["{$k['1']};;{$k['3']}"]['fbw'] += $k[5];
                    $dlnk["{$k['1']};;{$k['3']}"]['ftr'] += $dev[$k[1]]['ifout'][$k[2]];
                    $dlnk["{$k['1']};;{$k['3']}"]['fif'][] = "{$k['1']};;{$k['2']}";
                    $dlnk["{$k['1']};;{$k['3']}"]['fty']["{$k['6']}:" . date('j.M', $k[10])]++;
                }
                $ra = $dev[$k[1]]['reg'];
                $rb = $dev[$k[3]]['reg'];
                $ca = $dev[$k[1]]['cty'];
                $cb = $dev[$k[3]]['cty'];
                $ba = $dev[$k[1]]['bld'];
                $bb = $dev[$k[3]]['bld'];
                if ($mde != "f" and $ra != $rb) {
                    $reg[$ra]['nlk']++;
                    $reg[$ra]['alk'][$rb]++;
                    # Needed for arranging
                    if (array_key_exists("{$rb};;{$ra}", $rlnk)) {
                        # Reverse link exists?
                        $rlnk["{$rb};;{$ra}"]['rbw'] += $k[5];
                        $rlnk["{$rb};;{$ra}"]['rtr'] += $dev[$k[1]]['ifin'][$k[2]];
                        $rlnk["{$rb};;{$ra}"]['rif'][] = "{$k['1']};;{$k['2']}";
                        $rlnk["{$rb};;{$ra}"]['rty']["{$k['6']}:" . date('j.M', $k[10])]++;
                    } else {
                        if (!$rlnum) {
                            $reg[$rb]['nlk']++;
                            $reg[$rb]['alk'][$rb]++;
                            $rlnk["{$ra};;{$rb}"]['rbw'] += $k[5];
                            $rlnk["{$ra};;{$rb}"]['rtr'] += $dev[$k[1]]['ifin'][$k[2]];
                            $rlnk["{$ra};;{$rb}"]['rif'][] = "{$k['3']};;{$k['4']}";
                            $rlnk["{$ra};;{$rb}"]['rty']["{$k['6']}:" . date('j.M', $k[10])]++;
                        }
                        $rlnk["{$ra};;{$rb}"]['fbw'] += $k[5];
                        $rlnk["{$ra};;{$rb}"]['ftr'] += $dev[$k[1]]['ifout'][$k[2]];
                        $rlnk["{$ra};;{$rb}"]['fif'][] = "{$k['1']};;{$k['2']}";
                        $rlnk["{$ra};;{$rb}"]['fty']["{$k['6']}:" . date('j.M', $k[10])]++;
                    }
                }
                if ($mde != "f" and $lev > 1) {
                    if ("{$ra};;{$ca}" != "{$rb};;{$cb}") {
                        $cty[$ra][$ca]['nlk']++;
                        if ($ra == $rb) {
                            $cty[$ra][$ca]['alk'][$cb]++;
                        }
                        #TODO test whether this improves arranging!
                        if (array_key_exists("{$rb};;{$cb};;{$ra};;{$ca}", $clnk)) {
                            $clnk["{$rb};;{$cb};;{$ra};;{$ca}"]['rbw'] += $k[5];
                            $clnk["{$rb};;{$cb};;{$ra};;{$ca}"]['rtr'] += $dev[$k[1]]['ifin'][$k[2]];
                            $clnk["{$rb};;{$cb};;{$ra};;{$ca}"]['rif'][] = "{$k['1']};;{$k['2']}";
                            $clnk["{$rb};;{$cb};;{$ra};;{$ca}"]['rty']["{$k['6']}:" . date('j.M', $k[10])]++;
                        } else {
                            if (!$rlnum) {
                                $cty[$rb][$cb]['nlk']++;
                                if ($ra == $rb) {
                                    $cty[$rb][$cb]['alk'][$ca]++;
                                }
                                $clnk["{$ra};;{$ca};;{$rb};;{$cb}"]['rbw'] += $k[5];
                                $clnk["{$ra};;{$ca};;{$rb};;{$cb}"]['rtr'] += $dev[$k[1]]['ifin'][$k[2]];
                                $clnk["{$ra};;{$ca};;{$rb};;{$cb}"]['rif'][] = "{$k['3']};;{$k['4']}";
                                $clnk["{$ra};;{$ca};;{$rb};;{$cb}"]['rty']["{$k['6']}:" . date('j.M', $k[10])]++;
                            }
                            $clnk["{$ra};;{$ca};;{$rb};;{$cb}"]['fbw'] += $k[5];
                            $clnk["{$ra};;{$ca};;{$rb};;{$cb}"]['ftr'] += $dev[$k[1]]['ifout'][$k[2]];
                            $clnk["{$ra};;{$ca};;{$rb};;{$cb}"]['fif'][] = "{$k['1']};;{$k['2']}";
                            $clnk["{$ra};;{$ca};;{$rb};;{$cb}"]['fty']["{$k['6']}:" . date('j.M', $k[10])]++;
                        }
                    }
                }
                if ($mde != "f" and $lev > 2) {
                    if ("{$ra};;{$ca};;{$ba}" != "{$rb};;{$cb};;{$bb}") {
                        $bld[$ra][$ca][$ba]['nlk']++;
                        if ("{$ra};;{$ca}" == "{$rb};;{$cb}") {
                            $bld[$ra][$ca][$ba]['alk'][$bb]++;
                        }
                        if (array_key_exists("{$rb};;{$cb};;{$bb};;{$ra};;{$ca};;{$ba}", $blnk)) {
                            $blnk["{$rb};;{$cb};;{$bb};;{$ra};;{$ca};;{$ba}"]['rbw'] += $k[5];
                            $blnk["{$rb};;{$cb};;{$bb};;{$ra};;{$ca};;{$ba}"]['rtr'] += $dev[$k[1]]['ifin'][$k[2]];
                            $blnk["{$rb};;{$cb};;{$bb};;{$ra};;{$ca};;{$ba}"]['rif'][] = "{$k['1']};;{$k['2']}";
                            $blnk["{$rb};;{$cb};;{$bb};;{$ra};;{$ca};;{$ba}"]['rty']["{$k['6']}:" . date('j.M', $k[10])]++;
                        } else {
                            if (!$rlnum) {
                                $bld[$rb][$cb][$bb]['nlk']++;
                                if ("{$ra};;{$ca}" == "{$rb};;{$cb}") {
                                    $bld[$rb][$cb][$bb]['alk'][$ba]++;
                                }
                                $blnk["{$ra};;{$ca};;{$ba};;{$rb};;{$cb};;{$bb}"]['rbw'] += $k[5];
                                $blnk["{$ra};;{$ca};;{$ba};;{$rb};;{$cb};;{$bb}"]['rtr'] += $dev[$k[1]]['ifin'][$k[2]];
                                $blnk["{$ra};;{$ca};;{$ba};;{$rb};;{$cb};;{$bb}"]['rif'][] = "{$k['3']};;{$k['4']}";
                                $blnk["{$ra};;{$ca};;{$ba};;{$rb};;{$cb};;{$bb}"]['rty']["{$k['6']}:" . date('j.M', $k[10])]++;
                            }
                            $blnk["{$ra};;{$ca};;{$ba};;{$rb};;{$cb};;{$bb}"]['fbw'] += $k[5];
                            $blnk["{$ra};;{$ca};;{$ba};;{$rb};;{$cb};;{$bb}"]['ftr'] += $dev[$k[1]]['ifout'][$k[2]];
                            $blnk["{$ra};;{$ca};;{$ba};;{$rb};;{$cb};;{$bb}"]['fif'][] = "{$k['1']};;{$k['2']}";
                            $blnk["{$ra};;{$ca};;{$ba};;{$rb};;{$cb};;{$bb}"]['fty']["{$k['6']}:" . date('j.M', $k[10])]++;
                        }
                    }
                }
                if ($lev > 3) {
                    $dev[$k[1]]['nlk']++;
                    # Count devlinks for flatmode
                    $dev[$k[1]]['alk'][$k[3]]++;
                    # Needed for arranging
                    #if ($mde == "r") {# TODO find arrange method for building rings (only links within bld matter!)
                    #	$flr[$l[0]][$l[1]][$l[2]][$k[1]]['alk'][$k[3]]++;
                    #}
                    if (!$rlnum) {
                        $dev[$k[3]]['nlk']++;
                        $dev[$k[3]]['alk'][$k[1]]++;
                    }
                }
            }
        }
        DbFreeResult($lres);
    }
    $rk = array_keys($reg);
    $nr = count($rk);
    # Draw Layout
    $cud = 0;
    if ($mde == "f") {
        $fstnod = 1;
        $nd = count(array_keys($dev));
        foreach (Arrange($dev) as $dv) {
            $jdev[$dv] = $cud;
            list($dev[$dv]['x'], $dev[$dv]['y']) = CircleCoords(intval($xm / 2 + $xo), intval($ym / 2 - $yo), $cud, $nd, $dev[$dv]['nlk'], $len, $rot);
            $mapitems .= DrawItem($dev[$dv]['x'], $dev[$dv]['y'], '0', $dv, 'd');
            if ($lev == 6) {
                DrawNodes($dv);
            }
            $imgmap .= "<area href=\"Devices-Status.php?dev=" . urlencode($dv) . "\" coords=\"" . ($dev[$dv]['x'] - $imas) . "," . ($dev[$dv]['y'] - $imas) . "," . ($dev[$dv]['x'] + $imas) . "," . ($dev[$dv]['y'] + $imas) . "\" shape=\"rect\" title=\"{$dv} " . $dev[$dv]['ip'] . " CPU:" . $dev[$dv]['cpu'] . "% Temp:" . $dev[$dv]['tlb'] . "\">\n";
            if ($loi) {
                $mapinfo .= DrawLabel($dev[$dv]['x'], $dev[$dv]['y'] - 40, Safelabel($dev[$dv]['cty'] . " " . $dev[$dv]['bld']), 1, "cornflowerblue");
            } elseif ($debug) {
                $mapinfo .= DrawLabel($dev[$dv]['x'], $dev[$dv]['y'] - 40, "Pos{$cud}", 1, "cornflowerblue");
            }
            $cud++;
        }
    } else {
        if ($mde == "g") {
            # Prepare geographic stuff
            if (count($rk) == 1) {
                $ck = array_keys($cty[$rk[0]]);
                if (count($ck) == 1) {
                    $mapbg = TopoMap($rk[0], $ck[0]);
                } else {
                    $mapbg = TopoMap($rk[0]);
                }
            } else {
                $mapbg = TopoMap();
            }
            $bg = Imagecreatefromjpeg("../topo/{$mapbg}");
            $xm = Imagesx($bg);
            $ym = Imagesy($bg);
            Imagedestroy($bg);
        }
        $cur = 0;
        $toc = 0;
        $tob = 0;
        foreach (Arrange($reg) as $r) {
            if ($mde == "g") {
                list($reg[$r]['x'], $reg[$r]['y'], $reg[$r]['cmt']) = DbCoords($r);
            }
            if (!$reg[$r]['x']) {
                list($reg[$r]['x'], $reg[$r]['y']) = CircleCoords(intval($xm / 2 + $xo), intval($ym / 2 - $yo), $cur, $nr, $reg[$r]['nlk'], $len, $rot);
            }
            if ($lev == 1) {
                $jreg[$r] = $cur;
                $mapitems .= DrawItem($reg[$r]['x'], $reg[$r]['y'], $reg[$r]['ndv'], $r, 1);
                $imgmap .= "<area href=\"?lev=2&mde={$mde}&fmt=png&loo={$loo}&loa={$loa}&st[]=" . urlencode(TopoLoc($r)) . "\" coords=\"" . ($reg[$r]['x'] - $imas) . "," . ($reg[$r]['y'] - $imas) . "," . ($reg[$r]['x'] + $imas) . "," . ($reg[$r]['y'] + $imas) . "\" shape=\"rect\" title=\"{$sholbl}\">\n";
            } else {
                if ($loi) {
                    if (count($cty[$r]) > 1) {
                        $mapinfo .= DrawItem($reg[$r]['x'], $reg[$r]['y'], '0', $r . " " . $reg[$r]['cmt'], 'ri');
                    } else {
                        $mapinfo .= DrawLabel($reg[$r]['x'], $reg[$r]['y'] - 42, Safelabel($r), 1, "cornflowerblue");
                    }
                }
                $cuc = 0;
                $nc = count(array_keys($cty[$r]));
                foreach (Arrange($cty[$r]) as $c) {
                    if ($mde == "g") {
                        list($cty[$r][$c]['x'], $cty[$r][$c]['y'], $cty[$r][$c]['cmt']) = DbCoords($r, $c);
                    }
                    if (!$cty[$r][$c]['x']) {
                        list($cty[$r][$c]['x'], $cty[$r][$c]['y']) = CircleCoords($reg[$r]['x'], $reg[$r]['y'], $cuc, $nc, $cty[$r][$c]['nlk'], $len * 10 / $lsf, $cro);
                    }
                    if ($lev == 2) {
                        $jcty["{$r};;{$c}"] = $toc;
                        $mapitems .= DrawItem($cty[$r][$c]['x'], $cty[$r][$c]['y'], $cty[$r][$c]['ndv'], $c, 2);
                        $imgmap .= "<area href=\"?lev=3&mde={$mde}&fmt=png&loo={$loo}&loa={$loa}&st[]=" . urlencode(TopoLoc($r, $c)) . "\" coords=\"" . ($cty[$r][$c]['x'] - $imas) . "," . ($cty[$r][$c]['y'] - $imas) . "," . ($cty[$r][$c]['x'] + $imas) . "," . ($cty[$r][$c]['y'] + $imas) . "\" shape=\"rect\" title=\"{$sholbl}\">\n";
                    } else {
                        if ($loi) {
                            if (count($bld[$r][$c]) > 1) {
                                $mapinfo .= DrawItem($cty[$r][$c]['x'], $cty[$r][$c]['y'], '0', $c . " " . $cty[$r][$c]['cmt'], 'ci');
                            } else {
                                $mapinfo .= DrawLabel($cty[$r][$c]['x'], $cty[$r][$c]['y'] - 30, Safelabel($c), 1, "cornflowerblue");
                            }
                        }
                        $cub = 0;
                        $nb = count(array_keys($bld[$r][$c]));
                        foreach (Arrange($bld[$r][$c]) as $b) {
                            if ($mde == "g") {
                                list($bld[$r][$c][$b]['x'], $bld[$r][$c][$b]['y'], $bld[$r][$c][$b]['cmt']) = DbCoords($r, $c, $b);
                            }
                            if (!$bld[$r][$c][$b]['x']) {
                                list($bld[$r][$c][$b]['x'], $bld[$r][$c][$b]['y']) = CircleCoords($cty[$r][$c]['x'], $cty[$r][$c]['y'], $cub, $nb, $bld[$r][$c][$b]['nlk'] * ($mde == "b" ? $cb % 2 + 0.3 : 1), $len / pow($lsf / 10, 2), $bro);
                            }
                            if ($lev == 3) {
                                $jbld["{$r};;{$c};;{$b}"] = $tob;
                                $mapitems .= DrawItem($bld[$r][$c][$b]['x'], $bld[$r][$c][$b]['y'], $bld[$r][$c][$b]['ndv'], $b, 3);
                                $imgmap .= "<area href=\"?lev=4&mde={$mde}&fmt=png&loo={$loo}&loa={$loa}&st[]=" . urlencode(TopoLoc($r, $c, $b)) . "\" coords=\"" . ($bld[$r][$c][$b]['x'] - $imas) . "," . ($bld[$r][$c][$b]['y'] - $imas) . "," . ($bld[$r][$c][$b]['x'] + $imas) . "," . ($bld[$r][$c][$b]['y'] + $imas) . "\" shape=\"rect\" title=\"{$sholbl}\">\n";
                            } elseif ($mde == "b" or $mde == "g") {
                                DrawBuilding($bld[$r][$c][$b]['x'], $bld[$r][$c][$b]['y'], $r, $c, $b);
                            } else {
                                if ($loi) {
                                    if (count($flr[$r][$c][$b]) > 1) {
                                        $mapinfo .= DrawItem($bld[$r][$c][$b]['x'], $bld[$r][$c][$b]['y'], '0', $b . " " . $bld[$r][$c][$b]['cmt'], 'bi');
                                    } else {
                                        $mapinfo .= DrawLabel($bld[$r][$c][$b]['x'], $bld[$r][$c][$b]['y'] - 38, Safelabel($b), 1, "cornflowerblue");
                                    }
                                }
                                $cd = 0;
                                $nd = count(array_keys($flr[$r][$c][$b]));
                                foreach (Arrange($flr[$r][$c][$b]) as $d) {
                                    $jdev[$d] = $cud;
                                    list($dev[$d]['x'], $dev[$d]['y']) = CircleCoords($bld[$r][$c][$b]['x'], $bld[$r][$c][$b]['y'], $cd, $nd, $dev[$d]['nlk'], $fsz, 0, 0);
                                    $mapitems .= DrawItem($dev[$d]['x'], $dev[$d]['y'], '0', $d, 'd');
                                    $imgmap .= "<area href=\"Devices-Status.php?dev=" . urlencode($d) . "\" coords=\"" . ($dev[$d]['x'] - $imas) . "," . ($dev[$d]['y'] - $imas) . "," . ($dev[$d]['x'] + $imas) . "," . ($dev[$d]['y'] + $imas) . "\" shape=\"rect\" title=\"{$dv} " . $dev[$d]['ip'] . " CPU:" . $dev[$d]['cpu'] . "%  T:" . $dev[$d]['tmp'] . "C\">\n";
                                    if ($lev == 6) {
                                        DrawNodes($d);
                                    }
                                    $cd++;
                                    $cud++;
                                }
                            }
                            $cub++;
                            $tob++;
                        }
                    }
                    $cuc++;
                    $toc++;
                }
            }
            $cur++;
        }
    }
    # Draw Links
    if ($lev == 1) {
        $rlkeys = array_keys($rlnk);
        foreach ($rlkeys as $li) {
            $l = explode(';;', $li);
            if ($fmt == "json") {
                $ls = intval(sqrt($rlnk[$li]['fbw'] / 100000000 / $lsf) + 1);
                $maplinks .= "    {\"source\":" . $jreg[$l[0]] . ",\"target\":" . $jreg[$l[1]] . ",\"value\":{$ls}},\n";
            } else {
                DrawLink($reg[$l[0]]['x'], $reg[$l[0]]['y'], $reg[$l[1]]['x'], $reg[$l[1]]['y'], $rlnk[$li]);
            }
        }
    } elseif ($lev == 2) {
        foreach (array_keys($clnk) as $li) {
            $l = explode(';;', $li);
            if ($fmt == "json") {
                $ls = intval(sqrt($clnk[$li]['fbw'] / 100000000 / $lsf) + 1);
                $maplinks .= "    {\"source\":" . $jcty["{$l['0']};;{$l['1']}"] . ",\"target\":" . $jcty["{$l['2']};;{$l['3']}"] . ",\"value\":{$ls}},\n";
            } else {
                DrawLink($cty[$l[0]][$l[1]]['x'], $cty[$l[0]][$l[1]]['y'], $cty[$l[2]][$l[3]]['x'], $cty[$l[2]][$l[3]]['y'], $clnk[$li]);
            }
        }
    } elseif ($lev == 3) {
        foreach (array_keys($blnk) as $li) {
            $l = explode(';;', $li);
            if ($fmt == "json") {
                $ls = intval(sqrt($blnk[$li]['fbw'] / 100000000 / $lsf) + 1);
                $maplinks .= "    {\"source\":" . $jbld["{$l['0']};;{$l['1']};;{$l['2']}"] . ",\"target\":" . $jbld["{$l['3']};;{$l['4']};;{$l['5']}"] . ",\"value\":{$ls}},\n";
            } else {
                DrawLink($bld[$l[0]][$l[1]][$l[2]]['x'], $bld[$l[0]][$l[1]][$l[2]]['y'], $bld[$l[3]][$l[4]][$l[5]]['x'], $bld[$l[3]][$l[4]][$l[5]]['y'], $blnk[$li]);
            }
        }
    } elseif ($lev > 3) {
        foreach (array_keys($dlnk) as $li) {
            $l = explode(';;', $li);
            if ($fmt == "json") {
                $ls = intval(sqrt($dlnk[$li]['fbw'] / 100000000 / $lsf) + 1);
                $ls = $ls ? $ls : 1;
                $maplinks .= "    {\"source\":" . $jdev[$l[0]] . ",\"target\":" . $jdev[$l[1]] . ",\"value\":{$ls}},\n";
            } else {
                DrawLink($dev[$l[0]]['x'], $dev[$l[0]]['y'], $dev[$l[1]]['x'], $dev[$l[1]]['y'], $dlnk[$li]);
            }
        }
        if ($lev == 6) {
            foreach (array_keys($nlnk) as $li) {
                $l = explode(';;', $li);
                if ($fmt == "json") {
                    $ls = intval(sqrt($nlnk[$li]['fbw'] / 100000000 / $lsf) + 1);
                    $ls = $ls ? $ls : 1;
                    $maplinks .= "    {\"source\":" . $jdev[$l[0]] . ",\"target\":" . $jnod["{$l['0']};;{$l['1']}"] . ",\"value\":{$ls}},\n";
                } else {
                    DrawLink($dev[$l[0]]['x'], $dev[$l[0]]['y'], $nod[$l[1]]['x'], $nod[$l[1]]['y'], $nlnk[$li]);
                }
            }
        }
    }
}
    public function responseMsg($db, $user, $base_url)
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $debug = 0;
        if ($_GET['debug'] == 1) {
            $debug = 1;
        }
        if ($_GET['de_base']) {
            $de_base = 1;
        }
        if (!empty($postStr) or $debug == 1) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $msgType = $postObj->MsgType;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            if (empty($keyword)) {
                $keyword = $_GET['keyword'];
            }
            if (empty($fromUsername)) {
                if ($_GET['wxid']) {
                    $fromUsername = $_GET['wxid'];
                } else {
                    $fromUsername = '******';
                }
            }
            $textTpl = "<xml>\n                            <ToUserName><![CDATA[%s]]></ToUserName>\n                            <FromUserName><![CDATA[%s]]></FromUserName>\n                            <CreateTime>%s</CreateTime>\n                            <MsgType><![CDATA[%s]]></MsgType>\n                            <Content><![CDATA[%s]]></Content>\n                            <FuncFlag>0</FuncFlag>\n                            </xml>";
            $time = time();
            $lang = array();
            $setp = $db->getOne("SELECT `setp` FROM `wxch_user` WHERE `wxid` = '{$fromUsername}'");
            if ($setp == 2 or $setp == 3 or $setp == 10) {
                $uname = $db->getOne("SELECT `uname` FROM `wxch_user` WHERE `wxid` = '{$fromUsername}'");
            }
            if (empty($uname)) {
                $postfix = '&wxid=' . $fromUsername;
            } else {
                $ret['wxid'] = $db->getOne("SELECT `wxid` FROM `wxch_user` WHERE `wxid` = '{$fromUsername}'");
                $postfix = '&wxid=' . $ret['wxid'];
            }
            $m_ret = $db->getRow("SELECT * FROM  `wxch_cfg` WHERE `cfg_name` = 'murl'");
            $base_ret = $db->getRow("SELECT * FROM  `wxch_cfg` WHERE `cfg_name` = 'baseurl'");
            $imgpath_ret = $db->getRow("SELECT * FROM  `wxch_cfg` WHERE `cfg_name` = 'imgpath'");
            $plustj_ret = $db->getRow("SELECT * FROM  `wxch_cfg` WHERE `cfg_name` = 'plustj'");
            $cxbd = $db->getOne("SELECT `cfg_value` FROM `wxch_cfg` WHERE `cfg_name` = 'cxbd'");
            $oauth_state = $db->getOne("SELECT `cfg_value` FROM `wxch_cfg` WHERE `cfg_name` = 'oauth'");
            $goods_is_ret = $db->getOne("SELECT `cfg_value` FROM `wxch_cfg` WHERE `cfg_name` = 'goods'");
            $article_url = $db->getOne("SELECT `cfg_value` FROM `wxch_cfg` WHERE `cfg_name` = 'article'");
            $q_name = $db->getOne("SELECT `autoreg_name` FROM `wxch_autoreg` WHERE `autoreg_id` = 1");
            if (empty($q_name)) {
                $q_name = "weixin";
            }
            $affiliate_id = $db->getOne("SELECT `affiliate` FROM `wxch_user` WHERE `wxid` = '{$fromUsername}'");
            if ($affiliate_id >= 1) {
                $affiliate = '&u=' . $affiliate_id;
            }
            if ($goods_is_ret == 'false') {
                $goods_is = ' AND is_delete = 0 AND is_on_sale = 1';
            } else {
                $goods_is = '';
            }
            $plustj = $plustj_ret['cfg_value'];
            $wxch_bd = $db->getOne("SELECT `cfg_value` FROM `wxch_cfg` WHERE `cfg_name` = 'bd'");
            if (empty($base_ret['cfg_value'])) {
                $m_url = $base_url . $m_ret['cfg_value'];
            } else {
                $m_url = $base_ret['cfg_value'] . $m_ret['cfg_value'];
                $base_url = $base_ret['cfg_value'];
            }
            if ($de_base) {
                echo $base_url;
            }
            $img_path = $imgpath_ret['cfg_value'];
            $base_img_path = $base_url;
            if ($img_path == 'local') {
                $img_murl = $db->getOne("SELECT `cfg_value` FROM `wxch_cfg` WHERE `cfg_name` = 'murl'");
                if (empty($img_murl)) {
                    $temp_img_arr = explode('.', $base_ret['cfg_value']);
                    $temp_do = array('http://m', 'http://mobile');
                    if (in_array($temp_img_arr[0], $temp_do)) {
                        $base_img_path = 'http://www.' . $temp_img_arr[1] . '.' . $temp_img_arr[2];
                    }
                }
            }
            if (file_exists('config.php')) {
                include 'config.php';
            }
            $oauth_location = $base_url . 'wechat/oauth/wxch_oauths.php?uri=';
            $thistable = $db->prefix . 'users';
            $ret = $db->getRow("SELECT `user_id` FROM `{$thistable}` WHERE `user_name` ='{$uname}'");
            //甜 心 新增显示会员账号密码
            $user_name = $db->getOne("SELECT `user_name` FROM `{$thistable}` WHERE `wxid` ='{$fromUsername}'");
            $user_password = $db->getOne("SELECT `password_tianxin` FROM `{$thistable}` WHERE `wxid` ='{$fromUsername}'");
            //甜心    新增绑定多用户ID
            if (!empty($ret['user_id'])) {
                $user_id = $ret['user_id'];
            }
            $ret = $db->getRow("SELECT `wxid` FROM `wxch_user` WHERE `wxid` = '{$fromUsername}'");
            if (empty($ret)) {
                if (!empty($fromUsername)) {
                    $db->query("INSERT INTO `wxch_user` (`subscribe`, `wxid` , `dateline`) VALUES ('1','{$fromUsername}','{$time}')");
                }
            } else {
                $db->query("UPDATE  `wxch_user` SET  `subscribe` =  '1',`dateline` = '{$time}' WHERE  `wxch_user`.`wxid` = '{$fromUsername}';");
            }
            $subscribe = 1;
            if ($msgType == 'text') {
                $db->query("INSERT INTO `wxch_message` (`wxid`, `message`, `dateline`) VALUES\n( '{$fromUsername}', '{$keyword}', {$time});");
            }
            $belong = $db->insert_id();
            $thistable = $db->prefix . 'users';
            $ec_pwd = $db->getOne("SELECT `cfg_value` FROM `wxch_cfg` WHERE `cfg_name` = 'userpwd'");
            $autoreg_rand = $db->getOne("SELECT `autoreg_rand` FROM `wxch_autoreg` WHERE `autoreg_id` = 1");
            $s_mima = $this->randomkeys($autoreg_rand);
            $ec_pwd = $ec_pwd . $s_mima;
            $ec_pwd_no = $ec_pwd;
            $ec_pwd = md5($ec_pwd);
            $ret_22 = $db->getRow("SELECT * FROM `{$thistable}` WHERE `wxid` = '{$fromUsername}'");
            if (strlen($ret_22['user_name']) == 28) {
                $sql_del = "UPDATE `{$thistable}` SET `user_rank` = '99',`wxch_bd`='no' WHERE `wxid` ='{$fromUsername}'";
                $db->query($sql_del);
            }
            $zhanghaoinfo = "";
            if (empty($uname)) {
                $wxch_user_name_sql = "SELECT `user_name` FROM `{$thistable}` WHERE `wxch_bd`='ok' AND `wxid` = '{$fromUsername}'";
                $wxch_user_name = $db->getOne($wxch_user_name_sql);
                $wxch_user_wxid_sql = "SELECT `wxid` FROM `{$thistable}` WHERE `wxid`=`user_name` AND `wxid` = '{$fromUsername}'";
                $wxch_user_wxid = $db->getOne($wxch_user_wxid_sql);
                /*甜  心  1  00修复开发*/
                $db->query("UPDATE `wxch_user` SET `setp`= 3,`uname`='{$wxch_user_name}' WHERE `wxid`= '{$fromUsername}';");
                /*甜  心  1  00修复开发*/
                if (empty($wxch_user_wxid)) {
                    if (empty($wxch_user_name)) {
                        //echo "44444";
                        $wxch_nobd_wxid_sql = "SELECT `wxid` FROM `{$thistable}` WHERE `wxch_bd`='no' AND `wxid` = '{$fromUsername}'";
                        $wxch_nobd_wxid = $db->getOne($wxch_nobd_wxid_sql);
                        if (empty($wxch_nobd_wxid)) {
                            if (file_exists('uc_state.php')) {
                                include 'uc_state.php';
                            }
                            if ($uc_state) {
                                $salt = $uc_salt;
                                $uc_pwd = $uc_pwd;
                                $uc_sql = "INSERT INTO {$uc_table} (`username`, `password`, `salt`) VALUES ('{$fromUsername}', '{$uc_pwd}', '{$salt}')";
                                $db->query($uc_sql);
                                $ecs_user_id = $db->insert_id();
                                $uc_username = '******' . $ecs_user_id;
                                $uc_update = "UPDATE {$uc_table}  SET `username` = '{$uc_username}' WHERE `uid` = '{$ecs_user_id}'";
                                $db->query($uc_update);
                                $ecs_password = md5($ecs_password);
                                $wxch_user_sql = "INSERT INTO `{$thistable}` (`user_id`,`user_name`,`password`,`wxid`,`user_rank`,`wxch_bd`) VALUES ('{$ecs_user_id}','{$uc_username}','{$ecs_password}','{$fromUsername}','99','no')";
                                $db->query($wxch_user_sql);
                            } else {
                                $autoreg_state = $db->getOne("SELECT `state` FROM `wxch_autoreg` WHERE `autoreg_id` = 1");
                                if ($autoreg_state) {
                                    $wxch_user_sql = "INSERT INTO `{$thistable}` ( `user_name`,`password`,`wxid`,`user_rank`,`wxch_bd`,`password_tianxin`) VALUES ('{$fromUsername}','{$ec_pwd}','{$fromUsername}','99','no','{$ec_pwd_no}')";
                                    $db->query($wxch_user_sql);
                                    $ecs_user_id = $db->insert_id();
                                    $ecs_user_name = $q_name . $ecs_user_id;
                                    //$ecs_update = " UPDATE `$thistable` SET `user_name` = '$ecs_user_name',`parent_id`='$user_parent_id'  WHERE `user_id` = '$ecs_user_id'";
                                    $ecs_update = " UPDATE `{$thistable}` SET `user_name` = '{$ecs_user_name}'  WHERE `user_id` = '{$ecs_user_id}'";
                                    $db->query($ecs_update);
                                    //注册后默认绑定
                                    $db->query("UPDATE `wxch_user` SET `setp`= 3,`uname`='{$ecs_user_name}' WHERE `wxid`= '{$fromUsername}';");
                                    $db->query("UPDATE  ecs_users SET `wxch_bd`='ok',`wxid`='{$fromUsername}' WHERE `user_name`='{$ecs_user_name}'");
                                    $zhanghaoinfo = "您的账号:" . $ecs_user_name . "密码:" . $ec_pwd_no;
                                } else {
                                    $zhanghaoinfo = "自动注册功能未开启!";
                                }
                            }
                        }
                    }
                } else {
                    $wxch_user_sql = " UPDATE `{$thistable}` SET `user_rank` = '99',`wxch_bd`='no' WHERE `wxid` ='{$fromUsername}'";
                    $db->query($wxch_user_sql);
                }
            }
            $newsTpl = "<xml>\n                         <ToUserName><![CDATA[%s]]></ToUserName>\n                         <FromUserName><![CDATA[%s]]></FromUserName>\n                         <CreateTime>%s</CreateTime>\n                         <MsgType><![CDATA[%s]]></MsgType>\n                         <ArticleCount>%s</ArticleCount>\n                         <Articles>\n                         %s\n                         </Articles>\n                         <FuncFlag>0</FuncFlag>\n                         </xml>";
            $serviceTpl = "<xml>\n                        <ToUserName><![CDATA[%s]]></ToUserName>\n                        <FromUserName><![CDATA[%s]]></FromUserName>\n                        <CreateTime>%s</CreateTime>\n                        <MsgType><![CDATA[%s]]></MsgType>\n                        </xml>";
            $imageTpl = "<xml>\n                            <ToUserName><![CDATA[%s]]></ToUserName>\n                            <FromUserName><![CDATA[%s]]></FromUserName>\n                            <CreateTime>%s</CreateTime>\n                            <MsgType><![CDATA[%s]]></MsgType>\n                            <Image>\n                            <MediaId><![CDATA[%s]]></MediaId>\n                            </Image>\n                            </xml>";
            $voiceTpl = "<xml>\n                            <ToUserName><![CDATA[toUser]]></ToUserName>\n                            <FromUserName><![CDATA[fromUser]]></FromUserName>\n                            <CreateTime>12345678</CreateTime>\n                            <MsgType><![CDATA[voice]]></MsgType>\n                            <Voice>\n                            <MediaId><![CDATA[media_id]]></MediaId>\n                            </Voice>\n                            </xml>";
            $de_test = '123';
            if ($postObj->Event == 'subscribe') {
                if (strlen($postObj->EventKey) == 0) {
                    $ret = $db->getRow("SELECT `type_id` FROM  `wxch_coupon` WHERE `id` = 1");
                    if ($ret['type_id'] >= 1) {
                        $postObj->EventKey = 'gzyhj';
                    } else {
                        $postObj->EventKey = 'subscribe';
                    }
                } else {
                    $qrscene = $postObj->EventKey;
                    $scene_id_arr = explode("qrscene_", $qrscene);
                    $scene_id = $scene_id_arr[1];
                    $db->query("UPDATE `wxch_qr` SET `subscribe`=`subscribe` + 1 WHERE `scene_id`= '{$scene_id}';");
                    $scan_ret = $db->getRow("SELECT * FROM `wxch_qr` WHERE scene_id ={$scene_id}");
                    if ($scene_id >= 1) {
                        $postObj->EventKey = 'affiliate_推荐成功_' . $scene_id;
                    } else {
                        $postObj->EventKey = $scan_ret['function'];
                    }
                }
            } elseif ($postObj->Event == 'unsubscribe') {
                $db->query("UPDATE  `wxch_user` SET  `subscribe` =  '0' WHERE  `wxch_user`.`wxid` = '{$fromUsername}';");
                $subscribe = 0;
            } elseif ($postObj->Event == 'SCAN') {
                $qrscene = $postObj->EventKey;
                $scene_id = $qrscene;
                $update_sql = "UPDATE `wxch_qr` SET `scan`=`scan` + 1 WHERE `scene_id`= '{$scene_id}';";
                $db->query("{$update_sql}");
                $scan_ret = $db->getRow("SELECT * FROM `wxch_qr` WHERE scene_id ={$scene_id}");
                if ($scan_ret['affiliate'] >= 1) {
                    $postObj->EventKey = 'affiliate_推荐成功_' . $scan_ret['affiliate'];
                } else {
                    $postObj->EventKey = $scan_ret['function'];
                }
            }
            if ($wxch_bd == 'step') {
                if ($setp > 0 and $setp < 3) {
                    $msgType = "text";
                    if ($keyword == 'ko' or $keyword == 'KO' or $keyword == 'Ko' or $keyword == '退出') {
                        $db->query("UPDATE `wxch_user` SET `setp`= 0,`uname` = '' WHERE `wxid`= '{$fromUsername}';");
                        $contentStr = "您已退出会员绑定流程,再次绑定输入bd进入绑定流程";
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                        $this->universal($fromUsername, $base_url);
                        echo $resultStr;
                        exit;
                    }
                    if ($setp == 1) {
                        $users_table = $db->prefix . 'users';
                        $ret = $db->getRow("SELECT `user_name` FROM  `{$users_table}` WHERE `user_name` = '{$keyword}'");
                        if (empty($ret)) {
                            $contentStr = '您输入的用户名不存在,检查之后请重新输入,(输入ko退出绑定流程)' . $keyword;
                        } else {
                            $ret = $db->getRow("SELECT `uname` FROM  `wxch_user` WHERE `uname` = '{$keyword}' AND `setp`>=3");
                            if (!empty($ret)) {
                                $contentStr = $keyword . '已经被其他用户绑定了,请绑定其他账号,退出绑定输入 ko';
                                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                                $this->universal($fromUsername, $base_url);
                                echo $resultStr;
                                exit;
                            }
                            $db->query("UPDATE `wxch_user` SET `setp`=`setp`+1 WHERE `wxid`= '{$fromUsername}';");
                            $db->query("UPDATE `wxch_user` SET `uname` = '{$keyword}' WHERE `wxid`= '{$fromUsername}';");
                            $contentStr = '请输入密码';
                        }
                    } elseif ($setp == 2) {
                        $password = $keyword;
                        $verifyLogin = $user->login($uname, $password, '');
                        if (!$verifyLogin) {
                            $contentStr = '您输入的密码不正确,请重新输入,(输入ko退出绑定流程)';
                        } else {
                            $db->query("UPDATE `wxch_user` SET `setp`=`setp` + 1 WHERE `wxid`= '{$fromUsername}';");
                            $contentStr = $uname . ',您的账号已经绑定成功!';
                            $users_table = $db->prefix . 'users';
                            $db->query("UPDATE `{$users_table}` SET `wxch_bd`='ok',`wxid`='{$fromUsername}' WHERE `user_name`= '{$uname}';");
                            //甜心100修复,重新绑定账号后,上下级关系不变。
                            $affiliate = $db->getOne("SELECT `affiliate` FROM  `wxch_user` WHERE `wxid` = '{$fromUsername}'");
                            $users_table = $db->prefix . 'users';
                            $db->query("UPDATE `{$users_table}` SET `parent_id`='{$affiliate}' WHERE `wxid`= '{$fromUsername}';");
                        }
                    }
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->plusPoint($db, $uname, $keyword, $fromUsername);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
            }
            if ($wxch_bd == 'web') {
                $msgType = "text";
                if ($keyword == 'ko' or $keyword == 'KO' or $keyword == 'Ko' or $keyword == '退出') {
                    $db->query("UPDATE `wxch_user` SET `setp`= 0,`uname` = '' WHERE `wxid`= '{$fromUsername}';");
                    $contentStr = "您已退出会员绑定流程,再次绑定输入bd进入绑定流程";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
                $setp = $db->getOne("SELECT `setp` FROM `wxch_user` WHERE `wxid` = '{$fromUsername}'");
                if ($keyword == 'bd') {
                    if ($setp == 0) {
                        $bd_url = '<a href="' . $m_url . 'user_wxch.php?wxid=' . $fromUsername . '">点击绑定会员</a>';
                        $bd_lang = $db->getOne("SELECT `lang_value` FROM `wxch_lang` WHERE `lang_name` = 'bd'");
                        $contentStr = $bd_url . $bd_lang . ',(中途退出绑定,请输入ko退出绑定流程)';
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        $this->plusPoint($db, $uname, $keyword, $fromUsername);
                        $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                        $this->universal($fromUsername, $base_url);
                        echo $resultStr;
                        exit;
                    }
                    if ($setp >= 1 and $setp < 3) {
                        $bd_url = '<a href="' . $m_url . 'user_wxch.php?wxid=' . $fromUsername . '">点击绑定会员</a>';
                        $bd_lang = $db->getOne("SELECT `lang_value` FROM `wxch_lang` WHERE `lang_name` = 'bd'");
                        $contentStr = $bd_url . $bd_lang . ',(中途退出绑定,请输入ko退出绑定流程)';
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        $this->plusPoint($db, $uname, $keyword, $fromUsername);
                        $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                        $this->universal($fromUsername, $base_url);
                        echo $resultStr;
                        exit;
                    }
                }
                if ($setp >= 1 and $setp < 3) {
                    $bd_url = '<a href="' . $m_url . 'user_wxch.php?wxid=' . $fromUsername . '">点击绑定会员</a>';
                    $bd_lang = $db->getOne("SELECT `lang_value` FROM `wxch_lang` WHERE `lang_name` = 'bd'");
                    $contentStr = $bd_url . $bd_lang . ',(中途退出绑定,请输入ko退出绑定流程)';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->plusPoint($db, $uname, $keyword, $fromUsername);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
            }
            if ($setp == 10) {
                if ($keyword == 'ko' or $keyword == 'KO' or $keyword == 'Ko' or $keyword == '退出') {
                    $db->query("UPDATE `wxch_user` SET `setp`= 3 WHERE `wxid`= '{$fromUsername}';");
                    if ($cxbd == 'true') {
                        $contentStr = "您已退出会员绑定流程,再次绑定输入cxbd进入绑定流程";
                    } elseif ($cxbd == 'true') {
                        $contentStr = "您已退出会员绑定流程";
                    }
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
                $password = $keyword;
                //甜心100修改兼容点击菜单直接解除绑定BUG
                if (empty($password)) {
                    $password = $postObj->EventKey;
                }
                //甜心100修改兼容点击菜单直接解除绑定BUG
                $verifyLogin = $user->login($uname, $password, '');
                if (!$verifyLogin) {
                    $contentStr = '您输入的密码不正确,请重新输入,想要退出请输出ko';
                } else {
                    $db->query("UPDATE `wxch_user` SET `setp`=1,`uname` = '' WHERE `wxid`= '{$fromUsername}';");
                    $users_table = $db->prefix . 'users';
                    $contentStr = '已经解除:' . $uname . '账号的绑定' . "\r\n您已经重新进入会员绑定流程,想要退出绑定流程请回复ko或“退出”,继续请输入网站会员昵称";
                    $db->query("UPDATE `{$users_table}` SET `wxch_bd`='no',`wxid`='' WHERE `user_name`= '{$uname}';");
                    $db->query("UPDATE `wxch_user` SET `uname`='' WHERE `uname`= '{$uname}';");
                }
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            }
            if ($postObj->MsgType == 'event') {
                $keyword = $postObj->EventKey;
                $menu_message = 'menu:' . $keyword;
                $db->query("INSERT INTO `wxch_message` (`wxid`, `message`, `dateline`) VALUES\n( '{$fromUsername}', '{$menu_message}', {$time});");
            }
            if ($postObj->MsgType == 'voice') {
                $keyword = $postObj->Recognition;
                $menu_message = 'voice:' . $keyword;
                $db->query("INSERT INTO `wxch_message` (`wxid`, `message`, `dateline`) VALUES\n( '{$fromUsername}', '{$menu_message}', {$time});");
            }
            $wxch_table = 'wxch_msg';
            $wxch_msg = $db->getAll("SELECT * FROM  `{$wxch_table}`");
            foreach ($wxch_msg as $k => $v) {
                $commands[$k] = $v;
            }
            foreach ($commands as $kk => $vv) {
                $temp_msg = explode(" ", $vv['command']);
                if (in_array($keyword, $temp_msg)) {
                    $keyword = $vv['function'];
                }
            }
            $this->getauto($db, $keyword, $textTpl, $newsTpl, $base_url, $m_url, $fromUsername, $toUsername, $time, $article_url);
            if ($keyword == 'debug') {
                $imgsrc = "../qrcode/10.jpg";
                $width = 200;
                $height = 200;
                $time = time();
                $name = $this->resizejpg($imgsrc, $width, $height, $time);
                $imgs = $name;
                $target = '../qrcode/tianxin100.jpg';
                //背景图片
                $target_img = Imagecreatefromjpeg($target);
                $source = Imagecreatefromjpeg($imgs);
                imagecopy($target_img, $source, 16, 543, 0, 0, 200, 200);
                Imagejpeg($target_img, 'qrcode/' . $time . '.jpg');
                $data = dirname(__FILE__) . "\\qrcode\\/" . $time . ".jpg";
                $filedata = array("media" => "@" . $data);
                $this->access_token($db);
                $ret = $db->getRow("SELECT `access_token` FROM `wxch_config`");
                $access_token = $ret['access_token'];
                if (strlen($access_token) >= 64) {
                    $url = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image';
                    $res_json = $this->https_request($url, $filedata);
                    $json = json_decode($res_json);
                }
                $msgType = "image";
                $iipp = $_SERVER["REMOTE_ADDR"];
                $phone_state = $_SERVER['HTTP_USER_AGENT'];
                $contentStr = $json->media_id;
                $resultStr = sprintf($imageTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            }
            if ($keyword == 'kefu') {
                $msgType = "transfer_customer_service";
                $contentStr = '客服转接';
                $resultStr = sprintf($serviceTpl, $fromUsername, $toUsername, $time, $msgType);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            }
            //甜心100修复绑定上下级关系
            $aff_arr = explode('_', $keyword);
            if ($aff_arr[0] == 'affiliate') {
                if (!empty($aff_arr[2])) {
                    //ID有效
                    $aff_query = "SELECT * FROM `ecs_users` WHERE `user_id` = {$aff_arr['2']}";
                    $aff_db = $db->getRow($aff_query);
                    $flagetianxin100 = true;
                    if ($aff_db['wxid'] == $fromUsername) {
                        $flagetianxin100 = false;
                    } else {
                        $flagetianxin100 = true;
                    }
                    //1:上下级关系绑定不能改变
                    $aff_query = "SELECT parent_id FROM `ecs_users` WHERE `wxid` = '{$fromUsername}'";
                    $parent_id = $db->getOne($aff_query);
                    //2:验证上下级关系
                    //找出自己所有的下级
                    $aff_query = "SELECT user_id FROM `ecs_users` WHERE `wxid` = '{$fromUsername}'";
                    $user_id = $db->getOne($aff_query);
                    $sql = "SELECT * FROM  ecs_users  WHERE parent_id = '{$user_id}'";
                    $childinfo = $GLOBALS['db']->GetAll($sql);
                    $flag = true;
                    if (!empty($childinfo)) {
                        $flag = false;
                    } else {
                        $flag = true;
                    }
                    if (empty($parent_id)) {
                        if (!empty($aff_db) && $flag && $flagetianxin100) {
                            //绑定会员账号
                            $ecs_usertable = $db->prefix . 'users';
                            $aff_update = "UPDATE `{$ecs_usertable}` SET `parent_id` = '{$aff_arr['2']}' WHERE `wxid` = '{$fromUsername}';";
                            $db->query($aff_update);
                            //绑定微信账号
                            $wxch_usertable = 'wxch_user';
                            $aff_update = "UPDATE `{$wxch_usertable}` SET `affiliate` = '{$aff_arr['2']}' WHERE `wxid` = '{$fromUsername}';";
                            $db->query($aff_update);
                            //查询上级昵称
                            $qu_wxid = "SELECT wxid FROM `ecs_users` WHERE `user_id` = '{$aff_arr['2']}'";
                            $parent_wxid = $db->getOne($qu_wxid);
                            $qu_name = "SELECT nickname FROM `wxch_user` WHERE `wxid` = '{$parent_wxid}'";
                            $parent_name = $db->getOne($qu_name);
                            //查询自己的昵称
                            $nick_name_sql = "SELECT nickname FROM `wxch_user` WHERE `wxid` = '{$fromUsername}'";
                            $nick_name = $db->getOne($nick_name_sql);
                            //查询网站有多少会员
                            $num_sql = "SELECT COUNT(*) FROM `ecs_users`";
                            $num_user = $db->getOne($num_sql);
                            //查询店铺名字
                            $sql = "SELECT value FROM `ecs_touch_shop_config` " . " WHERE code='shop_name'";
                            $shop_name = $db->getOne($sql);
                            /*甜心100新增扫描关注带提醒*/
                            $up_uid = $aff_arr[2];
                            require ROOT_PATH . 'wxch_share.php';
                            $msgType = "text";
                            $contentStr = $nick_name . "恭喜您由" . $parent_name . "推荐成为" . $shop_name . "的会员!目前已经有【" . $num_user . "】位掌柜!点击左下角“" . $shop_name . "”立即购买成为" . $shop_name . "掌柜,裂变你的代理商,让你每天睡觉都能赚大钱!";
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                            $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                            $this->universal($fromUsername, $base_url);
                            echo $resultStr;
                            exit;
                        } else {
                            $msgType = "text";
                            $contentStr = "错误提示:推荐关系不合法可能情况1:自己不能成为自己的下级2:自己有下级后不能成为别人的下级";
                            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                            $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                            $this->universal($fromUsername, $base_url);
                            echo $resultStr;
                            exit;
                        }
                    } else {
                        //查询上级昵称
                        $qu_wxid = "SELECT wxid FROM `ecs_users` WHERE `user_id` = '{$parent_id}'";
                        $parent_wxid = $db->getOne($qu_wxid);
                        $qu_name = "SELECT nickname FROM `wxch_user` WHERE `wxid` = '{$parent_wxid}'";
                        $parent_name = $db->getOne($qu_name);
                        $msgType = "text";
                        $contentStr = "你已经有上级了哦,您的上级是" . $parent_name;
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                        $this->universal($fromUsername, $base_url);
                        echo $resultStr;
                        exit;
                    }
                }
            }
            if ($keyword == 'bd') {
                if ($setp < 3) {
                    if ($wxch_bd == 'web') {
                        $bd_url = '<a href="' . $m_url . 'user_wxch.php?wxid=' . $fromUsername . '">点击绑定会员</a>';
                        $bd_lang = $db->getOne("SELECT `lang_value` FROM `wxch_lang` WHERE `lang_name` = 'bd'");
                        $contentStr = $bd_url . $bd_lang . '';
                        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                        $this->plusPoint($db, $uname, $keyword, $fromUsername);
                        $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                        $this->universal($fromUsername, $base_url);
                        echo $resultStr;
                        exit;
                    }
                    $contentStr = '您已进入会员绑定流程,想要退出绑定流程请回复ko或“退出”,继续请输入网站会员昵称';
                    $db->query("UPDATE `wxch_user` SET `setp`=`setp`+1 WHERE `wxid`= '{$fromUsername}';");
                }
                if ($setp == 3) {
                    $ret = $db->getRow("SELECT `uname` FROM  `wxch_user` WHERE `wxid` = '{$fromUsername}'");
                    $uname = $ret['uname'];
                    if ($cxbd == 'true') {
                        $contentStr = '您已经绑定了会员账号:' . $uname . "\r\n" . '如需重新绑定请输入cxbd';
                    } else {
                        $contentStr = '您已经绑定了会员账号:' . $uname;
                    }
                }
                if ($setp == 0) {
                    $db->query("UPDATE `wxch_user` SET `setp`=1 WHERE `wxid`= '{$fromUsername}';");
                }
                $msgType = "text";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'cxbd') {
                if ($cxbd == 'false') {
                    $this->universal($fromUsername, $base_url, $keyword);
                    exit('false');
                }
                $msgType = "text";
                if ($setp == 3) {
                    $contentStr = '请输入' . $uname . '的密码才能继续绑定,(想要退出绑定流程请回复ko或“退出”)';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $db->query("UPDATE `wxch_user` SET `setp`=10 WHERE `wxid`= '{$fromUsername}';");
                    echo $resultStr;
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url, $keyword);
                    exit;
                } else {
                    $contentStr = '您没有绑定会员';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url, $keyword);
                    exit;
                }
            } elseif ($keyword == 'news') {
                $thistable = $db->prefix . 'goods';
                $query_sql = "SELECT * FROM  `{$thistable}` WHERE `is_new` = 1 {$goods_is} ORDER BY sort_order, last_update DESC  LIMIT 0 , 6 ";
                $ret = $db->getAll($query_sql);
                $ArticleCount = count($ret);
                $items = '';
                if ($ArticleCount >= 1) {
                    foreach ($ret as $v) {
                        if ($img_path == 'local') {
                            $v['thumbnail_pic'] = $base_img_path . $v['goods_img'];
                        } elseif ($img_path == 'server') {
                            $v['thumbnail_pic'] = $v['goods_img'];
                        }
                        if ($oauth_state == 'true') {
                            $goods_url = $oauth_location . $m_url . 'goods.php?id=' . $v['goods_id'] . $affiliate;
                        } elseif ($oauth_state == 'false') {
                            $goods_url = $m_url . 'goods.php?id=' . $v['goods_id'] . $postfix . $affiliate;
                        }
                        $items .= "<item>\n                 <Title><![CDATA[" . $v['goods_name'] . "]]></Title>\n                 <PicUrl><![CDATA[" . $v['thumbnail_pic'] . "]]></PicUrl>\n                 <Url><![CDATA[" . $goods_url . "]]></Url>\n                 </item>";
                    }
                    $msgType = "news";
                }
                $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $ArticleCount, $items);
                $w_message = '图文消息';
                $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'best') {
                $thistable = $db->prefix . 'goods';
                $query_sql = "SELECT * FROM  `{$thistable}` WHERE `is_best` = 1 {$goods_is} ORDER BY sort_order, last_update DESC  LIMIT 0 , 6 ";
                $ret = $db->getAll($query_sql);
                $ArticleCount = count($ret);
                $items = '';
                if ($ArticleCount >= 1) {
                    foreach ($ret as $v) {
                        if ($img_path == 'local') {
                            $v['thumbnail_pic'] = $base_img_path . $v['goods_img'];
                        } elseif ($img_path == 'server') {
                            $v['thumbnail_pic'] = $v['goods_img'];
                        }
                        if ($oauth_state == 'true') {
                            $goods_url = $oauth_location . $m_url . 'goods.php?id=' . $v['goods_id'] . $affiliate;
                        } elseif ($oauth_state == 'false') {
                            $goods_url = $m_url . 'goods.php?id=' . $v['goods_id'] . $postfix . $affiliate;
                        }
                        $items .= "<item>\n                 <Title><![CDATA[" . $v['goods_name'] . "]]></Title>\n                 <PicUrl><![CDATA[" . $v['thumbnail_pic'] . "]]></PicUrl>\n                 <Url><![CDATA[" . $goods_url . "]]></Url>\n                 </item>";
                    }
                    $msgType = "news";
                }
                $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $ArticleCount, $items);
                $w_message = '图文消息';
                $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'hot') {
                $thistable = $db->prefix . 'goods';
                $ret = $db->getAll("SELECT * FROM  `{$thistable}` WHERE `is_hot` = 1 {$goods_is} ORDER BY sort_order, last_update DESC  LIMIT 0 , 6 ");
                $ArticleCount = count($ret);
                $items = '';
                if ($ArticleCount >= 1) {
                    foreach ($ret as $v) {
                        if ($img_path == 'local') {
                            $v['thumbnail_pic'] = $base_img_path . $v['goods_img'];
                        } elseif ($img_path == 'server') {
                            $v['thumbnail_pic'] = $v['goods_img'];
                        }
                        if ($oauth_state == 'true') {
                            $goods_url = $oauth_location . $m_url . 'goods.php?id=' . $v['goods_id'] . $affiliate;
                        } elseif ($oauth_state == 'false') {
                            $goods_url = $m_url . 'goods.php?id=' . $v['goods_id'] . $postfix . $affiliate;
                        }
                        $items .= "<item>\n                 <Title><![CDATA[" . $v['goods_name'] . "]]></Title>\n                 <PicUrl><![CDATA[" . $v['thumbnail_pic'] . "]]></PicUrl>\n                 <Url><![CDATA[" . $goods_url . "]]></Url>\n                 </item>";
                    }
                    $msgType = "news";
                }
                $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $ArticleCount, $items);
                $w_message = '图文消息';
                $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'jfcx') {
                $thistable = $db->prefix . 'users';
                $sql = "SELECT * FROM `{$thistable}` WHERE `wxid` = '{$fromUsername}'";
                $ret = $db->getAll($sql);
                if (count($ret) >= 2) {
                    foreach ($ret as $v) {
                        if ($v['wxch_bd'] == 'ok') {
                            $pay_points = $v['pay_points'];
                            $money = $v['user_money'];
                        }
                    }
                }
                if (empty($pay_points)) {
                    $pay_points = $ret[0]['pay_points'];
                    $money = $ret[0]['user_money'];
                }
                $msgType = "text";
                $contentStr = "余额:{$money}\r\n积分:{$pay_points}";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'ddlb') {
                $msgType = "text";
                $thistable = $db->prefix . 'order_info';
                if ($setp == 3) {
                    $table2 = $db->prefix . 'users';
                    $user_id = $db->getOne("SELECT `user_id` FROM `{$table2}` WHERE `wxch_bd` = 'ok' AND `wxid` ='{$fromUsername}'");
                } else {
                    $table2 = $db->prefix . 'users';
                    $user_id = $db->getOne("SELECT `user_id` FROM `{$table2}` WHERE `wxch_bd` = 'no' AND `wxid` ='{$fromUsername}'");
                }
                $orders = $db->getAll("SELECT * FROM `{$thistable}` WHERE `user_id` = '{$user_id}' ORDER BY `order_id` DESC LIMIT 0,5");
                $ArticleCount = count($orders);
                if ($ArticleCount >= 1) {
                    $order_goods_tb = $db->prefix . 'order_goods';
                    $items = '';
                    foreach ($orders as $k => $v) {
                        $order_id = $v['order_id'];
                        $order_goods = $db->getAll("SELECT * FROM `{$order_goods_tb}`  WHERE `order_id` = '{$order_id}'");
                        $shopinfo = '';
                        foreach ($order_goods as $vv) {
                            if (empty($v['goods_attr'])) {
                                $shopinfo .= $vv['goods_name'] . '(' . $vv['goods_number'] . '),';
                            } else {
                                $shopinfo .= $vv['goods_name'] . '(' . $vv['goods_attr'] . ')' . '(' . $vv['goods_number'] . '),';
                            }
                        }
                        $shopinfo = substr($shopinfo, 0, strlen($shopinfo) - 1);
                        if ($k != 0) {
                            if ($oauth_state == 'true') {
                                $title = "\r\n" . '------------------' . "\r\n" . '订单号:<a href="' . $oauth_location . $m_url . 'user.php?act=order_detail&order_id=' . $v['order_id'] . '">' . $v['order_sn'] . "</a>";
                            } elseif ($oauth_state == 'false') {
                                $title = "\r\n" . '------------------' . "\r\n" . '订单号:<a href="' . $m_url . 'user.php?act=order_detail&order_id=' . $v['order_id'] . '&wxid=' . $fromUsername . '">' . $v['order_sn'] . "</a>";
                            }
                        } else {
                            if ($oauth_state == 'true') {
                                $title = '订单号:<a href="' . $oauth_location . $m_url . 'user.php?act=order_detail&order_id=' . $v['order_id'] . '">' . $v['order_sn'] . "</a>\r\n";
                            } elseif ($oauth_state == 'false') {
                                $title = '订单号:<a href="' . $m_url . 'user.php?act=order_detail&order_id=' . $v['order_id'] . '&wxid=' . $fromUsername . '">' . $v['order_sn'] . "</a>\r\n";
                            }
                        }
                        if ($v['order_amount'] == 0.0) {
                            if ($v['money_paid'] > 0) {
                                $v['order_amount'] = $v['money_paid'];
                            }
                        }
                        $description = "\r" . '商品信息:' . $shopinfo . "\r总金额:" . $v['order_amount'] . "\r物流公司:" . $v['shipping_name'] . ' 物流单号:' . $v['invoice_no'];
                        $items .= $title . $description;
                    }
                    if ($oauth_state == 'true') {
                        $items_oder_list = '<a href="' . $oauth_location . $m_url . 'user.php?act=order_list">"我的订单"</a>';
                    } elseif ($oauth_state == 'false') {
                        $items_oder_list = '<a href="' . $m_url . 'user.php?act=order_list&wxid=' . $fromUsername . '">"我的订单"</a>';
                    }
                    $items_more = "\r\n" . '更多详细信息请点击' . $items_oder_list . '';
                    $contentStr = $items . $items_more;
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->plusPoint($db, $uname, $keyword, $fromUsername);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                } else {
                    $msgType = "text";
                    $contentStr = "您还没有订单";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
            } elseif ($keyword == 'ddcx') {
                $ArticleCount = 1;
                $msgType = "news";
                $thistable = $db->prefix . 'order_info';
                $order_goods_tb = $db->prefix . 'order_goods';
                if ($setp == 3) {
                    $table2 = $db->prefix . 'users';
                    $ret = $db->getRow("SELECT `user_id` FROM `{$table2}` WHERE `wxch_bd`='ok' AND `wxid` ='{$fromUsername}'");
                    $user_id = $ret['user_id'];
                    $orders = $db->getRow("SELECT * FROM `{$thistable}` WHERE `user_id` = '{$user_id}' ORDER BY `order_id` DESC");
                    $order_id = $orders['order_id'];
                    $order_goods = $db->getAll("SELECT * FROM `{$order_goods_tb}`  WHERE `order_id` = '{$order_id}'");
                } else {
                    $table2 = $db->prefix . 'users';
                    $ret = $db->getRow("SELECT `user_id` FROM `{$table2}` WHERE `wxch_bd`='no' AND `wxid` ='{$fromUsername}'");
                    $user_id = $ret['user_id'];
                    $orders = $db->getRow("SELECT * FROM `{$thistable}` WHERE `user_id` = '{$user_id}' ORDER BY `order_id` DESC");
                    $order_id = $orders['order_id'];
                    $order_goods = $db->getAll("SELECT * FROM `{$order_goods_tb}`  WHERE `order_id` = '{$order_id}'");
                }
                $shopinfo = '';
                if (!empty($order_goods)) {
                    foreach ($order_goods as $v) {
                        if (empty($v['goods_attr'])) {
                            $shopinfo .= $v['goods_name'] . '(' . $v['goods_number'] . '),';
                        } else {
                            $v['goods_attr'] = $this->guolv($v['goods_attr']);
                            $shopinfo .= $v['goods_name'] . '(' . $v['goods_attr'] . ')' . '(' . $v['goods_number'] . '),';
                        }
                    }
                    $shopinfo = substr($shopinfo, 0, strlen($shopinfo) - 1);
                    $title = '订单号:' . $orders['order_sn'];
                    if ($orders['pay_status'] == 0) {
                        $pay_status = '支付状态:未付款';
                    } elseif ($orders['pay_status'] == 1) {
                        $pay_status = '支付状态:付款中';
                    } elseif ($orders['pay_status'] == 2) {
                        $pay_status = '支付状态:已付款';
                    }
                    if ($oauth_state == 'true') {
                        $url = $oauth_location . $m_url . 'user.php?act=order_detail&order_id=' . $orders['order_id'];
                    } elseif ($oauth_state == 'false') {
                        $url = $m_url . 'user.php?act=order_detail&order_id=' . $orders['order_id'] . $postfix;
                    }
                    if ($orders['order_amount'] == 0.0) {
                        if ($orders['money_paid'] > 0) {
                            $orders['order_amount'] = $orders['money_paid'];
                        }
                    }
                    $description = '商品信息:' . $shopinfo . "\r\n总金额:" . $orders['order_amount'] . "\r\n" . $pay_status . "\r\n快递公司:" . $orders['shipping_name'] . ' 物流单号:' . $orders['invoice_no'];
                    $items = "<item>\n                 <Title><![CDATA[" . $title . "]]></Title>\n                 <Description><![CDATA[" . $description . "]]></Description>\n                 <PicUrl><![CDATA[]]></PicUrl>\n                 <Url><![CDATA[" . $url . "]]></Url>\n                 </item>";
                    $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $ArticleCount, $items);
                    $w_message = '图文消息';
                    $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                    $this->plusPoint($db, $uname, $keyword, $fromUsername);
                    echo $resultStr;
                } else {
                    $msgType = "text";
                    $contentStr = "您还没有订单";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->universal($fromUsername, $base_url);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    echo $resultStr;
                }
                exit;
            } elseif ($keyword == 'kdcx') {
                $thistable = $db->prefix . 'order_info';
                $table2 = $db->prefix . 'users';
                if ($setp == 3) {
                    $ret = $db->getRow("SELECT `user_id` FROM `{$table2}` WHERE `wxch_bd` = 'ok' AND `wxid` ='{$fromUsername}'");
                    $user_id = $ret['user_id'];
                    $orders = $db->getRow("SELECT * FROM `{$thistable}` WHERE `user_id` = '{$user_id}' ORDER BY `order_id` DESC");
                } else {
                    $ret = $db->getRow("SELECT `user_id` FROM `{$table2}` WHERE `wxch_bd` = 'no' AND `wxid` ='{$fromUsername}'");
                    $user_id = $ret['user_id'];
                    $orders = $db->getRow("SELECT * FROM `{$thistable}` WHERE `user_id` = '{$user_id}' ORDER BY `order_id` DESC");
                }
                if (empty($orders)) {
                    $msgType = "text";
                    $contentStr = '您还没有订单,无法查询快递';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
                if (empty($orders['invoice_no'])) {
                    $msgType = "text";
                    $contentStr = '订单号:' . $orders['order_sn'] . '还没有快递单号,不能查询';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
                $k_arr = $this->kuaidi($orders['invoice_no'], $orders['shipping_name']);
                $contents = '';
                $msgType = "text";
                if ($k_arr['message'] == 'ok') {
                    $count = count($k_arr['data']) - 1;
                    for ($i = $count; $i >= 0; $i--) {
                        $contents .= "\r\n" . $k_arr['data'][$i]['time'] . "\r\n" . $k_arr['data'][$i]['context'];
                    }
                    $contentStr = "订单号:{$orders['invoice_no']}\r\n" . "快递信息" . $contents;
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->plusPoint($db, $uname, $keyword, $fromUsername);
                    $this->universal($fromUsername, $base_url, $keyword);
                    exit;
                } else {
                    $contentStr = "没有查到订单号:{$orders['invoice_no']} 的" . "快递信息";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->plusPoint($db, $uname, $keyword, $fromUsername);
                    $this->universal($fromUsername, $base_url, $keyword);
                }
                exit;
            } elseif ($keyword == 'reg') {
            } elseif ($keyword == 'help' or $keyword == 'HELP') {
                $msgType = "text";
                $lang['help'] = $db->getOne("SELECT `lang_value` FROM `wxch_lang` WHERE `lang_name` = 'help'");
                $contentStr = $lang['help'];
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'dzp') {
                $data = $this->dzp($db, $base_url, $fromUsername);
                $msgType = "news";
                $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $data['ArticleCount'], $data['items']);
                $w_message = '图文消息';
                $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'ggl') {
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
            } elseif ($keyword == 'login') {
                $bd_url = '<a href="' . $m_url . 'user.php?wxid=' . $fromUsername . '">会员中心</a>';
                $contentStr = $bd_url . ',(点击进入)';
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'zjd') {
                $data = $this->egg($db, $base_url, $fromUsername);
                $msgType = "news";
                $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $data['ArticleCount'], $data['items']);
                $w_message = '图文消息';
                $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'qrcode') {
                $ArticleCount = 1;
                $scene_id = $user_id;
                $affiliate = $user_id;
                $gourl = $base_url . 'wechat/egg/index1.php?scene_id=' . $scene_id;
                $type = 'tj';
                $qr_path = $db->getOne("SELECT `qr_path` FROM `wxch_qr` WHERE `scene_id`='{$scene_id}'");
                $user_name = $db->getOne("SELECT `user_name` FROM `ecs_users` WHERE `user_id`='{$scene_id}'");
                $scene = $user_name;
                if (!empty($qr_path)) {
                    $surl = $qr_path;
                } else {
                    $action_name = "QR_LIMIT_SCENE";
                    $json_arr = array('action_name' => $action_name, 'action_info' => array('scene' => array('scene_id' => $scene_id)));
                    $data = json_encode($json_arr);
                    $this->access_token($db);
                    $ret = $db->getRow("SELECT `access_token` FROM `wxch_config`");
                    $access_token = $ret['access_token'];
                    if (strlen($access_token) >= 64) {
                        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $access_token;
                        $res_json = $this->curl_grab_page($url, $data);
                        $json = json_decode($res_json);
                    }
                    $ticket = $json->ticket;
                    if ($ticket) {
                        $ticket_url = urlencode($ticket);
                        $ticket_url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket_url;
                        $imageinfo = $this->downloadimageformweixin($ticket_url);
                        $time = time();
                        $url = $_SERVER['HTTP_HOST'];
                        $path = '../images/qrcode/' . $time . '.jpg';
                        $surl = "http://" . $url . '/images/qrcode/' . $time . '.jpg';
                        $local_file = fopen($path, 'a');
                        if (false !== $local_file) {
                            if (false !== fwrite($local_file, $imageinfo)) {
                                fclose($local_file);
                                //将生成的二维码图片的地址放到数据库中
                                $insert_sql = "INSERT INTO `wxch_qr` (`type`,`action_name`,`ticket`, `scene_id`, `scene` ,`qr_path`,`function`,`affiliate`,`endtime`,`dateline`) VALUES\n\t\t\t\t\t('{$type}','{$action_name}', '{$ticket}','{$scene_id}', '{$scene}' ,'{$surl}','{$function}','{$affiliate}','{$endtime}','{$dateline}')";
                                $db->query($insert_sql);
                            }
                        }
                    }
                }
                $des = "扫描二维码可以获得推荐关系!";
                $items = "<item>\n\t\t\t\t<Title><![CDATA[推荐二维码]]></Title>\n\t\t\t\t<Description><![CDATA[" . $des . "]]></Description>\n\t\t\t\t<PicUrl><![CDATA[" . $surl . "]]></PicUrl>\n\t\t\t\t<Url><![CDATA[" . $gourl . "]]></Url>\n\t\t\t\t</item>";
                $msgType = "news";
                $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $ArticleCount, $items);
                $w_message = '图文消息';
                $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'tianxin100') {
            } elseif ($keyword == 'map232') {
                $url = 'http://api.map.baidu.com/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&desti
nation=大雁塔&mode=driving&region=西安';
                $name = '地图';
                $PicUrl = '';
                $items = "<item>\n             <Title><![CDATA[" . $name . "]]></Title>\n             <PicUrl><![CDATA[" . $PicUrl . "]]></PicUrl>\n             <Url><![CDATA[" . $url . "]]></Url>\n             </item>";
                $ArticleCount = 1;
                $msgType = "news";
                $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $ArticleCount, $items);
                $w_message = '图文消息';
                $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'gzyhj') {
                $msgType = "text";
                $contentStr = $this->coupon($db, $fromUsername);
                if (!empty($zhanghaoinfo)) {
                    $contentStr .= $zhanghaoinfo;
                } else {
                    $contentStr .= "您已经注册过!账号是" . $user_name . "默认密码是:" . $user_password;
                }
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'qiandao') {
                $jf_state = $db->getOne("SELECT `autoload` FROM `wxch_point` WHERE `point_name` = '{$keyword}'");
                $msgType = "text";
                if ($jf_state == 'yes') {
                    $qd_jf = $db->getOne("SELECT `point_value` FROM `wxch_point` WHERE `point_name` = '{$keyword}'");
                    $res = $this->plusPoint($db, $uname, $keyword, $fromUsername);
                    if ($res['errmsg'] == 'ok') {
                        $contentStr = $res['contentStr'] . $qd_jf;
                    } else {
                        $contentStr = $res['contentStr'];
                    }
                } elseif ($jf_state == 'no') {
                    $qdstop = $db->getOne("SELECT `lang_value` FROM `wxch_lang` WHERE `lang_name` = 'qdstop'");
                    if (empty($qdstop)) {
                        $qdstop = '签到积送已停止使用';
                    }
                    $contentStr = $qdstop;
                }
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            } elseif ($keyword == 'subscribe') {
                /* 甜  心 10 0  新 增修 复  如果是直接关注的则默认分配上级账号避免推荐关系混乱*/
                $affiliate = unserialize($GLOBALS['_CFG_MOBILE']['affiliate']);
                $parent_id = (double) $affiliate['config']['parent_id'];
                $db->query("UPDATE  ecs_users SET `parent_id`='{$parent_id}' WHERE `user_name`='{$ecs_user_name}'");
                $type1 = $db->getOne("SELECT `type` FROM `wxch_keywords1` WHERE `is_start` = 1");
                if ($type1 == 3) {
                    $keyword = "关注回复文本";
                } else {
                    $keyword = "关注回复图文";
                }
                $this->getauto_reg($db, $keyword, $textTpl, $newsTpl, $base_url, $m_url, $fromUsername, $toUsername, $time, $article_url, $user_name, $ec_pwd_no, $zhanghaoinfo, $user_password);
            }
            if (file_exists('wxch_development.php')) {
                include 'wxch_development.php';
            }
            if (!empty($keyword)) {
                $ck_keyword = strtolower($keyword);
                $ck_ret = stristr($ck_keyword, 'ck');
                if ($ck_ret) {
                    $ck_arr = explode('ck', $keyword);
                    $ck_sn = $ck_arr[1];
                    $ck_table = $db->prefix . 'goods';
                    $ck_ret = $db->getAll("SELECT * FROM  `{$ck_table}` WHERE  `goods_sn` LIKE '%{$ck_sn}%'");
                    $msgType = "text";
                    $ck_goods = '';
                    if (count($ck_ret) > 10) {
                        $contentStr = '结果超出十条以上,请您输入更准确的货号,例如:' . $ck_sn . 'AB';
                    } elseif (count($ck_ret) > 0) {
                        foreach ($ck_ret as $v) {
                            if ($v['is_on_sale'] == 0) {
                                $ck_title = '下架';
                            } elseif ($v['goods_number'] > 20) {
                                $ck_title = '充足';
                            } elseif ($v['goods_number'] >= 5 and $v['goods_number'] <= 20) {
                                $ck_title = '紧张';
                            } elseif ($v['goods_number'] >= 1 and $v['goods_number'] <= 5) {
                                $ck_title = $v['goods_number'];
                            } elseif ($v['goods_number'] == 0) {
                                $ck_title = '缺货';
                            }
                            $ck_goods .= $v['goods_sn'] . ':' . $v['goods_name'] . '--' . $ck_title . "\r\n";
                        }
                        $contentStr = $ck_goods;
                    } else {
                        $contentStr = '没有查询到' . $ck_sn . '货号的商品,建议您输入更简短的货号查询';
                    }
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
                $this->getauto($db, $keyword, $textTpl, $newsTpl, $base_url, $m_url, $fromUsername, $toUsername, $time, $article_url);
                $thistable = $db->prefix . 'goods';
                $goods_name = $keyword;
                $search_sql = "SELECT * FROM  `{$thistable}` WHERE  `goods_name` LIKE '%{$goods_name}%' {$goods_is} ORDER BY sort_order, last_update DESC LIMIT 0,6";
                $ret = $db->getAll($search_sql);
                $ArticleCount = count($ret);
                $items = '';
                if ($ArticleCount >= 1) {
                    foreach ($ret as $v) {
                        if ($img_path == 'local') {
                            $v['thumbnail_pic'] = $base_img_path . $v['goods_img'];
                        } elseif ($img_path == 'server') {
                            $v['thumbnail_pic'] = $v['goods_img'];
                        }
                        if ($oauth_state == 'true') {
                            $goods_url = $oauth_location . $m_url . 'goods.php?id=' . $v['goods_id'] . $affiliate;
                        } elseif ($oauth_state == 'false') {
                            $goods_url = $m_url . 'goods.php?id=' . $v['goods_id'] . $postfix . $affiliate;
                        }
                        $items .= "<item>\n                 <Title><![CDATA[" . $v['goods_name'] . "]]></Title>\n                 <PicUrl><![CDATA[" . $v['thumbnail_pic'] . "]]></PicUrl>\n                 <Url><![CDATA[" . $goods_url . "]]></Url>\n                 </item>";
                    }
                    $msgType = "news";
                } else {
                    $msgType = "text";
                    $thistable = $db->prefix . 'goods';
                    if ($plustj == 'true') {
                        $tj_str = $this->plusTj($db, $m_url, $postfix, $oauth_location, $oauth_state, $goods_is, $affiliate);
                        $contentStr = '没有搜索到"' . $goods_name . '"的商品' . $tj_str;
                    } elseif ($plustj == 'false') {
                        exit;
                    }
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    $this->insert_wmessage($db, $fromUsername, $contentStr, $time, $belong);
                    $this->plusPoint($db, $uname, $keyword, $fromUsername);
                    $this->universal($fromUsername, $base_url);
                    echo $resultStr;
                    exit;
                }
                $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $ArticleCount, $items);
                $w_message = '图文消息';
                $this->insert_wmessage($db, $fromUsername, $w_message, $time, $belong);
                $this->plusPoint($db, $uname, $keyword, $fromUsername);
                $this->universal($fromUsername, $base_url);
                echo $resultStr;
                exit;
            }
        } else {
            echo "";
            exit;
        }
    }