ClientService.php 61 KB

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