仰望星辰工作室

better-staridc-MNBT

Z zfhsh first commit 2 个月前
1<?php
2/**
3 * qmzl_domain 插件 - 账号与订单辅助函数
4 *
5 * 用户维度:user_info 插件用户(MN_plugin_user),前置依赖 user_info。
6 */
7if (!defined('IN_CRONLITE')) exit;
8
9/* ============================================================
10 * URL / 渲染 / 登录辅助
11 * ============================================================ */
12
13/** 生成带站点 base path 前缀的 URL(index.php?_r= 查询参数路由)。 */
14function qmzl_url($path = '')
15{
16 $scriptName = isset($_SERVER['SCRIPT_NAME']) ? str_replace('\\', '/', $_SERVER['SCRIPT_NAME']) : '';
17 $basePath = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
18 if ($basePath === '.' || $basePath === '/') {
19 $basePath = '';
20 }
21 $p = ltrim($path, '/');
22 $qpos = strpos($p, '?');
23 if ($qpos !== false) {
24 $route = substr($p, 0, $qpos);
25 $query = substr($p, $qpos + 1);
26 return $basePath . '/index.php?_r=/' . $route . '&' . $query;
27 }
28 return $basePath . '/index.php?_r=/' . $p;
29}
30
31/** 插件静态资源 URL。 */
32function qmzl_asset_url($path = '')
33{
34 return mnbt_plugin_url('qmzl_domain', 'assets/' . ltrim($path, '/'));
35}
36
37/** 输出 JSON 并退出(与 balance/hosting 一致)。 */
38function qmzl_json($code, $extra = [])
39{
40 @header('Content-Type: application/json; charset=UTF-8');
41 $payload = ['code' => $code];
42 if (is_array($extra)) {
43 $payload = array_merge($payload, $extra);
44 }
45 echo json_encode($payload, JSON_UNESCAPED_UNICODE);
46 exit;
47}
48
49/**
50 * 获取当前登录的 user_info 用户;未登录跳转登录页。
51 * $json=true 时输出 JSON 错误(供 API 路由使用)。
52 * @return array|void
53 */
54function qmzl_require_user($json = false)
55{
56 if (!function_exists('user_info_auth_current')) {
57 if ($json) qmzl_json('需要先启用 user_info 插件');
58 http_response_code(500);
59 echo '需要先启用 user_info 插件';
60 exit;
61 }
62 $user = user_info_auth_current();
63 if (!$user) {
64 if ($json) {
65 qmzl_json('请先登录', ['msg' => '请先登录', 'login_url' => qmzl_url('account/login')]);
66 }
67 header('Location: ' . qmzl_url('account/login'));
68 exit;
69 }
70 return $user;
71}
72
73/** 渲染用户端视图(views/ 目录,自包含页面)。 */
74function qmzl_render($view, $vars = [])
75{
76 $vars['current_user'] = $vars['current_user'] ?? (function_exists('user_info_auth_current') ? user_info_auth_current() : null);
77 extract($vars, EXTR_SKIP);
78 $viewFile = mnbt_plugin_path('qmzl_domain') . 'views/' . $view . '.php';
79 if (!is_file($viewFile)) {
80 http_response_code(500);
81 echo 'View not found: ' . htmlspecialchars($view);
82 return;
83 }
84 include $viewFile;
85}
86
87/* ============================================================
88 * 表结构自动升级(bootstrap 时调用一次,兼容已安装站点)
89 * ============================================================ */
90function qmzl_schema_upgrade()
91{
92 global $DB;
93 if (!isset($DB) || !is_object($DB)) return;
94
95 $tbl = $DB->get_row_prepare("SHOW TABLES LIKE 'plg_qmzl_account'");
96 if (!$tbl) {
97 @$DB->query("CREATE TABLE IF NOT EXISTS `plg_qmzl_account` (
98 `id` int(11) NOT NULL AUTO_INCREMENT,
99 `user_id` int(11) NOT NULL DEFAULT 0,
100 `username` varchar(64) NOT NULL DEFAULT '',
101 `account` varchar(255) NOT NULL DEFAULT '',
102 `password` text,
103 `jwt` text,
104 `jwt_expire` varchar(20) NOT NULL DEFAULT '0',
105 `status` varchar(20) NOT NULL DEFAULT 'ok',
106 `last_msg` varchar(255) NOT NULL DEFAULT '',
107 `created_at` varchar(50) NOT NULL DEFAULT '',
108 `updated_at` varchar(50) NOT NULL DEFAULT '',
109 PRIMARY KEY (`id`),
110 UNIQUE KEY `uq_user_id` (`user_id`)
111 ) ENGINE=MyISAM DEFAULT CHARSET=utf8");
112 }
113
114 $tbl = $DB->get_row_prepare("SHOW TABLES LIKE 'plg_qmzl_order'");
115 if (!$tbl) {
116 @$DB->query("CREATE TABLE IF NOT EXISTS `plg_qmzl_order` (
117 `id` int(11) NOT NULL AUTO_INCREMENT,
118 `user_id` int(11) NOT NULL DEFAULT 0,
119 `username` varchar(64) NOT NULL DEFAULT '',
120 `ddh` varchar(64) NOT NULL DEFAULT '',
121 `domain` varchar(255) NOT NULL DEFAULT '',
122 `year` int(11) NOT NULL DEFAULT 1,
123 `amount` varchar(20) NOT NULL DEFAULT '0',
124 `template_id` int(11) NOT NULL DEFAULT 0,
125 `cloud_order_id` varchar(64) NOT NULL DEFAULT '',
126 `gateway` varchar(64) NOT NULL DEFAULT '',
127 `status` varchar(20) NOT NULL DEFAULT 'Pending',
128 `remark` varchar(255) NOT NULL DEFAULT '',
129 `created_at` varchar(50) NOT NULL DEFAULT '',
130 `updated_at` varchar(50) NOT NULL DEFAULT '',
131 PRIMARY KEY (`id`),
132 KEY `idx_user` (`user_id`),
133 KEY `idx_ddh` (`ddh`),
134 KEY `idx_order` (`cloud_order_id`)
135 ) ENGINE=MyISAM DEFAULT CHARSET=utf8");
136 } else {
137 // 老表补齐字段
138 $cols = $DB->get_all_prepare("SHOW COLUMNS FROM `plg_qmzl_order` LIKE 'ddh'") ?: [];
139 if (empty($cols)) @$DB->query("ALTER TABLE `plg_qmzl_order` ADD COLUMN `ddh` varchar(64) NOT NULL DEFAULT '' AFTER `username`");
140 $cols = $DB->get_all_prepare("SHOW COLUMNS FROM `plg_qmzl_order` LIKE 'template_id'") ?: [];
141 if (empty($cols)) @$DB->query("ALTER TABLE `plg_qmzl_order` ADD COLUMN `template_id` int(11) NOT NULL DEFAULT 0 AFTER `amount`");
142 $cols = $DB->get_all_prepare("SHOW COLUMNS FROM `plg_qmzl_order` LIKE 'remark'") ?: [];
143 if (empty($cols)) @$DB->query("ALTER TABLE `plg_qmzl_order` ADD COLUMN `remark` varchar(255) NOT NULL DEFAULT '' AFTER `status`");
144 $cols = $DB->get_all_prepare("SHOW COLUMNS FROM `plg_qmzl_order` LIKE 'updated_at'") ?: [];
145 if (empty($cols)) @$DB->query("ALTER TABLE `plg_qmzl_order` ADD COLUMN `updated_at` varchar(50) NOT NULL DEFAULT '' AFTER `created_at`");
146 }
147
148 // 模板归属表
149 $tbl = $DB->get_row_prepare("SHOW TABLES LIKE 'plg_qmzl_template'");
150 if (!$tbl) {
151 @$DB->query("CREATE TABLE IF NOT EXISTS `plg_qmzl_template` (
152 `id` int(11) NOT NULL AUTO_INCREMENT,
153 `template_id` int(11) NOT NULL DEFAULT 0,
154 `user_id` int(11) NOT NULL DEFAULT 0,
155 `username` varchar(64) NOT NULL DEFAULT '',
156 `created_at` varchar(50) NOT NULL DEFAULT '',
157 PRIMARY KEY (`id`),
158 UNIQUE KEY `uq_tpl` (`template_id`)
159 ) ENGINE=MyISAM DEFAULT CHARSET=utf8");
160 }
161}
162
163/* ============================================================
164 * 账号(按 user_id)
165 * ============================================================ */
166
167/** 获取用户绑定记录 */
168function qmzl_account_get($user_id)
169{
170 global $DB;
171 $user_id = (int)$user_id;
172 if ($user_id <= 0) return false;
173 return $DB->get_row_prepare("SELECT * FROM plg_qmzl_account WHERE user_id=? LIMIT 1", [$user_id]);
174}
175
176/** 保存/更新绑定凭证(密码加密存储,登录后再写 token) */
177function qmzl_account_save_cred($user_id, $username, $account, $password)
178{
179 global $DB, $date;
180 $enc = qmzl_encrypt_pwd($password);
181 $exist = qmzl_account_get($user_id);
182 if ($exist) {
183 return (bool)$DB->query_prepare(
184 "UPDATE plg_qmzl_account SET username=?, account=?, password=?, updated_at=? WHERE user_id=?",
185 [$username, $account, $enc, $date, (int)$user_id]
186 );
187 }
188 return (bool)$DB->query_prepare(
189 "INSERT INTO plg_qmzl_account (user_id, username, account, password, jwt, jwt_expire, status, last_msg, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
190 [(int)$user_id, $username, $account, $enc, '', '0', 'ok', '', $date, $date]
191 );
192}
193
194/** 写 token 与过期时间 */
195function qmzl_account_set_token($user_id, $jwt, $expire)
196{
197 global $DB, $date;
198 return (bool)$DB->query_prepare(
199 "UPDATE plg_qmzl_account SET jwt=?, jwt_expire=?, updated_at=? WHERE user_id=?",
200 [(string)$jwt, (string)$expire, $date, (int)$user_id]
201 );
202}
203
204/** 更新状态(登录失败等) */
205function qmzl_account_update_status($user_id, $status, $msg = '')
206{
207 global $DB, $date;
208 $status = ($status === 'error') ? 'error' : 'ok';
209 $msg = mb_substr((string)$msg, 0, 250);
210 return (bool)$DB->query_prepare(
211 "UPDATE plg_qmzl_account SET status=?, last_msg=?, updated_at=? WHERE user_id=?",
212 [$status, $msg, $date, (int)$user_id]
213 );
214}
215
216/** 解绑账号 */
217function qmzl_account_delete($user_id)
218{
219 global $DB;
220 return (bool)$DB->query_prepare("DELETE FROM plg_qmzl_account WHERE user_id=? LIMIT 1", [(int)$user_id]);
221}
222
223/** 后台:账号列表 */
224function qmzl_account_list($page = 1, $limit = 200, $keyword = '')
225{
226 global $DB;
227 $page = max(1, (int)$page);
228 $limit = min(1000, max(1, (int)$limit));
229 $where = '';
230 $args = [];
231 if ($keyword !== '') {
232 $where = "WHERE username LIKE ? OR account LIKE ?";
233 $kw = '%' . $keyword . '%';
234 $args = [$kw, $kw];
235 }
236 $row = $DB->get_row_prepare("SELECT COUNT(*) AS c FROM plg_qmzl_account " . $where, $args);
237 $total = (int)($row['c'] ?? 0);
238 $offset = ($page - 1) * $limit;
239 $rows = $DB->get_all_prepare("SELECT * FROM plg_qmzl_account " . $where . " ORDER BY id DESC LIMIT {$limit} OFFSET {$offset}", $args) ?: [];
240 return ['total' => $total, 'rows' => $rows];
241}
242
243/* ============================================================
244 * 模式 / 代理商(agent)
245 * ============================================================ */
246
247/** 当前模式:client(客户自注册)/ agent(代理商) */
248function qmzl_mode()
249{
250 return qmzl_setting_get('mode', 'client') === 'agent' ? 'agent' : 'client';
251}
252
253/** 用户端路由前缀:client → qmzl,agent → qmzl_domain */
254function qmzl_route_prefix()
255{
256 return qmzl_mode() === 'agent' ? 'qmzl_domain' : 'qmzl';
257}
258
259/**
260 * 保存代理商开放接口凭证(平台账号 + API 密钥)并立即鉴权换取 JWT。
261 * 上游登录需人机验证,但开放接口鉴权(/api/v1/auth)用 API 密钥,无需人机验证。
262 */
263function qmzl_agent_save($username, $apiToken)
264{
265 $username = trim((string)$username);
266 $apiToken = trim((string)$apiToken);
267 if ($username === '' || $apiToken === '') {
268 return ['ok' => false, 'status' => 0, 'msg' => '平台账号和 API 密钥不能为空', 'data' => null];
269 }
270 $auth = qmzl_openapi_auth($username, $apiToken);
271 if (!$auth['ok']) {
272 qmzl_setting_set('agent_status', 'error');
273 qmzl_setting_set('agent_msg', $auth['msg']);
274 return ['ok' => false, 'status' => 0, 'msg' => '鉴权失败:' . $auth['msg'] . '(请确认平台账号与 API 密钥正确)', 'data' => null];
275 }
276 qmzl_setting_set('agent_username', $username);
277 qmzl_setting_set('agent_api_token', qmzl_encrypt_pwd($apiToken));
278 qmzl_setting_set('agent_jwt', $auth['data']['jwt']);
279 qmzl_setting_set('agent_jwt_expire', (string)$auth['data']['exp']);
280 qmzl_setting_set('agent_status', 'ok');
281 qmzl_setting_set('agent_msg', '');
282 return $auth;
283}
284
285/** 获取有效的代理商 JWT(过期自动用 API 密钥重新换取) */
286function qmzl_agent_token()
287{
288 $jwt = (string)qmzl_setting_get('agent_jwt', '');
289 $exp = (int)qmzl_setting_get('agent_jwt_expire', 0);
290 if ($jwt !== '' && $exp > time() + 300) {
291 return ['ok' => true, 'status' => 200, 'msg' => '', 'data' => ['jwt' => $jwt]];
292 }
293 $username = (string)qmzl_setting_get('agent_username', '');
294 $apiToken = qmzl_decrypt_pwd((string)qmzl_setting_get('agent_api_token', ''));
295 if ($username === '' || $apiToken === '') {
296 return ['ok' => false, 'status' => 0, 'msg' => '请先在后台配置代理商平台账号与 API 密钥', 'data' => null];
297 }
298 $auth = qmzl_openapi_auth($username, $apiToken);
299 if (!$auth['ok']) {
300 qmzl_setting_set('agent_status', 'error');
301 qmzl_setting_set('agent_msg', $auth['msg']);
302 return $auth;
303 }
304 qmzl_setting_set('agent_jwt', $auth['data']['jwt']);
305 qmzl_setting_set('agent_jwt_expire', (string)$auth['data']['exp']);
306 qmzl_setting_set('agent_status', 'ok');
307 qmzl_setting_set('agent_msg', '');
308 return $auth;
309}
310
311/**
312 * 获取上游 token(统一入口):
313 * agent 模式用管理员代理商账号,client 模式用用户绑定账号。
314 * @param array $user user_info 用户数组
315 */
316function qmzl_require_token($user)
317{
318 if (qmzl_mode() === 'agent') {
319 return qmzl_agent_token();
320 }
321 return qmzl_get_token((int)$user['id']);
322}
323
324/* ============================================================
325 * 模板归属(agent 模式:客户创建的模板记录归属,隔离查看/操作)
326 * ============================================================ */
327
328/** 查询上游模板的归属用户 ID(0 = 未记录/管理员私有) */
329function qmzl_template_owner_id($templateId)
330{
331 global $DB;
332 $r = $DB->get_row_prepare("SELECT user_id FROM plg_qmzl_template WHERE template_id=? LIMIT 1", [(int)$templateId]);
333 return $r ? (int)$r['user_id'] : 0;
334}
335
336/** 记录模板归属(已存在则忽略) */
337function qmzl_template_record($templateId, $userId, $username)
338{
339 global $DB, $date;
340 if ((int)$templateId <= 0 || (int)$userId <= 0) return false;
341 if (qmzl_template_owner_id($templateId) > 0) return true;
342 return (bool)$DB->query_prepare(
343 "INSERT INTO plg_qmzl_template (template_id, user_id, username, created_at) VALUES (?,?,?,?)",
344 [(int)$templateId, (int)$userId, $username, $date]
345 );
346}
347
348/** 模板是否属于该用户(agent 模式权限校验用) */
349function qmzl_template_owned($templateId, $userId)
350{
351 $owner = qmzl_template_owner_id($templateId);
352 return $owner > 0 && $owner === (int)$userId;
353}
354
355/** 某用户拥有的上游模板 ID 集合 */
356function qmzl_template_ids_by_user($userId)
357{
358 global $DB;
359 $rows = $DB->get_all_prepare("SELECT template_id FROM plg_qmzl_template WHERE user_id=? ORDER BY id DESC", [(int)$userId]) ?: [];
360 $ids = [];
361 foreach ($rows as $r) {
362 $ids[(int)$r['template_id']] = true;
363 }
364 return $ids;
365}
366
367/* ============================================================
368 * 后缀溢价(agent 模式:管理员为各后缀设置的一次性加价,元)
369 * ============================================================ */
370
371/** 溢价配置表:{".com": "10", ...} */
372function qmzl_markup_map()
373{
374 if (qmzl_mode() !== 'agent') return [];
375 $raw = qmzl_setting_get('agent_markup', '');
376 $map = json_decode((string)$raw, true);
377 return is_array($map) ? $map : [];
378}
379
380/** 某后缀的溢价金额(元,无则 0) */
381function qmzl_markup_for_suffix($suffix)
382{
383 $map = qmzl_markup_map();
384 $key = strtolower((string)$suffix);
385 if ($key !== '' && $key[0] !== '.') $key = '.' . ltrim($key, '.');
386 $v = (string)($map[$key] ?? '0');
387 $f = (float)$v;
388 return $f > 0 ? $f : 0;
389}
390
391/** 某完整域名的溢价金额(取第一个点之后的后缀) */
392function qmzl_markup_for_domain($domain)
393{
394 $pos = strpos((string)$domain, '.');
395 if ($pos === false) return 0;
396 return qmzl_markup_for_suffix(substr($domain, $pos));
397}
398
399/** 对价格列表应用溢价(agent 模式),返回溢价金额 */
400function qmzl_apply_markup(&$list, $domain)
401{
402 if (qmzl_mode() !== 'agent' || !is_array($list)) return 0;
403 $markup = qmzl_markup_for_domain($domain);
404 if ($markup <= 0) return 0;
405 foreach ($list as &$p) {
406 if (is_array($p) && isset($p['buyprice'])) {
407 $p['buyprice'] = (string)(round((float)$p['buyprice'] + $markup, 2));
408 $p['markup'] = $markup;
409 }
410 }
411 unset($p);
412 return $markup;
413}
414
415/* ============================================================
416 * 订单(按 user_id)
417 * ============================================================ */
418
419/** 新增本地订单记录 */
420function qmzl_order_create($user_id, $username, $ddh, $domain, $year, $amount, $templateId, $cloudOrderId, $gateway, $remark = '')
421{
422 global $DB, $date;
423 return (bool)$DB->query_prepare(
424 "INSERT INTO plg_qmzl_order (user_id, username, ddh, domain, year, amount, template_id, cloud_order_id, gateway, status, remark, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
425 [(int)$user_id, $username, (string)$ddh, $domain, (int)$year, (string)$amount, (int)$templateId, (string)$cloudOrderId, (string)$gateway, 'Pending', $remark, $date, $date]
426 );
427}
428
429/** 按本地主键查订单 */
430function qmzl_order_get_by_id($id)
431{
432 global $DB;
433 return $DB->get_row_prepare("SELECT * FROM plg_qmzl_order WHERE id=? LIMIT 1", [(int)$id]);
434}
435
436/** 按上游订单号查本地记录(client 模式) */
437function qmzl_order_get($cloudOrderId)
438{
439 global $DB;
440 return $DB->get_row_prepare("SELECT * FROM plg_qmzl_order WHERE cloud_order_id=? LIMIT 1", [(string)$cloudOrderId]);
441}
442
443/** 按 MNBT 订单号查本地记录(agent 模式) */
444function qmzl_order_get_by_ddh($ddh)
445{
446 global $DB;
447 return $DB->get_row_prepare("SELECT * FROM plg_qmzl_order WHERE ddh=? LIMIT 1", [(string)$ddh]);
448}
449
450/** 更新订单(白名单字段) */
451function qmzl_order_update($id, $fields = [])
452{
453 global $DB, $date;
454 $whitelist = ['ddh', 'domain', 'year', 'amount', 'template_id', 'cloud_order_id', 'gateway', 'status', 'remark'];
455 $set = [];
456 $args = [];
457 foreach ($fields as $k => $v) {
458 if (in_array($k, $whitelist, true)) {
459 $set[] = "`{$k}`=?";
460 $args[] = $v;
461 }
462 }
463 if (!$set) return false;
464 $set[] = "`updated_at`=?";
465 $args[] = $date;
466 $args[] = (int)$id;
467 return (bool)$DB->query_prepare("UPDATE plg_qmzl_order SET " . implode(', ', $set) . " WHERE id=?", $args);
468}
469
470/** 更新订单状态(按上游订单号,client 模式) */
471function qmzl_order_update_status($cloudOrderId, $status)
472{
473 global $DB, $date;
474 return (bool)$DB->query_prepare(
475 "UPDATE plg_qmzl_order SET status=?, updated_at=? WHERE cloud_order_id=?",
476 [$status, $date, (string)$cloudOrderId]
477 );
478}
479
480/** 用户订单列表 */
481function qmzl_order_list($user_id, $page = 1, $limit = 20)
482{
483 global $DB;
484 $page = max(1, (int)$page);
485 $limit = min(100, max(1, (int)$limit));
486 $row = $DB->get_row_prepare("SELECT COUNT(*) AS c FROM plg_qmzl_order WHERE user_id=?", [(int)$user_id]);
487 $total = (int)($row['c'] ?? 0);
488 $offset = ($page - 1) * $limit;
489 $rows = $DB->get_all_prepare("SELECT * FROM plg_qmzl_order WHERE user_id=? ORDER BY id DESC LIMIT {$limit} OFFSET {$offset}", [(int)$user_id]) ?: [];
490 return ['total' => $total, 'rows' => $rows];
491}
492
493/** 后台:全部订单列表 */
494function qmzl_order_admin_list($page = 1, $limit = 20, $status = '', $keyword = '')
495{
496 global $DB;
497 $page = max(1, (int)$page);
498 $limit = min(200, max(1, (int)$limit));
499 $where = '';
500 $args = [];
501 if ($status !== '' && in_array($status, ['Pending', 'Paid', 'Cancelled', 'Failed'], true)) {
502 $where = "WHERE status=?";
503 $args[] = $status;
504 }
505 if ($keyword !== '') {
506 $where .= ($where === '' ? 'WHERE ' : ' AND ') . "(domain LIKE ? OR username LIKE ? OR ddh LIKE ? OR cloud_order_id LIKE ?)";
507 $kw = '%' . $keyword . '%';
508 array_push($args, $kw, $kw, $kw, $kw);
509 }
510 $row = $DB->get_row_prepare("SELECT COUNT(*) AS c FROM plg_qmzl_order " . $where, $args);
511 $total = (int)($row['c'] ?? 0);
512 $offset = ($page - 1) * $limit;
513 $rows = $DB->get_all_prepare("SELECT * FROM plg_qmzl_order " . $where . " ORDER BY id DESC LIMIT {$limit} OFFSET {$offset}", $args) ?: [];
514 return ['total' => $total, 'rows' => $rows];
515}
516
517/* ============================================================
518 * 插件设置
519 * ============================================================ */
520
521function qmzl_setting_get($key, $default = '')
522{
523 return mnbt_plugin_option_get('qmzl_domain', $key, $default);
524}
525
526function qmzl_setting_set($key, $value)
527{
528 return mnbt_plugin_option_set('qmzl_domain', $key, $value);
529}