关闭连接

@param $con_name
508948
public static function closeCon($con_name)
    {
        if (isset(self::$instance[$con_name])) {
            self::instance($con_name)->close();
            unset(self::$instance[$con_name]);
        }
    }
1020686
private function startCommon(): void
    {
        if (self::$app !== null) {
            return;
        }
        self::$app = $this;
        // 加载框架配置文件
        $config = DataMap::loadFromPhpFile($this->mvcSourcePath . '/../config.inc.php');
        // 应用配置
        if ($this->config === null) {
            $appConfigFile = APP_CONFIG_PATH . '/./config.inc.php';
            if (is_file($appConfigFile)) {
                $appConfig = DataMap::loadFromPhpFile($appConfigFile);
                $config->mergeData($appConfig);
            }
        } else {
            $config->mergeData($this->config);
        }
        $this->config = $config;
        $this->loadContainer();
    }
647159
public function input($cname, $name, $cfg, $value = NULL, $id = 0) 
	{
		// 字段显示名称
		$text = (isset($cfg['validate']['required']) && $cfg['validate']['required'] == 1 ? '<font color="red">*</font> ' : '').$cname.'';
		// 表单宽度设置
		$width = isset($cfg['option']['width']) && $cfg['option']['width'] ? $cfg['option']['width'] : '150';
		$width = 'style="width:'.$width.(is_numeric($width) ? 'px' : '').';"';
		// 表单附加参数
		$attr = isset($cfg['validate']['formattr']) && $cfg['validate']['formattr'] ? $cfg['validate']['formattr'] : '';
		// 字段提示信息
		$tips = isset($cfg['validate']['tips']) && $cfg['validate']['tips'] ? $cfg['validate']['tips'] : '';
		// 字段默认值
		if (!$value) {
			if(isset($cfg['option']['value']) && is_numeric($cfg['option']['value'])) {
				$value = isset($cfg['option']['value']) && (int)$cfg['option']['value'] === '0' ? 0 : hst_time();
			} else if(isset($cfg['option']['value']) && !is_numeric($cfg['option']['value'])) {
				$value = hst_str2time($cfg['option']['value']);
			}
		} else {
			$value = $value ? $value : (strlen($value) == 1 && $value == 0 ? '' : hst_time());
		}
		$format = isset($cfg['option']['format']) && $cfg['option']['format'] ? $cfg['option']['format'] : 'Y-m-d H:i';
		$show = $value ? hst_time2str($value, $format) : '';
		
		$disabled = !$this->isadmin && $id && $value && isset($cfg['validate']['isedit']) && !$cfg['validate']['isedit'] ? ' disabled' : ' ';
		$required = isset($cfg['validate']['required']) && $cfg['validate']['required'] == 1 ? ' required="required"' : '';
		$str = '';
		$str.= '<input type="text" class="hstui-input J_datetime" value="'.$show.'" name="'.$name.'" id="hstcms_'.$name.'" ' . $width . $disabled . $attr.$required.' />';
        if ($name == 'updatetime') {

        }
		return $this->input_format($name, $text, $str, $tips);
	}
401360
private function get_option_name( $option_name_list ) {

		$option_name_list = (array) $option_name_list;

		foreach ( $option_name_list as $this_option_name ) {
			if ( null !== get_option( $this_option_name, null ) ) {
				return $this_option_name;
			}
		}

		return null;

	}
549904
private function parseNetwork()
    {
        // 用户名密码认证处理
        $username = $this->request->getAttribute('username');
        if(null != $username)
        {
            $auth = base64_encode($username . ':' . $this->request->getAttribute('password', ''));
            $this->request = $this->request->withAddedHeader('Authorization', 'Basic ' . $auth);
        }
        // 超时
        $this->settings['timeout'] = $this->request->getAttribute('timeout', 30000) / 1000;
    }
