/*
返回最后插入行的ID或序列值
$name
516241
public function lastId($name = null)
    {
        try {
            return $this->pdoStatement->lastInsertId();
        } catch (\PDOException $e) {
            echo $e->getMessage();
        }
    }
757706
public function getConnection($name = null) {
        if (is_null($name)) {
            $name = $this->defaultConnectionName;
        }

        if (isset($this->connectionMap[$name])) {
            return $this->connectionMap[$name];
        }

        if (!isset($this->connectionConfigs[$name])) {
            throw new SqlException("未定义的数据库连接，连接名称：{$name}");
        }

        $connConfig = $this->connectionConfigs[$name];
        $conn = $this->buildConnection($connConfig);

        $this->connectionMap[$name] = $conn;
        return $conn;
    }
1195804
public function clone(string $id, string $name): ?string
  {
    if ( \bbn\str::is_uid($id) && ($id_menu = $this->add(['text' => $name])) ){
      if ( ($bits = $this->pref->get_full_bits($id)) && !$this->_clone($id_menu, $bits) ){
        return null;
      }
      return $id_menu;
    }
    return null;
  }
710337
function GenID($seq='adodbseq',$start=1)
	{
		// if you have to modify the parameter below, your database is overloaded,
		// or you need to implement generation of id's yourself!
		$MAXLOOPS = 100;
		//$this->debug=1;
		while (--$MAXLOOPS>=0) {
			$num = $this->GetOne("select id from $seq");
			if ($num === false) {
				$this->Execute(sprintf($this->_genSeqSQL ,$seq));
				$start -= 1;
				$num = '0';
				$ok = $this->Execute("insert into $seq values($start)");
				if (!$ok) return false;
			}
			$this->Execute("update $seq set id=id+1 where id=$num");

			if ($this->affected_rows() > 0) {
				$num += 1;
				$this->genID = $num;
				return $num;
			} elseif ($this->affected_rows() == 0) {
				// some drivers do not return a valid value => try with another method
				$value = $this->GetOne("select id from $seq");
				if ($value == $num + 1) {
					return $value;
				}
			}
		}
		if ($fn = $this->raiseErrorFn) {
			$fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
		}
		return false;
	}
304413
function(id) {
      if (id == null) return void 0;
      return this._byId[id.id != null ? id.id : id];
    }
638292
public function getNameId()
    {
        $nameIdvalue = null;
        $nameIdData = $this->getNameIdData();
        if (!empty($nameIdData) && isset($nameIdData['Value'])) {
            $nameIdvalue = $nameIdData['Value'];
        }
        return $nameIdvalue;
    }
249211
public function input($cname, $name, $cfg, $value = NULL, $id = 0) 
	{
		$source = isset($cfg['option']['source']) && $cfg['option']['source'] ? 'true' : 'false';
		$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.'：';
		// 表单宽度设置
		$width = isset($cfg['option']['width']) && $cfg['option']['width'] ? $cfg['option']['width'] : '90%';
		// 表单高度设置
		$key = isset($cfg['option']['key']) && $cfg['option']['key'] ? $cfg['option']['key'] : '';
		$height = isset($cfg['option']['height']) && $cfg['option']['height'] ? $cfg['option']['height'] : '300';
		// 字段提示信息
		$tips = isset($cfg['validate']['tips']) && $cfg['validate']['tips'] ? $cfg['validate']['tips']: '';
		$_pagebreak = isset($cfg['option']['pagebreak']) ? $cfg['option']['pagebreak'] : 0;
		// 字段默认值
		$value = $value ? $value : $cfg['option']['value'];
		$style = 'style="width:'.$width.';height:'.$height.'px;"';
		// 输出
		$str = '';
		$tool = $this->isadmin ? "" : ''; // 后台引用时显示html工具栏
		$pagebreak = $name == 'content' || $_pagebreak ? ', \'pagebreak\'' : '';
		// 编辑器模式
		$mode = $this->isadmin ? $cfg['option']['mode'] : (isset($cfg['option']['mode2']) ? $cfg['option']['mode2'] : $cfg['option']['mode']);
		switch ($mode) {
			case 3: // 自定义
				$tool.= $this->isadmin ? $cfg['option']['tool'] : (isset($cfg['option']['tool2']) ? $cfg['option']['tool2'] : $cfg['option']['tool']);
				break;
			case 2: // 精简
				$tool.= "'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
						'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
						'insertunorderedlist', '|', 'emoticons'$pagebreak";
				break;
			case 1: // 默认
                $tool.= "'justifyleft', 'justifycenter', 'justifyright',
		'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
		'superscript', 'clearhtml', 'quickformat','undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
		'plainpaste', 'wordpaste', '|',  'selectall', 'fullscreen','|', '/',
		'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
		'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
		'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap',
		'anchor', 'link', 'unlink'$pagebreak";
				break;
		}
		
		// $uploadJson = site_index_url('upload/index', $urlA);
		$uploadJson ='';
		$str.= "
		<textarea class=\"hstui-input hstui-textarea\" name=\"$name\" id=\"hstcms_$name\" $style>$value</textarea>
		<script type=\"text/javascript\">
			Hstui.use('jquery', 'common', 'kindeditor', function() {
				Hstui.editer('#hstcms_$name', {
					source:$source,
					items:[$tool]
				});
			})
		</script>
		";
		return $this->input_format($name, $text, $str, $tips);
	}
1053274
private static function execTask($name)
	{
		$file = fopen(self::$lockFileName, 'w+');
		if(false === $file)
		{
			return;
		}
		flock($file,LOCK_EX);
		// 执行任务
		$className = $name . 'Task';
		require_once APP_TASK . $className . '.class.php';
		$className::exec();
		Config::set('Task.List.' . $name . '.LastRunTime',time());
		Config::save('Task');
		fclose($file);
		unlink(self::$lockFileName);
	}
936960
private function select() {
        $this->performed  = true;
        $this->resultSet  = [];
        $this->resultSets = [];
        $this->resultIdx  = 0;
        $this->maxIdx     = 0;
        $this->size       = 0;
        try {
            $this->checkDialect();
        } catch (DialectException $e) {
            $this->error = $e->getMessage();

            return;
        }
        //生成SQL
        if (!$this->sql) {
            $this->sql = $this->getSQL();
            if (!$this->sql) {
                $this->error       = 'can not generate the SQL';
                $this->errorSQL    = '';
                $this->errorValues = $this->values->__toString();

                return;
            }
            //重新生成SQL.
            $this->statement = null;
        }
        //生成prepare statement
        if (!$this->statement) {
            $this->prepareStatement();
        }
        //执行
        if ($this->statement) {
            try {
                if ($this->values) {
                    foreach ($this->values as $value) {
                        list ($name, $val, $type, $field, $rkey) = $value;
                        if ($this->whereData) {
                            $val = isset($this->whereData[ $rkey ]) ? $this->whereData[ $rkey ] : (isset($this->whereData[ $name ]) ? $this->whereData[ $name ] : $val);
                        }
                        if (!$this->statement->bindValue($name, $val, $type)) {
                            $this->errorSQL    = $this->sql;
                            $this->errorValues = $this->values->__toString();
                            $this->error       = 'can not bind the value ' . $val . '[' . $type . '] to the argument:' . $name . '(' . $field . ')';

                            return;
                        }
                    }
                }
                $rst = $this->statement->execute();
                QueryBuilder::addSqlCount();
                if ($rst) {
                    $this->resultSets = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
                    $this->size       = count($this->resultSets);
                    if ($this->size > 0) {
                        $this->maxIdx    = $this->size - 1;
                        $this->resultSet = $this->resultSets[0];
                    }
                } else {
                    $this->dumpSQL($this->statement);
                }
            } catch (\PDOException $e) {
                $this->exception   = $e;
                $this->error       = $e->getMessage();
                $this->errorSQL    = $this->sql;
                $this->errorValues = $this->values->__toString();
            }
        }
    }
1258343
function copy($name, $new_name, $update = false)
	{
		//replace not-allowed characters with _
		$new_name = preg_replace('/([^a-zA-Z0-9_])/', '_', $new_name);

		//initialise response element
		$result = array();
		$result['status'] = false;

		if ($name && $new_name) {
			//check to see if an integration was selected
			$db = Factory::getDBO();

			$query = $db->getQuery(true)
				->select('count(*)')
				->from('#__jfusion')
				->where('original_name IS NULL')
				->where('name LIKE ' . $db->quote($name));

			$db->setQuery($query);
			$record = $db->loadResult();

			$query = $db->getQuery(true)
				->select('id')
				->from('#__jfusion')
				->where('name = ' . $db->quote($new_name));

			$db->setQuery($query);
			$exsist = $db->loadResult();
			if ($exsist) {
				throw new RuntimeException($new_name . ' ' . Text::_('ALREADY_IN_USE'));
			} else if ($record) {
				$JFusionPlugin = Factory::getAdmin($name);
				if ($JFusionPlugin->multiInstance()) {
					$db = Factory::getDBO();
					if (!$update) {
						//add the new entry in the JFusion plugin table
						$query = $db->getQuery(true)
							->select('*')
							->from('#__jfusion')
							->where('name = ' . $db->quote($name));

						$db->setQuery($query);
						$plugin_entry = $db->loadObject();
						$plugin_entry->name = $new_name;
						$plugin_entry->id = null;
						//only change the original name if this is not a copy itself
						if (empty($plugin_entry->original_name)) {
							$plugin_entry->original_name = $name;
						}
						$db->insertObject('#__jfusion', $plugin_entry, 'id');
					}
					$result['message'] = $new_name . ': ' . Text::_('PLUGIN') . ' ' . $name . ' ' . Text::_('COPY') . ' ' . Text::_('SUCCESS');
					$result['status'] = true;
				} else {
					throw new RuntimeException(Text::_('CANT_COPY'));
				}
			} else {
				throw new RuntimeException(Text::_('INVALID_SELECTED'));
			}
		} else {
			throw new RuntimeException(Text::_('NONE_SELECTED'));
		}
		return $result;
	}
45594
final function _generateID()
    {
        $uniqStr = function($length) {
            $char = "abcdefghijklmnopqrstuvwxyz0123456789";
            $char = str_shuffle($char);
            for($i = 0, $rand = '', $l = strlen($char) - 1; $i < $length; $i ++) {
                $rand .= $char{mt_rand(0, $l)};
            }

            return $rand;
        };

        if ($this->ID == null) {
            $class     = get_called_class();
            $module    = $this->deriveModuleNamespace($class);
            $widget    = $this->deriveWidgetName($class);

            $this->ID  = (($module != '') ? $this->inflectName($module).'_' : '')
                .$this->inflectName($widget).'_'.$uniqStr(5);
        }

        return $this->ID;
    }
694412
public function insert_id()
	{
		$query = version_compare($this->version(), '8', '>=')
			? 'SELECT SCOPE_IDENTITY() AS last_id'
			: 'SELECT @@IDENTITY AS last_id';

		$query = $this->query($query);
		$query = $query->row();
		return $query->last_id;
	}
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;
    }
1345658
private function ValidateMixTypeID($Name, $Value, $MaxLength = 1, $AllowEmpty = false)
        {
            if (empty($Value)) {
                // 是否允許空值
                $this->IsAllowEmpty($Name, $AllowEmpty);
            } else {
                // 格式檢查
                $this->IsValidFormat($Name, '/^[0-9a-zA-Z]{1,'.$MaxLength.'}$/', $Value);
            }
        }
355744
public function __callBefore($name, $arguments)
	{
		if(isset($arguments[0]))
		{
			// getBy字段支持：
			$arr = explode('getBy',$name);
			if(''===$arr[0] && isset($arr[1]))
			{
				return $this->getBy($arr[1], $arguments[0]);
			}
			// selectBy字段支持：
			$arr = explode('selectBy',$name);
			if(''===$arr[0] && isset($arr[1]))
			{
				return $this->selectBy($arr[1], $arguments[0]);
			}
			unset($arr);
			// 全部转为小写，照顾所有大小写习惯的用户
			$name = strtolower($name);
		}
	}
642908
function get_by_id($id, $ammend_query = '')
	{
		if (isset(self::$_cache[$this->_table][$id])) {
			//var_dump(self::$_cache[$this->_table][$id]);
			return self::$_cache[$this->_table][$id];
		}

		$q = \Fw\Db::prepare("select * from " . $this->_table . " where id=? " . $ammend_query);
		$q->execute(array($id));
		$res = $q->fetchObject($this->_entity);
		self::$_cache[$this->_table][$id] = $res;

		return $res;
	}
747482
public function nextId(){
        $timestamp = $this->timeGen();
        $lastTimestamp = self::$lastTimestamp;
        
        // check is correct
        if ($timestamp < $lastTimestamp) {
            throw new Exception("Clock moved backwards.  Refusing to generate id for %d milliseconds", ($lastTimestamp - $timestamp));
        }
        
        // build sequence, same process id can build more sequence
        if ($lastTimestamp == $timestamp) {
            $sequenceMask = -1 ^ (-1 << $this->sequenceBits);
            self::$sequence = (self::$sequence + 1) & $sequenceMask;
            if (self::$sequence == 0) {
                $timestamp = $this->tilNextMillis($lastTimestamp);
            }
        } else {
            //self::$sequence = 0;
            self::$sequence = mt_rand(0, 4095);
        }
        self::$lastTimestamp = $timestamp;
        
        //时间毫秒/数据中心ID/机器ID,要左移的位数
        $timestampLeftShift = $this->machineIdBits + $this->sequenceBits;
        //组合3段数据返回: 时间戳.工作机器.序列
        
        if ($this->machineIdBits) {
            $nextId = (($timestamp - self::$epochTimestamp) << $timestampLeftShift) | ($this->machineId << $this->sequenceBits) | self::$sequence;
        } else {
            $nextId = (($timestamp - self::$epochTimestamp) << $timestampLeftShift) | self::$sequence;
        }
        return $nextId;
    }