ClientService.php 71 KB

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