构建sql
@param bool $return
@return sql|string
776730
private function _constructSql() {
        if($this->sql) {
            return [$this->sql,$this->params];
        }
        $distinct = $this->distinct ? 'DISTINCT' : '';
        $groupby = '';
        if (!empty($this->group)) {
            $groupby = 'GROUP BY ' . $this->group;
        }
        if (!empty($this->having)) {
            $groupby .= ' ' . $this->having;
        }
        $order = !empty($this->order) ? "ORDER BY $this->order" : '';

        $this->fields = $this->fields?$this->fields:'*';
        $sql = "SELECT $distinct $this->fields FROM `$this->table` $this->alias $this->join $this->where $groupby $order $this->limit";
        $sql = str_replace('table.',$this->alias.'.',$sql);
        return [$sql,$this->params];
    }
520885
public function delete($f = false)
    {
        $_where      = '';
        $_table_name = $this->_get_table_name();

        if ($this->where) {
            $_where = ' WHERE ' . $this->where;
        } elseif ($this->where == '' && $f == false) {
            throw_error('警告：您似乎漏掉了where条件。如果确认不使用where条件，请使用delete(true)');
        }

        // 清理使用过的变量
        $this->where = '';

        $this->sql = 'DELETE FROM ' . $_table_name . $_where;
        return $this->conn()->query($this->sql);
    }
57323
function _query($sql,$inputarr=false)
	{
		if (is_array($sql)) {
			$stmt = $sql[1];
		} else {
			$stmt = $this->_connectionID->prepare($sql);
		}
		#adodb_backtrace();
		#var_dump($this->_bindInputArray);
		if ($stmt) {
			$this->_driver->debug = $this->debug;
			if ($inputarr) {
				$ok = $stmt->execute($inputarr);
			}
			else {
				$ok = $stmt->execute();
			}
		}


		$this->_errormsg = false;
		$this->_errorno = false;

		if ($ok) {
			$this->_stmt = $stmt;
			return $stmt;
		}

		if ($stmt) {

			$arr = $stmt->errorinfo();
			if ((integer)$arr[1]) {
				$this->_errormsg = $arr[2];
				$this->_errorno = $arr[1];
			}

		} else {
			$this->_errormsg = false;
			$this->_errorno = false;
		}
		return false;
	}
392556
public function output($view = null, $return = false) {
        if ($view instanceof View) {
            $this->view = $view;
        } else if (is_string($view) || is_bool($view) || is_numeric($view)) {
            $this->view = new SimpleView ($view);
        } else if (is_array($view)) {
            $this->view = new JsonView ($view);
        } else if (is_object($view)) {
            $this->view = new JsonView (get_object_vars($view));
        }

        if ($this->view instanceof View) {
            if ($return) {
                $content = $this->view->render();

                return $content;
            } else {
                $this->view->echoHeader();
                $content = $this->view->render();
                if (is_string($content) && $content) {
                    $content = apply_filter('before_output_content', $content, $this->view);
                    echo $content;
                }
            }
        } else if (!$return) {
            Response::respond(404);
        }

        return null;
    }
999718
public function execute($sql, $bind = [])
    {
        $this->initConnect(true);
        if (!$this->linkID) {
            return false;
        }

        // 记录SQL语句
        $this->queryStr = $sql;
        if ($bind) {
            $this->bind = $bind;
        }

        //释放前次的查询结果
        if (!empty($this->PDOStatement) && $this->PDOStatement->queryString != $sql) {
            $this->free();
        }

        Db::$executeTimes++;
        try {
            // 预处理
            if (empty($this->PDOStatement)) {
                $this->PDOStatement = $this->linkID->prepare($sql);
            }
            // 是否为存储过程调用
            $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
            // 参数绑定
            if ($procedure) {
                $this->bindParam($bind);
            } else {
                $this->bindValue($bind);
            }
            // 执行语句
            $this->PDOStatement->execute();

            $this->numRows = $this->PDOStatement->rowCount();
            return $this->numRows;
        } catch (\PDOException $e) {
            if ($this->isBreak($e)) {
                return $this->close()->execute($sql, $bind);
            }
            throw new PDOException($e, $this->config, $this->getLastsql());
        } catch (\ErrorException $e) {
            if ($this->isBreak($e)) {
                return $this->close()->execute($sql, $bind);
            }
            throw $e;
        }
    }
