diff --git a/niucloud/niucloud/app/service/admin/auth/AuthService.php b/niucloud/niucloud/app/service/admin/auth/AuthService.php new file mode 100644 index 000000000..f275afbb9 --- /dev/null +++ b/niucloud/niucloud/app/service/admin/auth/AuthService.php @@ -0,0 +1,264 @@ +adminSiteId(); + //todo 将站点编号转化为站点id + $site_info = (new CoreSiteService())->getSiteCache($site_id); + //站点不存在 + if (empty($site_info)) throw new AuthException('SITE_NOT_EXIST'); + //没有当前站点的信息 + if (!AuthService::isSuperAdmin()) { + if (!$this->getAuthRole($site_id)) throw new AuthException('NO_SITE_PERMISSION'); + } + + $request->siteId($site_id); + $request->appType($site_info['app_type']); + return true; + } + + + /** + * 校验权限 + * @param Request $request + * @return bool + * @throws Exception + */ + public function checkRole(Request $request) + { + $this->checkAuthinfo($request); + + $rule = strtolower(trim($request->rule()->getRule())); + $method = strtolower(trim($request->method())); + $site_info = (new AuthSiteService())->getSiteInfo(); + if ($method != 'get') { +// throw new AuthException('演示站禁止操作'); + if ($site_info[ 'status' ] == SiteDict::EXPIRE) throw new AuthException('SITE_EXPIRE_NOT_ALLOW'); + if ($site_info[ 'status' ] == SiteDict::CLOSE) throw new AuthException('SITE_CLOSE_NOT_ALLOW'); + } + + $menu_service = new MenuService(); + $all_menu_list = $menu_service->getAllApiList($this->app_type); + //先判断当前访问的接口是否收到权限的限制 + $method_menu_list = $all_menu_list[$method] ?? []; + if (!in_array($rule, $method_menu_list)) { + $other_menu_list = $menu_service->getAllApiList($this->app_type == AppTypeDict::ADMIN ? AppTypeDict::SITE : AppTypeDict::ADMIN); + $method_menu_list = $other_menu_list[$method] ?? []; + if (!in_array($rule, $method_menu_list)) { + return true; + } else { + throw new AuthException('NO_PERMISSION'); + } + } + + $auth_role_list = $this->getAuthApiList(); + if (!empty($auth_role_list[$method]) && in_array($rule, $auth_role_list[$method])) + return true; + + throw new AuthException('NO_PERMISSION'); + + } + + public function checkAuthinfo(Request $request) { + $rule = strtolower(trim($request->rule()->getRule())); + $method = strtolower(trim($request->method())); + + if ($method == 'get') return; + + // niucloud/account/select、bind、cancel、token、logout:授权选择与官网登录态相关接口。 + // 授权域名校验本身依赖「已绑定的授权」,选择/更换/清除授权、以及登录/退出官网账号都是修复授权的前置动作, + // 必须豁免,否则域名与旧授权不一致时会陷入「校验失败 -> 无法重新选择授权」的死循环 + $ignore = ['niucloud/authinfo', 'upgrade', 'niucloud/build', 'sys/cache/clear', 'niucloud/account/select', 'niucloud/account/bind', 'niucloud/account/cancel', 'niucloud/account/token', 'niucloud/account/logout']; + foreach ($ignore as $item) { + if (strpos($rule, $item) !== false) return; + } + + $authinfo = []; + try { + $authinfo = (new CoreAuthService())->getAuthInfo()['data'] ?? [];; + } catch (Exception $e) { + } + if (empty($authinfo)) return; + + if (!$this->isCheckDomain()) return; + + $site_address = $authinfo['site_address'] ?? ''; + $domain = str_replace(['http://', 'https://'], '', request()->domain()); + + // 如果是站点域名不进行验证 + $site_id = (new CoreSiteService())->getSiteIdByDomain($domain); + if (!empty($site_id)) return; + + if (!empty($site_address) && strpos($domain, $site_address) !== false) return; + + throw new CommonException("授权域名校验失败!请确保当前访问域名与授权码绑定的域名一致"); + } + + private function isCheckDomain() { + return !(request()->ip() == '127.0.0.1' || request()->host() == 'localhost'); + } + + /** + * 获取授权用户的权限信息 + * @return mixed + */ + public function getAuthRole(int $site_id) + { + $user_role_service = new UserRoleService(); + return $user_role_service->getUserRole($site_id, $this->uid); + } + + /** + * 当前授权用户接口权限 + * @return array + */ + public function getAuthApiList() + { + if (AuthService::isSuperAdmin()) { + $is_admin = 1; + } else { + $user_role_info = $this->getAuthRole($this->site_id); + if (empty($user_role_info)) + return []; + + $is_admin = $user_role_info['is_admin'];//是否是超级管理员组 + } + + $menu_service = new MenuService(); + if ($is_admin) {//查询全部启用的权限 + //获取站点信息 + return (new AuthSiteService())->getApiList(1); + } else { + $user_role_ids = $user_role_info['role_ids']; + $role_service = new RoleService(); + $menu_keys = $role_service->getMenuIdsByRoleIds($this->site_id, $user_role_ids); + + return $menu_service->getApiListByMenuKeys($menu_keys, $this->app_type); + } + + } + + /** + * 当前授权用户菜单权限 + * @return array + */ + public function getAuthMenuList(int $is_tree = 0, $addon = 'all') + { + if (AuthService::isSuperAdmin()) { + $is_admin = 1; + } else { + $user_role_info = $this->getAuthRole($this->site_id); + if (empty($user_role_info)) + return []; + $is_admin = $user_role_info['is_admin'];//是否是超级管理员组 + } + + $menu_service = new MenuService(); + if ($is_admin) { + // 查询全部启用的权限 + $menu_list = (new MenuService())->getAllMenuList($this->app_type, 1, $is_tree, 1); + } else { + $user_role_ids = $user_role_info['role_ids']; + $role_service = new RoleService(); + $menu_keys = $role_service->getMenuIdsByRoleIds($this->site_id, $user_role_ids); + $menu_list = $menu_service->getMenuListByMenuKeys($this->site_id, $menu_keys, $this->app_type, $is_tree, $addon); + } + return $menu_list; + } + + /** + * 获取授权用户信息 + */ + public function getAuthInfo() + { + return (new SiteUserService())->getInfo($this->uid); + } + + /** + * 修改用户权限 + * @param string $field + * @param $data + * @return bool + */ + public function modifyAuth(string $field, $data) + { + return (new SiteUserService())->modify($this->uid, $field, $data); + } + + /** + * 修改用户 + * @param array $data + * @return true + */ + public function editAuth(array $data) + { + if (!empty($data['password'])) { + //检测原始密码是否正确 + $user = (new UserService())->find($this->uid); + if (!check_password($data['original_password'], $user->password)) + throw new AuthException('OLD_PASSWORD_ERROR'); + + } + return (new UserService())->edit($this->uid, $data); + } + + /** + * 是否是超级管理员 + * @return bool + */ + public static function isSuperAdmin() + { + $super_admin_uid = Cache::get('super_admin_uid'); + + if (!$super_admin_uid) { + $super_admin_uid = (new SysUserRole())->where([ + ['site_id', '=', request()->defaultSiteId()], + ['is_admin', '=', 1] + ])->value('uid'); + Cache::set('super_admin_uid', $super_admin_uid); + } + + return $super_admin_uid == (new self())->uid; + } + +} diff --git a/niucloud/niucloud/app/service/admin/niucloud/NiucloudAccountService.php b/niucloud/niucloud/app/service/admin/niucloud/NiucloudAccountService.php new file mode 100644 index 000000000..ccb832398 --- /dev/null +++ b/niucloud/niucloud/app/service/admin/niucloud/NiucloudAccountService.php @@ -0,0 +1,478 @@ + 清理 access_token 与 authinfo 缓存 -> 写 NIUCLOUD_CONFIG。 + */ +class NiucloudAccountService extends BaseAdminService +{ + /** + * 官网前端域名(embed 页所在站点) + */ + protected const OFFICIAL_WEB_HOST = 'https://www.niucloud.com'; + + /** + * 官网会员接口地址(与官网前端 VITE_APP_BASE_URL 一致,用于用 refresh_token 换取新的 access token) + * 可用环境变量 NIUCLOUD_API_PREFIX 覆盖(本地联调时指向本地官网接口) + */ + protected const DEFAULT_OFFICIAL_API_HOST = 'https://api.niucloud.com/api'; + + /** 续期得到的访问令牌本地缓存键(避免每次进页面都请求官网) */ + protected const ACCESS_TOKEN_CACHE_KEY = 'niucloud_web_access_token'; + + /** 距过期不足该秒数即提前续期,避免临界失效 */ + protected const TOKEN_REFRESH_AHEAD = 300; + + public $core_config_service; + + public function __construct() + { + parent::__construct(); + $this->core_config_service = new CoreConfigService(); + } + + /** + * 官网前端域名 + */ + public function getOfficialWebHost(): string + { + return rtrim(self::OFFICIAL_WEB_HOST, '/'); + } + + /** + * 本站域名(授权绑定用,不含协议与端口) + */ + public function getSiteDomain(): string + { + return request()->host(true); + } + + /** + * 生成本站的页面 origin(postMessage 校验用) + */ + public function getSiteOrigin(): string + { + return rtrim(request()->domain(), '/'); + } + + /** + * 生成官网 embed 页地址 + * + * @param string $mode login | authorize | switch + * @param string $origin 父页面 origin(由前端传 window.location.origin,最准确) + */ + public function getEmbedUrl(string $mode = 'login', string $origin = ''): array + { + $mode_path = [ + 'login' => 'login', + 'authorize' => 'authorize', + 'switch' => 'authorize', + 'account' => 'account' + ]; + $path = $mode_path[$mode] ?? 'login'; + $host = $origin ?: $this->getSiteOrigin(); + + $params = [ + 'host' => $host, + 'domain' => $this->getSiteDomain(), + 'mode' => $mode, + 'theme' => 'light', + // 当前产品线标识:内嵌页只展示符合本产品线的授权 + 'product_key' => BaseNiucloudClient::PRODUCT + ]; + // 官网登录态:本地缓存有效则直接用,过期则由服务端用 refresh_token 自动续期后注入 + $access_token = $this->getValidAccessToken(); + if (!empty($access_token)) $params['token'] = $access_token; + + $query = http_build_query($params); + + return [ + 'url' => $this->getOfficialWebHost() . '/embed/' . $path . '?' . $query, + 'host' => $host, + 'domain' => $this->getSiteDomain(), + 'mode' => $mode + ]; + } + + /** + * 获取账号与当前授权信息(只读本地配置,官网不可用时仍可展示) + * + * 授权信息统一取自系统授权配置 NIUCLOUD_CONFIG(选中授权即写入其中); + * 官网账号配置只保留登录态(token)、会员信息与同步状态 + */ + public function getAccountInfo(): array + { + $account = $this->getAccountConfig(); + $auth = $this->getAuthorizeConfig(); + + $authorization = !empty($auth['auth_code']) ? $this->buildAuthorizationFromLocal($auth) : []; + + return [ + // 系统已存在授权即视为“已有授权” + 'bound' => !empty($authorization['auth_code']), + // 是否已保存可用的官网登录态(前端据此决定内嵌登录页还是账号页,避免闪屏) + 'has_token' => $this->hasValidToken(), + // 登录态有效期:优先给刷新令牌的过期时间(访问令牌由服务端自动续期) + 'token_expires_time' => (int)($account['token']['refresh_expires_time'] ?? 0) ?: (int)($account['token']['expires_time'] ?? 0), + 'member' => $account['member'] ?? [], + 'authorization' => $authorization, + 'sync' => $account['sync'] ?? [] + ]; + } + + /** + * 保存官网账号登录态(内嵌页登录后回传的令牌) + * + * 说明: + * - 长期保存的是 refresh_token(access token 会过期,只有刷新令牌能实现长期免登录) + * - access token 只放缓存(短效),避免配置里长期存着一份会失效的凭据 + * - 官网旧版本未下发 refresh_token 时,退回只保存 access token,保证基本可用 + * - 不返回令牌内容,避免凭据外泄 + */ + public function saveToken(array $data): array + { + $token = trim((string)($data['token'] ?? '')); + $refresh_token = trim((string)($data['refresh_token'] ?? '')); + if (empty($token) && empty($refresh_token)) throw new CommonException('WEB_LOGIN_TOKEN_REQUIRE'); + + $expires_time = (int)($data['expires_time'] ?? 0); + $refresh_expires_time = (int)($data['refresh_expires_time'] ?? 0); + + $account = $this->getAccountConfig(); + $old_token = $account['token'] ?? []; + + $account['token'] = [ + // 长期凭据:access token 过期后用它换取新的 access token + 'refresh_token' => $refresh_token ?: ($old_token['refresh_token'] ?? ''), + 'refresh_expires_time' => $refresh_expires_time ?: (int)($old_token['refresh_expires_time'] ?? 0), + // 兼容:官网未下发刷新令牌时,退回保存访问令牌 + 'access_token' => $refresh_token ? '' : $token, + 'expires_time' => $refresh_token ? 0 : $expires_time, + 'update_time' => date('Y-m-d H:i:s') + ]; + $this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account); + + // 登录态已变更(含切换官网账号):先清掉上一份访问令牌缓存, + // 否则官网只回传 refresh_token 时,getValidAccessToken() 仍会优先返回上一个账号的令牌 + Cache::delete(self::ACCESS_TOKEN_CACHE_KEY); + + // 本次登录拿到的访问令牌直接进缓存,省去一次续期请求 + if (!empty($token)) $this->cacheAccessToken($token, $expires_time); + + return [ + 'has_token' => true, + 'token_expires_time' => $expires_time + ]; + } + + /** + * 可用的官网访问令牌(未登录 / 登录态已失效时返回空字符串) + * + * 优先级: + * 1. 本地缓存的访问令牌未过期(距过期不足 TOKEN_REFRESH_AHEAD 秒视为需续期)→ 直接返回 + * 2. 有未过期的 refresh_token → 向官网换取新的访问令牌(长期免登录的关键) + * 3. 兼容旧数据:只保存过访问令牌且未过期 → 直接返回 + */ + public function getValidAccessToken(): string + { + $auth_token = $this->getAccountConfig()['token'] ?? []; + + // 1. 本地缓存的访问令牌 + $cached = Cache::get(self::ACCESS_TOKEN_CACHE_KEY, []); + $cached_token = (string)($cached['token'] ?? ''); + $cached_expires = (int)($cached['expires_time'] ?? 0); + if (!empty($cached_token) && ($cached_expires <= 0 || $cached_expires > time() + self::TOKEN_REFRESH_AHEAD)) { + return $cached_token; + } + + // 2. 用刷新令牌续期 + $refresh_token = (string)($auth_token['refresh_token'] ?? ''); + if (!empty($refresh_token)) { + $refresh_expires_time = (int)($auth_token['refresh_expires_time'] ?? 0); + // 未记录有效期(0)时视为长期有效 + if ($refresh_expires_time > 0 && $refresh_expires_time <= time()) return ''; + + return $this->exchangeAccessToken($refresh_token); + } + + // 3. 兼容:仅保存过访问令牌 + $access_token = (string)($auth_token['access_token'] ?? ''); + if (empty($access_token)) return ''; + + $expires_time = (int)($auth_token['expires_time'] ?? 0); + if ($expires_time > 0 && $expires_time <= time()) return ''; + + return $access_token; + } + + /** + * 是否存在可用的官网登录态(refresh_token 未过期即视为可续期) + */ + public function hasValidToken(): bool + { + return $this->getValidAccessToken() !== ''; + } + + /** + * 官网会员接口地址 + */ + protected function getOfficialApiHost(): string + { + return rtrim((string)(env('NIUCLOUD_API_PREFIX') ?: self::DEFAULT_OFFICIAL_API_HOST), '/'); + } + + /** + * 缓存访问令牌(TTL 与令牌有效期对齐,未记录有效期时按 2 小时缓存) + */ + protected function cacheAccessToken(string $token, int $expires_time): void + { + $ttl = $expires_time > 0 ? max(60, $expires_time - time()) : 7200; + Cache::set(self::ACCESS_TOKEN_CACHE_KEY, [ + 'token' => $token, + 'expires_time' => $expires_time + ], $ttl); + } + + /** + * 官网会员接口客户端 + */ + protected function createOfficialClient(): Client + { + return new Client([ + 'base_uri' => $this->getOfficialApiHost() . '/', + 'timeout' => 10, + 'verify' => config('niucloud.http.verify', true) + ]); + } + + /** + * 用 refresh_token 向官网换取新的访问令牌(官网内嵌页专属接口 embed/refresh) + * + * 失败(网络异常 / 刷新令牌失效)返回空字符串,由调用方降级为"需重新登录", + * 不影响授权等其它功能。 + */ + protected function exchangeAccessToken(string $refresh_token): string + { + try { + $response = $this->createOfficialClient()->post('embed/refresh', [ + 'form_params' => [ 'refresh_token' => $refresh_token ] + ]); + $result = json_decode((string)$response->getBody(), true); + } catch (\Throwable $e) { + Log::write('官网登录态续期请求失败:' . $e->getMessage()); + return ''; + } + + $token = (string)($result['data']['token'] ?? ''); + if (empty($token)) { + Log::write('官网登录态续期失败:' . json_encode($result, JSON_UNESCAPED_UNICODE)); + return ''; + } + + $this->cacheAccessToken($token, (int)($result['data']['expires_time'] ?? 0)); + + return $token; + } + + /** + * 通知官网作废刷新令牌(官网内嵌页专属接口 embed/logout,幂等) + * + * 退出官网账号时调用,避免本地清掉后官网侧令牌仍可换取新的访问令牌; + * 失败只记日志,不阻塞本地退出。 + */ + protected function revokeRefreshToken(string $refresh_token): void + { + try { + $this->createOfficialClient()->post('embed/logout', [ + 'form_params' => [ 'refresh_token' => $refresh_token ] + ]); + } catch (\Throwable $e) { + Log::write('官网刷新令牌作废失败:' . $e->getMessage()); + } + } + + /** + * 选用授权:选中即写入系统授权配置(NIUCLOUD_CONFIG)并生效 + * + * 说明: + * - 复用现有授权校验链路:官网 authinfo 二次校验 -> 清理 authinfo/access_token 缓存 -> 写 NIUCLOUD_CONFIG + * - 校验不通过(授权码无效 / 官网不可达)会直接抛出异常,**不写入任何配置** + * - 不改动官网侧授权域名 + */ + public function saveSelectedAuth(array $data): array + { + $this->applyAuthorization($data); + + return $this->getAccountInfo(); + } + + /** + * 绑定授权(与选用授权等价,保留接口兼容) + */ + public function bindAuthorization(array $data): array + { + $this->applyAuthorization($data); + + return $this->getAccountInfo(); + } + + /** + * 取消选用授权:清空系统授权配置(NIUCLOUD_CONFIG),系统回到“未授权”状态 + * + * 说明: + * - 只清系统已选授权,不影响官网账号登录态(token / 会员信息保留),也不删除官网账号下的授权记录 + * - 幂等:本来就没有授权时同样返回成功 + * - 清空后依赖授权的功能(升级、应用下载、云编译等)会回到未授权状态 + * + * @param array $data 入参仅用于记录日志(auth_code 可选) + */ + public function cancelSelectedAuth(array $data = []): array + { + (new NiucloudService())->clearAuthorize(); + + $account = $this->getAccountConfig(); + $account['sync'] = [ + 'last_sync_time' => date('Y-m-d H:i:s'), + 'last_sync_status' => 'cancel' + ]; + $this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account); + + return $this->getAccountInfo(); + } + + /** + * 应用授权:把授权码/密钥写入系统授权配置 NIUCLOUD_CONFIG(选用 / 绑定共用) + * + * - 先校验后写:校验失败直接抛错,原有授权配置保持不变 + * - 授权信息只落 NIUCLOUD_CONFIG;官网账号配置仅更新同步状态 + */ + protected function applyAuthorization(array $data): void + { + $auth_code = $data['auth_code'] ?? ''; + $auth_secret = $data['auth_secret'] ?? ''; + if (empty($auth_code) || empty($auth_secret)) throw new CommonException('AUTH_NOT_EXISTS'); + + // 复用现有链路(含 authinfo 二次校验、缓存清理),不信任前端直接落库 + (new NiucloudService())->setAuthorize([ + 'auth_code' => $auth_code, + 'auth_secret' => $auth_secret + ]); + + $account = $this->getAccountConfig(); + // 授权信息已统一存于 NIUCLOUD_CONFIG,清掉历史遗留的副本 + unset($account['authorization']); + $account['sync'] = [ + 'last_sync_time' => date('Y-m-d H:i:s'), + 'last_sync_status' => 'success' + ]; + $this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account); + } + + /** + * 退出官网账号会话(仅清除账号信息,不解除本地授权) + */ + public function logout(): bool + { + $account = $this->getAccountConfig(); + // 主动作废官网侧的刷新令牌(失败不阻塞本地退出) + $refresh_token = (string)($account['token']['refresh_token'] ?? ''); + if (!empty($refresh_token)) $this->revokeRefreshToken($refresh_token); + + unset($account['member'], $account['token']); + // 一并清掉续期得到并缓存的访问令牌 + Cache::delete(self::ACCESS_TOKEN_CACHE_KEY); + $account['sync'] = [ + 'last_sync_time' => date('Y-m-d H:i:s'), + 'last_sync_status' => 'logout' + ]; + $this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account); + return true; + } + + /** + * 同步当前授权状态(读官网 authinfo,失败不抛出,仅记录状态) + */ + public function syncState(): array + { + $auth_info = []; + try { + $auth_info = (new CoreAuthService())->getAuthInfo()['data'] ?? []; + } catch (\Throwable $e) { + $auth_info = []; + } + + $account = $this->getAccountConfig(); + $account['sync'] = [ + 'last_sync_time' => date('Y-m-d H:i:s'), + 'last_sync_status' => empty($auth_info) ? 'fail' : 'success' + ]; + + // 官网记录的授权域名是否与本站一致:仅记录到同步信息里便于排查(授权信息本身在 NIUCLOUD_CONFIG) + if (!empty($auth_info)) { + $account['sync']['address_type'] = $auth_info['address_type'] ?? false; + } + + $this->core_config_service->setConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG, $account); + + return $this->getAccountInfo(); + } + + /** + * 官网账号配置 + */ + protected function getAccountConfig(): array + { + $config = $this->core_config_service->getConfig(0, ConfigKeyDict::NIUCLOUD_ACCOUNT_CONFIG); + return $config['value'] ?? []; + } + + /** + * 本地授权配置 + */ + protected function getAuthorizeConfig(): array + { + $config = $this->core_config_service->getConfig(0, ConfigKeyDict::NIUCLOUD_CONFIG); + return $config['value'] ?? []; + } + + /** + * 由系统授权配置构造授权信息(NIUCLOUD_CONFIG 只存 auth_code / auth_secret) + */ + protected function buildAuthorizationFromLocal(array $auth): array + { + return [ + 'auth_code' => $auth['auth_code'] ?? '', + 'site_address' => '', + 'company_name' => '', + 'product_key_name' => '', + 'source' => 'manual', + 'update_time' => '' + ]; + } +} diff --git a/niucloud/niucloud/app/service/admin/niucloud/NiucloudService.php b/niucloud/niucloud/app/service/admin/niucloud/NiucloudService.php new file mode 100644 index 000000000..ec8cf8cb4 --- /dev/null +++ b/niucloud/niucloud/app/service/admin/niucloud/NiucloudService.php @@ -0,0 +1,151 @@ +core_config_service = new CoreConfigService(); + + } + + /** + * 设置 授权信息 + * @param $data + * @return \app\model\sys\SysConfig|bool|\think\Model + */ + public function setAuthorize($data){ + + $data = [ + 'auth_code' => $data['auth_code'], + 'auth_secret' => $data['auth_secret'] + ]; + // 校验前先清缓存,否则更换授权码/密钥时校验会读到旧授权的数据: + // 1) authinfo 缓存是全局 key(不含授权码),不清会直接命中旧授权的信息,新授权码根本没被官网校验就落库 + // 2) access_token 与授权码绑定,留着旧 token 会让校验请求带上旧授权的令牌 + Cache::delete("authinfo"); + $service = (new CoreAuthService($data['auth_code'], $data['auth_secret'])); + $service->clearAccessToken(); + $auth_info = $service->getAuthInfo()['data'] ?? []; + if (empty($auth_info)) throw new CommonException('AUTH_NOT_EXISTS'); + return $this->core_config_service->setConfig(0,ConfigKeyDict::NIUCLOUD_CONFIG, $data); + } + + /** + * 清除授权信息(取消选用授权) + * + * 与 setAuthorize() 对称:删除 NIUCLOUD_CONFIG 配置并清理 authinfo / access_token 缓存, + * 避免升级、应用下载、云编译等依赖授权的功能仍读到已被取消的授权。 + * 幂等:本就没有授权时同样不报错。 + * + * @return bool + */ + public function clearAuthorize() + { + // 先取出旧授权,用于清理其 access_token 缓存(旧授权已失效时清理失败不影响取消动作) + $old = $this->getAuthorize(); + if (!empty($old['auth_code']) && !empty($old['auth_secret'])) { + try { + (new CoreAuthService($old['auth_code'], $old['auth_secret']))->clearAccessToken(); + } catch (\Throwable $e) { + // 忽略:旧授权凭据已失效 + } + } + + Cache::delete("authinfo"); + $this->core_config_service->clearConfig(0, ConfigKeyDict::NIUCLOUD_CONFIG); + + return true; + } + + /** + * 获取授权信息 + * @return mixed|string[] + */ + public function getAuthorize(){ + $info = $this->core_config_service->getConfig(0, ConfigKeyDict::NIUCLOUD_CONFIG); + if(empty($info)) + { + $info = []; + $info['value'] = [ + 'auth_code' => '', + 'auth_secret' => '' + ]; + } + return $info['value']; + } + + /** + * 获取框架最新版本 + */ + public function getFrameworkLastVersion() { + return (new CoreModuleService())->getFrameworkLastVersion(); + } + + /** + * 获取框架版本更新记录 + */ + public function getFrameworkVersionList() { + return (new CoreModuleService())->getFrameworkVersionList(); + } + + /** + * 获取应用/插件的版本更新记录 + */ + public function getAppVersionList($app_key) { + return (new CoreModuleService())->getAppVersionList($app_key); + } + + /** + * 设置 本地服务器地址 + * @param $data + * @return \app\model\sys\SysConfig|bool|\think\Model + */ + public function setLocalCloudCompileConfig($data){ + $data = [ + 'baseUri' => $data['url'], + 'isOpen' => $data['is_open'], + ]; + return $this->core_config_service->setConfig(0,'LOCAL_CLOUD_COMPILE_CONFIG', $data); + } + + /** + * 获取 本地服务器地址 + * @param $data + * @return \app\model\sys\SysConfig|bool|array|\think\Model + */ + public function getLocalCloudCompileConfig(){ + $config = $this->core_config_service->getConfig(0,'LOCAL_CLOUD_COMPILE_CONFIG')['value'] ?? []; + return [ + 'baseUri' => $config['baseUri'] ?? '', + 'isOpen' => $config['isOpen'] ?? 0, + ]; + + } + + +} diff --git a/niucloud/niucloud/vendor/topthink/think-orm/src/db/BaseQuery.php b/niucloud/niucloud/vendor/topthink/think-orm/src/db/BaseQuery.php new file mode 100644 index 000000000..4aafa8160 --- /dev/null +++ b/niucloud/niucloud/vendor/topthink/think-orm/src/db/BaseQuery.php @@ -0,0 +1,1757 @@ + +// +---------------------------------------------------------------------- +declare (strict_types = 1); + +namespace think\db; + +use Closure; +use Psr\SimpleCache\CacheInterface; +use ReflectionFunction; +use think\Collection; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException as Exception; +use think\db\exception\ModelNotFoundException; +use think\helper\Str; +use think\Model; +use think\Paginator; + +/** + * 数据查询基础类. + */ +abstract class BaseQuery +{ + use concern\TimeFieldQuery; + use concern\AggregateQuery; + use concern\ModelRelationQuery; + use concern\ParamsBind; + use concern\ResultOperation; + use concern\WhereQuery; + + /** + * 当前数据库连接对象 + * + * @var Connection + */ + protected $connection; + + /** + * 当前数据表名称(不含前缀). + * + * @var string + */ + protected $name = ''; + + /** + * 当前数据表主键. + * + * @var string|array + */ + protected $pk; + + /** + * 当前数据表自增主键. + * + * @var string + */ + protected $autoinc; + + /** + * 当前数据表前缀 + * + * @var string + */ + protected $prefix = ''; + + /** + * 当前数据表后缀 + * + * @var string + */ + protected $suffix = ''; + + /** + * 当前查询参数. + * + * @var array + */ + protected $options = []; + + /** + * 架构函数. + * + * @param ConnectionInterface $connection 数据库连接对象 + */ + public function __construct(ConnectionInterface $connection) + { + $this->connection = $connection; + $this->prefix = $this->getConfig('prefix'); + $timeRule = $this->getConfig('time_query_rule'); + if (!empty($timeRule)) { + $this->timeRule($timeRule); + } + } + + /** + * 利用__call方法实现一些特殊的Model方法. + * + * @param string $method 方法名称 + * @param array $args 调用参数 + * + * @throws Exception + * + * @return mixed + */ + public function __call(string $method, array $args) + { + if (strtolower(substr($method, 0, 5)) == 'getby') { + // 根据某个字段获取记录 + $field = Str::snake(substr($method, 5)); + + return $this->where($field, '=', $args[0])->find(); + } + + if (strtolower(substr($method, 0, 10)) == 'getfieldby') { + // 根据某个字段获取记录的某个值 + $name = Str::snake(substr($method, 10)); + + return $this->where($name, '=', $args[0])->value($args[1]); + } + + if (strtolower(substr($method, 0, 7)) == 'whereor') { + $name = Str::snake(substr($method, 7)); + array_unshift($args, $name); + + return call_user_func_array([$this, 'whereOr'], $args); + } + + if (strtolower(substr($method, 0, 5)) == 'where') { + $name = Str::snake(substr($method, 5)); + array_unshift($args, $name); + + return call_user_func_array([$this, 'where'], $args); + } + + if ($this->model && method_exists($this->model, 'scope' . $method)) { + // 动态调用命名范围 + array_unshift($args, $this); + $this->options['scope'][$method] = [[$this->model, 'scope' . $method], $args]; + + return $this; + } + + throw new Exception('method not exist:' . static::class . '->' . $method); + } + + /** + * 创建一个新的查询对象 + * + * @param string|null $class 查询对象类名 + * @return BaseQuery + */ + public function newQuery(?string $class = null): BaseQuery + { + if (null === $class) { + $query = new static($this->connection); + } else { + $query = new $class($this->connection); + } + + if ($this->model) { + $query->model($this->model); + } + + if (isset($this->options['table'])) { + $query->table($this->options['table']); + } else { + $query->name($this->name)->suffix($this->suffix); + } + + if (!empty($this->options['json'])) { + $query->json($this->options['json'], $this->options['json_assoc']); + } + + if (isset($this->options['field_type'])) { + $query->schema($this->options['field_type']); + } + + if (isset($this->options['lazy_fields'])) { + $query->lazyFields($this->options['lazy_fields']); + } + + return $query; + } + + /** + * 获取当前的数据库Connection对象 + * + * @return ConnectionInterface + */ + public function getConnection() + { + return $this->connection; + } + + /** + * 指定当前数据表名(不含前缀). + * + * @param string $name 不含前缀的数据表名字 + * + * @return $this + */ + public function name(string $name) + { + $this->name = $name; + + return $this; + } + + /** + * 指定当前数据表后缀. + * + * @param string $suffix 后缀 + * + * @return $this + */ + public function suffix(string $suffix) + { + $this->suffix = $suffix; + + return $this; + } + + /** + * 获取当前的数据表名称. + * + * @return string + */ + public function getName(): string + { + return $this->name ?: $this->model->getName(); + } + + /** + * 设置主键值. + * + * @param mixed $key 主键值 + * + * @return $this + */ + public function setKey($key) + { + $this->options['key'] = $key; + + return $this; + } + + /** + * 获取主键值. + * @param array $data 数据 + * + * @return mixed + */ + public function getKey(array $data = []) + { + if (!empty($data)) { + $pk = $this->getPk(); + if (is_string($pk) && isset($data[$pk])) { + $id = $data[$pk]; + } else { + $id = null; + } + return $id; + } + + return $this->getOption('key'); + } + + /** + * 获取数据库的配置参数. + * + * @param string $name 参数名称 + * + * @return mixed + */ + public function getConfig(string $name = '') + { + return $this->connection->getConfig($name); + } + + /** + * 得到当前数据表名称. + * @param bool $alias 是否返回数据表别名 + * + * @return string + */ + public function getTable(bool $alias = false) + { + if (isset($this->options['table'])) { + $table = $this->options['table']; + if ($alias && is_string($table) && !empty($this->options['alias'][$table])) { + return $this->options['alias'][$table]; + } + return $table; + } + + return $this->prefix . Str::snake($this->name) . $this->suffix; + } + + /** + * 设置字段类型信息. + * + * @param string $field 字段 + * @param string $type 字段类型 + * + * @return $this + */ + public function setFieldType(string $field, string $type) + { + $this->options['field_type'][$field] = $type; + + return $this; + } + + /** + * 设置字段类型信息. + * + * @param array $schema 字段类型信息 + * + * @return $this + */ + public function schema(array $schema) + { + $this->options['field_type'] = $schema; + + return $this; + } + + /** + * 设置只读字段. + * + * @param array $fields 只读字段 + * + * @return $this + */ + public function readonly(array $fields) + { + $this->options['readonly_fields'] = $fields; + + return $this; + } + + /** + * 获取最近一次查询的sql语句. + * + * @return string + */ + public function getLastSql(): string + { + return $this->connection->getLastSql(); + } + + /** + * 获取返回或者影响的记录数. + * + * @return int + */ + public function getNumRows(): int + { + return $this->connection->getNumRows(); + } + + /** + * 获取最近插入的ID. + * + * @param string|null $sequence 自增序列名 + * + * @return mixed + */ + public function getLastInsID(?string $sequence = null) + { + return $this->connection->getLastInsID($this, $sequence); + } + + /** + * 设置字段映射信息. + * + * @param array $map 字段映射信息 + * + * @return $this + */ + public function fieldMap(array $map) + { + $this->options['field_map'] = $map; + + return $this; + } + + /** + * 获取字段映射名 + * + * @param string $name 字段名 + * + * @return mixed + */ + public function getFieldMap(string $name) + { + $map = $this->getOption('field_map', []); + return $map[$name] ?? null; + } + + /** + * 得到某个字段的值 + * + * @param string $field 字段名 + * @param mixed $default 默认值 + * @param bool $useModelAttr 是否使用模型获取器 + * + * @return mixed + */ + public function value(string $field, $default = null, bool $useModelAttr = false) + { + $result = $this->connection->value($this, $field, $default); + + $array[$field] = $result; + if ($this->model && $useModelAttr) { + // JSON数据处理 + if (!empty($this->options['json'])) { + $this->jsonModelResult($array); + } + return $this->model->newInstance($array)->get($field); + } + + if (!empty($this->options['json'])) { + $this->jsonResult($array); + } + return $array[$field]; + } + + /** + * 得到某个字段的值 并且经过模型的获取器处理 + * + * @param string $field 字段名 + * @param mixed $default 默认值 + * + * @return mixed + */ + public function valueWithAttr(string $field, $default = null) + { + return $this->value($field, $default, true); + } + + /** + * 得到某个列的数组. + * + * @param string|array $field 字段名 多个字段用逗号分隔 + * @param string $key 索引 + * @param bool $useModelAttr 是否使用模型获取器 + * + * @return array + */ + public function column(string | array $field, string $key = '', bool $useModelAttr = false): array + { + $result = $this->connection->column($this, $field, $key); + return array_map(function ($item) use ($field, $useModelAttr) { + if (is_array($item)) { + if ($this->model && $useModelAttr) { + // JSON数据处理 + if (!empty($this->options['json'])) { + $this->jsonModelResult($item); + } + return $this->model->newInstance($item)->toArray(); + } + if (!empty($this->options['json'])) { + $this->jsonResult($item); + } + return $item; + } + + if (is_array($field) && 1 === count($field)) { + $field = current($field); + } + + $array[$field] = $item; + if ($this->model && $useModelAttr) { + if (!empty($this->options['json'])) { + $this->jsonModelResult($array); + } + return $this->model->newInstance($array)->get($field); + } + if (!empty($this->options['json'])) { + $this->jsonResult($array); + } + return $array[$field]; + }, $result); + } + + /** + * 得到某个列的数组 并且经过模型的获取器处理. + * + * @param string|array $field 字段名 多个字段用逗号分隔 + * @param string $key 索引 + * + * @return array + */ + public function columnWithAttr(string | array $field, string $key = '') + { + return $this->column($field, $key, true); + } + + /** + * 查询SQL组装 union. + * + * @param string|array|Closure $union UNION + * @param bool $all 是否适用UNION ALL + * + * @return $this + */ + public function union(string | array | Closure $union, bool $all = false) + { + $this->options['union']['type'] = $all ? 'UNION ALL' : 'UNION'; + + if (is_array($union)) { + $this->options['union'] = array_merge($this->options['union'], $union); + } else { + $this->options['union'][] = $union; + } + + return $this; + } + + /** + * 查询SQL组装 union all. + * + * @param mixed $union UNION数据 + * + * @return $this + */ + public function unionAll(string | array | Closure $union) + { + return $this->union($union, true); + } + + /** + * 指定查询字段. + * + * @param string|array|Raw|true $field 字段信息 + * + * @return $this + */ + public function field(string | array | Raw | bool $field) + { + if (empty($field)) { + return $this; + } elseif ($field instanceof Raw) { + $this->options['field'][] = $field; + + return $this; + } + + if (is_string($field)) { + if (preg_match('/[\<\'\"\(]/', $field)) { + return $this->fieldRaw($field); + } + + $field = array_map('trim', explode(',', $field)); + } + + if (true === $field) { + // 获取全部字段 + $fields = $this->getTableFields(); + $field = $fields ?: ['*']; + } + + if (isset($this->options['field'])) { + $field = array_merge((array) $this->options['field'], $field); + } + + $this->options['field'] = array_unique($field, SORT_REGULAR); + + return $this; + } + + /** + * 指定要排除的查询字段. + * + * @param array|string $field 要排除的字段 + * + * @return $this + */ + public function withoutField(array | string $field) + { + if (empty($field)) { + return $this; + } + + if (is_string($field)) { + $field = array_map('trim', explode(',', $field)); + } + + // 字段排除 + $fields = $this->getTableFields(); + $field = $fields ? array_diff($fields, $field) : $field; + + if (isset($this->options['field'])) { + $field = array_merge((array) $this->options['field'], $field); + } + + $this->options['field'] = array_unique($field, SORT_REGULAR); + + return $this; + } + + /** + * 指定其它数据表的查询字段. + * + * @param string|array|true $field 字段信息 + * @param string $tableName 数据表名 + * @param string $prefix 字段前缀 + * @param string $alias 别名前缀 + * + * @return $this + */ + public function tableField(string | array | bool $field, string $tableName, string $prefix = '', string $alias = '') + { + if (empty($field)) { + return $this; + } + + if (is_string($field)) { + $field = array_map('trim', explode(',', $field)); + } + + if (true === $field) { + // 获取全部字段 + $fields = $this->getTableFields($tableName); + $field = $fields ?: ['*']; + } + + // 添加统一的前缀 + $prefix = $prefix ?: $tableName; + foreach ($field as $key => &$val) { + // 兼容 field 数组中使用 Db::raw() 的表达式(如 ['total' => Db::raw('SUM(x) as total')]) + if (!is_string($val) || strpos($val, '.')) { + continue; + } + + if (is_numeric($key) && $alias) { + $field[$prefix . '.' . $val] = $alias . $val; + unset($field[$key]); + } elseif (is_numeric($key)) { + $val = $prefix . '.' . $val; + } + } + + if (isset($this->options['field'])) { + $field = array_merge((array) $this->options['field'], $field); + } + + $this->options['field'] = array_unique($field, SORT_REGULAR); + + return $this; + } + + /** + * 设置数据. + * + * @param array $data 数据 + * + * @return $this + */ + public function data(array $data) + { + $this->options['data'] = $data; + + return $this; + } + + /** + * 指定查询数量. + * + * @param int $offset 起始位置 + * @param int|null $length 查询数量 + * + * @return $this + */ + public function limit(int $offset, ?int $length = null) + { + $this->options['limit'] = $offset . ($length ? ',' . $length : ''); + + return $this; + } + + /** + * 指定分页. + * + * @param int $page 页数 + * @param int|null $listRows 每页数量 + * + * @return $this + */ + public function page(int $page, ?int $listRows = null) + { + $this->options['page'] = [$page, $listRows]; + + return $this; + } + + /** + * 指定当前操作的数据表. + * + * @param string|array|Raw $table 表名 + * + * @return $this + */ + public function table(string | array | Raw $table) + { + if (is_string($table) && !str_contains($table, ')')) { + $table = $this->tableStr($table); + } elseif (is_array($table)) { + $table = $this->tableArr($table); + } + + $this->options['table'] = $table; + return $this; + } + + /** + * 指定数据表(字符串). + * + * @param string $table 表名 + * + * @return array|string + */ + protected function tableStr(string $table): array | string + { + if (!str_contains($table, ',')) { + // 单表 + if (str_contains($table, ' ')) { + [$item, $alias] = explode(' ', $table); + $table = []; + $this->alias([$item => $alias]); + $table[$item] = $alias; + } + } else { + // 多表 + $tables = explode(',', $table); + $table = []; + + foreach ($tables as $item) { + $item = trim($item); + if (str_contains($item, ' ')) { + [$item, $alias] = explode(' ', $item); + $this->alias([$item => $alias]); + $table[$item] = $alias; + } else { + $table[] = $item; + } + } + } + return $table; + } + + /** + * 指定多个数据表(数组格式). + * + * @param array $tables 表名列表 + * + * @return array + */ + protected function tableArr(array $tables): array + { + $table = []; + foreach ($tables as $key => $val) { + if (is_numeric($key)) { + $table[] = $val; + } else { + $this->alias([$key => $val]); + $table[$key] = $val; + } + } + + return $table; + } + + /** + * 指定排序 order('id','desc') 或者 order(['id'=>'desc','create_time'=>'desc']). + * + * @param string|array|Raw $field 排序字段 + * @param string $order 排序 + * + * @return $this + */ + public function order(string | array | Raw $field, string $order = '') + { + if (empty($field)) { + return $this; + } elseif ($field instanceof Raw) { + $this->options['order'][] = $field; + return $this; + } + + if (is_string($field)) { + $field = $this->parseOrderField($this->getFieldMap($field) ?: $field); + if (is_string($field) && strpos($field, '->')) { + [$alias, $attr] = explode('->', $field, 2); + + $type = $this->getFieldType($alias); + if (is_null($type)) { + $this->hasWhere($alias); + $field = $alias . '.' . $attr; + } + } + + if (str_contains($field, ',')) { + $field = array_map('trim', explode(',', $field)); + } else { + $field = empty($order) ? $field : [$field => $order]; + } + } elseif (!empty($this->options['via'])) { + foreach ($field as $key => $val) { + if (is_numeric($key)) { + $field[$key] = $this->parseOrderField($val); + } else { + $key1 = $this->parseOrderField($key); + if ($key != $key1) { + $field[$key1] = $val; + unset($field[$key]); + } + } + } + } + + if (!isset($this->options['order'])) { + $this->options['order'] = []; + } + + if (is_array($field)) { + $this->options['order'] = array_merge($this->options['order'], $field); + } else { + $this->options['order'][] = $field; + } + + return $this; + } + + protected function parseOrderField(string $field): string + { + if (!empty($this->options['via']) && !str_contains($field, '.') && !str_contains($field, '->')) { + $field = $this->options['via'] . '.' . $field; + } + return $field; + } + /** + * 分页查询. + * + * @param int|array|null $listRows 每页数量 数组表示配置参数 + * @param int|bool $simple 是否简洁模式或者总记录数 + * + * @return Paginator + * + * @throws Exception + */ + public function paginate(int | array | null $listRows = null, int | bool $simple = false): Paginator + { + if (is_int($simple)) { + $total = $simple; + $simple = false; + } + + $defaultConfig = [ + 'query' => [], //url额外参数 + 'fragment' => '', //url锚点 + 'var_page' => 'page', //分页变量 + 'list_rows' => 15, //每页数量 + ]; + + if (is_array($listRows)) { + $config = array_merge($defaultConfig, $listRows); + $listRows = intval($config['list_rows']); + } else { + $config = $defaultConfig; + $listRows = intval($listRows ?: $config['list_rows']); + } + + $page = isset($config['page']) ? (int) $config['page'] : Paginator::getCurrentPage($config['var_page']); + $page = max($page, 1); + $config['path'] = $config['path'] ?? Paginator::getCurrentPath(); + + if (!isset($total) && !$simple) { + $options = $this->getOptions(); + + unset($this->options['order'], $this->options['cache'], $this->options['limit'], $this->options['page'], $this->options['field']); + + $bind = $this->bind; + $total = $this->count(); + if ($total > 0) { + $results = $this->options($options)->bind($bind)->page($page, $listRows)->select(); + } else { + if (!empty($this->model)) { + $results = new \think\model\Collection([]); + } else { + $results = new \think\Collection([]); + } + } + } elseif ($simple) { + $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select(); + $total = null; + } else { + $results = $this->page($page, $listRows)->select(); + } + + $this->removeOption('limit'); + $this->removeOption('page'); + + return Paginator::make($results, $listRows, $page, $total, $simple, $config); + } + + /** + * 根据数字类型字段进行分页查询(大数据). + * + * @param int|array|null $listRows 每页数量或者分页配置 + * @param string|null $key 分页索引键 + * @param string|null $sort 索引键排序 asc|desc + * + * @return Paginator + * + * @throws Exception + */ + public function paginateX(int | array | null $listRows = null, ?string $key = null, ?string $sort = null): Paginator + { + $defaultConfig = [ + 'query' => [], //url额外参数 + 'fragment' => '', //url锚点 + 'var_page' => 'page', //分页变量 + 'list_rows' => 15, //每页数量 + ]; + + $config = is_array($listRows) ? array_merge($defaultConfig, $listRows) : $defaultConfig; + $listRows = is_int($listRows) ? $listRows : (int) $config['list_rows']; + $page = isset($config['page']) ? (int) $config['page'] : Paginator::getCurrentPage($config['var_page']); + $page = max($page, 1); + + $config['path'] = $config['path'] ?? Paginator::getCurrentPath(); + + $key = $key ?: $this->getPk(); + $options = $this->getOptions(); + + if (is_null($sort)) { + $order = $options['order'] ?? ''; + if (!empty($order)) { + $sort = $order[$key] ?? 'desc'; + } else { + $this->order($key, 'desc'); + $sort = 'desc'; + } + } else { + $this->order($key, $sort); + } + + $newOption = $options; + unset($newOption['field'], $newOption['page']); + + $data = $this->newQuery() + ->options($newOption) + ->field($key) + ->where(true) + ->order($key, $sort) + ->limit(1) + ->find(); + + $result = $data[$key] ?? 0; + + if (is_numeric($result)) { + $lastId = 'asc' == $sort ? ($result - 1) + ($page - 1) * $listRows : ($result + 1) - ($page - 1) * $listRows; + } else { + throw new Exception('not support type'); + } + + $results = $this->when($lastId, function ($query) use ($key, $sort, $lastId) { + $query->where($key, 'asc' == $sort ? '>' : '<', $lastId); + }) + ->limit($listRows) + ->select(); + + $this->options($options); + + return Paginator::make($results, $listRows, $page, null, true, $config); + } + + /** + * 根据最后ID查询更多N个数据. + * + * @param int $limit 数量 + * @param int|string|null $lastId 最后ID + * @param string|null $key 分页索引键 默认为主键 + * @param string|null $sort 索引键排序 asc|desc + * + * @return array + * + * @throws Exception + */ + public function more(int $limit, int | string | null $lastId = null, ?string $key = null, ?string $sort = null): array + { + $key = $key ?: $this->getPk(); + + if (is_null($sort)) { + $order = $this->getOption('order'); + if (!empty($order)) { + $sort = $order[$key] ?? 'desc'; + } else { + $this->order($key, 'desc'); + $sort = 'desc'; + } + } else { + $this->order($key, $sort); + } + + $result = $this->when($lastId, function ($query) use ($key, $sort, $lastId) { + $query->where($key, 'asc' == $sort ? '>' : '<', $lastId); + })->limit($limit)->select(); + + $last = $result->last(); + + $result->first(); + + return [ + 'data' => $result, + 'lastId' => $last ? $last[$key] : null, + ]; + } + + /** + * 获取当前的缓存对象 + * + * @return CacheInterface|null + */ + public function getCache() + { + return $this->getConnection()->getCache(); + } + + /** + * 查询缓存 数据为空不缓存. + * + * @param mixed $key 缓存key + * @param int|\DateTime $expire 缓存有效期 + * @param string|array $tag 缓存标签 + * + * @return $this + */ + public function cache($key = true, $expire = null, $tag = null) + { + if (false === $key || !$this->getCache()) { + return $this; + } + + if ($key instanceof \DateTimeInterface || $key instanceof \DateInterval || (is_int($key) && is_null($expire))) { + $expire = $key; + $key = true; + } + + $this->options['cache'] = [$key, $expire, $tag ?: $this->getTable()]; + return $this; + } + + /** + * 查询缓存 允许缓存空数据. + * + * @param mixed $key 缓存key + * @param int|\DateTime $expire 缓存有效期 + * @param string|array $tag 缓存标签 + * + * @return $this + */ + public function cacheAlways($key = true, $expire = null, $tag = null) + { + $this->options['cache_always'] = true; + return $this->cache($key, $expire, $tag); + } + + /** + * 强制更新缓存 + * + * @param mixed $key 缓存key + * @param int|\DateTime $expire 缓存有效期 + * @param string|array $tag 缓存标签 + * + * @return $this + */ + public function cacheForce($key = true, $expire = null, $tag = null) + { + $this->options['force_cache'] = true; + + return $this->cache($key, $expire, $tag); + } + + /** + * 指定查询lock. + * + * @param bool|string $lock 是否lock + * + * @return $this + */ + public function lock(bool | string $lock = false) + { + $this->options['lock'] = $lock; + + if ($lock) { + $this->options['master'] = true; + } + + return $this; + } + + /** + * 指定数据表别名. + * + * @param array|string $alias 数据表别名 + * + * @return $this + */ + public function alias(array | string $alias) + { + if (is_array($alias)) { + $this->options['alias'] = $alias; + } else { + $table = $this->getTable(); + + $this->options['alias'][$table] = $alias; + } + + return $this; + } + + /** + * 获取数据表别名. + * + * @param string $table 数据表(留空取当前表) + * + * @return string + */ + public function getAlias(string $table = '') + { + if ('' === $table) { + $table = $this->getTable(); + } + + return $this->options['alias'][$table] ?? ''; + } + + /** + * 设置从主服务器读取数据. + * + * @param bool $readMaster 是否从主服务器读取 + * + * @return $this + */ + public function master(bool $readMaster = true) + { + $this->options['master'] = $readMaster; + + return $this; + } + + /** + * 设置是否严格检查字段名. + * + * @param bool $strict 是否严格检查字段 + * + * @return $this + */ + public function strict(bool $strict = true) + { + $this->options['strict'] = $strict; + + return $this; + } + + /** + * 设置自增序列名. + * + * @param string|null $sequence 自增序列名 + * + * @return $this + */ + public function sequence(?string $sequence = null) + { + $this->options['sequence'] = $sequence; + + return $this; + } + + /** + * 设置JSON字段信息. + * + * @param array $json JSON字段 + * @param bool $assoc 是否取出数组 + * + * @return $this + */ + public function json(array $json = [], bool $assoc = false) + { + $this->options['json'] = $json; + $this->options['json_assoc'] = $assoc; + + return $this; + } + + /** + * 设置延迟写入字段 用于实时获取缓存数据 + * + * @param array $fields 延迟写入字段 + * + * @return $this + */ + public function lazyFields(array $fields) + { + $this->options['lazy_fields'] = $fields; + + return $this; + } + + /** + * 指定数据表主键. + * + * @param string|array|bool|null $pk 主键 + * + * @return $this + */ + public function pk(string | array | bool | null $pk) + { + $this->pk = $pk; + + return $this; + } + + /** + * 查询参数批量赋值 + * + * @param array $options 表达式参数 + * + * @return $this + */ + protected function options(array $options) + { + $this->options = $options; + + return $this; + } + + /** + * 获取所有查询参数. + * + * @return mixed + */ + public function getOptions(): array + { + return $this->options; + } + + /** + * 获取查询参数. + * + * @param string $name 参数名 + * @param mixed $default 默认值 + * + * @return mixed + */ + public function getOption(string $name, $default = null) + { + return $this->options[$name] ?? $default; + } + + /** + * 设置当前的查询参数. + * + * @param string $option 参数名 + * @param mixed $value 参数值 + * + * @return $this + */ + public function setOption(string $option, $value) + { + $this->options[$option] = $value; + + return $this; + } + + /** + * 去除查询参数. + * + * @param string $option 参数名 留空去除所有参数 + * + * @return $this + */ + public function removeOption(string $option = '') + { + if ('' === $option) { + $this->options = []; + $this->bind = []; + } elseif (isset($this->options[$option])) { + unset($this->options[$option]); + } + + return $this; + } + + /** + * 设置当前字段添加的表别名. + * + * @param string $via 临时表别名 + * + * @return $this + */ + public function via(string $via = '') + { + $this->options['via'] = $via; + + return $this; + } + + /** + * 保存记录 自动判断insert或者update. + * + * @param array $data 数据 + * @param bool $forceInsert 是否强制insert + * + * @return int + */ + public function save(array $data = [], bool $forceInsert = false) + { + if ($forceInsert) { + return $this->insert($data); + } + + $this->options['data'] = array_merge($this->options['data'] ?? [], $data); + + if (!empty($this->options['where'])) { + $isUpdate = true; + } else { + $isUpdate = $this->parseUpdateData($this->options['data']); + } + + return $isUpdate ? $this->update() : $this->insert(); + } + + /** + * 插入记录. + * + * @param array $data 数据 + * @param bool $getLastInsID 返回自增主键 + * + * @return int|string + */ + public function insert(array $data = [], bool $getLastInsID = false) + { + if (!empty($data)) { + $this->options['data'] = $data; + } + + return $this->connection->insert($this, $getLastInsID); + } + + /** + * 插入记录并获取自增ID. + * + * @param array $data 数据 + * + * @return int|string + */ + public function insertGetId(array $data) + { + return $this->insert($data, true); + } + + /** + * 批量插入记录. + * + * @param array $dataSet 数据集 + * @param int $limit 每次写入数据限制 + * + * @return int + */ + public function insertAll(array $dataSet = [], int $limit = 0): int + { + if (empty($dataSet)) { + $dataSet = $this->options['data'] ?? []; + } + + if ($limit) { + $this->limit($limit); + } + + return $this->connection->insertAll($this, $dataSet); + } + + /** + * 批量插入记录 + * @access public + * @param array $keys 键值 + * @param array $values 数据 + * @param integer $limit 每次写入数据限制 + * @return integer + */ + public function insertAllByKeys(array $keys, array $values, int $limit = 0): int + { + if ($limit) { + $this->limit($limit); + } + + return $this->connection->insertAllByKeys($this, $keys, $values); + } + + /** + * 通过Select方式插入记录. + * + * @param array $fields 要插入的数据表字段名 + * @param string $table 要插入的数据表名 + * + * @return int + */ + public function selectInsert(array $fields, string $table): int + { + return $this->connection->selectInsert($this, $fields, $table); + } + + /** + * 更新记录. + * + * @param array $data 数据 + * + * @throws Exception + * + * @return int + */ + public function update(array $data = []): int + { + if (!empty($data)) { + $this->options['data'] = array_merge($this->options['data'] ?? [], $data); + } + + if (empty($this->options['where'])) { + $this->parseUpdateData($this->options['data']); + } + + if (empty($this->options['where']) && empty($this->options['scope'])) { + // 如果没有任何更新条件则不执行 + throw new Exception('miss update condition'); + } + + // 检查只读字段 + if (!empty($this->options['readonly_fields'])) { + foreach ($this->options['readonly_fields'] as $field) { + if (array_key_exists($field, $this->options['data'])) { + unset($this->options['data'][$field]); + } + } + } + + return $this->connection->update($this); + } + + /** + * 删除记录. + * + * @param mixed $data 表达式 true 表示强制删除 + * + * @throws Exception + * + * @return int + */ + public function delete($data = null): int + { + if (!is_null($data) && true !== $data) { + // AR模式分析主键条件 + $this->parsePkWhere($data); + } + + if (empty($this->options['where']) && !empty($this->options['key'])) { + if (is_array($this->pk)) { + $this->where($this->options['key']); + } else { + $this->where($this->pk, '=', $this->options['key']); + } + } + + if (true !== $data && empty($this->options['where']) && empty($this->options['scope'])) { + // 如果条件为空 不进行删除操作 除非设置 1=1 + throw new Exception('delete without condition'); + } + + if (!empty($this->options['soft_delete'])) { + // 软删除 + list($field, $condition) = $this->options['soft_delete']; + if ($condition) { + unset($this->options['soft_delete']); + $this->options['data'] = [$field => $condition]; + + return $this->connection->update($this); + } + } + + $this->options['data'] = $data; + + return $this->connection->delete($this); + } + + /** + * 查找记录. + * + * @param array $data 主键数据 + * + * @throws Exception + * @throws ModelNotFoundException + * @throws DataNotFoundException + * + * @return Collection + */ + public function select(array $data = []): Collection + { + if (!empty($data)) { + // 主键条件分析 + $this->parsePkWhere($data); + } + + $resultSet = $this->connection->select($this); + + // 返回结果处理 + if (!empty($this->options['fail']) && count($resultSet) == 0) { + $this->throwNotFound(); + } + + // 数据列表读取后的处理 + if (!empty($this->model)) { + // 生成模型对象 + $resultSet = $this->resultSetToModelCollection($resultSet); + } else { + $this->resultSet($resultSet); + } + + return $resultSet; + } + + /** + * 查找单条记录. + * + * @param mixed $data 主键数据 + * @param ?Closure $closure 闭包数据 + * + * @throws Exception + * @throws ModelNotFoundException + * @throws DataNotFoundException + * + * @return mixed|static + */ + public function find($data = null, ?Closure $closure = null) + { + if ($data instanceof Closure) { + $closure = $data; + } elseif (!is_null($data)) { + // AR模式分析主键条件 + $this->parsePkWhere($data); + } + + if (empty($this->options['where']) && empty($this->options['scope']) && empty($this->options['order']) && empty($this->options['sort'])) { + $result = []; + } else { + $result = $this->connection->find($this); + } + + // 数据处理 + if (empty($result)) { + return $this->resultToEmpty($closure); + } + + if (!empty($this->model)) { + // 返回模型对象 + $this->resultToModel($result); + } else { + $this->result($result); + } + + return $result; + } + + /** + * 分析表达式(可用于查询或者写入操作). + * + * @return array + */ + public function parseOptions(): array + { + // 执行全局查询范围 + $this->scopeQuery(); + + $options = $this->getOptions(); + + // 获取数据表 + if (empty($options['table'])) { + $options['table'] = $this->getTable(); + } + + if (!isset($options['where'])) { + $options['where'] = []; + } elseif (isset($options['view'])) { + // 视图查询条件处理 + $this->parseView($options); + } + + foreach (['data', 'order', 'join', 'union', 'filter', 'json', 'with_attr', 'with_relation_attr'] as $name) { + if (!isset($options[$name])) { + $options[$name] = []; + } + } + + if (!isset($options['strict'])) { + $options['strict'] = $this->getConfig('fields_strict'); + } + + foreach (['master', 'lock', 'fetch_sql', 'array', 'distinct', 'procedure', 'with_cache'] as $name) { + if (!isset($options[$name])) { + $options[$name] = false; + } + } + + foreach (['group', 'having', 'limit', 'force', 'comment', 'partition', 'duplicate', 'extra'] as $name) { + if (!isset($options[$name])) { + $options[$name] = ''; + } + } + + if (isset($options['page'])) { + // 根据页数计算limit + [$page, $listRows] = $options['page']; + + $page = $page > 0 ? $page : 1; + $listRows = $listRows ?: (is_numeric($options['limit']) ? $options['limit'] : 20); + $offset = $listRows * ($page - 1); + + $options['limit'] = $offset . ',' . $listRows; + } + + $this->options = $options; + + return $options; + } + + /** + * 分析数据是否存在更新条件. + * + * @param array $data 数据 + * + * @throws Exception + * + * @return bool + */ + public function parseUpdateData(array &$data): bool + { + $pk = $this->getPk(); + $isUpdate = false; + // 如果存在主键数据 则自动作为更新条件 + if (!empty($this->options['key'])) { + if (is_array($pk)) { + $this->where($this->options['key']); + } else { + $this->where($pk, '=', $this->options['key']); + } + $isUpdate = true; + } elseif (is_string($pk) && isset($data[$pk])) { + $this->where($pk, '=', $data[$pk]); + $this->options['key'] = $data[$pk]; + unset($data[$pk]); + $isUpdate = true; + } elseif (is_array($pk)) { + foreach ($pk as $field) { + if (isset($data[$field])) { + $this->where($field, '=', $data[$field]); + $isUpdate = true; + } else { + // 如果缺少复合主键数据则不执行 + throw new Exception('miss complex primary data'); + } + unset($data[$field]); + } + } + + return $isUpdate; + } + + /** + * 把主键值转换为查询条件 支持复合主键. + * + * @param mixed $data 主键数据 + * + * @throws Exception + * + * @return void + */ + public function parsePkWhere($data): void + { + $pk = $this->getPk(); + + if (!is_string($pk)) { + return; + } + + // 获取数据表 + if (empty($this->options['table'])) { + $this->options['table'] = $this->getTable(); + } + + $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table']; + + if (!empty($this->options['alias'][$table])) { + $alias = $this->options['alias'][$table]; + } + + $key = isset($alias) ? $alias . '.' . $pk : $pk; + // 根据主键查询 + if (is_array($data)) { + $this->where($key, 'in', $data); + } else { + $this->where($key, '=', $data); + $this->options['key'] = $data; + } + } + + /** + * 获取当前的查询标识. + * + * @return string + */ + public function getQueryGuid(): string + { + $data = $this->options; + unset($data['scope'], $data['default_model']); + $data['database'] = $this->getConfig('database'); + $data['table'] = $this->getTable(); + foreach (['AND', 'OR', 'XOR'] as $logic) { + if (isset($data['where'][$logic])) { + foreach ($data['where'][$logic] as $key => $val) { + if ($val instanceof Closure) { + $reflection = new ReflectionFunction($val); + $properties = $reflection->getStaticVariables(); + if (empty($properties)) { + $name = $reflection->getName() . $reflection->getStartLine() . '-' . $reflection->getEndLine(); + } else { + $name = var_export($properties, true); + } + $data['Closure'][] = $name; + unset($data['where'][$logic][$key]); + } + } + } + } + + return md5(serialize(var_export($data, true)) . serialize($this->getBind(false))); + } +} diff --git a/niucloud/niucloud/vendor/topthink/think-orm/src/model/relation/OneToOne.php b/niucloud/niucloud/vendor/topthink/think-orm/src/model/relation/OneToOne.php new file mode 100644 index 000000000..8edeb2eeb --- /dev/null +++ b/niucloud/niucloud/vendor/topthink/think-orm/src/model/relation/OneToOne.php @@ -0,0 +1,372 @@ + +// +---------------------------------------------------------------------- + +namespace think\model\relation; + +use Closure; +use think\db\BaseQuery as Query; +use think\db\exception\DbException as Exception; +use think\db\exception\InvalidArgumentException; +use think\helper\Str; +use think\model\contract\Modelable as Model; +use think\model\Relation; + +/** + * 一对一关联基础类. + */ +abstract class OneToOne extends Relation +{ + /** + * JOIN类型. + * + * @var string + */ + protected $joinType = 'INNER'; + + /** + * 绑定的关联属性. + * + * @var array + */ + protected $bindAttr = []; + + /** + * 关联名. + * + * @var string + */ + protected $relation; + + /** + * 获取一对多关联的最新一条数据. + * + * @param string $field 排序字段 + * + * @return $this + */ + public function firstOfMany(string $field = '') + { + return $this->first($field); + } + + /** + * 获取一对多关联的最旧一条数据. + * + * @param string $field 排序字段 + * + * @return $this + */ + public function lastOfMany(string $field = '') + { + return $this->last($field); + } + + /** + * 设置join类型. + * + * @param string $type JOIN类型 + * + * @return $this + */ + public function joinType(string $type) + { + $this->joinType = $type; + return $this; + } + + /** + * 预载入关联查询(JOIN方式). + * + * @param Query $query 查询对象 + * @param string $relation 关联名 + * @param mixed $field 关联字段 + * @param string $joinType JOIN方式 + * @param Closure $closure 闭包条件 + * @param bool $first + * + * @return void + */ + public function eagerly(Query $query, string $relation, $field = true, string $joinType = '', ?Closure $closure = null, bool $first = false): void + { + $name = Str::snake(class_basename($this->parent)); + + if ($first) { + $table = $query->getTable(); + $query->table([$table => $name]); + + if ($query->getOption('field')) { + $masterField = $query->getOption('field'); + $query->removeOption('field'); + } else { + $masterField = true; + } + + $query->tableField($masterField, $table, $name); + } + + // 预载入封装 + $joinTable = $this->query->getTable(); + // think-orm 3.x → 4.x 兼容:恢复 JOIN 别名使用「关联名原样」 + // 4.x 改为 Str::snake($relation),会把别名从 goodsSku 变成 goods_sku, + // 导致业务代码 where/field 里的 goodsSku.xxx 关系名前缀与别名不匹配, + // 报 SQLSTATE[42S22] 1054 Unknown column 'goodsSku.xxx'。 + $joinAlias = $relation; + $joinType = $joinType ?: $this->joinType; + if (true !== $field) { + $joinField = $field; + } elseif ($this->query->getOption('field')) { + $joinField = $this->query->getOption('field'); + } else { + $joinField = $field; + } + + $query->via($joinAlias); + + if ($this instanceof BelongsTo) { + $foreignKeyExp = $this->foreignKey; + + if (!str_contains($foreignKeyExp, '.')) { + $foreignKeyExp = $name . '.' . $this->foreignKey; + } + + $joinOn = $foreignKeyExp . '=' . $joinAlias . '.' . $this->localKey; + } else { + $foreignKeyExp = $this->foreignKey; + + if (!str_contains($foreignKeyExp, '.')) { + $foreignKeyExp = $joinAlias . '.' . $this->foreignKey; + } + + $joinOn = $name . '.' . $this->localKey . '=' . $foreignKeyExp; + } + + if ($closure) { + // 备份主查询字段:闭包里的 field 属于主查询,不能当作关联 JOIN 字段。 + // 否则 tableField() 会把已带表前缀的主查询字段当作关联字段全部跳过, + // 导致 JOIN 表的所有字段都不会被 SELECT,关联数据始终为空。 + $masterField = $query->getOption('field'); + $masterField = $masterField ? (array) $masterField : []; + + // 执行闭包查询(附加筛选条件,兼容 3.x 在闭包中写 field 的用法) + $closure($query); + + // 闭包里的 field 属于主查询(含 real_name as related_name 这类别名), + // 合并回主查询字段;关联表字段仍按全字段追加,保证关联数据可取。 + $closureField = $query->getOption('field'); + if (!empty($closureField)) { + foreach ((array) $closureField as $key => $item) { + if (is_int($key)) { + if (!in_array($item, $masterField, true)) { + $masterField[] = $item; + } + } else { + $masterField[$key] = $item; + } + } + } + + if (empty($masterField)) { + $query->removeOption('field'); + } else { + $query->setOption('field', $masterField); + } + } + + $query->join([$joinTable => $joinAlias], $joinOn, $joinType) + ->tableField($joinField, $joinTable, $joinAlias, $joinAlias . '__'); + } + + /** + * 预载入关联查询(数据集). + * + * @param array $resultSet + * @param string $relation + * @param array $subRelation + * @param Closure $closure + * + * @return mixed + */ + abstract protected function eagerlySet(array &$resultSet, string $relation, array $subRelation = [], ?Closure $closure = null); + + /** + * 预载入关联查询(数据). + * + * @param Model $result + * @param string $relation + * @param array $subRelation + * @param Closure $closure + * + * @return mixed + */ + abstract protected function eagerlyOne(Model $result, string $relation, array $subRelation = [], ?Closure $closure = null); + + /** + * 预载入关联查询(数据集). + * + * @param array $resultSet 数据集 + * @param string $relation 当前关联名 + * @param array $subRelation 子关联名 + * @param Closure $closure 闭包 + * @param array $cache 关联缓存 + * @param bool $join 是否为JOIN方式 + * + * @return void + */ + public function eagerlyResultSet(array &$resultSet, string $relation, array $subRelation = [], ?Closure $closure = null, array $cache = [], bool $join = false): void + { + if ($join) { + // 模型JOIN关联组装 + foreach ($resultSet as $result) { + $this->match($this->model, $relation, $result); + } + } else { + // IN查询 + $this->eagerlySet($resultSet, $relation, $subRelation, $closure, $cache); + } + } + + /** + * 预载入关联查询(数据). + * + * @param Model $result 数据对象 + * @param string $relation 当前关联名 + * @param array $subRelation 子关联名 + * @param Closure $closure 闭包 + * @param array $cache 关联缓存 + * @param bool $join 是否为JOIN方式 + * + * @return void + */ + public function eagerlyResult(Model $result, string $relation, array $subRelation = [], ?Closure $closure = null, array $cache = [], bool $join = false): void + { + if ($join) { + // 模型JOIN关联组装 + $this->match($this->model, $relation, $result); + } else { + // IN查询 + $this->eagerlyOne($result, $relation, $subRelation, $closure, $cache); + } + } + + /** + * 保存(新增)当前关联数据对象 + * + * @param array|Model $data 数据 可以使用数组 关联模型对象 + * @param bool $replace 是否自动识别更新和写入 + * + * @return Model|false + */ + public function save(array | Model $data, bool $replace = true) + { + $model = $this->make(); + + return $model->replace($replace)->save($data) ? $model : false; + } + + /** + * 创建关联对象实例. + * + * @param array|Model $data + * + * @return Model + */ + public function make(array | Model $data = []): Model + { + if ($data instanceof Model) { + $data = $data->getData(); + } + + // 保存关联表数据 + $data[$this->foreignKey] = $this->parent->{$this->localKey}; + + return (new $this->model($data))->setSuffix($this->getModel()->getSuffix()); + } + + /** + * 绑定关联表的属性到父模型属性. + * + * @param array $attr 要绑定的属性列表 + * + * @return $this + */ + public function bind(array $attr) + { + $this->bindAttr = $attr; + + return $this; + } + + /** + * 一对一 关联模型预查询拼装. + * + * @param string $model 模型名称 + * @param string $relation 关联名 + * @param Model $result 模型对象实例 + * + * @return void + */ + protected function match(string $model, string $relation, Model $result): void + { + $data = $result->getRelation($relation); + // JOIN 未匹配时关联表字段全为 null,应视为没有关联数据,避免生成空关联对象 + if (!empty($data) && !empty(array_filter($data, fn ($value) => null !== $value))) { + if ($this->bindAttr) { + $result->bindRelationAttr($data, $this->bindAttr); + } else { + $relationModel = new $model($data); + $result->setRelation($relation, $relationModel); + } + } + } + + /** + * 一对一 关联模型预查询(IN方式). + * + * @param array $where 关联预查询条件 + * @param string $key 关联键名 + * @param array $subRelation 子关联 + * @param Closure $closure + * @param array $cache 关联缓存 + * @param bool $collection 是否数据集查询 + * @return array + */ + protected function eagerlyWhere(array $where, string $key, array $subRelation = [], ?Closure $closure = null, array $cache = [], bool $collection = false) + { + // 预载入关联查询 支持嵌套预载入 + if ($closure) { + $this->baseQuery = true; + $closure($this->query); + } + + if ($collection) { + $this->query->removeOption('limit'); + } else { + $this->query->limit(1); + } + + $list = $this->query + ->where($where) + ->with($subRelation) + ->cache($cache[0] ?? false, $cache[1] ?? null, $cache[2] ?? null) + ->lazy(); + + // 组装模型数据 + $data = []; + foreach ($list as $set) { + if (!isset($data[$set->$key])) { + $data[$set->$key] = $set; + } + } + + return $data; + } +}