1040472
public function remove($col, $cond = [], $cb = null, $params = [])
    {
        if (mb_orig_strpos($col, '.') === false) {
            $col = $this->dbname . '.' . $col;
        }

        if (is_string($cond)) {
            $cond = new \MongoCode($cond);
        }

        if ($this->safeMode && is_array($cond)) {
            static::safeModeEnc($cond);
        }
        try {
            $this->request(
                self::OP_DELETE,
                "\x00\x00\x00\x00" . $col . "\x00" . "\x00\x00\x00\x00" . bson_encode($cond),
                false,
                null,
                function ($conn, $reqId = null) use ($col, $cb, $params) {
                    if (!$conn) {
                        !$cb || $cb(['$err' => 'Connection error.']);
                        return;
                    }
                    if ($cb !== null) {
                        $this->lastError($col, $cb, $params, $conn);
                    }
                }
            );
        } catch (\MongoException $e) {
            Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString());
            if ($cb !== null) {
                $cb(['$err' => $e->getMessage(), '$query' => $cond]);
            }
        }
    }
512128
public function getForeignKey(string $name = null)
    {
        // 构造 查询语句
        $sql = $this->db->getCreate($name ? $name : $this->tableName);
        $result = $this->query($sql);

        // 分析结果
        $statement = $result[0]['Create Table'];
        $matched = preg_match_all('/CONSTRAINT\s\S*\sFOREIGN\sKEY\s\(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)/i', $statement, $matches, PREG_SET_ORDER);
        if (!$matched) {
            return false;
        }

        // 如果有多个
        $fks = [];
        foreach ($matches as $m) {
            $fks[$m[1]] = [
                'table' => $m[2],
                'field' => $m[3]
            ];
        }
        return $fks;
    }
1229102
public function getOptionNameFromDefinition($constant_name)
    {
        if ($this->strStartsWith($constant_name, "'") && $this->strEndsWith($constant_name, "'")) {
            return trim(trim($constant_name, "'")); // single quote
        } else {
            if ($this->strStartsWith($constant_name, '"') && $this->strEndsWith($constant_name, '"')) {
                return trim(trim($constant_name, '"')); // double quote
            } else {
                return $constant_name;
            }
        }
    }
987862
public function configure($name)
    {
        if (isset($this->loadedConfigurations[$name])) {
            return;
        }
        //标记为已加载
        $this->loadedConfigurations[$name] = true;
        $path = $this->getConfigurationPath($name);
        if ($path) {
            $this->make('config')->set($name, require $path);
        }
    }
1361919
private function _get_table_name()
    {
        if ($this->table_name == '') {
            // 如果是在实例化后使用，则使用当前模型名称
            $current_class = get_class($this);
            if ($current_class != 'model') {
                $this->table_name = strtolower(substr($current_class, strrpos($current_class, '\\')+1, -5));

                // 如果设置了表前缀
                if (true == ($tb_prefix = Config::get('dbconfig.'.$this->db_config_name . '.tb_prefix'))) {
                    $this->table_name = $tb_prefix . $this->table_name;
                }
            } else {
                throw_error('Tablename cannot automatically infer.');
            }
        }

        return $this->table_name;
    }
