ClientService.php 70 KB

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