262260
public function query($sql, $bind = [], $master = false, $pdo = false)
    {
        $this->initConnect($master);

        if (!$this->linkID) {
            return false;
        }

        // 记录SQL语句
        $this->queryStr = $sql;

        $this->bind = $bind;

        Db::$queryTimes++;

        try {
            // 调试开始
            $this->debug(true);

            // 预处理
            $this->PDOStatement = $this->linkID->prepare($sql);

            // 是否为存储过程调用
            $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);

            // 参数绑定
            if ($procedure) {
                $this->bindParam($bind);
            } else {
                $this->bindValue($bind);
            }

            // 执行查询
            $this->PDOStatement->execute();

            // 调试结束
            $this->debug(false, '', $master);

            // 返回结果集
            return $this->getResult($pdo, $procedure);
        } catch (\PDOException $e) {
            if ($this->isBreak($e)) {
                return $this->close()->query($sql, $bind, $master, $pdo);
            }

            throw new PDOException($e, $this->config, $this->getLastsql());
        } catch (\Throwable $e) {
            if ($this->isBreak($e)) {
                return $this->close()->query($sql, $bind, $master, $pdo);
            }

            throw $e;
        } catch (\Exception $e) {
            if ($this->isBreak($e)) {
                return $this->close()->query($sql, $bind, $master, $pdo);
            }

            throw $e;
        }
    }
288558
function query($sql)
    {
        $res = false;

        for ($i = 0; $i < 2; $i++)
        {
            $res = mysql_query($sql, $this->conn);
            if ($res === false)
            {
                if (mysql_errno($this->conn) == 2006 or mysql_errno($this->conn) == 2013 or (mysql_errno($this->conn) == 0 and !$this->ping()))
                {
                    $r = $this->checkConnection();
                    if ($r === true)
                    {
                        continue;
                    }
                }
                \Swoole\Error::info(__CLASS__." SQL Error", $this->errorMessage($sql));
                return false;
            }
            break;
        }

        if (!$res)
        {
            Swoole\Error::info(__CLASS__." SQL Error", $this->errorMessage($sql));
            return false;
        }
        if (is_bool($res))
        {
            return $res;
        }
        return new MySQLRecord($res);
    }
499171
public function valid($return=false)
    {
        $encryptStr="";
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $postStr = file_get_contents("php://input");
            $array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->log($postStr);
            if (isset($array['Encrypt'])) {
                $encryptStr = $array['Encrypt'];
                $this->agentidxml = isset($array['AgentID']) ? $array['AgentID']: '';
            }
        } else {
            $encryptStr = isset($_GET["echostr"]) ? $_GET["echostr"]: '';

        }
        if ($encryptStr) {
            $ret=$this->checkSignature($encryptStr);
        }
        if (!isset($ret) || !$ret) {
        	if (!$return) {
        	    die('no access');
        	} else {
        	    return false;
        	}
        }
        $pc = new Prpcrypt($this->encodingAesKey);
        $array = $pc->decrypt($encryptStr,$this->appid);
        if (!isset($array[0]) || ($array[0] != 0)) {
            if (!$return) {
        	    die('解密失败！');
        	} else {
        	    return false;
        	}
        }
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $this->postxml = $array[1];
            //$this->log($array[1]);
            return ($this->postxml!="");
        } else {
            $echoStr = $array[1];
            if ($return) {
            	return $echoStr;
            } else {
                die($echoStr);
            }
        }
        return false;
    }
643833
public function SQL() {
      if(is_null($this->_SQL)) {
         $Name = $this->Engine . 'Driver';
         $this->_SQL = Gdn::Factory($Name);
         $this->_SQL->Database = $this;
      }
      
      return $this->_SQL;
   }