937227
protected function getRelation(&$result,$name='',$return=false) {
        if(!empty($this->_link)) {
            foreach($this->_link as $key=>$val) {
                    $mappingName =  !empty($val['mapping_name'])?$val['mapping_name']:$key; // 映射名称
                    if(empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName,$name))) {
                        $mappingType = !empty($val['mapping_type'])?$val['mapping_type']:$val;  //  关联类型
                        $mappingClass  = !empty($val['class_name'])?$val['class_name']:$key;            //  关联类名
                        $mappingFields = !empty($val['mapping_fields'])?$val['mapping_fields']:'*';     // 映射字段
                        $mappingCondition = !empty($val['condition'])?$val['condition']:'1=1';          // 关联条件
                        $mappingKey =!empty($val['mapping_key'])? $val['mapping_key'] : $this->getPk(); // 关联键名
                        if(strtoupper($mappingClass)==strtoupper($this->name)) {
                            // 自引用关联 获取父键名
                            $mappingFk   =   !empty($val['parent_key'])? $val['parent_key'] : 'parent_id';
                        }else{
                            $mappingFk   =   !empty($val['foreign_key'])?$val['foreign_key']:strtolower($this->name).'_id';     //  关联外键
                        }
                        // 获取关联模型对象
                        $model = D($mappingClass);
                        switch($mappingType) {
                            case self::HAS_ONE:
                                $pk   =  $result[$mappingKey];
                                $mappingCondition .= " AND {$mappingFk}='{$pk}'";
                                $relationData   =  $model->where($mappingCondition)->field($mappingFields)->find();
                                if (!empty($val['relation_deep'])){
                                    $model->getRelation($relationData,$val['relation_deep']);
                                }                                
                                break;
                            case self::BELONGS_TO:
                                if(strtoupper($mappingClass)==strtoupper($this->name)) {
                                    // 自引用关联 获取父键名
                                    $mappingFk   =   !empty($val['parent_key'])? $val['parent_key'] : 'parent_id';
                                }else{
                                    $mappingFk   =   !empty($val['foreign_key'])?$val['foreign_key']:strtolower($model->getModelName()).'_id';     //  关联外键
                                }
                                $fk   =  $result[$mappingFk];
                                $mappingCondition .= " AND {$model->getPk()}='{$fk}'";
                                $relationData   =  $model->where($mappingCondition)->field($mappingFields)->find();
                                if (!empty($val['relation_deep'])){
                                    $model->getRelation($relationData,$val['relation_deep']);
                                }                                
                                break;
                            case self::HAS_MANY:
                                $pk   =  $result[$mappingKey];
                                $mappingCondition .= " AND {$mappingFk}='{$pk}'";
                                $mappingOrder =  !empty($val['mapping_order'])?$val['mapping_order']:'';
                                $mappingLimit =  !empty($val['mapping_limit'])?$val['mapping_limit']:'';
                                // 延时获取关联记录
                                $relationData   =  $model->where($mappingCondition)->field($mappingFields)->order($mappingOrder)->limit($mappingLimit)->select();
                                if (!empty($val['relation_deep'])){
                                    foreach($relationData as $key=>$data){                                    
                                        $model->getRelation($data,$val['relation_deep']);
                                        $relationData[$key]     =   $data;
                                    }                                      
                                }
                                break;
                            case self::MANY_TO_MANY:
                                $pk     =   $result[$mappingKey];
                                $prefix =   $this->tablePrefix;
                                $mappingCondition = " {$mappingFk}='{$pk}'";
                                $mappingOrder =  $val['mapping_order'];
                                $mappingLimit =  $val['mapping_limit'];
                                $mappingRelationFk = $val['relation_foreign_key']?$val['relation_foreign_key']:$model->getModelName().'_id';
                                if(isset($val['relation_table'])){
                                    $mappingRelationTable   =   preg_replace_callback("/__([A-Z_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $val['relation_table']);
                                }else{
                                    $mappingRelationTable   =   $this->getRelationTableName($model);
                                }
                                $sql = "SELECT b.{$mappingFields} FROM {$mappingRelationTable} AS a, ".$model->getTableName()." AS b WHERE a.{$mappingRelationFk} = b.{$model->getPk()} AND a.{$mappingCondition}";
                                if(!empty($val['condition'])) {
                                    $sql   .= ' AND '.$val['condition'];
                                }
                                if(!empty($mappingOrder)) {
                                    $sql .= ' ORDER BY '.$mappingOrder;
                                }
                                if(!empty($mappingLimit)) {
                                    $sql .= ' LIMIT '.$mappingLimit;
                                }
                                $relationData   =   $this->query($sql);
                                if (!empty($val['relation_deep'])){
                                    foreach($relationData as $key=>$data){                                    
                                        $model->getRelation($data,$val['relation_deep']);
                                        $relationData[$key]     =   $data;
                                    }                                      
                                }                                
                                break;
                        }
                        if(!$return){
                            if(isset($val['as_fields']) && in_array($mappingType,array(self::HAS_ONE,self::BELONGS_TO)) ) {
                                // 支持直接把关联的字段值映射成数据对象中的某个字段
                                // 仅仅支持HAS_ONE BELONGS_TO
                                $fields =   explode(',',$val['as_fields']);
                                foreach ($fields as $field){
                                    if(strpos($field,':')) {
                                        list($relationName,$nick) = explode(':',$field);
                                        $result[$nick]  =  $relationData[$relationName];
                                    }else{
                                        $result[$field]  =  $relationData[$field];
                                    }
                                }
                            }else{
                                $result[$mappingName] = $relationData;
                            }
                            unset($relationData);
                        }else{
                            return $relationData;
                        }
                    }
            }
        }
        return $result;
    }
