仰望星辰工作室

better-staridc-MNBT

Z zfhsh first commit 2 个月前
1<?php
2/**
3 * zjmfmanager_reserve 插件 - 辅助函数库
4 *
5 * 提供:URL/渲染/认证/金额辅助、商品、订单、主机、日志的数据库操作,
6 * 以及主机开通编排(支付成功后调用上游开通,失败自动退款)。
7 */
8
9if (!defined('IN_CRONLITE')) {
10 exit;
11}
12
13/* ============================================================
14 * 常量
15 * ============================================================ */
16
17/** 业务类型标识(MN_dd.lx),用于 order.paid 钩子过滤 */
18define('ZJMF_LX', 'zjmf');
19
20/** 本地订单号前缀 */
21define('ZJMF_ORDER_PREFIX', 'ZJM');
22
23/* ============================================================
24 * URL / 渲染辅助
25 * ============================================================ */
26
27/** 生成带站点 base path 前缀的 URL。 */
28function zjmf_url($path = '')
29{
30 $scriptName = isset($_SERVER['SCRIPT_NAME'])
31 ? str_replace('\\', '/', $_SERVER['SCRIPT_NAME']) : '';
32 $basePath = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
33 if ($basePath === '.' || $basePath === '/') {
34 $basePath = '';
35 }
36 // 使用查询参数路由(index.php?_r=/path),避免依赖 Web 服务器 rewrite
37 $p = ltrim($path, '/');
38 $qpos = strpos($p, '?');
39 if ($qpos !== false) {
40 $route = substr($p, 0, $qpos);
41 $query = substr($p, $qpos + 1);
42 return $basePath . '/index.php?_r=/' . $route . '&' . $query;
43 }
44 return $basePath . '/index.php?_r=/' . $p;
45}
46
47/** 插件静态资源 URL。 */
48function zjmf_asset_url($path = '')
49{
50 return mnbt_plugin_url('zjmfmanager_reserve', 'assets/' . ltrim($path, '/'));
51}
52
53/** 管理员端插件页面 URL(admin/plugin.php?p=zjmfmanager_reserve&page=xxx)。 */
54function zjmf_admin_url($page, $extra = '')
55{
56 $base = 'plugin.php?p=zjmfmanager_reserve&page=' . rawurlencode($page);
57 if ($extra !== '') {
58 $base .= '&' . ltrim($extra, '&');
59 }
60 return $base;
61}
62
63/** 金额(分)→ 元(保留 2 位小数)。 */
64function zjmf_format_cents($cents)
65{
66 return number_format((int)$cents / 100, 2, '.', '');
67}
68
69/** 生成本地订单号。 */
70function zjmf_order_no()
71{
72 return ZJMF_ORDER_PREFIX . date('YmdHis') . mt_rand(1000, 9999);
73}
74
75/** 获取当前登录的 user_info 用户,未登录跳转登录页。 */
76function zjmf_require_user()
77{
78 if (!function_exists('user_info_auth_current')) {
79 http_response_code(500);
80 echo '需要先启用 user_info 插件';
81 exit;
82 }
83 $user = user_info_auth_current();
84 if (!$user) {
85 header('Location: ' . zjmf_url('account/login'));
86 exit;
87 }
88 return $user;
89}
90
91/** 渲染用户端视图。 */
92function zjmf_render($view, $vars = [])
93{
94 $vars['current_user'] = $vars['current_user']
95 ?? (function_exists('user_info_auth_current') ? user_info_auth_current() : null);
96 extract($vars, EXTR_SKIP);
97 $viewFile = mnbt_plugin_path('zjmfmanager_reserve') . 'views/' . $view . '.php';
98 if (!is_file($viewFile)) {
99 http_response_code(500);
100 echo 'View not found: ' . htmlspecialchars($view);
101 return;
102 }
103 include $viewFile;
104}
105
106/** 渲染管理员端视图。 */
107function zjmf_render_admin($view, $vars = [])
108{
109 extract($vars, EXTR_SKIP);
110 $viewFile = mnbt_plugin_path('zjmfmanager_reserve') . 'views/admin/' . $view . '.php';
111 if (!is_file($viewFile)) {
112 http_response_code(500);
113 echo 'Admin view not found: ' . htmlspecialchars($view);
114 return;
115 }
116 include $viewFile;
117}
118
119/** 输出 JSON 并退出。 */
120function zjmf_json($code, $extra = [])
121{
122 @header('Content-Type: application/json; charset=UTF-8');
123 $payload = ['code' => $code];
124 if (is_array($extra)) {
125 $payload = array_merge($payload, $extra);
126 }
127 echo json_encode($payload, JSON_UNESCAPED_UNICODE);
128 exit;
129}
130
131/**
132 * 获取 AES-256 加密密钥(32 字节原始密钥,不可用时返回 null)。
133 * 来源优先级:
134 * 1. 环境变量 / 常量 MNBT_SECRET_KEY(任意字符串,sha256 派生 32 字节)
135 * 2. 站点根 runtime/zjmf/zjmf_secret.key 密钥文件(插件目录之外,
136 * runtime/ 为仓库既有数据目录惯例并带 .htaccess 禁止 Web 访问;
137 * 不存在时自动生成 64 hex 字符随机密钥并尝试 chmod 600)
138 * 两者均不可用时返回 null(调用方退回旧 authcode 并记日志)。
139 */
140function zjmf_secret_key_raw()
141{
142 static $cached = null;
143 if ($cached !== null) {
144 return $cached['key'] ?? null;
145 }
146 $cached = ['key' => null];
147 // 1. 环境变量 / 常量
148 $secret = getenv('MNBT_SECRET_KEY');
149 if ($secret === '' || $secret === false) {
150 $secret = defined('MNBT_SECRET_KEY') ? (string)constant('MNBT_SECRET_KEY') : '';
151 }
152 if ($secret !== '') {
153 $cached['key'] = hash('sha256', (string)$secret, true);
154 return $cached['key'];
155 }
156 // 2. 密钥文件(站点根 runtime/zjmf/,插件 data 目录之外)
157 $base = defined('ROOT') ? ROOT : dirname(dirname(dirname(__DIR__))) . '/';
158 $dir = $base . 'runtime/zjmf';
159 $file = $dir . '/zjmf_secret.key';
160 $secret = '';
161 if (is_file($file)) {
162 $secret = trim((string)@file_get_contents($file));
163 }
164 if ($secret === '') {
165 // 自动生成 64 hex 字符随机密钥并落盘
166 if (!is_dir($dir) && !@mkdir($dir, 0755, true) && !is_dir($dir)) {
167 @error_log('[zjmfmanager_reserve] 加密密钥目录创建失败:' . $dir);
168 return null;
169 }
170 // 目录防 Web 直接访问(.htaccess 拒绝 + 空 index.html 防目录列举)
171 $ht = $dir . '/.htaccess';
172 if (!is_file($ht)) {
173 @file_put_contents($ht, "Deny from all\n");
174 }
175 $ix = $dir . '/index.html';
176 if (!is_file($ix)) {
177 @file_put_contents($ix, '');
178 }
179 $secret = bin2hex(random_bytes(32));
180 if (@file_put_contents($file, $secret) === false) {
181 @error_log('[zjmfmanager_reserve] 加密密钥文件写入失败:' . $file
182 . ',退回旧 authcode 加密');
183 return null;
184 }
185 @chmod($file, 0600);
186 }
187 $cached['key'] = hash('sha256', $secret, true);
188 return $cached['key'];
189}
190
191/**
192 * 加密上游主机密码等敏感信息。
193 * 密钥可用时 AES-256-GCM,密文格式 'v2:' + base64(nonce.tag.ciphertext);
194 * 密钥不可用时退回旧 authcode(记日志)。
195 */
196function zjmf_encrypt($plain)
197{
198 $plain = (string)$plain;
199 if ($plain === '') {
200 return '';
201 }
202 $key = zjmf_secret_key_raw();
203 if ($key !== null) {
204 $nonce = random_bytes(12);
205 $tag = '';
206 $cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag);
207 if ($cipher !== false) {
208 return 'v2:' . base64_encode($nonce . $tag . $cipher);
209 }
210 @error_log('[zjmfmanager_reserve] AES-256-GCM 加密失败,退回旧 authcode');
211 }
212 return authcode($plain, 'ENCODE', SYS_KEY);
213}
214
215/**
216 * 密文解密(防御式)。
217 * 'v2:' 前缀走 AES-256-GCM(与 zjmf_encrypt 对称);无前缀走旧 authcode
218 * 解密以兼容存量数据。authcode 解密分支在 PHP 8 下对乱码密文会抛
219 * TypeError,这里对空/过短密文直接返回,异常兜底为空串。
220 */
221function zjmf_decrypt($cipher)
222{
223 $cipher = (string)$cipher;
224 if ($cipher === '') {
225 return '';
226 }
227 if (strpos($cipher, 'v2:') === 0) {
228 $key = zjmf_secret_key_raw();
229 if ($key === null) {
230 return ''; // 密钥不可用(如密钥文件被删),无法解密
231 }
232 $raw = base64_decode(substr($cipher, 3), true);
233 if ($raw === false || strlen($raw) <= 12 + 16) {
234 return '';
235 }
236 $nonce = substr($raw, 0, 12);
237 $tag = substr($raw, 12, 16);
238 $ct = substr($raw, 28);
239 $plain = openssl_decrypt($ct, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag);
240 return $plain === false ? '' : $plain;
241 }
242 if (strlen($cipher) <= 4) {
243 return ''; // 未设置密码或非 authcode 密文
244 }
245 try {
246 $out = authcode($cipher, 'DECODE', SYS_KEY);
247 return is_string($out) ? $out : '';
248 } catch (Throwable $e) {
249 return '';
250 }
251}
252
253/** 写操作日志。 */
254function zjmf_log($user_id, $order_no, $action, $result, $content, $supplier_id = 0)
255{
256 global $DB, $date;
257 $now = $date ?: date('Y-m-d H:i:s');
258 $DB->query_prepare(
259 "INSERT INTO MN_plugin_zjmf_log
260 (user_id, supplier_id, order_no, action, result, content, created_at)
261 VALUES (?,?,?,?,?,?,?)",
262 [(int)$user_id, (int)$supplier_id, (string)$order_no, (string)$action,
263 (string)$result, (string)$content, $now]
264 );
265}
266
267/** 日志列表(管理员,分页)。 */
268function zjmf_log_list_all($page = 1, $per_page = 30)
269{
270 global $DB;
271 $page = max(1, (int)$page);
272 $per_page = max(1, min(200, (int)$per_page));
273 $offset = ($page - 1) * $per_page;
274 $count_row = $DB->get_row_prepare("SELECT COUNT(*) AS cnt FROM MN_plugin_zjmf_log");
275 $total = $count_row ? (int)$count_row['cnt'] : 0;
276 $list = $DB->get_all_prepare(
277 "SELECT l.*, u.username AS user_name, s.name AS supplier_name
278 FROM MN_plugin_zjmf_log l
279 LEFT JOIN MN_plugin_user u ON u.id = l.user_id
280 LEFT JOIN MN_plugin_zjmf_supplier s ON s.id = l.supplier_id
281 ORDER BY l.id DESC LIMIT {$offset},{$per_page}"
282 ) ?: [];
283 return ['list' => $list, 'total' => $total, 'page' => $page, 'per_page' => $per_page];
284}
285
286/* ============================================================
287 * 计费周期
288 * ============================================================ */
289
290/** 可用计费周期(key 与上游 billingcycle 一致,WHMCS 风格)。 */
291function zjmf_cycles()
292{
293 return [
294 'Monthly' => ['name' => '月付'],
295 'Quarterly' => ['name' => '季付'],
296 'SemiAnnually' => ['name' => '半年付'],
297 'Annually' => ['name' => '年付'],
298 'Biennially' => ['name' => '两年付'],
299 'Triennially' => ['name' => '三年付'],
300 ];
301}
302
303/**
304 * 渲染商品简介为规范的展示 HTML。
305 * 上游常见 `&lt;li&gt;CPU:4核&lt;/li&gt; &lt;li&gt;内存:4G&lt;/li&gt;...` 格式:
306 * 解码实体 → 白名单过滤标签 → 压缩标签间空白 → 外层包裹 <ul> 渲染成列表。
307 * 白名单:p/br/b/strong/em/i/ul/ol/li/a[href|target]/span,
308 * a 的 href 仅允许 http/https 协议,其余标签的全部属性(含 style/on*、
309 * script/iframe 等危险标签)一律剥除,防上游描述注入 XSS。
310 */
311function zjmf_render_description($raw)
312{
313 $html = (string)$raw;
314 if ($html === '') {
315 return '';
316 }
317 // 解码实体直到稳定(兼容单/双重编码)
318 $i = 0;
319 do {
320 $prev = $html;
321 $html = html_entity_decode($html, ENT_QUOTES | ENT_HTML5, 'UTF-8');
322 $i++;
323 } while ($html !== $prev && $i < 3);
324 // 第一步:仅保留白名单标签(script/iframe 等连同标签一并剥除)
325 $html = strip_tags(
326 $html,
327 '<p><br><b><strong><em><i><ul><ol><li><a><span>'
328 );
329 // 第二步:逐标签重建,白名单外的属性全部剥除;a 仅恢复安全的 href/target
330 $html = preg_replace_callback(
331 '/<([a-zA-Z0-9]+)((?:\s+[^<>]*?)?)(\/?)>/u',
332 function ($m) {
333 $tag = strtolower($m[1]);
334 $attrs = $m[2] ?? '';
335 $selfClose = $m[3] ?? '';
336 if ($tag === 'a') {
337 $out = '<a';
338 // href 仅 http/https 协议,杜绝 javascript:/data: 等协议注入
339 if (preg_match('/href\s*=\s*(?:"|\')?\s*((?:https?:\/\/)[^"\'\s>]+)/iu', $attrs, $am)) {
340 $out .= ' href="' . htmlspecialchars($am[1], ENT_QUOTES) . '"';
341 }
342 if (preg_match('/target\s*=\s*(?:"|\')?_blank(?:"|\')?/iu', $attrs)) {
343 $out .= ' target="_blank" rel="noopener"';
344 }
345 return $out . '>';
346 }
347 // 其余标签剥除全部属性(<br/>、<br> 统一输出为 <br>)
348 return '<' . $tag . '>';
349 },
350 $html
351 );
352 if (stripos($html, '<li') === false) {
353 return $html;
354 }
355 $html = preg_replace('/>\s+</', '><', $html);
356 if (stripos($html, '<ul') === false) {
357 $html = '<ul>' . $html . '</ul>';
358 }
359 return $html;
360}
361
362/* ============================================================
363 * 供应商管理
364 * ============================================================ */
365
366/** 获取单个供应商(行数组)。 */
367function zjmf_supplier_get($supplier_id)
368{
369 global $DB;
370 return $DB->get_row_prepare(
371 "SELECT * FROM MN_plugin_zjmf_supplier WHERE id=? LIMIT 1",
372 [(int)$supplier_id]
373 ) ?: null;
374}
375
376/** 全部供应商列表(管理员,按 sort 升序)。 */
377function zjmf_supplier_list_all()
378{
379 global $DB;
380 return $DB->get_all_prepare(
381 "SELECT * FROM MN_plugin_zjmf_supplier ORDER BY sort ASC, id ASC"
382 ) ?: [];
383}
384
385/** 供应商加价标签(用于列表展示)。 */
386function zjmf_supplier_markup_label($supplier)
387{
388 $type = (int)($supplier['markup_type'] ?? 0);
389 $value = (int)($supplier['markup_value'] ?? 0);
390 return $type === 1
391 ? '固定 +' . zjmf_format_cents($value) . ' 元'
392 : '比例 +' . ($value / 10) . '%';
393}
394
395/** 供应商是否可销售(存在且启用)。 */
396function zjmf_supplier_usable($supplier_id)
397{
398 $supplier = zjmf_supplier_get($supplier_id);
399 return $supplier && (int)$supplier['status'] === 1;
400}
401
402/**
403 * 删除供应商(有商品/订单/主机时拒绝)。
404 *
405 * @return array ['ok'=>bool, 'msg'=>string]
406 */
407function zjmf_supplier_delete($supplier_id)
408{
409 global $DB;
410 $supplier_id = (int)$supplier_id;
411 $tables = [
412 'MN_plugin_zjmf_product' => '商品',
413 'MN_plugin_zjmf_order' => '订单',
414 'MN_plugin_zjmf_host' => '主机',
415 ];
416 foreach ($tables as $table => $label) {
417 $row = $DB->get_row_prepare(
418 "SELECT COUNT(*) AS cnt FROM {$table} WHERE supplier_id=? LIMIT 1",
419 [$supplier_id]
420 );
421 if ($row && (int)$row['cnt'] > 0) {
422 return ['ok' => false, 'msg' => '该供应商下存在' . $label . '数据,无法删除'];
423 }
424 }
425 $ok = $DB->query_prepare(
426 "DELETE FROM MN_plugin_zjmf_supplier WHERE id=?",
427 [$supplier_id]
428 );
429 return $ok ? ['ok' => true, 'msg' => '已删除'] : ['ok' => false, 'msg' => '删除失败'];
430}
431
432/* ============================================================
433 * 商品管理
434 * ============================================================ */
435
436/** 获取单个商品。 */
437function zjmf_product_get($product_id)
438{
439 global $DB;
440 return $DB->get_row_prepare(
441 "SELECT * FROM MN_plugin_zjmf_product WHERE id=? LIMIT 1",
442 [(int)$product_id]
443 ) ?: null;
444}
445
446/** 按供应商 + 上游商品 ID 获取商品。 */
447function zjmf_product_get_by_up($supplier_id, $up_product_id)
448{
449 global $DB;
450 return $DB->get_row_prepare(
451 "SELECT * FROM MN_plugin_zjmf_product
452 WHERE supplier_id=? AND up_product_id=? LIMIT 1",
453 [(int)$supplier_id, (int)$up_product_id]
454 ) ?: null;
455}
456
457/** 上架商品列表(用户端,仅所属供应商启用时可见;带供应商名供分组展示)。 */
458function zjmf_product_list_active()
459{
460 global $DB;
461 return $DB->get_all_prepare(
462 "SELECT p.*, s.name AS supplier_name
463 FROM MN_plugin_zjmf_product p
464 LEFT JOIN MN_plugin_zjmf_supplier s ON s.id = p.supplier_id
465 WHERE p.status=1 AND s.status=1
466 ORDER BY s.sort ASC, p.sort ASC, p.id ASC"
467 ) ?: [];
468}
469
470/** 全部商品列表(管理员,含供应商名)。 */
471function zjmf_product_list_all()
472{
473 global $DB;
474 return $DB->get_all_prepare(
475 "SELECT p.*, s.name AS supplier_name
476 FROM MN_plugin_zjmf_product p
477 LEFT JOIN MN_plugin_zjmf_supplier s ON s.id = p.supplier_id
478 ORDER BY s.sort ASC, p.sort ASC, p.id ASC"
479 ) ?: [];
480}
481
482/** 解析商品周期 JSON,返回 ['cycle' => ['name'=>, 'price_cents'=>, 'override'=>]]。 */
483function zjmf_product_cycles($product)
484{
485 $raw = isset($product['cycles']) ? json_decode($product['cycles'], true) : null;
486 if (!is_array($raw)) {
487 return [];
488 }
489 $map = [];
490 // 旧版扁平格式:["Monthly","月",2500]
491 if (isset($raw[0]) && !is_array($raw[0])) {
492 if ($raw[0] !== '' && isset($raw[2])) {
493 $cycle = (string)$raw[0];
494 $map[$cycle] = [
495 'cycle' => $cycle,
496 'up_cycle' => '',
497 'name' => (string)$raw[1],
498 'price_cents' => (int)$raw[2],
499 'agent_price_cents' => (int)$raw[2],
500 'override' => 0,
501 ];
502 }
503 return $map;
504 }
505 foreach ($raw as $item) {
506 $cycle = (string)($item['cycle'] ?? '');
507 if ($cycle === '') {
508 continue;
509 }
510 $map[$cycle] = [
511 'cycle' => $cycle,
512 'up_cycle' => (string)($item['up_cycle'] ?? ''),
513 'name' => (string)($item['name'] ?? $cycle),
514 'price_cents' => (int)($item['price_cents'] ?? 0),
515 'agent_price_cents' => (int)($item['agent_price_cents'] ?? 0),
516 'override' => (int)($item['override'] ?? 0),
517 ];
518 }
519 return $map;
520}
521
522/**
523 * 计算本地售价(分)。
524 *
525 * @param int $agentCents 上游代理价(分)
526 * @param int $markupType 0=比例 1=固定(分)
527 * @param int $markupValue 比例(千分比)或固定加价(分)
528 * @return int
529 */
530function zjmf_calc_price($agentCents, $markupType, $markupValue)
531{
532 $agentCents = max(0, (int)$agentCents);
533 if ($markupType === 1) {
534 return max(0, $agentCents + max(0, (int)$markupValue));
535 }
536 $rate = max(0, (int)$markupValue);
537 return max(0, (int)round($agentCents * (1000 + $rate) / 1000));
538}
539
540/**
541 * 重算商品各周期本地售价并写回 cycles 字段。
542 * 加价规则:单品有配置则用单品,否则用所属供应商配置。
543 *
544 * @param int $product_id
545 * @return void
546 */
547function zjmf_product_recalc_price($product_id)
548{
549 global $DB, $date;
550 $product = zjmf_product_get($product_id);
551 if (!$product) {
552 return;
553 }
554 $supplier = zjmf_supplier_get((int)$product['supplier_id']);
555 // 单品已配置加价(比例 type=0 或固定 type=1 且 value>0)时用单品规则,否则用供应商
556 $hasOwn = (int)($product['markup_type'] ?? 0) !== 0
557 || (int)($product['markup_value'] ?? 0) > 0;
558 $markupType = $hasOwn
559 ? (int)$product['markup_type'] : (int)($supplier['markup_type'] ?? 0);
560 $markupValue = $hasOwn
561 ? (int)$product['markup_value'] : (int)($supplier['markup_value'] ?? 0);
562
563 $cycles = zjmf_product_cycles($product);
564 if ($cycles === []) {
565 return;
566 }
567 foreach ($cycles as $cycle => &$cfg) {
568 // 管理员手动设置过售价(override>0)时保持不动,否则按加价规则重算
569 if ((int)($cfg['override'] ?? 0) > 0) {
570 $cfg['price_cents'] = (int)$cfg['override'];
571 } else {
572 $cfg['price_cents'] = zjmf_calc_price(
573 $cfg['agent_price_cents'] ?? 0,
574 $markupType,
575 $markupValue
576 );
577 }
578 }
579 unset($cfg);
580 $now = $date ?: date('Y-m-d H:i:s');
581 $DB->query_prepare(
582 "UPDATE MN_plugin_zjmf_product SET cycles=?, updated_at=? WHERE id=?",
583 [json_encode(array_values($cycles), JSON_UNESCAPED_UNICODE), $now, (int)$product_id]
584 );
585}
586
587/* ============================================================
588 * 订单管理
589 * ============================================================ */
590
591/** 按 ID 查询订单。 */
592function zjmf_order_get($order_id)
593{
594 global $DB;
595 return $DB->get_row_prepare(
596 "SELECT * FROM MN_plugin_zjmf_order WHERE id=? LIMIT 1",
597 [(int)$order_id]
598 ) ?: null;
599}
600
601/** 按订单号查询订单。 */
602function zjmf_order_get_by_no($order_no)
603{
604 global $DB;
605 return $DB->get_row_prepare(
606 "SELECT * FROM MN_plugin_zjmf_order WHERE order_no=? LIMIT 1",
607 [$order_no]
608 ) ?: null;
609}
610
611/** 用户订单列表(分页)。 */
612function zjmf_order_list_by_user($user_id, $page = 1, $per_page = 20)
613{
614 global $DB;
615 $user_id = (int)$user_id;
616 $page = max(1, (int)$page);
617 $per_page = max(1, min(100, (int)$per_page));
618 $offset = ($page - 1) * $per_page;
619 $count_row = $DB->get_row_prepare(
620 "SELECT COUNT(*) AS cnt FROM MN_plugin_zjmf_order WHERE user_id=?",
621 [$user_id]
622 );
623 $total = $count_row ? (int)$count_row['cnt'] : 0;
624 $list = $DB->get_all_prepare(
625 "SELECT o.* FROM MN_plugin_zjmf_order o
626 WHERE o.user_id=? ORDER BY o.id DESC LIMIT {$offset},{$per_page}",
627 [$user_id]
628 ) ?: [];
629 return ['list' => $list, 'total' => $total, 'page' => $page, 'per_page' => $per_page];
630}
631
632/** 全部订单列表(管理员,分页 + 简单筛选)。 */
633function zjmf_order_list_all($page = 1, $per_page = 30, $filters = [])
634{
635 global $DB;
636 $page = max(1, (int)$page);
637 $per_page = max(1, min(200, (int)$per_page));
638 $offset = ($page - 1) * $per_page;
639
640 $where = '1';
641 $params = [];
642 if (!empty($filters['status'])) {
643 $where .= ' AND status=?';
644 $params[] = $filters['status'];
645 }
646 if (!empty($filters['order_no'])) {
647 $where .= ' AND order_no LIKE ?';
648 $params[] = '%' . $filters['order_no'] . '%';
649 }
650 if (!empty($filters['user_id'])) {
651 $where .= ' AND user_id=?';
652 $params[] = (int)$filters['user_id'];
653 }
654 if (!empty($filters['supplier_id'])) {
655 $where .= ' AND supplier_id=?';
656 $params[] = (int)$filters['supplier_id'];
657 }
658
659 $count_row = $DB->get_row_prepare(
660 "SELECT COUNT(*) AS cnt FROM MN_plugin_zjmf_order WHERE {$where}",
661 $params
662 );
663 $total = $count_row ? (int)$count_row['cnt'] : 0;
664 $list = $DB->get_all_prepare(
665 "SELECT o.*, s.name AS supplier_name
666 FROM MN_plugin_zjmf_order o
667 LEFT JOIN MN_plugin_zjmf_supplier s ON s.id = o.supplier_id
668 WHERE {$where} ORDER BY o.id DESC LIMIT {$offset},{$per_page}",
669 $params
670 ) ?: [];
671 return ['list' => $list, 'total' => $total, 'page' => $page, 'per_page' => $per_page];
672}
673
674/**
675 * 创建本地订单(未支付)。
676 *
677 * @param array $user user_info 当前用户
678 * @param array $product 本地商品行
679 * @param string $cycle 计费周期
680 * @param array $cycleCfg 周期配置(name/price_cents)
681 * @param string $action buy/upgrade_config/upgrade_product
682 * @param array $extra 附加字段(up_host_id/host_id/order_params/cost_cents)
683 * @return array ['ok'=>bool, 'order_no'=>string, 'order_id'=>int, 'msg'=>string]
684 */
685function zjmf_order_create($user, $product, $cycle, $cycleCfg, $action = 'buy', $extra = [])
686{
687 global $DB, $date;
688 $now = $date ?: date('Y-m-d H:i:s');
689 $order_no = zjmf_order_no();
690 $cycleName = (string)($cycleCfg['name'] ?? $cycle);
691
692 $ok = $DB->query_prepare(
693 "INSERT INTO MN_plugin_zjmf_order
694 (order_no, action, supplier_id, user_id, product_id, up_product_id,
695 product_name, cycle, cycle_name, amount_cents, cost_cents, order_params,
696 up_order_id, up_host_id, host_id, username, status,
697 pay_time, opened_at, remark, created_at)
698 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
699 [
700 $order_no,
701 $action,
702 (int)($product['supplier_id'] ?? 0),
703 (int)$user['id'],
704 (int)($product['id'] ?? 0),
705 (int)($product['up_product_id'] ?? 0),
706 (string)($product['name'] ?? ''),
707 $cycle,
708 $cycleName,
709 (int)($cycleCfg['price_cents'] ?? 0),
710 (int)($extra['cost_cents'] ?? 0),
711 (string)($extra['order_params'] ?? ''),
712 (int)($extra['up_order_id'] ?? 0),
713 (int)($extra['up_host_id'] ?? 0),
714 (int)($extra['host_id'] ?? 0),
715 (string)($extra['username'] ?? ''),
716 'pending',
717 '',
718 '',
719 '',
720 $now,
721 ]
722 );
723 if (!$ok) {
724 return ['ok' => false, 'order_no' => '', 'order_id' => 0, 'msg' => '订单写入失败'];
725 }
726 $row = $DB->get_row_prepare(
727 "SELECT id FROM MN_plugin_zjmf_order WHERE order_no=? LIMIT 1",
728 [$order_no]
729 );
730 return [
731 'ok' => true,
732 'order_no' => $order_no,
733 'order_id' => $row ? (int)$row['id'] : 0,
734 'msg' => '',
735 ];
736}
737
738/** 更新订单状态。 */
739function zjmf_order_set_status($order_id, $status, $remark = '')
740{
741 global $DB, $date;
742 $now = $date ?: date('Y-m-d H:i:s');
743 $extra = '';
744 $params = [$status];
745 if ($status === 'paid') {
746 $extra = ', pay_time=?';
747 $params[] = $now;
748 } elseif ($status === 'opened') {
749 $extra = ', opened_at=?';
750 $params[] = $now;
751 }
752 if ($remark !== '') {
753 $extra .= ', remark=?';
754 $params[] = $remark;
755 }
756 $params[] = (int)$order_id;
757 return (bool)$DB->query_prepare(
758 "UPDATE MN_plugin_zjmf_order SET status=?{$extra} WHERE id=?",
759 $params
760 );
761}
762
763/** 回填订单开通信息。 */
764function zjmf_order_fill_opened($order_id, $upOrderId, $upHostId, $username)
765{
766 global $DB;
767 return (bool)$DB->query_prepare(
768 "UPDATE MN_plugin_zjmf_order
769 SET up_order_id=?, up_host_id=?, username=?
770 WHERE id=?",
771 [(int)$upOrderId, (int)$upHostId, (string)$username, (int)$order_id]
772 );
773}
774
775/**
776 * 创建升级订单(扣款前)。
777 *
778 * @param array $user user_info 当前用户
779 * @param array $host 本地主机映射行
780 * @param string $action upgrade_config / upgrade_product
781 * @param int $amountCents 升级差额(分)
782 * @param string $orderParams 升级参数 JSON(selection)
783 * @return array ['ok'=>bool, 'order_no'=>string, 'order_id'=>int, 'msg'=>string]
784 */
785function zjmf_upgrade_order_create($user, $host, $action, $amountCents, $orderParams)
786{
787 global $DB, $date;
788 $now = $date ?: date('Y-m-d H:i:s');
789 $order_no = zjmf_order_no();
790
791 $ok = $DB->query_prepare(
792 "INSERT INTO MN_plugin_zjmf_order
793 (order_no, action, supplier_id, user_id, product_id, up_product_id,
794 product_name, cycle, cycle_name, amount_cents, cost_cents, order_params,
795 up_order_id, up_host_id, host_id, username, status,
796 pay_time, opened_at, remark, created_at)
797 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
798 [
799 $order_no,
800 $action,
801 (int)($host['supplier_id'] ?? 0),
802 (int)$user['id'],
803 0,
804 (int)$host['up_product_id'],
805 '升级:' . $host['name'],
806 (string)($host['cycle'] ?? ''),
807 (string)($host['cycle'] ?? ''),
808 (int)$amountCents,
809 0,
810 (string)$orderParams,
811 0,
812 (int)$host['up_host_id'],
813 (int)$host['id'],
814 '',
815 'pending',
816 '',
817 '',
818 '',
819 $now,
820 ]
821 );
822 if (!$ok) {
823 return ['ok' => false, 'order_no' => '', 'order_id' => 0, 'msg' => '订单写入失败'];
824 }
825 $row = $DB->get_row_prepare(
826 "SELECT id FROM MN_plugin_zjmf_order WHERE order_no=? LIMIT 1",
827 [$order_no]
828 );
829 return [
830 'ok' => true,
831 'order_no' => $order_no,
832 'order_id' => $row ? (int)$row['id'] : 0,
833 'msg' => '',
834 ];
835}
836
837/* ============================================================
838 * 主机映射管理
839 * ============================================================ */
840
841/** 按 ID 查询主机映射。 */
842function zjmf_host_get($host_id)
843{
844 global $DB;
845 return $DB->get_row_prepare(
846 "SELECT * FROM MN_plugin_zjmf_host WHERE id=? LIMIT 1",
847 [(int)$host_id]
848 ) ?: null;
849}
850
851/** 校验主机归属当前用户后返回。 */
852function zjmf_host_get_by_user($user_id, $host_id)
853{
854 global $DB;
855 return $DB->get_row_prepare(
856 "SELECT h.*, s.name AS supplier_name
857 FROM MN_plugin_zjmf_host h
858 LEFT JOIN MN_plugin_zjmf_supplier s ON s.id = h.supplier_id
859 WHERE h.id=? AND h.user_id=? LIMIT 1",
860 [(int)$host_id, (int)$user_id]
861 ) ?: null;
862}
863
864/** 按上游主机 ID 查询映射。 */
865function zjmf_host_get_by_up($up_host_id)
866{
867 global $DB;
868 return $DB->get_row_prepare(
869 "SELECT * FROM MN_plugin_zjmf_host WHERE up_host_id=? LIMIT 1",
870 [(int)$up_host_id]
871 ) ?: null;
872}
873
874/** 用户主机列表(含供应商名)。 */
875function zjmf_host_list_by_user($user_id)
876{
877 global $DB;
878 return $DB->get_all_prepare(
879 "SELECT h.*, s.name AS supplier_name
880 FROM MN_plugin_zjmf_host h
881 LEFT JOIN MN_plugin_zjmf_supplier s ON s.id = h.supplier_id
882 WHERE h.user_id=? ORDER BY h.id DESC",
883 [(int)$user_id]
884 ) ?: [];
885}
886
887/** 全部主机列表(管理员,分页,含供应商名)。 */
888function zjmf_host_list_all($page = 1, $per_page = 30)
889{
890 global $DB;
891 $page = max(1, (int)$page);
892 $per_page = max(1, min(200, (int)$per_page));
893 $offset = ($page - 1) * $per_page;
894 $count_row = $DB->get_row_prepare("SELECT COUNT(*) AS cnt FROM MN_plugin_zjmf_host");
895 $total = $count_row ? (int)$count_row['cnt'] : 0;
896 $list = $DB->get_all_prepare(
897 "SELECT h.*, u.username AS user_name, s.name AS supplier_name
898 FROM MN_plugin_zjmf_host h
899 LEFT JOIN MN_plugin_user u ON u.id = h.user_id
900 LEFT JOIN MN_plugin_zjmf_supplier s ON s.id = h.supplier_id
901 ORDER BY h.id DESC LIMIT {$offset},{$per_page}"
902 ) ?: [];
903 return ['list' => $list, 'total' => $total, 'page' => $page, 'per_page' => $per_page];
904}
905
906/** 新增主机映射。 */
907function zjmf_host_create($data)
908{
909 global $DB, $date;
910 $now = $date ?: date('Y-m-d H:i:s');
911 $ok = $DB->query_prepare(
912 "INSERT INTO MN_plugin_zjmf_host
913 (supplier_id, user_id, order_id, up_host_id, up_product_id, name, username,
914 password, cycle, status, renew_date, created_at, updated_at)
915 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
916 [
917 (int)($data['supplier_id'] ?? 0),
918 (int)($data['user_id'] ?? 0),
919 (int)($data['order_id'] ?? 0),
920 (int)($data['up_host_id'] ?? 0),
921 (int)($data['up_product_id'] ?? 0),
922 (string)($data['name'] ?? ''),
923 (string)($data['username'] ?? ''),
924 (string)($data['password'] ?? ''),
925 (string)($data['cycle'] ?? ''),
926 (string)($data['status'] ?? 'active'),
927 (string)($data['renew_date'] ?? ''),
928 $now,
929 $now,
930 ]
931 );
932 if (!$ok) {
933 return 0;
934 }
935 $row = $DB->get_row_prepare(
936 "SELECT id FROM MN_plugin_zjmf_host
937 WHERE order_id=? ORDER BY id DESC LIMIT 1",
938 [(int)($data['order_id'] ?? 0)]
939 );
940 return $row ? (int)$row['id'] : 0;
941}
942
943/** 更新主机缓存信息(状态/到期/周期)。 */
944function zjmf_host_update_cache($host_id, $data)
945{
946 global $DB, $date;
947 $sets = [];
948 $params = [];
949 foreach (['status', 'renew_date', 'cycle', 'up_product_id'] as $key) {
950 if (array_key_exists($key, $data)) {
951 $sets[] = "`{$key}`=?";
952 $params[] = (string)$data[$key];
953 }
954 }
955 if ($sets === []) {
956 return false;
957 }
958 $now = $date ?: date('Y-m-d H:i:s');
959 $sets[] = "updated_at=?";
960 $params[] = $now;
961 $params[] = (int)$host_id;
962 return (bool)$DB->query_prepare(
963 "UPDATE MN_plugin_zjmf_host SET " . implode(',', $sets) . " WHERE id=?",
964 $params
965 );
966}
967
968/**
969 * 归一化上游返回的日期/时间戳为 Y-m-d H:i:s(精确到秒,与 created_at 展示一致)。
970 * 魔方财务部分版本接口返回 Unix 时间戳(秒/毫秒),部分返回 Y-m-d / Y-m-d H:i:s;
971 * 已含时分秒的标准串原样保留。
972 *
973 * @param mixed $val
974 * @return string
975 */
976function zjmf_normalize_date($val)
977{
978 $s = trim((string)$val);
979 if ($s === '') {
980 return '';
981 }
982 // 已是标准日期(时间)串:截断到秒粒度并保留
983 if (preg_match('/^\d{4}-\d{2}-\d{2}/', $s)) {
984 $s = preg_replace(
985 '/^(\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?)?).*$/',
986 '$1',
987 $s
988 );
989 return $s;
990 }
991 if (preg_match('/^\d+$/', $s)) {
992 $t = (int)$s;
993 if ($t > 100000000000) {
994 $t = (int)($t / 1000); // 毫秒时间戳
995 }
996 return $t > 0 ? date('Y-m-d H:i:s', $t) : '';
997 }
998 $t = strtotime($s);
999 return $t ? date('Y-m-d H:i:s', $t) : $s;
1000}
1001
1002/**
1003 * 补齐本地主机缺失的上游主机 ID(up_host_id<=0 时),确定性匹配。
1004 *
1005 * 匹配键:开通流程保存在订单 order_params.up_host 的本地生成主机标识
1006 * (upstream.php purchase() add_to_shop 时的 host 参数),与上游
1007 * host/list 返回的 domain 精确相等才绑定;已带 up_host_id 的正常路径
1008 * 不会进入本函数。不再做"产品名前缀 + 日期最近"的猜测匹配(曾发生
1009 * 误绑上游他人主机的越权风险)。
1010 * 匹配不到不写库(保持 up_host_id=0),仅记一条告警日志提示人工绑定。
1011 * 本函数只应在开通流程内或管理端调用,用户端 GET 请求不得触发写库。
1012 *
1013 * @param array $host MN_plugin_zjmf_host 行
1014 * @return array 回填后的主机行(未匹配则原样返回)
1015 */
1016function zjmf_backfill_host_upid($host)
1017{
1018 global $DB, $date;
1019 if (!is_array($host) || (int)($host['id'] ?? 0) <= 0 || (int)($host['up_host_id'] ?? 0) > 0) {
1020 return $host;
1021 }
1022 $supplierId = (int)($host['supplier_id'] ?? 0);
1023 if ($supplierId <= 0) {
1024 return $host;
1025 }
1026 $supplier = zjmf_supplier_get($supplierId);
1027 if (!$supplier || (int)$supplier['status'] !== 1) {
1028 return $host;
1029 }
1030 // 确定性匹配键:订单参数中保存的本地生成 host 标识
1031 $wantDomain = '';
1032 $orderNo = '';
1033 $order = zjmf_order_get((int)($host['order_id'] ?? 0));
1034 if ($order) {
1035 $orderNo = (string)($order['order_no'] ?? '');
1036 $params = json_decode((string)($order['order_params'] ?? ''), true);
1037 if (is_array($params) && isset($params['up_host'])) {
1038 $wantDomain = trim((string)$params['up_host']);
1039 }
1040 }
1041 if ($wantDomain === '') {
1042 // 无匹配键(历史数据/指派单等):不猜测,提示人工绑定
1043 zjmf_log((int)($host['user_id'] ?? 0), $orderNo, 'backfill', 'failed',
1044 '主机 #' . (int)$host['id'] . ' 缺少上游主机 ID 且无可用的确定性匹配键,'
1045 . '已放弃自动回填,请管理员人工绑定', $supplierId);
1046 return $host;
1047 }
1048 $res = ZjmfUpstream::hostList($supplier, ['orderby' => 'id', 'sort' => 'DESC']);
1049 $list = empty($res['ok']) ? [] : ($res['data']['list'] ?? []);
1050 $matched = null;
1051 foreach ((array)$list as $item) {
1052 if (is_array($item) && trim((string)($item['domain'] ?? '')) === $wantDomain) {
1053 $matched = $item;
1054 break;
1055 }
1056 }
1057 if (!$matched || (int)($matched['id'] ?? 0) <= 0) {
1058 // 上游列表中无该 domain(主机可能仍在异步创建):不写库
1059 zjmf_log((int)($host['user_id'] ?? 0), $orderNo, 'backfill', 'failed',
1060 '主机 #' . (int)$host['id'] . ' 未能按 host=' . $wantDomain
1061 . ' 在上游主机列表中确定性匹配,保持 up_host_id=0,请人工核对绑定', $supplierId);
1062 return $host;
1063 }
1064 $upId = (int)$matched['id'];
1065 // 代码级防重:该上游主机已被其他本地主机绑定时不重复写库
1066 $dup = $DB->get_row_prepare(
1067 "SELECT id FROM MN_plugin_zjmf_host
1068 WHERE supplier_id=? AND up_host_id=? AND id<>? LIMIT 1",
1069 [$supplierId, $upId, (int)$host['id']]
1070 );
1071 if ($dup) {
1072 zjmf_log((int)($host['user_id'] ?? 0), $orderNo, 'backfill', 'failed',
1073 '上游主机 #' . $upId . ' 已被本地主机 #' . (int)$dup['id'] . ' 绑定,'
1074 . '主机 #' . (int)$host['id'] . ' 放弃自动回填,请人工核对', $supplierId);
1075 return $host;
1076 }
1077 $status = function_exists('zjmf_map_upstream_status')
1078 ? zjmf_map_upstream_status((string)($matched['domainstatus'] ?? ''))
1079 : (string)($host['status'] ?? '');
1080 // nextduedate 部分版本为 Unix 时间戳,统一归一化为 Y-m-d
1081 $renew = zjmf_normalize_date((string)($matched['nextduedate'] ?? $host['renew_date'] ?? ''));
1082 $now = $date ?: date('Y-m-d H:i:s');
1083 $DB->query_prepare(
1084 "UPDATE MN_plugin_zjmf_host
1085 SET up_host_id=?, status=?, renew_date=?, updated_at=? WHERE id=?",
1086 [$upId, $status, $renew, $now, (int)$host['id']]
1087 );
1088 $host['up_host_id'] = $upId;
1089 $host['status'] = $status;
1090 $host['renew_date'] = $renew;
1091 return $host;
1092}
1093
1094/**
1095 * 上游状态 → 本地展示状态(统一映射表,主实现)。
1096 * ZjmfUpstream::mapHostStatus 委托调用本函数;除常规 domainstatus 外
1097 * 补充 off/true/false/deleted/Unpaid 等分支(true/false/off 多见于
1098 * DCIM/云主机开关机状态,deleted/Unpaid 见于部分上游版本)。
1099 */
1100function zjmf_map_upstream_status($status)
1101{
1102 $st = strtolower(trim((string)$status));
1103 if (in_array($st, ['active', 'on', 'true', 'completed', '运行中'], true)) {
1104 return 'active';
1105 }
1106 if (in_array($st, ['pending', 'wait', 'waiting', 'unpaid', '待开通', '未付款'], true)) {
1107 return 'pending';
1108 }
1109 if (in_array($st, ['suspended', 'suspend', 'paused', 'off', 'false', '已暂停', '已关机'], true)) {
1110 return 'suspend';
1111 }
1112 if (in_array($st, ['cancelled', 'cancel', 'terminated', 'terminate', 'deleted', 'delete', 'fraud', '已终止', '已删除'], true)) {
1113 return 'terminated';
1114 }
1115 return 'unknown';
1116}
1117
1118/* ============================================================
1119 * 主机操作辅助
1120 * ============================================================ */
1121
1122/** 操作标识 → 上游 func 名称(视上游模块而定,联调时按实际调整)。 */
1123function zjmf_action_func($action)
1124{
1125 $map = [
1126 'on' => 'on',
1127 'off' => 'off',
1128 'reboot' => 'reboot',
1129 'reset_password' => 'passwd',
1130 'reinstall' => 'reinstall',
1131 ];
1132 return $map[$action] ?? '';
1133}
1134
1135/** 操作成功后建议写入的缓存状态(空表示不修改)。 */
1136function zjmf_action_status($action)
1137{
1138 $map = [
1139 'on' => 'active',
1140 'reboot' => 'active',
1141 // 关机不写 suspend:本地主机表无独立电源字段,写入 suspend 会与
1142 // 上游真实状态(domainstatus 仍为 active)脱节,由调用方刷新上游
1143 // 状态回写真实状态
1144 'off' => '',
1145 ];
1146 return $map[$action] ?? '';
1147}
1148
1149/** 用户端主机状态展示标签映射。 */
1150function zjmf_host_status_label($status)
1151{
1152 $map = [
1153 'active' => '运行中',
1154 'suspend' => '已暂停',
1155 'pending' => '待开通',
1156 'terminated' => '已终止',
1157 'unknown' => '未知',
1158 ];
1159 return $map[$status] ?? $status;
1160}
1161
1162/* ============================================================
1163 * 主机开通(核心编排)
1164 * ============================================================ */
1165
1166/**
1167 * 支付成功后开通主机:调用上游开通,落库映射,失败自动退款。
1168 *
1169 * @param int $order_id MN_plugin_zjmf_order.id
1170 * @return array ['ok'=>bool, 'msg'=>string, 'host_id'=>int]
1171 */
1172function zjmf_open_host($order_id)
1173{
1174 global $DB, $date;
1175 $order = zjmf_order_get($order_id);
1176 if (!$order) {
1177 return ['ok' => false, 'msg' => '订单不存在'];
1178 }
1179 if ($order['status'] !== 'paid') {
1180 return ['ok' => false, 'msg' => '订单状态非已支付,无法开通'];
1181 }
1182 // 幂等:已开通或已有映射跳过
1183 $existing = $DB->get_row_prepare(
1184 "SELECT id FROM MN_plugin_zjmf_host WHERE order_id=? LIMIT 1",
1185 [(int)$order_id]
1186 );
1187 if ($existing) {
1188 return ['ok' => true, 'msg' => '该订单已开通', 'host_id' => (int)$existing['id']];
1189 }
1190
1191 // 供应商校验:缺失或停用时直接失败退款
1192 $supplier = zjmf_supplier_get((int)$order['supplier_id']);
1193 if (!$supplier || (int)$supplier['status'] !== 1) {
1194 $msg = '供应商不存在或已停用,无法开通';
1195 zjmf_order_set_status($order_id, 'failed', $msg);
1196 zjmf_log((int)$order['user_id'], $order['order_no'], 'purchase',
1197 'failed', json_encode(['msg' => $msg], JSON_UNESCAPED_UNICODE),
1198 (int)$order['supplier_id']);
1199 $amount = (int)$order['amount_cents'];
1200 if ($amount > 0 && function_exists('balance_add')) {
1201 balance_add((int)$order['user_id'], $amount, 'refund',
1202 $order['order_no'], '开通失败自动退款');
1203 }
1204 return ['ok' => false, 'msg' => $msg];
1205 }
1206
1207 // 调用上游开通(代理商直通,按订单供应商路由)
1208 $result = ZjmfUpstream::purchase($order, $supplier);
1209 if (empty($result['ok'])) {
1210 $msg = (string)($result['msg'] ?? '上游开通失败');
1211 zjmf_order_set_status($order_id, 'failed', $msg);
1212 zjmf_log((int)$order['user_id'], $order['order_no'],
1213 'purchase', 'failed', json_encode(['msg' => $msg], JSON_UNESCAPED_UNICODE),
1214 (int)$order['supplier_id']);
1215 // 自动原路退回余额
1216 $amount = (int)$order['amount_cents'];
1217 if ($amount > 0 && function_exists('balance_add')) {
1218 balance_add((int)$order['user_id'], $amount, 'refund',
1219 $order['order_no'], '开通失败自动退款');
1220 }
1221 return ['ok' => false, 'msg' => $msg];
1222 }
1223
1224 $now = $date ?: date('Y-m-d H:i:s');
1225 $upHostId = (int)($result['up_host_id'] ?? 0);
1226 $username = (string)($result['username'] ?? '');
1227 $password = (string)($result['password'] ?? '');
1228 $upOrderId = (int)($result['up_order_id'] ?? 0);
1229
1230 // 保存本次开通使用的本地生成主机标识(add_to_shop 的 host 参数),
1231 // 供开通响应未带主机 ID 时的确定性回填匹配(S2,避免猜测匹配越权)
1232 $genHost = trim((string)($result['host'] ?? ''));
1233 if ($genHost !== '') {
1234 $params = json_decode((string)($order['order_params'] ?? ''), true);
1235 if (!is_array($params)) {
1236 $params = [];
1237 }
1238 if ((string)($params['up_host'] ?? '') !== $genHost) {
1239 $params['up_host'] = $genHost;
1240 $DB->query_prepare(
1241 "UPDATE MN_plugin_zjmf_order SET order_params=? WHERE id=?",
1242 [json_encode($params, JSON_UNESCAPED_UNICODE), (int)$order_id]
1243 );
1244 }
1245 }
1246
1247 // 写主机映射(先建主机,成功后再标记订单 opened,避免中间态):
1248 // 主机映射写入失败时订单保持 paid 可人工重试,不得标 opened
1249 $hostId = zjmf_host_create([
1250 'supplier_id' => (int)$order['supplier_id'],
1251 'user_id' => (int)$order['user_id'],
1252 'order_id' => (int)$order_id,
1253 'up_host_id' => $upHostId,
1254 'up_product_id' => (int)$order['up_product_id'],
1255 'name' => (string)($result['name'] ?? $order['product_name']),
1256 'username' => $username,
1257 'password' => $password !== '' ? zjmf_encrypt($password) : '',
1258 'cycle' => $order['cycle'],
1259 'status' => 'active',
1260 'renew_date' => (string)($result['renew_date'] ?? ''),
1261 ]);
1262 if ($hostId <= 0) {
1263 @error_log('[zjmfmanager_reserve] host create failed, order stays paid: order_id='
1264 . (int)$order_id . ' up_host_id=' . $upHostId);
1265 zjmf_log((int)$order['user_id'], $order['order_no'], 'purchase', 'failed',
1266 '上游开通成功但本地主机映射写入失败,订单保持已支付待人工处理'
1267 . '(up_host_id=' . $upHostId . ')', (int)$order['supplier_id']);
1268 return ['ok' => false, 'msg' => '上游开通成功但本地主机映射写入失败,请人工处理', 'host_id' => 0];
1269 }
1270
1271 // 回填订单并标记 opened
1272 zjmf_order_fill_opened($order_id, $upOrderId, $upHostId, $username);
1273 zjmf_order_set_status($order_id, 'opened', '主机已开通');
1274
1275 // 开通响应未带主机 ID 时,在开通流程内同步做一次确定性回填(失败不阻断)
1276 if ($upHostId <= 0) {
1277 $hostRow = zjmf_host_get($hostId);
1278 if ($hostRow) {
1279 zjmf_backfill_host_upid($hostRow);
1280 }
1281 }
1282
1283 zjmf_log((int)$order['user_id'], $order['order_no'],
1284 'purchase', 'success',
1285 json_encode([
1286 'up_order_id' => $upOrderId,
1287 'up_host_id' => $upHostId,
1288 'username' => $username,
1289 ], JSON_UNESCAPED_UNICODE),
1290 (int)$order['supplier_id']);
1291
1292 return ['ok' => true, 'msg' => '开通成功', 'host_id' => $hostId];
1293}