434757
public function reply($msg = array(), $return = false)
    {
        if (empty($msg)) {
            if (empty($this->_msg)) {   //防止不先设置回复内容，直接调用reply方法导致异常
                return false;
            }
            $msg = $this->_msg;
        }
        $xmldata = Tools::arr2xml($msg);
        if ($this->encrypt_type == 'aes') { //如果来源消息为加密方式
            !class_exists('Prpcrypt', false) && require __DIR__ . '/Lib/Prpcrypt.php';
            $pc = new Prpcrypt($this->encodingAesKey);
            // 如果是第三方平台，加密得使用 component_appid
            $array = $pc->encrypt($xmldata, empty($this->config['component_appid']) ? $this->appid : $this->config['component_appid']);
            $ret = $array[0];
            if ($ret != 0) {
                Tools::log('Encrypt Error!', "ERR - {$this->appid}");
                return false;
            }
            $timestamp = time();
            $nonce = rand(77, 999) * rand(605, 888) * rand(11, 99);
            $encrypt = $array[1];
            $tmpArr = array($this->token, $timestamp, $nonce, $encrypt);
            sort($tmpArr, SORT_STRING);
            $signature = sha1(implode($tmpArr));
            $format = "<xml><Encrypt><![CDATA[%s]]></Encrypt><MsgSignature><![CDATA[%s]]></MsgSignature><TimeStamp>%s</TimeStamp><Nonce><![CDATA[%s]]></Nonce></xml>";
            $xmldata = sprintf($format, $encrypt, $signature, $timestamp, $nonce);
        }
        if ($return) {
            return $xmldata;
        }
        echo $xmldata;
    }
659451
public function distribute($return = false)
    {
        $this->processSessionValues();

        try {
            $routing = $this->request
                ->parseWDBRequest()
                ->getWDBRouting();
        } catch (NotFoundException $e) {
            throw $e;
        }

        $this->processQueryArguments();

        $input_file = $this->getInputFile();
        if (empty($input_file)) {
            $input_path = $this->getInputPath();
            if (!empty($input_path)) {
                $input_file = Kernel::getPath('web').trim($input_path, '/');
            }
        }
        $result = null;
        if (!empty($routing)) {
            $ctrl_cls   = $routing['controller_classname'];
            /* @var \WebDocBook\Abstracts\AbstractController $ctrl_obj */
            $ctrl_obj   = new $ctrl_cls();
            $this->setController($ctrl_obj);
            $result     = Helper::fetchArguments(
                $this->getController(), $routing['action'], array('path'=>$input_file)
            );
        }
        if (empty($result) || !is_array($result) || (count($result)!=2 && count($result)!=3)) {
            $str        = gettype($result);
            if (is_array($result)) {
                $str    .= ' length '.count($result);
            }
            throw new RuntimeException(
                sprintf('A controller action must return a two or three entries array like [ template file , content (, params) ]! Received %s from class "%s::%s()".',
                $str, $routing['controller_classname'], $routing['action'])
            );
        } else {
            $template   = $result[0];
            $content    = $result[1];
            $params     = isset($result[2]) ? $result[2] : array();
        }

        // debug if so
        if (!empty($_GET) && isset($_GET['debug'])) {
            Kernel::debug($this);
        }

        $this->display($content, $template, $params, true);
    }
1307572
protected function query($sql) {
        $vars = func_get_args();
		$cleaner = "/[\s,].+|[^a-zA-Z]/";
		$illegal = "/[\\\\'\"\%]/";
        try {
            $pdo = $this->dbConnect();
            $stmt = $pdo->prepare($sql);
            $binds = explode(':', $sql);
            foreach($binds as $n => $b) {
				if($n != 0 && substr($b,1)!=false) {
					$b = ':' . preg_replace($cleaner,'',$b);
					$vars[$n] = preg_replace($illegal,'',$vars[$n]);
					$stmt->bindParam($b,$vars[$n]);
				}
            }
            $stmt->execute();
            return (strpos($sql,'SELECT') !== FALSE) ? $stmt->fetchAll() : true;
        } catch(PDOException $e) {
            return array('query_error' => $e);
        }
    }