52853
public function __isset($name)
    {
        // 存在字段映射，则被映射的对象属性必能访问
        if($this->columnMap && key_exists($name, $this->columnMap)) {
            // 显式声明属性名
            $attr = $this->columnMap[$name];
            return !is_null($this->$attr);
        }

        return key_exists($name, $this->attrs);
    }
1237068
public function input($cname, $name, $cfg, $value = NULL, $id = 0) 
	{
		$cfg['option']['value'] = isset($cfg['option']['value']) ? $cfg['option']['value'] : "";
		// 字段显示名称
		$text = (isset($cfg['validate']['required']) && $cfg['validate']['required'] == 1 ? '<font color="red">*</font>&nbsp;' : '').$cname;
		// 表单附加参数
		$attr = isset($cfg['validate']['formattr']) && $cfg['validate']['formattr'] ? $cfg['validate']['formattr'] : '';
		// 字段提示信息
		$tips = isset($cfg['validate']['tips']) && $cfg['validate']['tips'] ? $cfg['validate']['tips']: '';
		// 字段默认值
		$value = $value ? $value : $cfg['option']['value'];
        $str = '';
		// 表单选项
		$options = isset($cfg['option']['list']) && $cfg['option']['list'] ? $cfg['option']['list'] : '';// 禁止修改
		$disabled = !$this->isadmin && $id && $value && isset($cfg['validate']['isedit']) && $cfg['validate']['isedit'] ? 'disabled' : '';
		if ($options) {
			$options = explode(PHP_EOL, str_replace(array(chr(13), chr(10)), PHP_EOL, $options));
			$_i = 0;
			foreach ($options as $t) {
				if ($t) {
					$_i++;
					$n = $v = $selected = '';
					list($n, $v) = explode('|', $t);
					$v = $v === NULL ? trim($n) : trim($v);
					$selected = $v == $value ? ' checked' : '';
					if(!$selected && $_i == 1){
						$selected = 'checked';
					}
					$str.= '<input '.$disabled.' type="radio" name="'.$name.'" value="'.$v.'" '.$selected.' '.$attr.' />&nbsp;<label>'.$n.'</label>&nbsp;&nbsp;&nbsp;&nbsp;';
				}
			}
		}
		return $this->input_format($name, $text, $str, $tips);
	}
