ClientService.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. <?php
  2. namespace App\JsonRpc;
  3. use Hyperf\RpcServer\Annotation\RpcService;
  4. use App\Tools\Result;
  5. use Hyperf\DbConnection\Db;
  6. //mocle
  7. use App\Model\Complaint;
  8. use App\Model\JobEnum;
  9. use App\Model\User;
  10. use App\Model\webisitecategory;
  11. use App\Model\WebsiteTemplate;
  12. use Hyperf\Coroutine\Coroutine;
  13. use Hyperf\Redis\Redis;
  14. use Hyperf\Di\Annotation\Inject;
  15. use function Hyperf\Support\env;
  16. use Symfony\Component\Filesystem\Filesystem;
  17. use Hyperf\Paginator\Paginator;
  18. #[RpcService(name: "ClientService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
  19. class ClientService implements ClientServiceInterface
  20. {
  21. #[Inject]
  22. protected Redis $redis;
  23. /**
  24. * @param array $data
  25. * @return array
  26. */
  27. public function test(array $data): array
  28. {
  29. var_dump($data, '-------1--------');
  30. $time = date('Y-m-d H:i:s', time());
  31. $data = [
  32. 'code' => 200,
  33. 'msg' => 'success',
  34. 'data' => [
  35. 'time' => $time,
  36. 'data' => $data,
  37. ]
  38. ];
  39. //mysql直接查询连接数
  40. $activeConnections = Db::select("SHOW STATUS LIKE 'Threads_connected'");
  41. // $activeConnectionsCount = $activeConnections[0]->Value ?? 0;
  42. // $users = Db::select('SELECT * FROM article;');
  43. return ['code' => 200, 'msg' => 'success', 'data' => $activeConnections];
  44. }
  45. public function indexData(array $data): array
  46. {
  47. $time1 = microtime(true);
  48. // 调整获取方式
  49. // 根据网站id获取,从website_template中获取 website_template
  50. $website_id = $data['website_id'] ?? 2;
  51. var_dump("网站id:", $website_id);
  52. $template = Db::table('website_template')->where('website_id', $website_id)->first();
  53. var_dump("模板:", $template);
  54. $template = $template->template_data;
  55. $data = json_decode($template, true);
  56. // $data = json_decode($data['template'], true);
  57. // $website_id = $data['base']['website_id'] ?? 2;
  58. //设置缓存
  59. $websiteInfoCacheKey = "awebsite:category:{$website_id}";
  60. $websiteInfo = $this->redis->get($websiteInfoCacheKey); //false;
  61. if ($websiteInfo === false) {
  62. // Redis 中没有缓存,从数据库中查询
  63. $websiteInfo = Db::table('website_category')->where('website_id', $website_id)->get()->toArray();
  64. // 将查询结果存入 Redis,设置缓存时间为 3600 秒(1 小时)
  65. $this->redis->setex($websiteInfoCacheKey, 3600, json_encode($websiteInfo));
  66. } else {
  67. // 从 Redis 中获取的数据需要反序列化
  68. $websiteInfo = json_decode($websiteInfo, true);
  69. }
  70. $websiteInfo = Db::table('website_category')->where('website_id', $website_id)->get()->toArray();
  71. //取出website
  72. var_dump($websiteInfo, 'websiteInfo');
  73. //取出category_id 对应的数据
  74. $websiteInfoIndexed = array_column($websiteInfo, null, 'category_id');
  75. // 取出category_id 对应的aLIas_pinyin
  76. $categoryIds = array_column($websiteInfo, 'category_id');
  77. $aliasPinyins = array_column($websiteInfo, 'aLIas_pinyin');
  78. $cat_arr = array_combine($categoryIds, $aliasPinyins);
  79. // var_dump($cat_arr, 'cat_arr');
  80. //根据 category_arr_id 组合出 aLIas_pinyin
  81. $catiall = [];
  82. //一级所有子级的记录
  83. $cat_1st_arr = [];
  84. foreach ($websiteInfo as $key => $value) {
  85. //算出路由拼音
  86. $category_arr_id = json_decode($value->category_arr_id);
  87. $pinyin_str = '';
  88. foreach ($category_arr_id as $k => $v) {
  89. $pinyin_str .= $cat_arr[$v] . '/';
  90. }
  91. $pinyin_str = rtrim($pinyin_str, '/');
  92. $catiall[$value->category_id][] = $pinyin_str;
  93. // $cat_id = $value->category_id;
  94. $websiteInfoIndexed[$value->category_id]->pinyin = $pinyin_str;
  95. // 算出一级 并且算出子级
  96. if ($value->pid == 0) {
  97. if (empty($cat_1st_arr[$value->category_id]))
  98. $cat_1st_arr[$value->category_id] = [];
  99. } else {
  100. if ($value->pid == 11) {
  101. var_dump($value->category_id, 'value->category_id');
  102. }
  103. $cat_1st_arr[$value->pid][] = $value->category_id;
  104. }
  105. }
  106. var_dump($cat_1st_arr, 'cat_1st_arr');
  107. $time2 = microtime(true);
  108. $time_ = ($time2 - $time1);
  109. var_dump($time2, $time1, $time_, '返回路由需要多少时间');
  110. //获取
  111. // $getpage = $data['base']['getpage'] ?? 'index';
  112. $getpage = $data['getpage'] ?? 'index';
  113. var_dump($getpage, 'leixing ');
  114. // index = 首页
  115. // class = 频道页
  116. // list = 列表页
  117. // article = 详情页
  118. // search = 搜索页
  119. // aboutList = 底部导航列表页
  120. // aboutArticle = 底部导航详情页
  121. // return $cat_1st_arr;
  122. // return $cat_1st_arr;
  123. // var_dump($cat_1st_arr[11], 'cat_1st_arr'); //一级所有子级的记录
  124. // var_dump($catiall, 'catiall');//拼音
  125. $templateData = [];
  126. switch ($getpage) {
  127. case 'index':
  128. $ceng = $data['template']['index'];
  129. var_dump($ceng, 'ceng================');
  130. foreach ($ceng as $k_ceng => $v_ceng) {
  131. $componetList = $v_ceng['componentList'];
  132. //计算一级的所有子级;组成一个数据,key是一级的category_id,value是所有的子级数据,加上个二级的pinyin属性,放的是catiall的数据
  133. foreach ($componetList as $key => $value) {
  134. //取出componentData
  135. $componentData = $value['componentData'];
  136. if (!$componentData) {
  137. continue;
  138. };
  139. // $page = $componentData['page'];
  140. // $pageSize = $componentData['pageSize'];
  141. // $listType = $componentData['listType'];
  142. $category_id = $componentData['category_id'] ?? 0;
  143. //此处应该有值
  144. $imgSize = $componentData['imgSize'];
  145. $textSize = $componentData['textSize'];
  146. $level = $componentData['level'];
  147. $child = $componentData['child'];
  148. //获取子级
  149. if ($child) {
  150. $child_id = $componentData['category_id'] ?? 0;
  151. $child_imgSize = $child['imgSize'] ?? 0;
  152. $child_textSize = $child['textSize'] ?? 0;
  153. }
  154. // 拼音就是路由----
  155. // unset($listType['pinyin']);
  156. //查询查询数据,返回到data字段里,根据这几个
  157. if ($category_id > 0) {
  158. var_dump($category_id, '------------------category_id');
  159. var_dump($cat_1st_arr, '-----------1-------2');
  160. // 第一次查询:imgurl 不为空的数据
  161. if ($imgSize > 0) {
  162. $imgArticles = Db::table('article')
  163. ->leftJoin('article_ignore', function ($join) use ($website_id) {
  164. $join->on('article.id', '=', 'article_ignore.article_id')->where('article_ignore.website_id', '=', $website_id);
  165. })->whereNull('article_ignore.article_id')->whereIn('catid', $temp_arr = array_merge([$category_id], $cat_1st_arr[$category_id]))->where('status', 1)
  166. ->whereNotNull('imgurl')->where('imgurl', '!=', '')->limit($imgSize)->orderBy('updated_at', 'desc')->get()->toArray();
  167. //拼接上拼音
  168. foreach ($imgArticles as $k => $v) {
  169. $imgArticles[$k]->pinyin = $catiall[$v->catid][0];
  170. }
  171. }
  172. // 第二次查询:imgurl 为空的数据
  173. if ($textSize > 0) {
  174. $textArticles = Db::table('article')
  175. ->leftJoin('article_ignore', function ($join) use ($website_id) {
  176. $join->on('article.id', '=', 'article_ignore.article_id')->where('article_ignore.website_id', '=', $website_id);
  177. })->whereNull('article_ignore.article_id')->whereIn('catid', $temp_arr = array_merge([$category_id], $cat_1st_arr[$category_id]))->where('status', 1)
  178. ->where('status', 1)->limit($textSize)->orderBy('updated_at', 'desc')->get()->toArray();
  179. //拼接上拼音
  180. foreach ($textArticles as $k => $v) {
  181. $textArticles[$k]->pinyin = $catiall[$v->catid][0];
  182. }
  183. }
  184. }
  185. var_dump($level, 'level');
  186. if ($level > 0) {
  187. // 取出一级的所有子级
  188. //取出所有的子级的imgurl 不为空的数据
  189. if ($imgSize > 0) {
  190. $imgArticles = Db::table('article')
  191. ->leftJoin('article_ignore', function ($join) use ($website_id) {
  192. $join->on('article.id', '=', 'article_ignore.article_id')->where('article_ignore.website_id', '=', $website_id);
  193. })->whereNull('article_ignore.article_id')
  194. ->whereRaw('MATCH(level_text) AGAINST(? IN NATURAL LANGUAGE MODE)', [$level])->where('status', 1)->whereIn('catid', $categoryIds)->whereNotNull('imgurl')->where('imgurl', '!=', '')->limit($imgSize)->orderBy('updated_at', 'desc')->get()->toArray();
  195. //拼接上拼音
  196. foreach ($imgArticles as $k => $v) {
  197. $imgArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  198. }
  199. }
  200. //取出所有的子级的imgurl 为空的数据 ->whereNull('imgurl')
  201. if ($textSize > 0) {
  202. $textArticles = Db::table('article')->where('status', 1)
  203. ->leftJoin('article_ignore', function ($join) use ($website_id) {
  204. $join->on('article.id', '=', 'article_ignore.article_id')->where('article_ignore.website_id', '=', $website_id);
  205. })->whereNull('article_ignore.article_id')
  206. ->whereRaw('MATCH(level_text) AGAINST(? IN NATURAL LANGUAGE MODE)', [$level])->whereIn('catid', $categoryIds)->limit($textSize)->orderBy('updated_at', 'desc')->get()->toArray();
  207. //拼接上拼音
  208. foreach ($textArticles as $k => $v) {
  209. $textArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  210. }
  211. }
  212. }
  213. //将查询到的数据放到componentData里
  214. $componetList[$key]['componentData']['data']['alias'] = $websiteInfoIndexed[$category_id]->alias ?? 'aliasnull' . $category_id;
  215. $componetList[$key]['componentData']['data']['pinyin'] = $websiteInfoIndexed[$category_id]->pinyin ?? 'aliasnull' . $category_id;
  216. $componetList[$key]['componentData']['data']['category_id'] = $category_id;
  217. $componetList[$key]['componentData']['data']['textnum'] = $textArticles ?? [];
  218. $componetList[$key]['componentData']['data']['imgnum'] = $imgArticles ?? [];
  219. //判断child
  220. var_dump($child_id, '--------child_id---');
  221. if ($child_id > 0) {
  222. //取出子级的imgurl 不为空的数据
  223. if ($child_imgSize > 0) {
  224. $child_imgArticles = Db::table('article')->where('catid', $child_id)
  225. ->where('status', 1)
  226. ->whereNotNull('imgurl')->limit($child_imgSize)->orderBy('updated_at', 'desc')->get()->toArray();
  227. } else {
  228. $child_imgArticles = [];
  229. }
  230. //取出子级的imgurl 为空的数据
  231. if ($child_textSize > 0) {
  232. $child_textArticles = Db::table('article')
  233. ->where('status', 1)
  234. ->where('catid', $child_id)->whereNull('imgurl')->limit($child_textSize)->orderBy('updated_at', 'desc')->get()->toArray();
  235. } else {
  236. $child_textArticles = [];
  237. }
  238. //将查询到的数据放到componentData里
  239. $componetList[$key]['componentData']['data']['child']['alias'] = $websiteInfoIndexed[$child_id]->alias;
  240. $componetList[$key]['componentData']['data']['child']['pinyin'] = $websiteInfoIndexed[$child_id]->pinyin;
  241. $componetList[$key]['componentData']['data']['child']['category_id'] = $child_id;
  242. $componetList[$key]['componentData']['data']['child']['textnum'] = $child_textArticles;
  243. $componetList[$key]['componentData']['data']['child']['imgnum'] = $child_imgArticles;
  244. $componetList[$key]['componentData']['data']['child']['is_url'] = $websiteInfoIndexed[$child_id]->is_url ?? 0;
  245. //取出自己
  246. $all_childcat = $cat_1st_arr[$category_id];
  247. $componetList[$key]['componentData']['data']['child']['children_count'] = count($all_childcat);
  248. $processedChildCat = array_map(function ($v) use ($websiteInfoIndexed, $cat_1st_arr) {
  249. // 从 $websiteInfoIndexed 中获取对应的数据
  250. $info = $websiteInfoIndexed[$v];
  251. var_dump($info, $v, '-------child循环--------');
  252. // 返回一个包含所需信息的数组
  253. return [
  254. 'pinyin' => $info->pinyin,
  255. 'alias' => $info->alias,
  256. 'category_id' => $info->category_id,
  257. 'aLIas_pinyin' => $info->aLIas_pinyin,
  258. 'pid' => $info->pid,
  259. 'cat_arr_id' => $info->category_arr_id ?? ['出错'],
  260. 'is_url' => $info->is_url ?? 0,
  261. 'children_count' => isset($cat_1st_arr[$v]) ? count($cat_1st_arr[$v]) : 0
  262. ];
  263. }, $all_childcat);
  264. $componetList[$key]['componentData']['data']['child']['all_childcat'] = $processedChildCat ?? [];
  265. }
  266. }
  267. $data['template']['index'][$k_ceng]['componentList'] = $componetList;
  268. }
  269. //将修改后的数据放到template里
  270. break;
  271. case 'class':
  272. $componetList = $data['template']['class']['data'][0]['componentList'];
  273. $class_count = count($componetList);
  274. $parent_id = $data['template']['class']['parent_id'] ?? 0;
  275. //获取子级;
  276. $child = $cat_1st_arr[$parent_id]; //获取子级
  277. // var_dump($child, 'child');
  278. //如果$child的数量小于$class_count,就填充一样多的数据给child,如果大于就截取一样的数量给child
  279. if (count($child) < $class_count) {
  280. $child = array_pad($child, $class_count, end($child) ?? 0);
  281. } elseif (count($child) > $class_count) {
  282. $child = array_slice($child, 0, $class_count);
  283. }
  284. foreach ($componetList as $key => $value) {
  285. $componentData = $value['componentData'];
  286. //取出imgSize和textSize,获取相应的文章,
  287. $category_id = $child[$key] ?? 0;
  288. $imgSize = $componentData['imgSize'] ?? 0;
  289. $textSize = $componentData['textSize'] ?? 0;
  290. $listType = $componentData['listType'] ?? [];
  291. var_dump($listType, 'before unset listType');
  292. // 定义要移除的元素数组
  293. $valuesToRemove = ['category_name', 'pinyin'];
  294. // 循环移除每个元素
  295. foreach ($valuesToRemove as $value) {
  296. while (($key = array_search($value, $listType)) !== false) {
  297. // 移除该元素
  298. unset($listType[$key]);
  299. }
  300. }
  301. var_dump($listType, 'listType');
  302. //child
  303. $child = $componentData['child'] ?? [];
  304. $data_class = [];
  305. //查询imgurl不为空的数据
  306. $imgArticles = Db::table('article')
  307. ->where('catid', $category_id)
  308. ->whereNotNull('imgurl')
  309. ->limit($imgSize)
  310. // ->select($listType)
  311. ->orderBy('updated_at', 'desc')
  312. ->get()
  313. ->toArray();
  314. //拼接上拼音
  315. foreach ($imgArticles as $k => $v) {
  316. $imgArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  317. }
  318. //查询imgurl为空的数据
  319. $textArticles = Db::table('article')
  320. ->where('catid', $category_id)
  321. ->whereNull('imgurl')
  322. ->limit($textSize)
  323. ->orderBy('updated_at', 'desc')
  324. ->get()
  325. ->toArray();
  326. //拼接上拼音
  327. foreach ($textArticles as $k => $v) {
  328. $textArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  329. }
  330. $data_class['alias'] = $websiteInfoIndexed[$category_id]->alias ?? 'aliasnull' . $category_id;
  331. $data_class['pinyin'] = $websiteInfoIndexed[$category_id]->pinyin ?? 'aliasnull' . $category_id;
  332. $data_class['category_id'] = $category_id;
  333. $data_class['textnum'] = $textArticles ?? [];
  334. $data_class['imgnum'] = $imgArticles ?? [];
  335. $data['data'] = $data_class;
  336. }
  337. break;
  338. case 'list':
  339. $componetListdata = $data['template']['list']['data'];
  340. $category_id = $data['template']['list']['category_id'] ?? 0;
  341. foreach ($componetListdata as $k => $v) {
  342. if (!isset($v['componentList']) || !is_array($v['componentList'])) {
  343. continue; // 如果 componentList 不存在或不是数组,跳过当前循环
  344. }
  345. $componentList = &$data['template']['list']['data'][$k]['componentList'];
  346. var_dump(count($componentList), 'componentList111');
  347. foreach ($componentList as $key => $value) {
  348. $componentData = $value['componentData'];
  349. if (isset($value['componentData']['category_id'])) {
  350. $value['componentData']['category_id'] = $category_id;
  351. $page = $componentData['papageTypege']['page'] ?? 1;
  352. $pageSize = $componentData['papageTypege']['pageSize'] ?? 10;
  353. $listType = $componentData['listType'];
  354. $articals = Db::table('article')
  355. ->where('catid', $category_id)
  356. ->where('status', 1)
  357. ->orderBy('updated_at', 'desc')
  358. ->get();
  359. // ->paginate($pageSize, ['*'], 'page', $page);
  360. //拼接上拼音
  361. foreach ($articals as $k => $v) {
  362. $articals[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  363. }
  364. $value['componentData']['data'] = $articals;
  365. }
  366. var_dump(isset($value['componentData']['level']), $key, '---------------------------------------');
  367. if (isset($value['componentData']['level'])) {
  368. //取出imgSize和textSize,获取相应的文章,
  369. $imgSize = $componentData['imgnum'] ?? 0;
  370. $textSize = $componentData['textnum'] ?? 0;
  371. $listType = $componentData['listType'] ?? [];
  372. // 定义要移除的元素数组
  373. $valuesToRemove = ['category_name', 'pinyin'];
  374. // 循环移除每个元素
  375. foreach ($valuesToRemove as $value) {
  376. while (($key = array_search($value, $listType)) !== false) {
  377. // 移除该元素
  378. unset($listType[$key]);
  379. }
  380. }
  381. //查询imgurl不为空的数据
  382. if ($imgSize > 0) {
  383. $imgArticles = Db::table('article')
  384. ->where('catid', $category_id)
  385. ->whereNotNull('imgurl')
  386. ->limit($imgSize)
  387. ->orderBy('updated_at', 'desc')
  388. ->get()
  389. ->toArray();
  390. //拼接上拼音
  391. foreach ($imgArticles as $k => $v) {
  392. $imgArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  393. }
  394. }
  395. //查询imgurl为空的数据
  396. if ($textSize > 0) {
  397. $textArticles = Db::table('article')
  398. ->where('catid', $category_id)
  399. ->whereNull('imgurl')
  400. ->limit($textSize)
  401. ->orderBy('updated_at', 'desc')
  402. ->get()
  403. ->toArray();
  404. //拼接上拼音
  405. foreach ($textArticles as $k => $v) {
  406. $textArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  407. }
  408. }
  409. //将查询到的数据放到componentData里
  410. $componetList[$key]['componentData']['data']['alias'] = $websiteInfoIndexed[$category_id]->alias ?? 'aliasnull' . $category_id;
  411. $componetList[$key]['componentData']['data']['pinyin'] = $websiteInfoIndexed[$category_id]->pinyin ?? 'aliasnull' . $category_id;
  412. $componetList[$key]['componentData']['data']['category_id'] = $category_id;
  413. $componetList[$key]['componentData']['data']['textnum'] = $textArticles ?? [];
  414. $componetList[$key]['componentData']['data']['imgnum'] = $imgArticles ?? [];
  415. //将修改后的数据放到template里
  416. // $data['template']['list']['data'][0]['componentList'] = $componetList;
  417. }
  418. }
  419. }
  420. break;
  421. case 'article':
  422. $article_id = 51434; //假设这是文章ID
  423. $componetListdata = &$data['template']['article']['data'];
  424. var_dump($categoryIds, '----------------');
  425. // $category_id = $data['template']['article']['category_id'] ?? 0;
  426. foreach ($componetListdata as $k => $v) {
  427. foreach ($v['componentList'] as $key => $value) {
  428. $componentData = $value['componentData'];
  429. if (isset($value['componentData']['article_id'])) {
  430. $value['componentData']['article_id'] = $article_id;
  431. // $page = $componentData['papageTypege']['page'] ?? 1;
  432. // $pageSize = $componentData['papageTypege']['pageSize'] ?? 10;
  433. $listType = $componentData['listType'];
  434. //查询数据
  435. $articals = Db::table('article')
  436. ->where('id', $article_id)
  437. ->where('status', 1)
  438. ->leftJoin('article_data', 'article.id', '=', 'article_data.article_id')
  439. ->select('article.*', 'article_data.content')
  440. ->orderBy('updated_at', 'desc')
  441. ->get();
  442. //拼接上拼音
  443. $value['componentData']['data'] = $articals;
  444. }
  445. if (isset($value['componentData']['level'])) {
  446. //:1:头条 2:轮播图 3:推荐图 4:最新新闻;5:推荐新闻;6:热点资讯 7:自动关联
  447. //4 update 5 30天之内 6 库中
  448. $level = $componentData['level'] ?? 0;
  449. $imgSize = $componentData['imgnum'] ?? 0;
  450. $textSize = $componentData['textnum'] ?? 0;
  451. if (in_array($level, [1, 2, 3, 6])) {
  452. //查询imgurl不为空的数据
  453. $imgArticles = Db::table('article')->whereIn('catid', $categoryIds)->whereNotNull('imgurl')
  454. ->where('status', 1)
  455. ->whereRaw('MATCH(level_text) AGAINST(? IN NATURAL LANGUAGE MODE)', [$level])
  456. ->limit($imgSize)->orderBy('updated_at', 'desc')->get()->toArray();
  457. //拼接上拼音
  458. foreach ($imgArticles as $k => $v) {
  459. $imgArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  460. }
  461. //查询imgurl为空的数据
  462. $textArticles = Db::table('article')->where('catid', $categoryIds)->whereNull('imgurl')
  463. ->where('status', 1)
  464. ->whereRaw('MATCH(level_text) AGAINST(? IN NATURAL LANGUAGE MODE)', [$level])
  465. ->limit($textSize)->orderBy('updated_at', 'desc')->get()->toArray();
  466. //拼接上拼音
  467. foreach ($textArticles as $k => $v) {
  468. $textArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  469. }
  470. } else if ($level == 4) {
  471. //查询imgurl不为空的数据
  472. $imgArticles = Db::table('article')->whereIn('catid', $categoryIds)->whereNotNull('imgurl')
  473. ->where('status', 1)
  474. ->limit($imgSize)->orderBy('updated_at', 'desc')->get()->toArray();
  475. //拼接上拼音
  476. if (!empty($imgArticles)) {
  477. foreach ($imgArticles as $k => $v) {
  478. $imgArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  479. }
  480. }
  481. //查询imgurl为空的数据
  482. $textArticles = Db::table('article')->whereIn('catid', $categoryIds)->whereNull('imgurl')
  483. ->where('status', 1)
  484. ->limit($textSize)->orderBy('updated_at', 'desc')->get()->toArray();
  485. //拼接上拼音
  486. var_dump('---4------');
  487. if (!empty($textArticles)) {
  488. foreach ($textArticles as $k => $v) {
  489. $textArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  490. }
  491. }
  492. } else if ($level == 5) {
  493. var_dump($value['componentData']['level'], 'level');
  494. //查询imgurl不为空的数据
  495. $imgArticles = Db::table('article')->whereIn('catid', $categoryIds)->whereNotNull('imgurl')
  496. ->where('status', 1)
  497. //最近三十天
  498. ->where('updated_at', '>=', date('Y-m-d H:i:s', strtotime('-30 days')))
  499. ->limit($imgSize)->orderBy('updated_at', 'desc')->get()->toArray();
  500. //拼接上拼音
  501. if (!empty($imgArticles)) {
  502. foreach ($imgArticles as $k => $v) {
  503. $imgArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  504. }
  505. }
  506. //查询imgurl为空的数据
  507. $textArticles = Db::table('article')->whereIn('catid', $categoryIds)->whereNull('imgurl')
  508. ->where('status', 1)
  509. ->where('updated_at', '>=', date('Y-m-d H:i:s', strtotime('-30 days')))
  510. ->limit($textSize)->orderBy('updated_at', 'desc')->get()->toArray();
  511. //拼接上拼音
  512. var_dump('---5------');
  513. if (!empty($textArticles)) {
  514. foreach ($textArticles as $k => $v) {
  515. $textArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  516. }
  517. }
  518. } else if ($level == 7) {
  519. //获取artical的keyword
  520. $keword = DB::table('artical')->where('id', $article_id)->select('keyword')->get();
  521. $kewordl = $keword[0]->keyword;
  522. $kewordl = explode(',', $kewordl);
  523. //筛选出符合条件的article来
  524. $imgArticles = Db::table('article')->whereIn('catid', $categoryIds)->whereNotNull('imgurl')
  525. ->where('status', 1)
  526. // ->whereJsonContains('keyword', $kewordl)
  527. ->whereRaw('MATCH(keyword) AGAINST(? IN NATURAL LANGUAGE MODE)', [$kewordl])
  528. ->limit($imgSize)->orderBy('updated_at', 'desc')->get()->toArray();
  529. //拼接上拼音
  530. foreach ($imgArticles as $k => $v) {
  531. $imgArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  532. }
  533. $textArticles = Db::table('article')->whereIn('catid', $categoryIds)->whereNull('imgurl')
  534. ->where('status', 1)
  535. // ->whereJsonContains('keyword', $kewordl)
  536. ->whereRaw('MATCH(keyword) AGAINST(? IN NATURAL LANGUAGE MODE)', [$kewordl])
  537. ->limit($textSize)->orderBy('updated_at', 'desc')->get()->toArray();
  538. //拼接上拼音
  539. foreach ($textArticles as $k => $v) {
  540. $textArticles[$k]->pinyin = $catiall[$v->catid][0] ?? '=====';
  541. }
  542. }
  543. }
  544. $value['componentData']['data']['imgnum'] = $imgArticles ?? [];
  545. $value['componentData']['data']['textnum'] = $textArticles ?? [];
  546. }
  547. }
  548. break;
  549. case 'search':
  550. break;
  551. case 'aboutList':
  552. $fact_id = 7;
  553. $componetList = &$data['template']['aboutList']['componentData'];
  554. $componetList['fact_id'] = $fact_id;
  555. $content = Db::table('footer_content')
  556. ->where('fcat_id', $fact_id)
  557. ->orderBy('updated_at', 'desc')
  558. ->get()
  559. ->toArray();
  560. $componetList['data'] = $content;
  561. break;
  562. case 'aboutArticle':
  563. $fact_id = 7;
  564. $componetList = &$data['template']['aboutList']['componentData'];
  565. $componetList['fact_id'] = $fact_id;
  566. $content = Db::table('footer_content')
  567. ->where('id', $fact_id)
  568. ->orderBy('updated_at', 'desc')
  569. ->get()
  570. ->toArray();
  571. $componetList['data'] = $content;
  572. break;
  573. default:
  574. $componetList = [];
  575. break;
  576. }
  577. return $data;
  578. }
  579. public function indexData1(array $data): array
  580. {
  581. $time1 = microtime(true);
  582. // 解析模板数据
  583. $templateData = json_decode($data['template'], true);
  584. $website_id = $templateData['base']['website_id'] ?? 2;
  585. $componentList = $templateData['template']['index'][0]['componentList'];
  586. // 1️⃣ 获取网站分类信息
  587. $websiteInfo = Db::table('website_category')
  588. ->where('website_id', $website_id)
  589. ->get()
  590. ->toArray();
  591. // 构建索引和拼音映射
  592. $websiteInfoIndexed = array_column($websiteInfo, null, 'category_id');
  593. $categoryIds = array_column($websiteInfo, 'category_id');
  594. $aliasPinyins = array_column($websiteInfo, 'aLIas_pinyin');
  595. $cat_arr = array_combine($categoryIds, $aliasPinyins);
  596. // 构建 catiall 和 cat_1st_arr
  597. $catiall = [];
  598. $cat_1st_arr = [];
  599. foreach ($websiteInfo as $item) {
  600. $arrId = json_decode($item->category_arr_id);
  601. $pinyin_str = implode('/', array_map(fn($id) => $cat_arr[$id], $arrId));
  602. $pinyin_str = rtrim($pinyin_str, '/');
  603. $catiall[$item->category_id][] = $pinyin_str;
  604. $websiteInfoIndexed[$item->category_id]->pinyin = $pinyin_str;
  605. if ($item->pid == 0) {
  606. $cat_1st_arr[$item->category_id] = [];
  607. } else {
  608. $cat_1st_arr[$item->pid][] = $item->category_id;
  609. }
  610. }
  611. // 2️⃣ 提前聚合所有需要查询的 category_id 和限制参数
  612. $allCatIds = [];
  613. $imgLimits = [];
  614. $txtLimits = [];
  615. $childImgLimits = [];
  616. $childTxtLimits = [];
  617. foreach ($componentList as $item) {
  618. $componentData = $item['componentData'];
  619. $category_id = $componentData['category_id'] ?? 0;
  620. if ($category_id > 0) {
  621. $allCatIds[] = $category_id;
  622. $imgLimits[$category_id] = $componentData['imgSize'] ?? 0;
  623. $txtLimits[$category_id] = $componentData['textSize'] ?? 0;
  624. if (!empty($cat_1st_arr[$category_id])) {
  625. $allCatIds = array_merge($allCatIds, $cat_1st_arr[$category_id]);
  626. }
  627. }
  628. // 子级
  629. $child = $componentData['child'] ?? null;
  630. if ($child && isset($child['id']) && $child['id'] > 0) {
  631. $child_id = $child['id'];
  632. $childImgLimits[$child_id] = $child['imgSize'] ?? 0;
  633. $childTxtLimits[$child_id] = $child['textSize'] ?? 0;
  634. }
  635. }
  636. $allCatIds = array_unique(array_filter($allCatIds));
  637. // 3️⃣ 一次性查询所有 article 数据
  638. $allArticles = Db::table('article')
  639. ->whereIn('catid', $allCatIds)
  640. ->where('status', 1)
  641. ->get()
  642. ->toArray();
  643. // 构建按 imgurl 分类的文章集合
  644. $articlesByCat = ['img' => [], 'txt' => []];
  645. foreach ($allArticles as $article) {
  646. if (!empty($article->imgurl)) {
  647. $articlesByCat['img'][$article->catid][] = $article;
  648. } else {
  649. $articlesByCat['txt'][$article->catid][] = $article;
  650. }
  651. }
  652. // 4️⃣ 使用协程并发处理每个组件
  653. $results = [];
  654. foreach ($componentList as $key => $value) {
  655. $componentKey = $key;
  656. $componentData = $value['componentData'];
  657. Coroutine::create(function () use (&$results, $componentKey, $componentData, $websiteInfoIndexed, $cat_1st_arr, $catiall, $articlesByCat, $imgLimits, $txtLimits, $childImgLimits, $childTxtLimits) {
  658. $result = [];
  659. $category_id = $componentData['category_id'] ?? 0;
  660. $imgLimit = $imgLimits[$category_id] ?? 0;
  661. $txtLimit = $txtLimits[$category_id] ?? 0;
  662. if ($category_id > 0) {
  663. // 图文数据
  664. $imgArticles = array_slice($articlesByCat['img'][$category_id] ?? [], 0, $imgLimit);
  665. foreach ($imgArticles as &$v) {
  666. $v->pinyin = $catiall[$v->catid][0] ?? '';
  667. }
  668. // 纯文字数据
  669. $textArticles = array_slice($articlesByCat['txt'][$category_id] ?? [], 0, $txtLimit);
  670. foreach ($textArticles as &$v) {
  671. $v->pinyin = $catiall[$v->catid][0] ?? '';
  672. }
  673. $result['imgnum'] = $imgArticles;
  674. $result['textnum'] = $textArticles;
  675. $result['alias'] = $websiteInfoIndexed[$category_id]['alias'] ?? '';
  676. $result['pinyin'] = $websiteInfoIndexed[$category_id]['pinyin'] ?? '';
  677. $result['category_id'] = $category_id;
  678. }
  679. // 子级处理
  680. $child = $componentData['child'] ?? null;
  681. if ($child && isset($child['id']) && $child['id'] > 0) {
  682. $child_id = $child['id'];
  683. $c_imgLimit = $childImgLimits[$child_id] ?? 0;
  684. $c_txtLimit = $childTxtLimits[$child_id] ?? 0;
  685. $childImg = array_slice($articlesByCat['img'][$child_id] ?? [], 0, $c_imgLimit);
  686. foreach ($childImg as &$v) {
  687. $v->pinyin = $catiall[$v->catid][0] ?? '';
  688. }
  689. $childText = array_slice($articlesByCat['txt'][$child_id] ?? [], 0, $c_txtLimit);
  690. foreach ($childText as &$v) {
  691. $v->pinyin = $catiall[$v->catid][0] ?? '';
  692. }
  693. $result['child'] = [
  694. 'alias' => $websiteInfoIndexed[$child_id]['alias'] ?? '',
  695. 'pinyin' => $websiteInfoIndexed[$child_id]['pinyin'] ?? '',
  696. 'category_id' => $child_id,
  697. 'textnum' => $childText,
  698. 'imgnum' => $childImg,
  699. 'all_childcat' => array_map(fn($v) => $websiteInfoIndexed[$v], $cat_1st_arr[$category_id] ?? []),
  700. ];
  701. }
  702. $results[$componentKey] = $result;
  703. });
  704. }
  705. // 等待所有协程完成(生产环境应使用 WaitGroup)
  706. usleep(200000); // 示例中简单等待
  707. // 5️⃣ 回填结果到 componentList
  708. foreach ($componentList as $key => &$component) {
  709. $componentData = $component['componentData'];
  710. $category_id = $componentData['category_id'] ?? 0;
  711. if (isset($results[$key])) {
  712. $component['componentData']['data'] = $results[$key];
  713. }
  714. }
  715. // 6️⃣ 返回最终数据
  716. $templateData['template']['index'][0]['componentList'] = $componentList;
  717. return $templateData;
  718. }
  719. public function addWeb($data)
  720. {
  721. $result = WebsiteTemplate::insertGetId($data);
  722. if ($result) {
  723. return Result::success($result);
  724. } else {
  725. return Result::error('添加失败');
  726. }
  727. }
  728. public function deleteWeb($data)
  729. {
  730. $result = WebsiteTemplate::where('id', $data['id'])->delete();
  731. if ($result) {
  732. return Result::success($result);
  733. } else {
  734. return Result::error('删除失败');
  735. }
  736. }
  737. public function updateWeb($data)
  738. {
  739. $result = WebsiteTemplate::where('id', $data['id'])->update($data);
  740. if ($result) {
  741. return Result::success($result);
  742. } else {
  743. return Result::error('更新失败');
  744. }
  745. }
  746. public function getWebInfo($data)
  747. {
  748. $result = WebsiteTemplate::where('website_template.id', $data['id'])
  749. ->leftJoin('website', 'website.id', '=', 'website_template.website_id')
  750. ->select('website_template.*', 'website.website_name as website_name', 'website.website_url as website_url')
  751. ->first();
  752. return Result::success($result);
  753. }
  754. public function getWebList($data)
  755. {
  756. var_dump($data, 'data');
  757. $where = [];
  758. if (isset($data['website_name'])) {
  759. $where[] = ['website.website_name', 'like', '%' . $data['website_name'] . '%'];
  760. }
  761. if (isset($data['status'])) {
  762. $where[] = ['website_template.status', '=', $data['status']];
  763. }
  764. $result = WebsiteTemplate::where([])
  765. ->where($where)
  766. ->leftJoin('website', 'website.id', '=', 'website_template.website_id')
  767. ->select('website_template.*', 'website.website_name as website_name', 'website.website_url as website_url')
  768. ->paginate($data['pageSize'], ['*'], 'page', $data['page']);
  769. if ($result) {
  770. return Result::success($result);
  771. } else {
  772. return Result::error('获取列表失败');
  773. }
  774. }
  775. public function updateWebConfig($data)
  776. {
  777. var_dump($data, 'data1');
  778. // return Result::success($data);
  779. $where = [];
  780. if (isset($data['website_id'])) {
  781. $where['website_template.website_id'] = $data['website_id'];
  782. }
  783. $result = WebsiteTemplate::where([])
  784. ->where($where)
  785. ->leftJoin('website', 'website.id', '=', 'website_template.website_id')
  786. ->select('website_template.id', 'website_template.port', 'website.website_name as website_name', 'website.website_url as website_url', 'website_template.siteId')
  787. ->first()->toArray();
  788. var_dump($result, 'result');
  789. $domain = json_decode($result['website_url'], true);
  790. $domainlist = $domain;
  791. var_dump(empty($result['port']), 'port');
  792. $domain = $domain[3];
  793. if ($domain == null || empty($domain) || !isset($domain)) {
  794. return Result::error('域名不存在');
  795. }
  796. $port = $result['port'];
  797. if ($port == null || empty($port) || !isset($port)) {
  798. var_dump($port, 'youp0------port');
  799. return Result::error('端口不存在');
  800. }
  801. $postData = [
  802. 'domain' => $domain,
  803. 'port' => $port
  804. ];
  805. var_dump(empty($result['siteId']), 'siteId---');
  806. if (empty($result['siteId'])) {
  807. //实例化对象
  808. $api = new bt_api();
  809. //获取面板日志
  810. $r_data = $api->GetLogs();
  811. //输出JSON数据到浏览器
  812. echo json_encode($r_data);
  813. $webname = [
  814. 'domain' => $domain,
  815. 'domainlist' => $domainlist,
  816. 'count' => count($domainlist) - 1
  817. ];
  818. $siteData = [
  819. 'path' => '/www2/www/wwwroot/' . $domain,
  820. 'ftp' => 'false',
  821. 'type' => 'PHP',
  822. 'type_id' => 0,
  823. 'ps' => $domain,
  824. 'port' => 80,
  825. 'version' => '00',
  826. 'need_index' => 0,
  827. 'need_404' => 0,
  828. 'sql' => 'false',
  829. 'codeing' => 'utf8mb4',
  830. 'webname' => json_encode($webname),
  831. 'add_dns_record' => 'false'
  832. ];
  833. $r_data = $api->addSite($siteData);
  834. /*
  835. {
  836. "siteStatus": true,
  837. "siteId": 20,
  838. "ftpStatus": false,
  839. "databaseStatus": false,
  840. "gitStatus": false
  841. }
  842. */
  843. var_dump($r_data, '----------1--r_data--------');
  844. if (isset($r_data['status']) && $r_data['status'] == false) {
  845. return Result::error('宝塔添加失败' . $r_data['msg']);
  846. }
  847. if (isset($r_data['siteStatus']) && $r_data['siteStatus'] == true) {
  848. //记录siteId
  849. $siteId = $r_data['siteId'];
  850. //更新网站模板的siteId WebsiteTemplate
  851. WebsiteTemplate::where('website_id', $data['website_id'])
  852. ->update([
  853. 'siteId' => $siteId,
  854. 'dir' => '/www2/www/wwwroot/' . $domain,
  855. 'status' => 2
  856. ]);
  857. }
  858. // return Result::success($r_data);
  859. }
  860. // 使用Guzzle HTTP客户端发送POST请求
  861. try {
  862. $client = new \GuzzleHttp\Client();
  863. $response = $client->post('http://adminpre.bjzxtw.org.cn/create.php', [
  864. 'json' => $postData,
  865. 'timeout' => 30,
  866. 'headers' => [
  867. 'Content-Type' => 'application/json',
  868. ]
  869. ]);
  870. // 获取响应内容
  871. $responseBody = $response->getBody()->getContents();
  872. $responseData = json_decode($responseBody, true);
  873. var_dump($responseData, '脚本返回数据------------------------');
  874. // 检查响应是否为有效的JSON
  875. if (json_last_error() === JSON_ERROR_NONE) {
  876. // 如果远程服务器返回成功结果
  877. if (isset($responseData['code']) && $responseData['code'] === 1) {
  878. return Result::success([
  879. 'message' => '远程服务器处理成功' . $responseData['message'],
  880. 'output' => $responseData['output'],
  881. 'file' => $responseData['file'],
  882. 'code' => $responseData['code'],
  883. 'exec' => $responseData['exec'],
  884. 'domain' => $domain,
  885. 'port' => $port,
  886. 'remote_response' => $responseData
  887. ]);
  888. } else {
  889. // 远程服务器返回错误
  890. return Result::error(500, '远程服务器处理失败', [
  891. 'remote_response' => $responseData
  892. ]);
  893. }
  894. } else {
  895. // 响应不是有效的JSON
  896. return Result::success([
  897. 'message' => '收到远程服务器响应(非JSON格式)',
  898. 'domain' => $domain,
  899. 'port' => $port,
  900. 'raw_response' => $responseBody
  901. ]);
  902. }
  903. } catch (\GuzzleHttp\Exception\RequestException $e) {
  904. // HTTP请求异常
  905. $errorMessage = 'HTTP请求失败';
  906. if ($e->hasResponse()) {
  907. $response = $e->getResponse();
  908. $errorMessage .= ': ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase();
  909. } else {
  910. $errorMessage .= ': ' . $e->getMessage();
  911. }
  912. return Result::error(500, $errorMessage, [
  913. 'exception' => $e->getMessage()
  914. ]);
  915. } catch (\Exception $e) {
  916. // 其他异常
  917. return Result::error(500, '请求处理异常: ' . $e->getMessage(), [
  918. 'exception' => $e->getMessage()
  919. ]);
  920. }
  921. if ($result) {
  922. return Result::success($result);
  923. } else {
  924. return Result::error('获取列表失败');
  925. }
  926. }
  927. private function bt($data) {}
  928. public function updateWebConfig1($data)
  929. {
  930. // 先根据
  931. // 根据是否测试环境配置不同 的vue项目的 配置文件
  932. //获取根目录下 yuan 源代码,开始处理
  933. //获取目前目录,获取根目录
  934. $root = dirname(dirname(__DIR__));
  935. $yuan = $root . '/yuan';
  936. //取出envAPP_ENV=dev
  937. $APP_ENV = env('APP_ENV');
  938. switch ($APP_ENV) {
  939. case 'dev':
  940. $file = $yuan . '/plugins/category.ts';
  941. break;
  942. case 'prod':
  943. $file = $yuan . '/plugins/category.ts';
  944. break;
  945. default:
  946. $file = $yuan . '/plugins/category.ts';
  947. }
  948. //处理文件plugins\category.ts
  949. //找到 export default defineNuxtPlugin((nuxtApp) => {,处理到文件结尾
  950. /*
  951. export default defineNuxtPlugin((nuxtApp) => {
  952. //master 环境
  953. nuxtApp.provide('pageNav', navMaster)
  954. //pre 环境
  955. // nuxtApp.provide('pageNav', navPre)
  956. })
  957. */
  958. if (0 == 1) {
  959. $content = file_get_contents($file);
  960. $content = str_replace("nuxtApp.provide('pageNav', navPre)", "//nuxtApp.provide('pageNav', navPre)", $content);
  961. $content = str_replace("//nuxtApp.provide('pageNav', navMaster)", "nuxtApp.provide('pageNav', navMaster)", $content);
  962. //写入文件
  963. $res = file_put_contents($file, $content);
  964. var_dump('已经处理/plugins/category.ts');
  965. //处理文件\plugins\globals.js
  966. $file = $yuan . '/plugins/globals.js';
  967. $content = file_get_contents($file);
  968. // 1️⃣ 将没有注释的 nuxtApp.provide(...) 行加上注释
  969. $content = preg_replace('/^(?!\s*\/\/)(?=.*nuxtApp\.provide)/m', '// ', $content);
  970. // 2️⃣ 找到 "//乡村网正式环境" 下面的注释行并取消注释
  971. $lines = explode("\n", $content);
  972. $output = [];
  973. $foundSection = false;
  974. foreach ($lines as $line) {
  975. // 判断是否进入目标区域
  976. if (preg_match('/\/\/乡村网正式环境/', $line)) {
  977. $foundSection = true;
  978. $output[] = $line;
  979. continue;
  980. }
  981. // 在目标区域内,去掉注释
  982. if ($foundSection && preg_match('/^\s*\/\/\s*(nuxtApp\.provide)/', $line, $matches)) {
  983. $output[] = preg_replace('/^\s*\/\/\s*/', '', $line, 1);
  984. } else {
  985. // 如果遇到下一个注释块或空白行,结束当前处理
  986. if ($foundSection && preg_match('/^\s*$/', $line)) {
  987. $foundSection = false;
  988. }
  989. $output[] = $line;
  990. }
  991. }
  992. // 合并回字符串
  993. $newContent = implode("\n", $output);
  994. // 写入文件
  995. $res1 = file_put_contents($file, $newContent);
  996. var_dump($res1, '已经处理/plugins/globals.js');
  997. //处理文件\plugins\request.js
  998. $file = $yuan . '/plugins/request.js';
  999. $content = file_get_contents($file);
  1000. $lines = explode("\n", $content);
  1001. $in_prod = false;
  1002. $in_pre = false;
  1003. for ($i = 0; $i < count($lines); $i++) {
  1004. $line = $lines[$i];
  1005. // 匹配 "//正式环境"
  1006. if (preg_match('/\/\/正式环境/', $line)) {
  1007. $in_prod = true;
  1008. $in_pre = false;
  1009. continue;
  1010. }
  1011. // 匹配 "//pre环境"
  1012. if (preg_match('/\/\/pre环境/', $line)) {
  1013. $in_pre = true;
  1014. $in_prod = false;
  1015. continue;
  1016. }
  1017. // 处理正式环境下的两行:去注释
  1018. if ($in_prod && $i + 0 <= count($lines) && $i + 1 <= count($lines)) {
  1019. for ($j = $i + 0; $j <= $i + 1; $j++) {
  1020. if (isset($lines[$j])) {
  1021. $lines[$j] = preg_replace('/^\s*\/\/\s*/', '', $lines[$j]);
  1022. }
  1023. }
  1024. $in_prod = false; // 只处理一次
  1025. }
  1026. // 处理 pre 环境下的两行:添加注释
  1027. if ($in_pre && $i + 0 <= count($lines) && $i + 1 <= count($lines)) {
  1028. for ($j = $i + 1; $j <= $i + 2; $j++) {
  1029. if (isset($lines[$j]) && !preg_match('/^\s*\/\//', $lines[$j])) {
  1030. // $lines[$j] = '// ' . $lines[$j];
  1031. }
  1032. }
  1033. $in_pre = false; // 只处理一次
  1034. }
  1035. }
  1036. // 写回文件
  1037. $res2 = file_put_contents($file, implode("\n", $lines));
  1038. var_dump($res2, '已经处理/plugins/request.js');
  1039. echo "✅ 环境配置切换完成!";
  1040. //第三步 定位到yuan目录,执行 npm run build 生成output目录
  1041. chdir($yuan);
  1042. $APP_ENV = env('APP_ENV');
  1043. $res3 = exec("npm run build");
  1044. var_dump($res, '执行 npm run build');
  1045. echo "✅ 构建完成!";
  1046. //第四步
  1047. //修改 .output\server\chunks\routes\index.mjs ,
  1048. // 根据网站的id的port更改端口
  1049. //第五步
  1050. //x
  1051. $file4 = $yuan . '/.output/server/chunks/routes/index.mjs';
  1052. $content = file_get_contents($file4);
  1053. // 使用正则将 "destr(...) || 3e3" 替换为 "destr(...) || 9000"
  1054. $content = preg_replace(
  1055. '/(destr$[^)]+$$\s*\|\|\s*)3e3/i',
  1056. '$19000',
  1057. $content
  1058. );
  1059. // 写回文件
  1060. file_put_contents($file, $content);
  1061. }
  1062. //第六步 yuan压缩成压缩包,复制到/hyperf-skeleton/web1/,解压
  1063. $dir_yuan = $yuan . '/.output/';
  1064. // 移动到web 没有就创建
  1065. $dir_web = '/hyperf-skeleton/' . '/web1/';
  1066. if (!is_dir($dir_web)) {
  1067. mkdir($dir_web, 0755, true);
  1068. }
  1069. $fs = new Filesystem();
  1070. $fs->rename($dir_yuan, $dir_web . 'output', true);
  1071. var_dump('已经移动到/hyperf-skeleton/web1/output');
  1072. $result = [
  1073. 'res' => $res,
  1074. 'res1' => $res1,
  1075. 'res2' => $res2,
  1076. 'res3' => $res3,
  1077. 'root' => $root,
  1078. 'yuan' => $yuan,
  1079. 'APP_ENV' => $APP_ENV,
  1080. 'website_id' => $data['website_id'],
  1081. ];
  1082. if ($result) {
  1083. return Result::success($result);
  1084. } else {
  1085. return Result::error('更新配置失败');
  1086. }
  1087. }
  1088. public function updateWebOutput($data)
  1089. {
  1090. // return Result::error('更新输出失败');
  1091. //根据源程序, 复制出来,更改配置文件,打包,
  1092. // $result = 1;
  1093. $projectRoot = dirname(dirname(__DIR__)); // 从当前文件向上两级目录
  1094. $projectDir = $projectRoot . '/../zizhujianzhan_web';
  1095. $command = "cd " . escapeshellarg($projectDir) . " && npm run build";
  1096. // 执行命令并获取输出
  1097. exec($command, $output, $returnCode);
  1098. // 输出结果
  1099. echo "Return Code: " . $returnCode . "\n";
  1100. echo "Output:\n";
  1101. foreach ($output as $line) {
  1102. echo $line . "\n";
  1103. }
  1104. $result = $returnCode;
  1105. if ($result) {
  1106. return Result::success($result);
  1107. } else {
  1108. return Result::error('更新输出失败');
  1109. }
  1110. }
  1111. public function updateWebMove($data)
  1112. {
  1113. //更改到dir目录,
  1114. $result = WebsiteTemplate::where('id', $data['id'])->update($data);
  1115. if ($result) {
  1116. return Result::success($result);
  1117. } else {
  1118. return Result::error('更新移动失败');
  1119. }
  1120. }
  1121. public function runWeb($data)
  1122. {
  1123. //运行网站, 先检查是否有配置文件, pm2启动
  1124. $result = WebsiteTemplate::where('id', $data['id'])->update($data);
  1125. if ($result) {
  1126. return Result::success($result);
  1127. } else {
  1128. return Result::error('运行失败');
  1129. }
  1130. }
  1131. public function stopWeb($data)
  1132. {
  1133. $result = WebsiteTemplate::where('id', $data['id'])->update($data);
  1134. if ($result) {
  1135. return Result::success($result);
  1136. } else {
  1137. return Result::error('停止失败');
  1138. }
  1139. }
  1140. }
  1141. class bt_api
  1142. {
  1143. private $BT_KEY = "RN0wTXLHpKKBXXxyDJoovHMpBhyLVFWZ"; //接口密钥
  1144. private $BT_PANEL = "http://192.168.1.234:18888"; //面板地址
  1145. //如果希望多台面板,可以在实例化对象时,将面板地址与密钥传入
  1146. public function __construct($bt_panel = null, $bt_key = null)
  1147. {
  1148. if ($bt_panel) $this->BT_PANEL = $bt_panel;
  1149. if ($bt_key) $this->BT_KEY = $bt_key;
  1150. }
  1151. //示例取面板日志
  1152. public function GetLogs()
  1153. {
  1154. //拼接URL地址
  1155. $url = $this->BT_PANEL . '/data?action=getData';
  1156. //准备POST数据
  1157. $p_data = $this->GetKeyData(); //取签名
  1158. $p_data['table'] = 'logs';
  1159. $p_data['limit'] = 10;
  1160. $p_data['tojs'] = 'test';
  1161. //请求面板接口
  1162. $result = $this->HttpPostCookie($url, $p_data);
  1163. //解析JSON数据
  1164. $data = json_decode($result, true);
  1165. return $data;
  1166. }
  1167. public function addSite(array $siteData): array
  1168. {
  1169. //拼接URL地址
  1170. $url = $this->BT_PANEL . '/site?action=AddSite';
  1171. //准备POST数据
  1172. $p_data = $this->GetKeyData(); //取签名
  1173. // Merge site data with key data
  1174. $p_data = array_merge($p_data, $siteData);
  1175. //请求面板接口
  1176. $result = $this->HttpPostCookie($url, $p_data);
  1177. //解析JSON数据
  1178. $data = json_decode($result, true);
  1179. return $data;
  1180. }
  1181. /**
  1182. * 检查删除数据
  1183. * ids [21]
  1184. */
  1185. public function checkDelSite(array $siteData): array
  1186. {
  1187. //拼接URL地址
  1188. $url = $this->BT_PANEL . '/site?action=check_del_data';
  1189. //准备POST数据
  1190. $p_data = $this->GetKeyData(); //取签名
  1191. // Merge site data with key data
  1192. $p_data = array_merge($p_data, $siteData);
  1193. //请求面板接口
  1194. $result = $this->HttpPostCookie($url, $p_data);
  1195. //解析JSON数据
  1196. $data = json_decode($result, true);
  1197. return $data;
  1198. }
  1199. /**
  1200. * 删除网站
  1201. * id 21
  1202. * webname t2.lj
  1203. * path 1
  1204. */
  1205. public function delSite(array $siteData): array
  1206. {
  1207. //拼接URL地址
  1208. $url = $this->BT_PANEL . '/site?action=DeleteSite';
  1209. //准备POST数据
  1210. $p_data = $this->GetKeyData(); //取签名
  1211. // Merge site data with key data
  1212. $p_data = array_merge($p_data, $siteData);
  1213. //请求面板接口
  1214. $result = $this->HttpPostCookie($url, $p_data);
  1215. //解析JSON数据
  1216. $data = json_decode($result, true);
  1217. return $data;
  1218. }
  1219. /**
  1220. * 构造带有签名的关联数组
  1221. */
  1222. private function GetKeyData()
  1223. {
  1224. $now_time = time();
  1225. $p_data = array(
  1226. 'request_token' => md5($now_time . '' . md5($this->BT_KEY)),
  1227. 'request_time' => $now_time
  1228. );
  1229. return $p_data;
  1230. }
  1231. /**
  1232. * 发起POST请求
  1233. * @param String $url 目标网填,带http://
  1234. * @param Array|String $data 欲提交的数据
  1235. * @return string
  1236. */
  1237. private function HttpPostCookie($url, $data, $timeout = 60)
  1238. {
  1239. //定义cookie保存位置
  1240. $cookie_file = './' . md5($this->BT_PANEL) . '.cookie';
  1241. if (!file_exists($cookie_file)) {
  1242. $fp = fopen($cookie_file, 'w+');
  1243. fclose($fp);
  1244. }
  1245. $ch = curl_init();
  1246. curl_setopt($ch, CURLOPT_URL, $url);
  1247. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  1248. curl_setopt($ch, CURLOPT_POST, 1);
  1249. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  1250. curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
  1251. curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
  1252. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  1253. curl_setopt($ch, CURLOPT_HEADER, 0);
  1254. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  1255. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1256. $output = curl_exec($ch);
  1257. curl_close($ch);
  1258. return $output;
  1259. }
  1260. }