917738
public function build(bool $complete = true): string
    {
        $sql = [];
        $sql = $this->getSelectSql($sql);
        $sql = $this->getColumnsSql($sql);
        $sql = $this->getFromSql($sql);
        $sql = $this->getJoinSql($sql);
        $sql = $this->condition->getWhereSql($sql);
        $sql = $this->getGroupBySql($sql);
        $sql = $this->condition->getHavingSql($sql);
        $sql = $this->getOrderBySql($sql);
        $sql = $this->getLimitSql($sql);
        $sql = $this->getUnionSql($sql);
        $result = trim(implode(' ', $sql));
        $result = $this->getAliasSql($result);
        if ($complete) {
            $result = trim($result) . ';';
        }

        return $result;
    }
327656
protected function getDatabaseConfigs(array &$return)
    {
        $return['localhost'] = 'localhost';

        $return['host']     = $this->connection->getConfig('host');
        $return['database'] = $this->connection->getConfig('database');
        $return['username'] = $this->connection->getConfig('username');
        $return['password'] = $this->connection->getConfig('password');
        $return['connection_username'] = $return['username'];
        $return['connection_password'] = $return['password'];

        if ( ! in_array($return['host'], ['localhost', '127.0.0.1']))
        {
            $return['localhost'] = $this->command->ask('Database is on the other server. Provide local IP/hostname.');
        }
    }
777050
public function save($data = null, $return = Db::RETURN_ISOK)
	{
		if(null === $data)
		{
			$data = $this->data;
		}
		$table = $this->getOptionTable();
		if(empty($this->fields) || $table !== $this->tableName())
		{
			$this->loadFields($fields, $fieldNames, $pk, $bitFields, $table);
		}
		else
		{
			$pk = $this->pk;
		}
		$pk = explode(',', $pk);
		$isEdit = true;
		foreach($pk as $tpk)
		{
			if(!array_key_exists($tpk, $data))
			{
				$isEdit = false;
				break;
			}
		}
		// 判断记录是否存在，来决定$isEdit的值
		if($isEdit)
		{
			$option = $this->operationOption;
			$isEdit = $this->wherePk($data,$table)->count() > 0;
			$this->operationOption = $option;
		}
		// 2个if不要合并！
		if($isEdit)
		{
			$result = $this->wherePk($data,$table)->edit($data,$return);
			if(Db::RETURN_INSERT_ID === $result)
			{
				return $pk[0];
			}
			else
			{
				return $result;
			}
		}
		else
		{
			return $this->add($data);
		}
	}
561980
function _query($sql,$inputarr=false)
	{

		$dbc = $this->_connectionID;
		$false = false;

	//	return rs
		if ($inputarr) {

			if (!empty($this->charPage))
				$oCmd = new COM('ADODB.Command',null,$this->charPage);
			else
				$oCmd = new COM('ADODB.Command');
			$oCmd->ActiveConnection = $dbc;
			$oCmd->CommandText = $sql;
			$oCmd->CommandType = 1;

      // Map by http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmthcreateparam.asp
      // Check issue http://bugs.php.net/bug.php?id=40664 !!!
			foreach ($inputarr as $val) {
				$type = gettype($val);
				$len=strlen($val);
				if ($type == 'boolean')
					$this->adoParameterType = 11;
				else if ($type == 'integer')
					$this->adoParameterType = 3;
				else if ($type == 'double')
					$this->adoParameterType = 5;
				elseif ($type == 'string')
					$this->adoParameterType = 202;
				else if (($val === null) || (!defined($val)))
					$len=1;
				else
					$this->adoParameterType = 130;

				// name, type, direction 1 = input, len,
        		$p = $oCmd->CreateParameter('name',$this->adoParameterType,1,$len,$val);

				$oCmd->Parameters->Append($p);
			}
			$p = false;
			$rs = $oCmd->Execute();
			$e = $dbc->Errors;
			if ($dbc->Errors->Count > 0) return $false;
			return $rs;
		}

		$rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);

		if ($dbc->Errors->Count > 0) return $false;
		if (! $rs) return $false;

		if ($rs->State == 0) {
			$true = true;
			return $true; // 0 = adStateClosed means no records returned
		}
		return $rs;
	}
631314
public function render( $return = false ) {

		// Get the rendered output.
		$output = $this->get_renderer()->render( $this, true );

		if ( $return ) {
			return $output;
		}

		echo wp_kses( $output, wp_kses_allowed_html( 'post' ) );
	}