314708
public function input($cname, $name, $cfg, $value = NULL, $id = 0) 
	{
		$upauto = isset($cfg['option']['upauto']) ? $cfg['option']['upauto'] ? 'true' : 'false'  : 'true';
		$upbuttontext = isset($cfg['option']['upbuttontext']) ? $cfg['option']['upbuttontext'] : hst_lang('hstcms::fields.file.select.pic');
		$uptips = isset($cfg['option']['uptips']) ? $cfg['option']['uptips'] : '';
		$multiNum = isset($cfg['option']['multiNum']) ? $cfg['option']['multiNum'] : 5;
		$upapp = isset($cfg['option']['upapp']) ? $cfg['option']['upapp'] : '';
		// 是否必须
		$text = (isset($cfg['validate']['required']) && $cfg['validate']['required'] == 1 ? '<font color="red">*</font>&nbsp;' : '').$cname;
		// 字段提示信息
		$tips = isset($cfg['validate']['tips']) && $cfg['validate']['tips'] ? $cfg['validate']['tips'] : '';
		// 禁止修改
		$disabled = !$this->isadmin && $id && $value && isset($cfg['validate']['isedit']) && $cfg['validate']['isedit'] ? 'false' : 'true';
		$postDatas ='';
		$attachs = [];
		if ($value) {
			$attachs = $value;
		}
		$attachs = json_encode($attachs);
		$uploadUrl = route('uploadSave');
		$str = '<div class="hstui-upload J_upload_'.$name.'" style="line-height: 20px;"></div>';
		$str .= "<script>
			Hstui.use('jquery', 'common', 'upload', function() {
				$(\".J_upload_$name\").hstuiUpload({
					autoUpload: $upauto,
					selectText: '$upbuttontext',
					multi: true,
					multiNum: $multiNum, //多文件上传时允许的有效文件数
					fileName: 'filedata',
					fName: '$name',
					isedit: $disabled,
					dataList: $attachs,
					queue: {
					},
					showNote: '$uptips',
					url: '$uploadUrl',
					formParam: {
						upapp:'$upapp'
					}
				})
			})
		</script>";
		return $this->input_format($name, $text, $str, $tips);
	}
174036
public function setConstType($const_name, Type\Union $const_type)
    {
        self::$public_namespace_constants[$this->namespace_name][$const_name] = $const_type;
    }
806614
public void inc(String name, int con) throws IOException
    {
        if (hasLocalVariable(name))
        {
            tinc(name, con);
        }
        else
        {
            VariableElement field = El.getField(subClass, name);
            if (field == null)
            {
                throw new IllegalArgumentException("field "+name+" not found");
            }
            aload(0);
            getField(field);
            TypeMirror type = field.asType();
            tconst(type, con);
            tadd(type);
            aload(0);
            swap();
            putField(field);
        }
    }
305053
private static function init()
    {
        $config = Config::getEnv("database.redis");
        if (empty($config)) {
            throw new \InvalidArgumentException("配置项'database.redis'不能为空");
        }
        $config = (array) $config;
        $db_conn_name_list = \Qp\Kernel\Database\QpDB::getConnectionNameList();

        foreach ($config as $name => $data) {
            $name = strval($name);
            if (in_array($name, $db_conn_name_list)) {
                throw new \InvalidArgumentException("配置项'database.redis'的连接名'{$name}'和其他类型的数据库连接名冲突");
            }

            $data = (array) $data;
            if (empty($data)) {
                throw new \InvalidArgumentException("配置项'database.redis.{$name}'必须为非空数组");
            }
            $conn_name = $name;
            self::handleConfigArr($data, 'host', $host);
            self::handleConfigArr($data, 'auth', $auth);
            self::handleConfigArr($data, 'database', $database);
            self::handleConfigArr($data, 'port', $port);
            self::handleConfigArr($data, 'prefix', $prefix);

            $prefix = strval($prefix);
            if ($prefix == "") {
                $data['prefix'] = ":";
            } else {
                $data['prefix'] = "_" . $prefix . ":";
            }

            self::$config_list[$conn_name] = new ConfigObj($conn_name, $host, $auth, $database, $port, $data['prefix'], $data);
        }

        if (self::$frontCache === null) {
            self::$frontCache = new \Phalcon\Cache\Frontend\Data(self::$frontCacheData);
        }
    }