ClientService.php 62 KB

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