作者 李小龙

拷贝C端生成页面服务

<?php
namespace App\Services\Html;
use App\Models\Blog\Blog;
use App\Models\News\News;
use App\Models\Product\Category;
use App\Models\Product\CategoryRelated;
use App\Models\Product\Keyword;
use App\Models\Product\Product;
use App\Models\RouteMap;
use App\Models\WebSetting\WebSetting;
use App\Models\WebSetting\WebSettingAmp;
use App\Models\WebSetting\WebSettingNum;
use App\Models\WebSetting\WebSettingSeo;
class AmpService
{
/**
* 获取首页html
* @param $project
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
* @author Akun
* @date 2024/03/14 15:04
*/
public static function getIndexHtml($project)
{
//站点配置
$project_config = self::getProjectConfig($project->id);
//产品所有分类
$category = self::getProductsCategory($project->id);
//排序最前的3个产品
$products = self::getProductsList($project->id, 1, 3)['data'];
//排序最前的3篇新闻
$news = self::getNewsBlogList($project->id, 1, 1, 3)['data'];
//排序最前的3篇博客
$blogs = AmpService::getNewsBlogList($project->id, 2, 1, 3)['data'];
//当前页面地址
$current_url = self::getCurrentUrl($project->domain);
return view('amp/index', compact('project_config', 'category', 'products', 'news', 'blogs', 'current_url'));
}
/**
* 获取路由页html
* @param $project
* @param $route
* @param $source
* @param $page
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
* @author Akun
* @date 2024/03/14 15:05
*/
public static function getHtmlByRoute($project, $route, $source, $page)
{
//站点配置
$project_config = self::getProjectConfig($project->id);
//产品所有分类
$category = self::getProductsCategory($project->id);
//固定菜单页面
if ($route == '404') {
//404页面
$current_url = self::getCurrentUrl($project->domain, '/404/');
return view('amp/404', compact('project_config', 'category', 'current_url'));
} elseif ($route == 'contact-us') {
//contact-us页面
$current_url = self::getCurrentUrl($project->domain, '/contact-us/');
return view('amp/contact', compact('project_config', 'category', 'current_url'));
} elseif ($route == 'about-us') {
//about-us页面
$current_url = self::getCurrentUrl($project->domain, '/aboout-us/');
return view('amp/about', compact('project_config', 'category', 'current_url'));
} elseif ($route == 'products') {
//产品列表
$products = self::getProductsList($project->id, $page, 8);
//当前分类详情
$category_info = self::getCategoryInfo($project->id, 0);
$current_url = self::getCurrentUrl($project->domain, '/' . $category_info['route'] . '/' . ($page > 1 ? $page . '/' : ''));
return view('amp/products', compact('project_config', 'category', 'products', 'category_info', 'page', 'current_url'));
} elseif ($route == 'news') {
//新闻列表
$news = self::getNewsBlogList($project->id, 1, $page, 5);
$current_url = self::getCurrentUrl($project->domain, '/news/' . ($page > 1 ? $page . '/' : ''));
return view('amp/news', compact('project_config', 'category', 'news', 'page', 'current_url'));
} elseif ($route == 'blog') {
//博客列表
$blogs = self::getNewsBlogList($project->id, 2, $page, 5);
$current_url = self::getCurrentUrl($project->domain, '/blog/' . ($page > 1 ? $page . '/' : ''));
return view('amp/blogs', compact('project_config', 'category', 'blogs', 'page', 'current_url'));
} elseif (strpos($route, 'top-search') !== false) {
//top-search页面
$pageService = new PageService();
$search_list = $pageService->getProductKeywordsByLetter($project, $route, $page);
//处理路由后缀为-tag的关键词
foreach ($search_list['pageInfo']['pageListData'] as &$v) {
if (substr($v['route'], -4, 4) == '-tag') {
$v['route'] = substr($v['route'], 0, -4);
}
}
//俄语站没有首字母筛选
if ($project->serve_id == 3) {
$search_list['keywordsLabel'] = [];
}
$total_page = count($search_list['pageInfo']['pageNum']);
$search_list['pageInfo']['center_pages'] = page_init($page, $total_page);
$search_list['pageInfo']['prev'] = max($page - 1, 1);
$search_list['pageInfo']['next'] = min($page + 1, $total_page);
$current_url = self::getCurrentUrl($project->domain, '/' . $route . '/' . ($page > 1 ? $page . '/' : ''));
return view('amp/top_search', compact('project_config', 'category', 'search_list', 'page', 'route', 'current_url'));
} else {
//剩下的页面:产品分类,产品详情,新闻详情,关键词详情
$map = ['route' => $route];
if ($source) {
$map['source'] = $source;
}
$route_info = RouteMap::where($map)->orderByRaw("FIELD(source, 'product_category','product','news','blog','product_keyword')")->first();
if (!$route_info) {
//特殊情况:关键词后缀为-tag
$map['route'] = $route . '-tag';
$map['source'] = 'product_keyword';
$route_info = RouteMap::where($map)->first();
}
if (!$route_info) {
$current_url = self::getCurrentUrl($project->domain, '/404/');
return view('amp/404', compact('project_config', 'category', 'current_url'));
}
switch ($route_info->source) {
case 'product_category':
//产品列表
$products = self::getProductsList($project->id, $page, 8, $route_info->source_id);
//当前分类详情
$category_info = self::getCategoryInfo($project->id, $route_info->source_id);
$current_url = self::getCurrentUrl($project->domain, '/' . $category_info['route'] . '/' . ($page > 1 ? $page . '/' : ''));
return view('amp/products', compact('project_config', 'category', 'products', 'category_info', 'page', 'current_url'));
case 'product':
//获取产品详情
$product_info = self::getProductInfo($project->id, $route_info->source_id);
//获取关联产品
$relate_products = self::getRelateProducts($project->id, $product_info['id'], $product_info['category_id'], 8);
$current_url = self::getCurrentUrl($project->domain, '/' . $product_info['route'] . '/');
return view('amp/product_info', compact('project_config', 'category', 'product_info', 'relate_products', 'current_url'));
case 'news':
//新闻详情
$news_info = self::getNewsBlogInfo($project->id, 1, $route_info->source_id);
$current_url = self::getCurrentUrl($project->domain, '/news/' . $news_info['url'] . '/');
return view('amp/news_info', compact('project_config', 'category', 'news_info', 'current_url'));
case 'blog':
//博客详情
$blog_info = self::getNewsBlogInfo($project->id, 2, $route_info->source_id);
$current_url = self::getCurrentUrl($project->domain, '/blog/' . $blog_info['url'] . '/');
return view('amp/blog_info', compact('project_config', 'category', 'blog_info', 'current_url'));
case 'product_keyword':
//获取关键词详情
$tag_info = self::getTagInfo($project->id, $route_info->source_id);
//获取关联产品和热门产品
$pageService = new PageService();
$products = $pageService->getRecommendAndHotProducts($project, $tag_info['route']) ?: [];
//获取关联新闻
$news = self::getNewsBlogList($project->id, 1, 1, 2)['data'];
//随机获取关键词列表
$relate_tags = self::getRelateTags($project->id);
$current_url = self::getCurrentUrl($project->domain, '/' . $tag_info['route'] . '/');
return view('amp/tag', compact('project_config', 'category', 'tag_info', 'products', 'news', 'relate_tags', 'current_url'));
default:
$current_url = self::getCurrentUrl($project->domain, '/404/');
return view('amp/404', compact('project_config', 'category', 'current_url'));
}
}
}
/**
* 拼接当前页面完整路径
* @param $domain
* @param $path
* @return string
* @author Akun
* @date 2024/03/15 15:48
*/
public static function getCurrentUrl($domain, $path = '')
{
$host_array = explode('.', $domain);
if (count($host_array) <= 2) {
array_unshift($host_array, 'm');
} else {
$host_array[0] = 'm';
}
$amp_domain = implode('.', $host_array);
return 'https://' . $amp_domain . $path;
}
/**
* 获取站点amp配置
* @param $project_id
* @return mixed
* @author Akun
* @date 2024/01/26 16:07
*/
public static function getProjectConfig($project_id)
{
$config_amp = WebSettingAmp::where('project_id', $project_id)->first();
$config_index = WebSetting::where('project_id', $project_id)->first();
$config_seo = WebSettingSeo::where('project_id', $project_id)->first();
$show_news = News::where('project_id', $project_id)->where('status', 1)->count('id');
$show_blogs = Blog::where('project_id', $project_id)->where('status', 1)->count('id');
return [
'show_news' => $show_news,
'show_blogs' => $show_blogs,
'top_backgroundcolor' => $config_amp->top_backgroundcolor ?? '',
'web_icon' => $config_amp->web_icon ?? '',
'top_logo' => $config_amp->top_logo ?? [],
'index_banner' => $config_amp->index_banner ?? [],
'index_intro' => $config_amp->index_intro ?? '',
'company_image' => $config_amp->company_image ?? [],
'company_about' => $config_amp->company_about ?? '',
'company_email' => $config_amp->company_email ?? '',
'company_address' => $config_amp->company_address ?? '',
'company_tel' => $config_amp->company_tel ?? '',
'third_code' => $config_amp->third_code ?? '',
'index_title' => $config_index->title ?? '',
'index_description' => $config_index->remark ?? '',
'index_keywords' => $config_index->keyword ?? '',
'single_page_suffix' => $config_seo->single_page_suffix ?? '',
'tab_suffix' => $config_seo->tab_suffix ?? '',
'tab_prefix' => $config_seo->tab_prefix ?? '',
'product_cate_suffix' => $config_seo->product_cate_suffix ?? '',
'product_cate_prefix' => $config_seo->product_cate_prefix ?? '',
'product_suffix' => $config_seo->product_suffix ?? '',
'product_prefix' => $config_seo->product_prefix ?? '',
];
}
/**
* 获取分类列表
* @param $project_id
* @return array
* @author Akun
* @date 2024/01/29 11:25
*/
public static function getProductsCategory($project_id)
{
$category = [];
$result = Category::where('project_id', $project_id)->where('title', '!=', 'Featured Products')->where('status', 1)->orderBy("sort", "desc")->orderBy("id", "desc")->get();
if ($result->count() > 0) {
$result_tree = list_to_tree($result->toArray());
foreach ($result_tree as $cate) {
if ($cate['title'] == 'Products' || $cate['title'] == 'products') {
foreach ($cate['_child'] as $child) {
$category[] = $child;
}
} else {
$category[] = $cate;
}
}
}
return $category;
}
/**
* 获取分类详情
* @param $project_id
* @param $category_id
* @return array
* @author Akun
* @date 2024/01/29 11:31
*/
public static function getCategoryInfo($project_id, $category_id)
{
if ($category_id > 0) {
$category_info = Category::where('project_id', $project_id)->where('id', $category_id)->first();
} else {
$category_info = Category::where('project_id', $project_id)->whereIn('title', ['Products', 'products'])->first();
if ($category_info) {
$category_info->id = 0;
} else {
return [
'id' => 0,
'route' => 'products',
'title' => 'Products',
'keywords' => '',
'describe' => '',
'seo_title' => '',
'seo_keywords' => '',
'seo_description' => '',
];
}
}
return [
'id' => $category_info->id ?? 0,
'route' => $category_info->route ?? '',
'title' => $category_info->title ?? '',
'keywords' => $category_info->keywords ?? '',
'describe' => $category_info->describe ?? '',
'seo_title' => $category_info->seo_title ?? '',
'seo_keywords' => $category_info->seo_keywords ?? '',
'seo_description' => $category_info->seo_des ?? '',
];
}
/**
* 根据分类id获取产品id
* @param $category_id
* @return mixed
* @author Akun
* @date 2024/01/29 11:26
*/
public static function getProductIdByCategory($category_id)
{
return CategoryRelated::where('cate_id', $category_id)->pluck('product_id')->toArray();
}
/**
* 获取产品列表
* @param int $project_id
* @param int $page
* @param int $limit
* @param int $category_id
* @param string $search
* @return array
* @author Akun
* @date 2024/01/26 16:07
*/
public static function getProductsList($project_id, $page = 1, $limit = 20, $category_id = 0, $search = '')
{
$total_page = 0;
$products = [];
$model = Product::where('project_id', $project_id)->where('status', 1);
//根据分类id获取关联的产品id
if ($category_id > 0) {
$product_ids = self::getProductIdByCategory($category_id);
if ($product_ids) {
$model = $model->whereIn('id', $product_ids);
}
} else {
//获取所有产品需要排除掉Featured Products分类
$fp_cate_id = Category::where('title', 'Featured Products')->value('id');
$model->where('category_id', '!=', ',' . $fp_cate_id . ',');
}
//搜索条件
if ($search) {
if (strpos($search, '\\') !== false) {
$search = str_replace('\\', '\\\\', $search);
}
$model = $model->where('title', 'like', "%$search%");
}
$count = $model->count('id');
if ($count > 0) {
$total_page = (int)ceil($count / $limit);
//获取产品自定义排序规则
$sort_rule = self::getProductSortRule($project_id);
foreach ($sort_rule as $rk => $rv) {
$model = $model->orderBy($rk, $rv);
}
$result = $model->select(['id', 'title', 'thumb', 'intro', 'content', 'route'])->offset(($page - 1) * $limit)->limit($limit)->get();
if ($result->count() > 0) {
foreach ($result as $value) {
$thumb = [];
if ($value->thumb) {
$thumb_arr = json_decode($value->thumb, true);
$thumb = [
'alt' => (isset($thumb_arr['alt']) && $thumb_arr['alt']) ? $thumb_arr['alt'] : $value->title,
'url' => getImageUrl($thumb_arr['url'] ?? '')
];
}
$intro = $value->intro ?: $value->content;
$intro = strip_tags(special2str($intro));
$products[] = [
'id' => $value->id,
'title' => $value->title,
'thumb' => $thumb,
'route' => $value->route,
'intro' => strlen($intro) > 200 ? substr($intro, 0, 200) . '...' : $intro,
];
}
}
}
$pre = max($page - 1, 1);
$next = min($page + 1, $total_page);
$center_pages = page_init($page, $total_page);
return ['data' => $products, 'total_page' => $total_page, 'prev' => $pre, 'next' => $next, 'center_pages' => $center_pages];
}
/**
* 获取产品自定义排序规则
* @param $project_id
* @return array|string[]
* @author Akun
* @date 2024/03/21 11:13
*/
public static function getProductSortRule($project_id)
{
$order_list = [];
$orderDataFirst = WebSettingNum::where('project_id', $project_id)->where('type', 10)->first();
if ($orderDataFirst && $orderDataFirst->data) {
$orderData = json_decode($orderDataFirst->data, true);
foreach ($orderData as $key => $orderDataItem) {
$orderKey = $key == "created_at" ? "send_time" : $key;
$order_list[$orderKey] = $orderDataItem;
if ($key != "id") {
$order_list['id'] = 'desc';
}
}
} else {
$order_list = [
'sort' => 'desc',
'id' => 'desc'
];
}
return $order_list;
}
/**
* 获取产品详情
* @param $project_id
* @param $id
* @return array
* @author Akun
* @date 2024/01/30 9:22
*/
public static function getProductInfo($project_id, $id)
{
$gallery = [];
$seo = [
'title' => '',
'keywords' => '',
'description' => ''
];
$product_info = Product::where('project_id', $project_id)->where('status', 1)->where('id', $id)->first();
if ($product_info) {
if ($product_info->gallery) {
$gallery_arr = json_decode($product_info->gallery, true);
foreach ($gallery_arr as $vg) {
$gallery[] = [
'alt' => (isset($vg['alt']) && $vg['alt']) ? $vg['alt'] : $product_info->title,
'url' => getImageUrl($vg['url'] ?? '')
];
}
}
if ($product_info->seo_mate) {
$seo_arr = json_decode($product_info->seo_mate, true);
$seo['title'] = $seo_arr['title'] ?? '';
$seo['keywords'] = $seo_arr['keywords'] ?? '';
$seo['description'] = $seo_arr['description'] ?? '';
}
}
return [
'id' => $product_info->id ?? 0,
'route' => $product_info->route ?? '',
'gallery' => $gallery,
'title' => $product_info->title ?? '',
'intro' => $product_info->intro ?? '',
'content' => $product_info->content ?? '',
'seo' => $seo,
'category_id' => $product_info->category_id ?? ''
];
}
/**
* 获取关联产品
* @param $project_id
* @param $id
* @param $category_id
* @param $limit
* @return array
* @author Akun
* @date 2024/01/30 9:34
*/
public static function getRelateProducts($project_id, $id, $category_id, $limit = 2)
{
if (is_string($category_id)) {
$category_id = explode(',', $category_id);
}
$relate_ids = CategoryRelated::whereIn('cate_id', $category_id)->where('product_id', '!=', $id)->limit($limit)->pluck('product_id')->toArray();
$relate_products = [];
if ($relate_ids) {
$result = Product::where('project_id', $project_id)->whereIn('id', $relate_ids)->where('status', 1)->orderBy('sort', 'desc')->limit(8)->get();
if ($result->count() == 0) {
$result = Product::where('project_id', $project_id)->where('status', 1)->inRandomOrder()->take(8)->get();
}
if ($result->count() > 0) {
foreach ($result as $value) {
$thumb = '';
if ($value->thumb) {
$thumb_arr = json_decode($value->thumb, true);
$thumb = [
'alt' => (isset($thumb_arr['alt']) && $thumb_arr['alt']) ? $thumb_arr['alt'] : $value->title,
'url' => getImageUrl($thumb_arr['url'] ?? '')
];
}
$relate_products[] = [
'id' => $value->id,
'route' => $value->route,
'title' => $value->title,
'thumb' => $thumb
];
}
}
}
return $relate_products;
}
/**
* 获取新闻博客列表
* @param $project_id
* @param int $type
* @param int $page
* @param int $limit
* @return array
* @author Akun
* @date 2024/01/26 16:38
*/
public static function getNewsBlogList($project_id, $type = 1, $page = 1, $limit = 10)
{
$total_page = 0;
$news = [];
if ($type == 1) {
$model = new News();
} else {
$model = new Blog();
}
$count = $model->where('project_id', $project_id)->where('status', 1)->count('id');
if ($count > 0) {
$total_page = (int)ceil($count / $limit);
$result = $model->select(['id', 'name', 'image', 'remark', 'text', 'release_at', 'created_at', 'url'])->where('project_id', $project_id)->where('status', 1)->orderBy('sort', 'desc')->orderBy('id', 'desc')->offset(($page - 1) * $limit)->limit($limit)->get();
if ($result->count() > 0) {
foreach ($result as $value) {
$remark = $value->remark ?: $value->text;
$remark = strip_tags(special2str($remark));
$news[] = [
'type' => $type,
'id' => $value->id,
'name' => $value->name,
'url' => $value->url,
'image' => getImageUrl($value->image),
'remark' => strlen($remark) > 200 ? substr($remark, 0, 200) . '...' : $remark,
'release_at' => $value->release_at ? $value->release_at : $value->created_at
];
}
}
}
$pre = max($page - 1, 1);
$next = min($page + 1, $total_page);
$center_pages = page_init($page, $total_page);
return ['data' => $news, 'total_page' => $total_page, 'prev' => $pre, 'next' => $next, 'center_pages' => $center_pages];
}
/**
* 获取新闻博客详情
* @param $project_id
* @param $type
* @param $id
* @return array
* @author Akun
* @date 2024/01/30 11:17
*/
public static function getNewsBlogInfo($project_id, $type, $id)
{
if ($type == 1) {
$model = new News();
} else {
$model = new Blog();
}
$news_info = $model->where('project_id', $project_id)->where('status', 1)->where('id', $id)->first();
$release_at = '';
if (isset($news_info->release_at) && $news_info->release_at) {
$release_at = $news_info->release_at;
} elseif (isset($news_info->created_at) && $news_info->created_at) {
$release_at = $news_info->created_at;
}
return [
'id' => $news_info->id ?? 0,
'name' => $news_info->name ?? '',
'sort' => $news_info->sort ?? 0,
'url' => $news_info->url ?? 0,
'text' => $news_info->text ?? '',
'image' => getImageUrl($news_info->image ?? ''),
'seo_title' => $news_info->seo_title ?? '',
'seo_keywords' => $news_info->seo_keywords ?? '',
'seo_description' => $news_info->seo_description ?? '',
'release_at' => $release_at
];
}
/**
* 获取关键词详情
* @param $project_id
* @param $id
* @return array
* @author Akun
* @date 2024/01/30 16:17
*/
public static function getTagInfo($project_id, $id)
{
$tag_info = Keyword::where('project_id', $project_id)->where('status', 1)->where('id', $id)->first();
return [
'id' => $tag_info->id ?? 0,
'route' => $tag_info->route ?? '',
'title' => $tag_info->title ?? '',
'keyword_title' => $tag_info->keyword_title ?? '',
'keyword_content' => $tag_info->keyword_content ?? '',
'seo_title' => $tag_info->seo_title ?? '',
'seo_keywords' => $tag_info->seo_keywords ?? '',
'seo_description' => $tag_info->seo_description ?? '',
];
}
/**
* 获取关联关键词
* @param $project_id
* @return mixed
* @author Akun
* @date 2024/01/30 18:30
*/
public static function getRelateTags($project_id)
{
return Keyword::select(['id', 'title', 'route'])->where('project_id', $project_id)->where('status', 1)->inRandomOrder()->take(10)->get()->toArray();
}
}
... ...
<?php
namespace App\Services\Html;
use App\Console\Commands\ProjectService;
use App\Helper\Translate;
use App\Models\Project\DeployBuild;
use App\Models\Project\DeployOptimize;
use App\Models\Project\DomainInfo;
use App\Models\Project\Project;
use App\Models\Project\UpdateProgressModel;
use App\Models\RouteMap;
use App\Models\WebSetting\WebLanguage;
use App\Models\WebSetting\WebProofreading;
use App\Models\WebSetting\WebSetting;
use App\Models\WebSetting\WebSettingCountry;
use App\Models\WebSetting\WebSettingHtml;
use App\Models\WebSetting\WebSettingText;
use App\Models\WebSetting\WebTemplateCommon;
use Illuminate\Support\Facades\Redis;
use phpQuery;
/**
* 生成静态页相关
*/
class CommonService
{
/**
* 翻译
*/
public function webHtmlTranslate($project,$content, $lang,$domain)
{
//翻译过滤器
$lang = $lang == "zh-ct" ? "zh-TW" : $lang;
$tlsList = Translate::$tls_list;
if (isset($tlsList[$lang])){
$main_lang = $project->main_lang_id;
$mainLangInfo = WebLanguage::getProjectMainLang($main_lang);
$master_lang = $mainLangInfo ? $mainLangInfo->short : 'en';
//翻译
if ($master_lang != 'en') {
$result = Translate::translate($content, $lang, $master_lang);
$content = $result[0]['texts'] ?? '';
} else {
$content = Translate::tran($content, $lang);
}
// 翻译有时会返回空数据 再翻译一次 FIXME 后续需要重新封装
if (empty($content)) {
$result = Translate::translate($content, $lang, $master_lang);
$content = $result[0]['texts'] ?? '';
}
//翻译校对
$content = $this->translationProofread($project,$content,$lang,$domain);
}
return $content;
}
/**
* 翻译校对
*/
public function translationProofread($project, $content, $lang,$domain)
{
$webProofreading = WebProofreading::where("project_id",$project->id)->where("alias",$lang)->get();
if (!empty($webProofreading)){
foreach ($webProofreading as $item){
$content = str_ireplace($item->text,$item->translate,$content);
}
}
return $content;
}
/**
* 处理第三方代码
*/
public function thirdPartyCodeHandle($project,$content,$route,$routeMap=null): string
{
if (Redis::get("project_".$project->id."_third_party_code") != null){
$webSettingHtml = json_decode(Redis::get("project_".$project->id."_third_party_code"));
}else{
$webSettingHtml = WebSettingHtml::where("project_id",$project->id)->first();
Redis::set("project_".$project->id."_third_party_code", json_encode($webSettingHtml));
Redis::expire("project_".$project->id."_third_party_code", WebSetting::$redisExpireTime);
}
$phpQueryDom = phpQuery::newDocument($content);
//处理自定义页面样式问题
// if ($globalsojsSyles != ""){
// $phpQueryDom->find("#globalsojs-styles")->remove();
// $phpQueryDom->find('head')->append($globalsojsSyles);
// }
//网站icon
$webIcon = WebSetting::where("project_id",$project->id)->first();
if (!empty($webIcon)){
$iconDom = $phpQueryDom->find("link[rel=icon]");
if (count($iconDom) >= 1){
if (isset($webIcon->web_site_icon) && !empty($webIcon->web_site_icon) && $webIcon->web_site_icon != "" && $webIcon->web_site_icon != 0){
$iconDom->attr("href",$webIcon->web_site_icon);
}else{
$iconDom->attr("href","");
}
}
}
//第三方代码(网页顶部,中间,底部),以后启用位置
if (!empty($webSettingHtml)) {
$phpQueryDom->find('head')->append($webSettingHtml->head_html?:'');
$phpQueryDom->find('body')->append($webSettingHtml->body_html?:'');
$phpQueryDom->find('html')->append($webSettingHtml->footer_html?:'');
}
//A端添加的网站追踪代码
$deployOptimize = DeployOptimize::where("project_id",$project->id)->first();
if (!empty($deployOptimize)){
if (isset($deployOptimize->meta) && !empty($deployOptimize->meta)){
$phpQueryDom->find('head')->append($deployOptimize->meta);
}
}
//去掉非index页面header上面的headerindex属性
//if ($route != "index"){
//$phpQueryDom->find('header')->removeAttr("headerindex");
//}
//首页头部独立样式
if ($route == "index"){
$phpQueryDom->find('header')->attr("headerprivate","");
}
//处理header顶部搜索跳转链接
$phpQueryDom->find('header form')->attr("action", "/search/");
//生成锚点,以后启用位置
//$content = $this->anchorTextHandle($project,$route,$content);
//C端访问埋点
$isBodyEnd = $phpQueryDom->find('body')->eq(0);
if (count($isBodyEnd)>=1){
$phpQueryDom->find('body')->append("<script src='https://ecdn6.globalso.com/public/customerVisit.min.js'></script>");
}else{
$phpQueryDom->find('html')->append("<script src='https://ecdn6.globalso.com/public/customerVisit.min.js'></script>");
}
$data = date("Y-m-d H:i:s");
$phpQueryDom->find('html')->append("<!-- Globalso Cache file was created on ".$data." -->");
//这个功能其他类型页面移到面包屑导航处理
if ($route == "index" || (!empty($routeMap) && $routeMap->source == WebTemplateCommon::$pageName)){
$phpQueryDom->find('head')->append('<script>var currentPage = "'.$route.'"</script>');
}
if ($route == "search"){
//暂时先去掉小语种按钮显示
$phpQueryDom->find(".change-language")->remove();
$phpQueryDom->find('head')->append('<meta name="robots" content="noindex, nofollow"/>');
}
$phpQueryDom->find('body')->attr("unevents","");
$content = $phpQueryDom->htmlOuter();
unset($phpQueryDom);
phpQuery::unloadDocuments();
//处理全部内容,如果有上线正式域名,则把所有的测试域名替换为正式域名
$projectDomainInfo = DomainInfo::where("project_id",$project->id)->first();
if (!empty($projectDomainInfo)){
$deployBuild = DeployBuild::where("project_id",$project->id)->first();
if (!empty($deployBuild)){
$parsedUrl = parse_url($deployBuild->test_domain);
$domain = $projectDomainInfo->domain;
$testDomain = $parsedUrl['host'];
if ($domain != '' && $testDomain != ''){
$content = str_replace($testDomain,$domain,$content);
}
}
}
return $content;
}
/**
* 处理锚文本
*/
public function anchorTextHandle($project,$route,$content): string
{
$source = "";
//解析路由
if ($route != "index"){
$routerNewsMap = RouteMap::where("project_id",$project->id)->where("route",$route)->first();
if (!empty($routerNewsMap)){
$source = $routerNewsMap->source;
}
}else{
$source = "index";
}
//判断来源类型
switch ($source) {
case 'news_category' || 'news':
$num = 4;
break;
case 'product_category' || 'product':
$num = 2;
break;
case 'blog_category' || 'blog':
$num = 6;
break;
case 'page':
$num = 1;
break;
default:
$num = 1;
}
//网站设置锚文本
$webSetting = WebSetting::getWebSetting($project);
if (!empty($webSetting)){
$anchorIsEnable = $webSetting->anchor_is_enable;
if ($anchorIsEnable == 0){
$anchorSetting = $webSetting->anchor_setting;
$anchorSettingArr = explode(',', substr($anchorSetting, 1, -1));
foreach ($anchorSettingArr as $item){
$itemArr = explode('"', substr($item, 1, -1));
$tracingText[] = intval($itemArr[0]);
}
if (in_array($num, $tracingText)) {
$webSettingText = WebSettingText::getWebSettingText($project);
$phpQueryDom=phpQuery::newDocument($content);
$mainElement = $phpQueryDom->find('main');
$con = $mainElement->html();
if (!empty($webSettingText)){
foreach ($webSettingText as $v){
$con = str_replace( $v->key_words, '<a target="_blank" href="'. $v->url.'">'. $v->key_words.'</a>', $con);
}
}
$mainElement->html($con);
return $phpQueryDom->htmlOuter();
}
}
}
return $content;
}
/**
* 链接项目
*/
public function connectProject($updateData)
{
$project = null;
$projectIn = Project::getProjectByDomain($updateData->domain);
if (!empty($projectIn)){
$project = Project::where("id",$projectIn->project_id)->first();
if (!empty($project)){
$project->domain = $updateData->domain;
}
ProjectService::useProject($project->id,$updateData->domain);
}
return $project;
}
/**
* 获取小语种更新国家
*/
public function getMinorLanguage($updateData)
{
$minorLanguage = [];
$updateProgressQuery = UpdateProgressModel::find($updateData->id);
if (!empty($updateProgressQuery)){
$extends = $updateProgressQuery->extends;
if (!empty($extends)){
$extends = json_decode($extends);
if (isset($extends->language) && !empty($extends->language)){
$language = $extends->language;
foreach ($language as $lang){
$minorLanguage[] = (int)$lang;
}
}
}
}
return WebSettingCountry::whereIn("id", $minorLanguage)->get();
}
}
... ...
<?php
/**
* Created by PhpStorm.
* User: zhl
* Date: 2024/2/19
* Time: 15:46
*/
namespace App\Services\Html;
use App\Models\Project\Project;
use App\Models\RouteMap\RouteMap;
use App\Services\TdkService;
class CreateHtmlService
{
public function __construct(){}
/**
* 返回最终需要的HTML
* @return string
*/
public function getHtml($project_id, $route, $lang = [], $page = 0)
{
$projectModel = new Project();
$projectInfo = $projectModel->with(['payment', 'deploy_build'])->where(['id'=>$project_id])->first()->toArray();
$routeMapModel = new RouteMap();
$routeInfo = $routeMapModel->read(['route'=>$route]);
if($routeInfo === false){
if($route == 'top-search' || $route == 'products' || $route == 'news' || $route == 'blog'){
$html = '';
}else{
$html = '';
}
}else{
//TODO::5.0,6.0获取html,自定义页面还需要单独处理
if(($routeInfo['source'] == RouteMap::SOURCE_PAGE) && ($route != 'index')){
$customTemplateService = new CustomTemplateService();
$data = $customTemplateService->getHtml($projectInfo,$routeInfo['source_id']);
if($data === false){
return false;
}
$html = $data['html'];
}else{
$generatePageService = new GeneratePageService();
$data = $generatePageService->generateHtml($projectInfo,$routeInfo);
if($data === false){
return false;
}
$html = $data['html'];
}
}
//处理页面tdk
$tdkService = new TdkService();
$html = $tdkService->pageTdkHandle($projectInfo,$html,$routeInfo['source'],$routeInfo);
return ['html'=>$html];
}
/**
* 返回6.0页面最终HTML
* @return mixed
*/
public function getHtmlV6($project_id,$route)
{
// 初始化后续需要渲染页面需要的数据 路由、主语种、tdk、嵌入等信息
$origin_html = $this->originHtml($project_id,$route);
$html = $this->renderData($origin_html);
$html = $this->plugHead($html);
$html = $this->processFinal($html);
/** ... 调用其他方法, 直至返回完整的正确的HTML */
return $html;
}
/**
* 根据路由信息 返回 路由属性及详细信息
* @param string $route
* @return array
*/
public function getInfoByRoute($route)
{
$routeMapModel = new RouteMap();
$routeInfo = $routeMapModel->read(['route'=>$route]);
if($routeInfo === false){
if($route == 'top-search' || $route == 'products' || $route == 'news' || $route == 'blog'){
$routeInfo = $route;
}else{
$routeInfo = [];
}
}
// TODO 获取详情需要通过路由查下路由信息, 以及数据信息, 要处理特殊几个路由: top-search、products、news、blog, 这几个如果存在就用查下的信息, 如果不存在要初始化信息
return $routeInfo;
}
namespace App\Services\Html;
/**
* 获取可视化HTML
* @return string
*/
public function originHtml($project_id,$route)
{
}
/**
* 补充其他信息
* TDK mate信息等
* @param $html
* @return mixed
*/
public function plugHead($html)
{
/** 渲染tdk信息、 mate信息、 嵌入信息、 图标信息*/
return $html;
}
/**
* 处理最终信息
* 处理标签、最后代码标识、特殊规则或者字符等
* @param string $html
* @return string
*/
public function processFinal($html)
{
return $html;
}
use phpDocumentor\Reflection\Project;
/**
* 生成页面
*/
class CreateHtmlService{
/**
* 渲染页面数据
* @param string $html
* @return string
* 获取页面
*/
public function renderData($html, $page)
public function getHtml($projectId, $route, $lang = "", $page = null)
{
/**
* 根据可视化HTML中关键词渲染数据
* 这个方法还需要进行拆分, 这个功能内容应该会比较多
* 并且还会根据路由信息和分页信息不同, 渲染不同数据, 只要针对列表页面
*/
return $html;
$project = Project::find($projectId);
$createPageService = new CreatePageService();
return $createPageService->getPageByLangRoutePage($project,$route,$page);
}
}
... ...
<?php
namespace App\Services\Html;
use App\Helper\Str;
use App\Models\Blog\Blog;
use App\Models\Module\Module;
use App\Models\Module\ModuleCategory;
use App\Models\News\News;
use App\Models\News\NewsCategory;
use App\Models\Product\Category;
use App\Models\Product\CategoryRelated;
use App\Models\Product\Keyword;
use App\Models\Product\Product;
use App\Models\Project\CollectTask;
use App\Models\Project\Country;
use App\Models\Project\CountryCustom;
use App\Models\Project\DeployBuild;
use App\Models\Project\DomainInfo;
use App\Models\Project\Notify;
use App\Models\Project\Project;
use App\Models\Project\UpdateHtmlModel;
use App\Models\Project\UpdateMasterWebsiteModel;
use App\Models\Project\UpdateMinorLanguagesModel;
use App\Models\Project\UpdateProgressModel;
use App\Models\RouteMap;
use App\Models\Template\BSetting;
use App\Models\WebSetting\WebCustom;
use App\Models\WebSetting\WebLanguage;
use App\Models\WebSetting\WebSettingNum;
use App\Models\WebSetting\WebTemplate;
use App\Models\WebSetting\WebTemplateCommon;
use App\Repositories\StaticHtmlRepository;
use Illuminate\Support\Facades\File;
use phpQuery;
use stdClass;
/**
* C端生成页面服务
*/
class CreatePageService{
/**
* 获取升级项目小语种采集的页面
* @param $project
* @param $route
* @param $source
* @param $lang
* @return string
* @author Akun
* @date 2024/01/08 11:40
*/
public function getMinorLanguagePage($project,$route,$source,$lang){
if($project['update_info']['is_language_update'] == 0){
return '';
}
if ($source == 'news' || $source == 'blog' || $source == 'product' || $source == 'page' || $source == 'module'){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->where("source",$source)->first();
}elseif($source == ''){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->whereIn("source",["product","page","module"])->orderBy('source','desc')->first();
}else{
return '';
}
if($routerMap) {
switch ($routerMap->source) {
//产品详情
case WebTemplateCommon::$productName:
$detail = Product::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->first();
break;
//博客详情
case WebTemplateCommon::$blogName:
$detail = Blog::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->first();
break;
//新闻详情
case WebTemplateCommon::$newsName:
$detail = News::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->first();
break;
//自定义模块详情
case WebTemplateCommon::$extendName:
$detail = Module::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",0)->first();
break;
default:
//单页详情
$detail = WebCustom::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->first();
}
if($detail && $detail->six_read){
return $this->getOldHtml($project,$routerMap,$project['update_info']['old_domain_test'],$project['update_info']['old_domain_online'],$lang);
}else{
return '';
}
}else{
return '';
}
}
/**
* 根据语言,路由,分页数,获取页面内容
*/
public function getPageByLangRoutePage($project,$route,$page=null,$source=""): string
{
$html = "";
$page = $page == null ? null : (int)$page;
$router = $route == "" ? "404" : $route;
$productKeywordRouter = new Keyword();
$productKeywordRouters = $productKeywordRouter->product_keyword_route;
if (in_array($router, $productKeywordRouters)) {
$html = $this->getProductKeywordListPage($project,$router,$page);
unset($productKeywordRouter);
} else {
//新增:products,news,blog 三个路由为C端固定路由,数据库路由表没有路由也可以访问或调数据
if ($router == "products" || $router == "news" || $router == "blog"){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$router)->first();
$routerMapRegular = new stdClass();
if (empty($routerMap)){
if ($router == "products"){
$routerMapRegular->source = WebTemplateCommon::$productCategoryName;
$routerMapRegular->route = "products";
}
if ($router == "news"){
$routerMapRegular->source = WebTemplateCommon::$newsCategoryName;
$routerMapRegular->route = "news";
}
if ($router == "blog"){
$routerMapRegular->source = WebTemplateCommon::$blogCategoryName;
$routerMapRegular->route = "blog";
}
$routerMapRegular->source_id = 0;
$routerMapRegular->project_id = $project->id;
$routerMap = $routerMapRegular;
unset($routerMapRegular);
}
}else{
if ($project->update_info["is_update"] == 1){
if ($source != ""){
//$source可能值:news,blog,news_category,blog_category
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$router)->where("source",$source)->first();
}else{
//product_category,product,page,product_keyword,module_category,module
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$router)->whereIn("source",["product","product_category","page","module_category","module","product_keyword"])->orderByRaw("FIELD(source, 'product_category','product','module_category','module','page','product_keyword')")->first();
}
if (empty($routerMap)){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$router)->first();
}
}else{
//6.0
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$router)->first();
}
}
if (!empty($routerMap)){
$type = $routerMap->source;
switch ($type) {
//产品详情
case WebTemplateCommon::$productName:
$html = $this->getProductPage($project,$routerMap);
break;
//产品列表
case WebTemplateCommon::$productCategoryName:
$html = $this->getProductListPage($project,$routerMap,$page);
break;
//博客详情
case WebTemplateCommon::$blogName:
$html = $this->getBlogPage($project,$routerMap);
break;
//博客列表
case WebTemplateCommon::$blogCategoryName:
$html = $this->getBlogListPage($project,$routerMap,$page);
break;
//新闻详情
case WebTemplateCommon::$newsName:
$html = $this->getNewsPage($project,$routerMap);
break;
//新闻列表
case WebTemplateCommon::$newsCategoryName:
$html = $this->getNewsListPage($project,$routerMap,$page);
break;
//自定义模块列表
case WebTemplateCommon::$extendCategoryName:
$html = $this->getModuleListPage($project,$routerMap,$page);
break;
//自定义模块详情
case WebTemplateCommon::$extendName:
$html = $this->getModulePage($project,$routerMap);
break;
//聚合页
case WebTemplateCommon::$productKeywordName:
$html = $this->getProductKeywordPage($project,$routerMap);
break;
case WebTemplateCommon::$pageName:
if ($router == WebTemplateCommon::$indexName){
//首页
$html = $this->getIndexPage($project,$routerMap);
}else{
//单页面
$html = $this->getSinglePage($project,$routerMap);
}
break;
default:
$html = $this->getSinglePage($project,$routerMap);
}
}
}
return $html;
}
/**
* 获取首页html
*/
public function getIndexPage($project,$routerMap): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
//首页模板
$info = BSetting::where("project_id",$project->id)->first();
if (empty($info)){
return "";
}
$webIndexTemplate = WebTemplate::where("project_id",$project->id)->where("template_id",$info->template_id)->where("source",1)->first();
if (!empty($webIndexTemplate)){
$html = $pageService->isAndGetVisualizationHtml($project,WebTemplateCommon::$indexName,$routerMap);
if ($html == ""){
//组装首页页面
$html = $pageService->assembleIndexPage($project,$webIndexTemplate);
}
// $filePath = public_path("6666.html");
// file_put_contents($filePath, $html);
// dd(5656);
//公共处理
$html = $pageService->publicHtmlHandle($html,$project->id);
$isVisual = $pageService->isOpenVisualization($project,WebTemplateCommon::$indexName);
if ((int)$isVisual == 1 || $isVisual == null){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$html = $pageService->generalTemplateProcessingForDataModules($html,$project->id);
}
//第三方
$html = $commonService->thirdPartyCodeHandle($project,$html,WebTemplateCommon::$indexName);
//TDK处理
$html = $tdkService->pageTdkHandle($project,$html,WebTemplateCommon::$indexName,$routerMap);
//特殊首页模块处理
// $html = $pageService->specialIndexModuleHandle($project,$html);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html);
}else{
return "";
}
}else{
return "";
}
}
/**
* 获取产品列表页html
*/
public function getProductListPage($project,$routerMap,$page): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
//公共拼接页面方法
$webCustomHtml = $pageService->publicMontagePage($project,WebTemplateCommon::$productCategoryName,$routerMap);
//公共面包屑导航,左侧导航处理,内页banner背景图,列表页分页
$webCustomHtml = $pageService->publicMdAndLeftNavInnerImageListDetailsDataHandle($webCustomHtml,$project,WebTemplateCommon::$productCategoryName,$routerMap,$page);
//是否开启可视化
$isVisual = $pageService->isOpenVisualization($project,WebTemplateCommon::$productCategoryName);
if ((int)$isVisual == 1 || $isVisual == null){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$webCustomHtml = $pageService->generalTemplateProcessingForDataModules($webCustomHtml,$project->id);
}
$webCustomHtml = $tdkService->pageTdkHandle($project,$webCustomHtml,WebTemplateCommon::$productCategoryName,$routerMap);
$webCustomHtml = $pageService->publicHtmlHandle($webCustomHtml,$project->id);
unset($pageService);
$html = $commonService->thirdPartyCodeHandle($project,$webCustomHtml,$routerMap->route);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html,"",$page);
}else{
return "";
}
}
/**
* 获取产品页html
*/
public function getProductPage($project,$routerMap,$lang=''): string
{
$pageService = new PageService();
$commonService = new CommonService();
$products_detail = Product::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->whereNotNull('route')->first();
if($project['update_info']['is_update'] && $products_detail && $products_detail->six_read){
return $this->getOldHtml($project,$routerMap,$project['update_info']['old_domain_test'],$project['update_info']['old_domain_online'],$lang);
}else{
$products_detail = $pageService->productDataHandle($project,$products_detail);
if (!empty($products_detail)){
//公共拼接页面方法
$webCustomHtml = $pageService->publicMontagePage($project,WebTemplateCommon::$productName,$routerMap);
//公共面包屑导航,左侧导航处理,内页banner背景图,列表页分页
$webCustomHtml = $pageService->publicMdAndLeftNavInnerImageListDetailsDataHandle($webCustomHtml,$project,"product",$routerMap,null);
$isVisual = $pageService->isOpenVisualization($project,WebTemplateCommon::$productName);
if ((int)$isVisual == 1 || $isVisual == null){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$webCustomHtml = $pageService->generalTemplateProcessingForDataModules($webCustomHtml,$project->id);
}
$webCustomHtml = $pageService->productsDetailTdkHandle($project,$webCustomHtml,$products_detail);
$webCustomHtml = $pageService->publicHtmlHandle($webCustomHtml,$project->id);
unset($pageService);
$html = $commonService->thirdPartyCodeHandle($project,$webCustomHtml,$routerMap->route);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html);
}else{
return "";
}
}else{
return "";
}
}
}
/**
* 获取产品关键词页html
*/
public function getProductKeywordPage($project,$routerMap): string
{
$pageService = new PageService();
$commonService = new CommonService();
$keywordModel = new Keyword();
$tdkService = new TdkService();
$routePath = $routerMap->route;
//公共头部底部
$publicTemplate = $pageService->getPublicTemplate($project);
$headerHtml = $publicTemplate->headerHtml;
$footerHtml = $publicTemplate->footerHtml;
//关键词详情
$keywordsDetails = $pageService->getKeywordDetails($project, $routerMap->route);
if (!empty($keywordsDetails)){
if (!empty($keywordsDetails->embed_code)){
$videoUrl = $keywordsDetails->embed_code;
preg_match('/src="([^"]+)"/', $videoUrl, $matches);
$src = $matches[1];
$keywordsDetails->video = $src;
}
//随机获取关键词列表
$productsKeywordsList = $keywordModel->getProductsKeywordsList($project);
//调整为相关产品
$productsRecommendAndHot = $pageService->getRecommendAndHotProducts($project,$routePath);
//博客新闻数据
$blogT = $pageService->getProductsBlogNews($project);
$viewPath = isset($keywordsDetails->video) && !empty($keywordsDetails->video) ? "products/products_video_keywords" : "products/products_keywords";
$html = view($viewPath, compact("headerHtml", "footerHtml", "routePath", "productsKeywordsList", "productsRecommendAndHot", "blogT","keywordsDetails"))->__toString();
$html = $pageService->publicHtmlHandle($html, $project->id);
//生成静态页
$webCustomHtml = $commonService->thirdPartyCodeHandle($project, $html, $routerMap->route);
//TDK
unset($html,$productsKeywordsList,$productsRecommendAndHot,$blogT);
$html = $tdkService->pageTdkHandle($project,$webCustomHtml,WebTemplateCommon::$productKeywordName,$routerMap);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html);
}else{
return "";
}
}else{
return "";
}
}
/**
* 获取产品新闻列表页html
*/
public function getNewsListPage($project,$routerMap,$page): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
$routePath = $routerMap->route;
//公共拼接页面方法
$webCustomHtml = $pageService->publicMontagePage($project,WebTemplateCommon::$newsCategoryName,$routerMap);
//公共面包屑导航,左侧导航处理,内页banner背景图,列表页分页
$webCustomHtml = $pageService->publicMdAndLeftNavInnerImageListDetailsDataHandle($webCustomHtml,$project,WebTemplateCommon::$newsCategoryName,$routerMap,$page);
$isVisual = $pageService->isOpenVisualization($project,WebTemplateCommon::$newsCategoryName);
if ((int)$isVisual == 1 || $isVisual == null){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$webCustomHtml = $pageService->generalTemplateProcessingForDataModules($webCustomHtml,$project->id);
}
$webCustomHtml = $tdkService->pageTdkHandle($project,$webCustomHtml,WebTemplateCommon::$newsCategoryName,$routerMap);
$webCustomHtml = $pageService->publicHtmlHandle($webCustomHtml,$project->id);
unset($pageService);
$html = $commonService->thirdPartyCodeHandle($project,$webCustomHtml,$routePath);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html,"",$page);
}else{
return "";
}
}
/**
* 自定义模块列表
*/
public function getModuleListPage($project,$routerMap,$page): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
$routePath = $routerMap->route;
//公共拼接页面方法
$webCustomHtml = $pageService->publicMontagePage($project,WebTemplateCommon::$extendCategoryName,$routerMap);
//公共面包屑导航,左侧导航处理,内页banner背景图,列表页分页
$webCustomHtml = $pageService->publicMdAndLeftNavInnerImageListDetailsDataHandle($webCustomHtml,$project,WebTemplateCommon::$extendCategoryName,$routerMap,$page);
$moduleCategoryInfo = ModuleCategory::getModuleCategoryAndExtendById($project->id,$routerMap->source_id);
if (isset($moduleCategoryInfo->getExtend->list_visualization) && $moduleCategoryInfo->getExtend->list_visualization == 1){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$webCustomHtml = $pageService->generalTemplateProcessingForDataModules($webCustomHtml,$project->id);
}
$webCustomHtml = $tdkService->pageTdkHandle($project,$webCustomHtml,WebTemplateCommon::$extendCategoryName,$routerMap);
$webCustomHtml = $pageService->publicHtmlHandle($webCustomHtml,$project->id);
unset($pageService);
$html = $commonService->thirdPartyCodeHandle($project,$webCustomHtml,$routePath);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html,"",$page);
}else{
return "";
}
}
/**
* 获取产品新闻页html
*/
public function getNewsPage($project,$routerMap,$lang=''): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
//页面路由
$routePath = $routerMap->route;
$news_detail = News::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->first();
if (!empty($news_detail)){
if($project['update_info']['is_update'] && $news_detail->six_read){
return $this->getOldHtml($project,$routerMap,$project['update_info']['old_domain_test'],$project['update_info']['old_domain_online'],$lang);
}else{
//公共拼接页面方法
$webCustomHtml = $pageService->publicMontagePage($project,WebTemplateCommon::$newsName,$routerMap);
//公共面包屑导航,左侧导航处理,内页banner背景图,列表页分页
$webCustomHtml = $pageService->publicMdAndLeftNavInnerImageListDetailsDataHandle($webCustomHtml,$project,WebTemplateCommon::$newsName,$routerMap,null);
$isVisual = $pageService->isOpenVisualization($project,WebTemplateCommon::$newsName);
if ((int)$isVisual == 1 || $isVisual == null){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$webCustomHtml = $pageService->generalTemplateProcessingForDataModules($webCustomHtml,$project->id);
}
//TDK处理
$webCustomHtml = $tdkService->pageTdkHandle($project,$webCustomHtml,WebTemplateCommon::$newsName,$routerMap);
//网页公共部分
$webCustomHtml = $pageService->publicHtmlHandle($webCustomHtml,$project->id);
unset($pageService);
$html = $commonService->thirdPartyCodeHandle($project,$webCustomHtml,$routePath);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html);
}else{
return "";
}
}
}else{
return "";
}
}
/**
* 自定义模块详情
*/
public function getModulePage($project,$routerMap,$lang=''): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
//页面路由
$routePath = $routerMap->route;
$module_detail = Module::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",0)->first();
if (!empty($module_detail)){
if($project['update_info']['is_update'] && $module_detail->six_read){
return $this->getOldHtml($project,$routerMap,$project['update_info']['old_domain_test'],$project['update_info']['old_domain_online'],$lang);
}else{
//公共拼接页面方法
$webCustomHtml = $pageService->publicMontagePage($project,WebTemplateCommon::$extendName,$routerMap);
//公共面包屑导航,左侧导航处理,内页banner背景图,列表页分页
$webCustomHtml = $pageService->publicMdAndLeftNavInnerImageListDetailsDataHandle($webCustomHtml,$project,WebTemplateCommon::$extendName,$routerMap,null);
$moduleCategoryInfo = Module::getModuleCategory($project->id,$module_detail);
if (isset($moduleCategoryInfo->getExtend->detail_visualization) && $moduleCategoryInfo->getExtend->detail_visualization == 1){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$webCustomHtml = $pageService->generalTemplateProcessingForDataModules($webCustomHtml,$project->id);
}
//TDK处理
$webCustomHtml = $tdkService->pageTdkHandle($project,$webCustomHtml,WebTemplateCommon::$extendName,$routerMap);
//网页公共部分
$webCustomHtml = $pageService->publicHtmlHandle($webCustomHtml,$project->id);
unset($pageService);
$html = $commonService->thirdPartyCodeHandle($project,$webCustomHtml,$routePath);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html);
}else{
return "";
}
}
}else{
return "";
}
}
/**
* 获取博客列表页html
*/
public function getBlogListPage($project,$routerMap,$page): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
//公共拼接页面方法
$webCustomHtml = $pageService->publicMontagePage($project,WebTemplateCommon::$blogCategoryName,$routerMap);
//公共面包屑导航,左侧导航处理,内页banner背景图,列表页分页
$webCustomHtml = $pageService->publicMdAndLeftNavInnerImageListDetailsDataHandle($webCustomHtml,$project,WebTemplateCommon::$blogCategoryName,$routerMap,$page);
$isVisual = $pageService->isOpenVisualization($project,WebTemplateCommon::$blogCategoryName);
if ((int)$isVisual == 1 || $isVisual == null){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$webCustomHtml = $pageService->generalTemplateProcessingForDataModules($webCustomHtml,$project->id);
}
$webCustomHtml = $tdkService->pageTdkHandle($project,$webCustomHtml,WebTemplateCommon::$blogCategoryName,$routerMap);
$webCustomHtml = $pageService->publicHtmlHandle($webCustomHtml,$project->id);
unset($pageService);
$html = $commonService->thirdPartyCodeHandle($project,$webCustomHtml,$routerMap->route);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html,"",$page);
}else{
return "";
}
}
/**
* 获取博客页html
*/
public function getBlogPage($project,$routerMap,$lang=''): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
$blog_detail = Blog::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->first();
if (!empty($blog_detail)){
if($project['update_info']['is_update'] && $blog_detail->six_read){
return $this->getOldHtml($project,$routerMap,$project['update_info']['old_domain_test'],$project['update_info']['old_domain_online'],$lang);
}else{
//公共拼接页面方法
$webCustomHtml = $pageService->publicMontagePage($project,WebTemplateCommon::$blogName,$routerMap);
//公共面包屑导航,左侧导航处理,内页banner背景图,列表页分页
$webCustomHtml = $pageService->publicMdAndLeftNavInnerImageListDetailsDataHandle($webCustomHtml,$project,WebTemplateCommon::$blogName,$routerMap,null);
$isVisual = $pageService->isOpenVisualization($project,WebTemplateCommon::$blogName);
if ((int)$isVisual == 1 || $isVisual == null){
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$webCustomHtml = $pageService->generalTemplateProcessingForDataModules($webCustomHtml,$project->id);
}
$webCustomHtml = $tdkService->pageTdkHandle($project,$webCustomHtml,WebTemplateCommon::$blogName,$routerMap);
$webCustomHtml = $pageService->publicHtmlHandle($webCustomHtml,$project->id);
unset($pageService);
//生成静态页
$html = $commonService->thirdPartyCodeHandle($project,$webCustomHtml,$routerMap->route);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html);
}else{
return "";
}
}
}else{
return "";
}
}
/**
* 获取单页面html
*/
public function getSinglePage($project,$routerMap,$lang=''): string
{
$pageService = new PageService();
$commonService = new CommonService();
$tdkService = new TdkService();
//页面路由
$routePath = $routerMap->route;
$webCustom = WebCustom::where("id",$routerMap->source_id)->where("status",1)->first();
if (!empty($webCustom)){
if($project['update_info']['is_update'] && $webCustom->six_read){
return $this->getOldHtml($project,$routerMap,$project['update_info']['old_domain_test'],$project['update_info']['old_domain_online'],$lang);
}else{
//公共拼接页面方法
$content = $pageService->publicMontagePage($project,WebTemplateCommon::$pageName,$routerMap);
//公共左侧导航处理
$phpQueryDom=phpQuery::newDocument($content);
$pageService->leftNavSideNavHandle($project,WebTemplateCommon::$pageName,$phpQueryDom,$routerMap);
$content = $phpQueryDom->htmlOuter();
unset($phpQueryDom);
//产品,产品分类,新闻,博客(section模板通用数据模块处理)
$content = $pageService->generalTemplateProcessingForDataModules($content,$project->id);
//生成静态页
$content = $tdkService->pageTdkHandle($project,$content,WebTemplateCommon::$pageName,$routerMap);
$content = $pageService->publicHtmlHandle($content,$project->id);
unset($pageService);
$html = $commonService->thirdPartyCodeHandle($project,$content,$routePath,$routerMap);
//处理URL等,处理html链接a标签href
if (!empty($html)){
return $this->pageUrlHandle($project,$routerMap,$html);
}else{
return "";
}
}
}else{
return "";
}
}
/**
* 获取关键词列表页面
*/
public function getProductKeywordListPage($project,$router,$page): string
{
if (isset($router->route) && $router->route != null) {
$routePath = $router->route;
} else {
$routePath = $router;
}
//公共头部底部
$pageService = new PageService();
$commonService = new CommonService();
$publicTemplate = $pageService->getPublicTemplate($project);
$headerHtml = $publicTemplate->headerHtml;
$footerHtml = $publicTemplate->footerHtml;
//获取字母开头关键词列表
$keywords = $pageService->getProductKeywordsByLetter($project,$router,$page);
$html = view("products/products_keywords_list",compact("headerHtml","footerHtml","keywords","routePath"))->__toString();
$html = $pageService->publicHtmlHandle($html, $project->id);
//生成静态页
$webCustomHtml = $commonService->thirdPartyCodeHandle($project, $html, $routePath);
//top-search TDK处理,分页link索引处理
$webCustomHtml = $pageService->productKeywordListTdkHandle($webCustomHtml,$project,$routePath,$keywords,$page);
//处理URL等,处理html链接a标签href
if (!empty($html)){
$webCustomHtml = $this->pageUrlHandle($project,$routePath,$webCustomHtml);
}else{
return "";
}
unset($keywords);
unset($html);
return $webCustomHtml;
}
/**
* TODO:处理URL等,处理html链接a标签href,获取最终html
*/
public function pageUrlHandle($project,$routerMap,$html,$lang="",$page=null): string
{
if (isset($routerMap->route) && $routerMap->route != null) {
$route = $routerMap->route;
} else {
$route = $routerMap;
}
$pageService = new PageService();
$phpQueryDom=phpQuery::newDocument($html);
$domainEnd = $project->domain_end;
//主站a链接处理
$this->masterWebATagHandle($phpQueryDom,$project,$domainEnd);
//html 标签处理
$this->htmlTagHandle($phpQueryDom,$project);
//888项目禁用鼠标右键点击,查看元素
// $this->prohibitRightMouseClick($phpQueryDom,$project);
//国家
$webCountry = $pageService->getCountryList($project->id);
//语种 alternate
$this->setHrefLang($phpQueryDom,$project,$route,$page,$lang,$webCountry);
//以-tag的聚合页结尾的路由加上 <meta name="robots" content="noindex">
$this->setTagRobotsNoindex($phpQueryDom,$routerMap);
//<meta name="cookie_consent_banner" content="参数值"> 配置
$this->setCookieConsentBanner($phpQueryDom,$project);
$html = $phpQueryDom->htmlOuter();
unset($phpQueryDom);
phpQuery::unloadDocuments();
//根据配置读取不同的资源路径功能
$html = $this->setResourcePath($project,$html);
//网站语种列表
return $pageService->publicCountryLanguageHandle($html,$project,$route);
}
/**
* html 标签处理
*/
public function htmlTagHandle($phpQueryDom,$project)
{
$phpQueryDom->find("html")->attr("dir","ltr");
$mainLang = WebLanguage::getProjectMainLang($project->main_lang_id);
if ($mainLang->short == "ru"){
$phpQueryDom->find('main .keyword_search')->remove();
}
$lang = $mainLang ? $mainLang->short : 'en';
$phpQueryDom->find("html")->attr("lang",$lang);
}
/**
* 888项目禁用鼠标右键点击,查看元素
*/
public function prohibitRightMouseClick($phpQueryDom,$project)
{
if ($project->id == 888){
$phpQueryDom->find("body")->attr("ondragstart","window.event.returnValue=false");
$phpQueryDom->find("body")->attr("oncontextmenu","window.event.returnValue=false");
$phpQueryDom->find("body")->attr("onselectstart","event.returnValue=false");
}
}
/**
*主站a链接处理
*/
public function masterWebATagHandle($phpQueryDom,$project,$domainEnd)
{
foreach ($phpQueryDom->find('a') as $a) {
$href = pq($a)->attr('href');
//a标签href字符串是否有http://或者https://等协议头,有的话不做处理
if (strpos($href, 'http://') !== false || strpos($href, 'https://') !== false || strpos($href, 'javascript') !== false || strpos($href, 'javasctipt') !== false || strpos($href, '#') !== false || empty($href) || strpos($href, '.zip') !== false || strpos($href, '.txt') !== false || strpos($href, 'tel:') !== false || strpos($href, 'mailto') !== false || strpos($href, '.pdf') !== false || strpos($href, '.tar') !== false || strpos($href, '.jpg') !== false || strpos($href, '.png') !== false || strpos($href, '.jpeg') !== false || strpos($href, '.xml') !== false || strpos($href, 'skype:') !== false || strpos($href, 'whatsapp:') !== false) {
$domain = $project->domain;
$domain = str_replace("http://","",$domain);
$domain = str_replace("https://","",$domain);
$domain = str_replace("/","",$domain);
$domainArr = parse_url($domain);
if (strpos($href, '#') !== false || strpos($href, '.xml') !== false){}else{
if (isset($domainArr["path"]) && !empty($domainArr["path"])){
if (strpos($href, 'http://') !== false || strpos($href, 'https://') !== false){
$domain = $domainArr["path"];
if (strpos($href, $domain) !== false){
$href = str_replace("http://","",$href);
$href = str_replace("https://","",$href);
$href = str_replace($domain,"",$href);
if ($domainEnd == Project::$domainEndSlash){
//以斜杠结尾
$href = substr($href, -1) === '/' ? $href : $href . "/";
}else{
//不以斜杠结尾
if (substr($href, -1) === '/') {
if ($href != "/"){
$href = rtrim($href, '/');
}
}
}
}
}
}
}
pq($a)->attr('href', $href);
}else{
if ($domainEnd == Project::$domainEndSlash){
//以斜杠结尾
$href = substr($href, -1) === '/' ? $href : $href . "/";
if (strpos($href, ".html") !== false || strpos($href, ".htm") !== false){
$href = rtrim($href, '/');
}
}else{
//不以斜杠结尾
if (substr($href, -1) === '/') {
if ($href != "/"){
$href = rtrim($href, '/');
}
}
}
}
pq($a)->attr('href', $href);
}
}
/**
* <meta name="cookie_consent_banner" content="参数值"> 配置
*/
public function setCookieConsentBanner($phpQueryDom,$project)
{
$deployBuildInfo = DeployBuild::where("project_id",$project->id)->first();
if (!empty($deployBuildInfo)){
$phpQueryDom->find('head')->append('<meta name="cookie_consent_banner" content="'.$deployBuildInfo->cookie_consent_banner.'">');
}
}
/**
* 语种 alternate
*/
public function setHrefLang($phpQueryDom,$project,$route,$page,$lang,$webCountry)
{
//处理源代码语言url
$countryUrl = [];
$createPageService = new CreatePageService();
$domain = $createPageService->domainHandle($project->domain);
$mainLang = WebLanguage::getProjectMainLang($project->main_lang_id);
if (!empty($webCountry)) {
foreach ($webCountry as $key => $item) {
//语种列表调整,新增自定义跳转链接
if (isset($item->country_custom) && !empty($item->country_custom)){
if ($item->country_custom->is_create == 1){
$page = (int)$page != null && (int)$page != 0 ? (int)$page . "/" : "";
if (!empty($mainLang) && $item->short != $mainLang->short){
$countryUrl[$key]["url"] = "https://" . $item->country_custom->custom_domain . "/" . $route . "/" . $page;
}else{
$countryUrl[$key]["url"] = "https://" . $domain . "/" . $route . "/" . $page;
}
}else{
$countryUrl[$key]["url"] = "https://" . $item->country_custom->custom_domain . "/";
}
$countryUrl[$key]["alias"] = $item->short;
}else{
if (!empty($mainLang) && $item->short != $mainLang->short){
$langShort = $item->short."/";
}else{
$langShort = "";
}
if ((int)$page != null) {
$countryUrl[$key]["url"] = "https://" . $domain . "/" .$langShort . $route . "/" . (int)$page . "/";
} else {
$countryUrl[$key]["url"] = $route == "index" ? "https://" . $domain . "/" . $langShort : "https://" . $domain . "/" . $langShort. $route . "/";
}
$countryUrl[$key]["alias"] = $item->short;
}
//之前
// $langShort = $item->short == "en" ? "" : $item->short."/";
// if ((int)$page != null) {
// $countryUrl[$key]["url"] = "https://" . $domain . "/" .$langShort . $route . "/" . (int)$page . "/";
// } else {
// $countryUrl[$key]["url"] = $route == "index" ? "https://" . $domain . "/" . $langShort : "https://" . $domain . "/" . $langShort. $route . "/";
// }
// $countryUrl[$key]["alias"] = $item->short;
}
}
//路径
if ($route == "index") {
$webUrl = "https://" . $domain . "/";
} else {
if ((int)$page != null || (int)$page != 0) {
if ($lang != "") {
$langShort = $lang == "en" ? "" : $lang."/";
$webUrl = "https://" . $domain . "/" .$langShort. $route . "/" . (int)$page . "/";
} else {
$webUrl = "https://" . $domain . "/" . $route . "/" . (int)$page . "/";
}
} else {
if ($lang != "") {
$langShort = $lang == "en" ? "" : $lang."/";
$webUrl = "https://" . $domain . "/" . $langShort . $route . "/";
} else {
$webUrl = "https://" . $domain . "/" . $route . "/";
}
}
}
$phpQueryDom->find('head')->append("<meta property='og:url' content='$route'/>");
$phpQueryDom->find('head')->append("<link rel='canonical' href='$webUrl' />");
if (!empty($countryUrl)){
foreach ($countryUrl as $item){
if (isset($item['alias']) && isset($item['url'])){
$phpQueryDom->find('head')->append("<link rel='alternate' hreflang='".$item['alias']."' href='".$item['url']."'>");
}
}
}
}
/**
* 以-tag的聚合页结尾的路由加上 <meta name="robots" content="noindex">
*/
public function setTagRobotsNoindex($phpQueryDom,$routerMap)
{
if (isset($routerMap->source) && $routerMap->source == WebTemplateCommon::$productKeywordName){
$routerSuffix = substr($routerMap->route, -4);
$routerLength = strlen($routerMap->route);
if ($routerLength >= 4 && $routerSuffix == "-tag"){
$phpQueryDom->find('head')->append('<meta name="robots" content="noindex,nofollow">');
}
}
}
/**
* 配置资源路径
*/
public function setResourcePath($project,$html)
{
$projectLocation = $project->project_location;
$storageType = $project->storage_type;
if ($projectLocation == Project::$projectLocationZero){
//普通项目
if ($storageType == Project::$storageTypeZero){
//压缩项目
$html = str_replace(Project::$storageTypeOneFileFix,Project::$storageTypeZeroFileFix,$html);
}else{
//非压缩项目
$html = str_replace(Project::$storageTypeZeroFileFix,Project::$storageTypeOneFileFix,$html);
}
}else{
//危险项目
$html = str_replace(Project::$storageTypeOneFileFix,Project::$projectLocationDangerousFileFix,$html);
$html = str_replace(Project::$storageTypeZeroFileFix,Project::$projectLocationDangerousFileFix,$html);
}
return $html;
}
/**
* 放入文件
*/
public function putHtmlToPageFile($project,$lang,$route,$page,$html,$routeType=""): bool
{
if (empty($html) || $html == ""){
return true;
}
if (strpos($route, '.php') !== false || strpos($route, '.env') !== false || strpos($route, '.jpg') !== false || strpos($route, '.asp') !== false || strpos($route, '.png') !== false || strpos($route, '.gif') !== false ){
return true;
}
$domain = $project->domain;
$domain = str_replace("https://","",$domain);
$domain = str_replace("http://","",$domain);
$domain = str_replace("/","",$domain);
$originLang = $lang;
$lang = $lang == "zh-TW" ? "zh-ct" : $lang;
$lang = $lang=="" ? "" : "/".$lang;
$page = $page == null || (int)$page == 1 ? null : "/".(int)$page;
//是否是5.0升级项目
if (isset($project->update_info["is_update"]) && $project->update_info["is_update"] == 1){
//5.0生成路径
$path = $this->getProjectRoutePath5($project,$domain,$route,$routeType,$lang,$page);
}else{
//6.0生成路径
$path = $this->getProjectRoutePath6($project,$domain,$route,$routeType,$lang,$page);
}
try {
//$filePath = iconv("UTF-8", "GBK", $path);
$filePath = $path;
if (!file_exists(public_path($filePath))) {
mkdir(public_path($filePath), 0777, true);
}
if (strpos($route, ".html") !== false || strpos($route, ".htm") !== false) {
file_put_contents(public_path($filePath . ".html"), $html);
chmod(public_path($filePath . ".html"), 0777);
}else{
file_put_contents(public_path($filePath . "/index.html"), $html);
chmod(public_path($filePath . "/index.html"), 0777);
}
} catch (\Exception $e) {
return true;
}
return true;
}
/**
* 6.0生成路径
*/
public function getProjectRoutePath6($project,$domain,$route,$routeType,$lang,$page): string
{
if ($routeType == "news" || $routeType == "blogs"){
if ($routeType == "blogs"){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->whereIn('path', ['blog','blogs',''])->first();
}else{
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->where("path",$routeType)->first();
}
}else{
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->first();
}
if (!empty($routerMap)){
if ($routerMap->source == "news"){
$route = "/news/".$route;
}elseif($routerMap->source == "blog"){
$route = "/blogs/".$route;
}elseif($routerMap->source == "module"){
$modules = Module::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",0)->first();
$moduleCategoryInfo = Module::getModuleCategory($project->id,$modules);
if (isset($moduleCategoryInfo->route) && !empty($moduleCategoryInfo->route)){
$route = "/".$moduleCategoryInfo->route."/".$route;
}
}else{
$route = $route == "index" ? "" : "/".$route;
}
}else{
$route = $route == "index" ? "" : "/".$route;
}
$route = str_replace(".html","",$route);
$route = str_replace(".htm","",$route);
return $domain.$lang.$route.$page;
}
/**
* 5.0生成路径
*/
public function getProjectRoutePath5($project,$domain,$route,$routeType,$lang,$page): string
{
if ($routeType == "news" || $routeType == "blogs"){
if ($routeType == "blogs"){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->whereIn('path', ['blog','blogs',''])->first();
}else{
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->where("path",$routeType)->first();
}
}else{
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->where("path","")->first();
if (empty($routerMap)){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->first();
}
}
if (!empty($routerMap)){
if ($routerMap->source == "news"){
$route = "/news/".$route;
}elseif($routerMap->source == "blog" || $routerMap->source == "blogs"){
$route = "/blogs/".$route;
}elseif ($routerMap->source == "news_category"){
if ($route == "news"){
$route = $page == null || $page == 1 ? "/".$route : "/".$route . "/page";
}else{
$route = $page == null || $page == 1 ? "/news_catalog/".$route : "/news_catalog/".$route."/page";
}
}elseif ($routerMap->source == "blog_category"){
if ($route == "blog"){
$route = $page == null || $page == 1 ? "/".$route : "/".$route."/page";
}else{
$route = $page == null || $page == 1 ? "/blog_catalog/".$route : "/blog_catalog/".$route."/page";
}
}elseif ($routerMap->source == "product_category"){
$route = $page == null || $page == 1 ? "/".$route : "/".$route."/page";
}elseif ($routerMap->source == "module_category"){
$moduleCategory = ModuleCategory::getModuleCategoryAndExtendById($project->id,$routerMap->source_id);
if (!empty($moduleCategory->getExtend->route)){
if ($moduleCategory->getExtend->route == $route){
$route = "/".$moduleCategory->route;
}else{
$route = "/".$moduleCategory->getExtend->route."_catalog/".$moduleCategory->route."/page";
}
}else{
$route = "/".$moduleCategory->route."/page";
}
}elseif ($routerMap->source == "module"){
$modules = Module::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",0)->first();
$moduleCategoryInfo = Module::getModuleCategory($project->id,$modules);
if (isset($moduleCategoryInfo->getExtend->route) && !empty($moduleCategoryInfo->getExtend->route)){
$route = "/".$moduleCategoryInfo->route."/".$modules->route;
}else{
$route = "/".$modules->route;
}
}else{
$route = $route == "index" ? "" : "/".$route;
}
}else{
if ($route == "products"){
if ($page == null || $page == 1){
$route = "/".$route;
}else{
$route = "/".$route."/page";
}
}elseif ($route == "news"){
$route = $page == null || $page == 1 ? "/".$route : "/".$route;
}elseif ($route == "blog"){
$route = $page == null || $page == 1 ? "/blog_catalog/".$route : "/blog_catalog/".$route."/page";
}else{
$route = $route == "index" ? "" : "/".$route;
}
}
$route = str_replace(".html","",$route);
$route = str_replace(".htm","",$route);
return $domain.$lang.$route.$page;
}
/**
* 从主站拿页面
*/
public function getHtmlToPageFile($project,$lang,$route,$page,$routeType = "")
{
$domain = $project->domain;
$domain = str_replace("https://","",$domain);
$domain = str_replace("http://","",$domain);
$domain = str_replace("/","",$domain);
$lang = $lang=="" ? "" : "/".$lang;
$page = $page == null || (int)$page == 1 ? null : "/".(int)$page;
//是否是5.0升级项目
if (isset($project->update_info["is_update"]) && $project->update_info["is_update"] == 1){
//取5.0生成路径
$path = $this->getProjectRoutePagePath5($project,$domain,$route,$routeType,$lang,$page);
}else{
//取6.0生成路径
$path = $this->getProjectRoutePagePath6($project,$domain,$route,$routeType,$lang,$page);
}
try {
$filePath = iconv("UTF-8", "GBK", $path);
if (file_exists(public_path($filePath . "/index.html"))) {
$html = file_get_contents(public_path($filePath . "/index.html"));
}else{
$html = "";
}
} catch (\Exception $e) {
$html = "";
}
return $html;
}
/**
* 拿6.0页面
*/
public function getProjectRoutePagePath6($project,$domain,$route,$routeType,$lang,$page): string
{
if ($routeType == "news" || $routeType == "blogs"){
if ($routeType == "blogs"){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->whereIn('path', ['blog','blogs',''])->first();
}else{
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->where("path",$routeType)->first();
}
}else{
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->where("path","")->first();
if (empty($routerMap)){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->first();
}
}
if (!empty($routerMap)){
if ($routerMap->source == "news"){
$route = "/news/".$route;
}elseif($routerMap->source == "blog"){
$route = "/blogs/".$route;
}elseif($routerMap->source == "module"){
$modules = Module::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",0)->first();
$moduleCategoryInfo = Module::getModuleCategory($project->id,$modules);
if (isset($moduleCategoryInfo->route) && !empty($moduleCategoryInfo->route)){
$route = "/".$moduleCategoryInfo->route."/".$route;
}
}else{
$route = $route == "index" ? "" : "/".$route;
}
}else{
$route = $route == "index" ? "" : "/".$route;
}
return $domain.$lang.$route.$page;
}
/**
* 拿5.0页面
*/
public function getProjectRoutePagePath5($project,$domain,$route,$routeType,$lang,$page): string
{
if ($routeType == "news" || $routeType == "blogs"){
if ($routeType == "blogs"){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->whereIn('path', ['blog','blogs',''])->first();
}else{
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->where("path",$routeType)->first();
}
}else{
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->where("path","")->first();
if (empty($routerMap)){
$routerMap = RouteMap::where("project_id",$project->id)->where("route",$route)->first();
}
}
if (!empty($routerMap)){
if ($routerMap->source == "news"){
$route = "/news/".$route;
}elseif($routerMap->source == "blog" || $routerMap->source == "blogs"){
$route = "/blogs/".$route;
}elseif ($routerMap->source == "news_category"){
$route = "/news_catalog/".$route."/page";
}elseif ($routerMap->source == "blog_category"){
$route = "/blog_catalog/".$route."/page";
}elseif ($routerMap->source == "product_category"){
$route = "/".$route."/page";
}elseif ($routerMap->source == "module"){
$modules = Module::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",0)->first();
$moduleCategoryInfo = Module::getModuleCategory($project->id,$modules);
if (isset($moduleCategoryInfo->getExtend->route) && !empty($moduleCategoryInfo->getExtend->route)){
$route = "/".$moduleCategoryInfo->getExtend->route."_catalog/".$moduleCategoryInfo->route."/page";
}else{
$route = "/extend_catalog/".$moduleCategoryInfo->route."/page";
}
}else{
$route = $route == "index" ? "" : "/".$route;
}
}else{
$route = $route == "index" ? "" : "/".$route;
}
return $domain.$lang.$route.$page;
}
/**
* 翻译
*/
public function translateWebPage($project,$html,$lang,$domain,$route="",$page=null,$countryLang=null): string
{
if (empty($html) || $html == ""){
return $html;
}
$staticHtmlRepository = new StaticHtmlRepository();
try {
//非主站处理html语言
$htmlOld = $this->langUrlHandle($project,$lang,$html,$route,$page,$countryLang);
$phpQueryDomOld = phpQuery::newDocument($htmlOld);
$langDomContent = $phpQueryDomOld->find("header .change-language")->eq(0)->html();
$footerFormDomContent = $phpQueryDomOld->find(".form-footer-inquiry-block")->eq(0)->html();
$mainFormDomContent = $phpQueryDomOld->find(".section-form-wrap-block")->eq(0)->html();
$popFormDomContent = $phpQueryDomOld->find(".pop-box.inquiry-box")->eq(0)->html();
$topSearchDomContent = $phpQueryDomOld->find("main .top-search-title-first-letter-list")->eq(0)->html();
$langDomContent5 = $phpQueryDomOld->find(".prisna-wp-translate-seo")->eq(0)->html();
unset($phpQueryDomOld);
phpQuery::unloadDocuments();
$newHtml = "";
if ($lang != '') {
//翻译测试成功,用下面第二红最新翻译
// 第一种翻译
// $commonService = new CommonService();
// $htmlNew = $commonService->webHtmlTranslate($project,$htmlOld,$lang,$domain);
// 第二种翻译
$htmlNew = $staticHtmlRepository->getTranHtml($project,$htmlOld,$lang,$route,$page);
$phpQueryDomNew = phpQuery::newDocument($htmlNew);
unset($htmlOld);
$phpQueryDomNew->find("header .change-language")->eq(0)->html($langDomContent);
//取消根据翻译状态,翻译tag状态显示主站小语种列表功能(2024.02.27)
// $phpQueryDomNew->find("header div[data-module=2]")->find(".change-language-cont")->removeAttr("style");
$phpQueryDomNew->find(".form-footer-inquiry-block")->eq(0)->html($footerFormDomContent);
$phpQueryDomNew->find(".section-form-wrap-block")->eq(0)->html($mainFormDomContent);
$phpQueryDomNew->find(".pop-box.inquiry-box")->eq(0)->html($popFormDomContent);
$phpQueryDomNew->find("main .top-search-title-first-letter-list")->eq(0)->html($topSearchDomContent);
$phpQueryDomNew->find(".prisna-wp-translate-seo")->eq(0)->html($langDomContent5);
$newHtml = $phpQueryDomNew->htmlOuter();
unset($phpQueryDomNew,$htmlNew,$langDomContent,$footerFormDomContent,$mainFormDomContent,$popFormDomContent);
}
phpQuery::unloadDocuments();
} catch (\Exception $e) {
$newHtml = $staticHtmlRepository->getTranHtml($project,$html,$lang,$route,$page);
}
return $newHtml;
}
/**
* 小语种url处理
*/
public function langUrlHandle($project,$lang,$html,$route="",$page=null,$countryLang=null)
{
// $html = str_replace("\n","",$html);
$content = $html;
//主站翻译,不进行小语种链接和页面处理
if ($project->is_lang_translate == 1){
$langInfo = WebLanguage::getProjectMainLang($project->main_lang_id);
if ($langInfo->short == $lang){
return $content;
}
}
//当前语言国徽背景图片处理
if ($lang != ""){
$oldLang = $lang;
$oldRoute = $route;
$phpQueryDom = phpQuery::newDocument($content);
//去掉小语种搜索框
$phpQueryDom->find("header .search")->remove();
$phpQueryDom->find("header .btn--search")->remove();
$phpQueryDom->find("header .btn-search")->remove();
$phpQueryDom->find("header .head-search")->remove();
$page = $page == null ? "" : $page."/";
$route = $route == "index" || $route == "" ? "" : $route."/";
$lang = $lang."/";
$langUrl = "https://".$project->domain."/".$lang.$route.$page;
$phpQueryDom->find("link[rel=canonical]")->attr("href",$langUrl);
//翻译版块当前小语种显示
$countryDom = $phpQueryDom->find("header div[data-module=2]");
$langInfo = WebLanguage::where("short",$oldLang)->first();
if (!empty($langInfo)){
$countryDom->find(".change-language-title span")->text($langInfo->english);
}
$oldTwLang = $oldLang == "zh-ct" ? "zh-TW" : $oldLang;
$countryDom->find(".change-language-title .country-flag")->attr("class","country-flag language-flag-".$oldTwLang);
//html 标签处理
if ($oldLang == "ar" || $oldLang == "ug"){
$phpQueryDom->find("html")->attr("dir","rtl");
}else{
$phpQueryDom->find("html")->attr("dir","ltr");
}
$phpQueryDom->find("html")->attr("lang",$oldLang);
//1:2级目录 2:2级域名
$linkingFormat = 1;
$mainLang = null;
$projectBuild = $project->deployBuild;
if (!empty($projectBuild)){
$linkingFormat = $projectBuild->linking_format;
}
if (isset($project->main_lang_id) && !empty($project->main_lang_id)){
$mainLang = WebLanguage::getProjectMainLang($project->main_lang_id);
}
//小语种自定义跳转
$countryCustomInfo = CountryCustom::getCountryCustomByProjectId($project->id);
$countryCustomInfoNew = [];
if (!empty($countryCustomInfo)){
foreach ($countryCustomInfo as $countryCustomInfoItem){
if (isset($countryCustomInfoItem->country_custom_language->short)){
$countryCustomInfoNew[$countryCustomInfoItem->country_custom_language->short]["custom_domain"] = $countryCustomInfoItem->custom_domain;
}
}
}
// 1、处理A标签跳过图标 2、获取图标HTML a标签处理完成 还原图标HTML
//a标签路径问题
foreach ($phpQueryDom->find('a') as $a) {
$class =pq($a)->attr('class');
if (strpos($class, 'language-flag') !== false){
continue;
}
$href = pq($a)->attr('href');
//a标签href字符串是否有http://或者https://等协议头,有的话不做处理
if (strpos($href, 'http://') !== false || strpos($href, 'https://') !== false || strpos($href,'javascript') !== false || strpos($href, 'javasctipt') !== false || $href == "#" || empty($href) || strpos($href, '.zip') !== false || strpos($href, '.txt') !== false || strpos($href, 'tel:') !== false || strpos($href, 'mailto') !== false || strpos($href, '.pdf') !== false || strpos($href, '.tar') !== false || strpos($href, '.jpg') !== false || strpos($href, '.png') !== false || strpos($href, '.jpeg') !== false || strpos($href, '.xml') !== false || strpos($href, 'skype:') !== false || strpos($href, 'whatsapp:') !== false) {
}else{
if ($lang != ''){
if (!empty($mainLang)){
if ($lang != $mainLang->short){
//小语种自定义链接
if (isset($countryCustomInfoNew[$oldLang])){
continue;
}
if ($linkingFormat == 1){
$hrefNew = '/'.$lang . ltrim($href, '/');
}else{
$hrefNew = '/' . ltrim($href, '/');
}
}else{
$hrefNew = '/' . ltrim($href, '/');
}
pq($a)->attr('href', $hrefNew);
}
}
}
}
$data = date("Y-m-d H:i:s");
$phpQueryDom->find('html')->append("<!-- Globalso translate Cache file was created on ".$data." -->");
$content = $phpQueryDom->htmlOuter();
unset($html,$phpQueryDom);
phpQuery::unloadDocuments();
return $content;
}
return $content;
}
/**
* 生成robots
* @param Project $project
* @return bool
*/
public function createRobots($project)
{
if (!empty($project)){
$robotTxtPath = public_path($project->domain."/robots.txt");
$createSitemapService = new CreateSitemapService();
//A端是否开启允许robots爬虫爬取
if ($project->robots == 0){
$sitemapContent = $this->getRefuseRobotsStr($project->domain);
}else{
$sitemapContent = $this->getAllowRobotsStr($project->domain);
}
$domainPath = public_path($project->domain);
if (!file_exists($domainPath)){
mkdir($domainPath, 0777, true);
}
$res = $createSitemapService->putSitemapFile($robotTxtPath,$sitemapContent);
if ($res){
return true;
}
}
return true;
}
/**
* 生成允许爬虫爬取robots内容
* @param $domain
* @return string
*/
public function getAllowRobotsStr($domain)
{
$domain_arr = config('custom.robots_disallow_domain');
$disallow = '';
if (in_array($domain, $domain_arr)) {
$langArr = WebLanguage::pluck('short');
foreach ($langArr as $val) {
if ($val == 'en')
continue;
$disallow .= 'Disallow: /' . $val . '/' . PHP_EOL;
}
}
$trans_string = is_file(public_path($domain . '/trans_sitemap.xml')) ? "Sitemap: https://".$domain."/trans_sitemap.xml" : '';
return "User-agent: *
Allow: /
Disallow: /404/
".$disallow."
User-agent: MSNBot
Disallow: /
User-agent: YoudaoBot
Disallow: /
User-agent: JikeSpider
Disallow: /
User-agent: EasouSpider
Disallow: /
User-agent: AhrefsBot
Disallow: /
User-agent: MJ12bot
Disallow: /
User-agent: YYSpider
Disallow: /
User-agent: Teoma
Disallow: /
User-agent: rogerbot
Disallow: /
User-agent: exabot
Disallow: /
User-agent: DotBot
Disallow: /
User-agent: gigabot
Disallow: /
User-agent: BLEXBot
Disallow: /
User-agent: DOCOMO Sprider
Disallow: /
User-agent: Applebot
Disallow: /
User-agent: SeznamBot
Disallow: /
User-agent: SemrushBot
Disallow: /
Sitemap: https://".$domain."/sitemap.xml
$trans_string";
}
/**
* 获取允许爬虫爬取robots内容
*/
public function getRefuseRobotsStr($domain): string
{
return "User-agent: *
Disallow: /";
}
/**
* 升级项目,并且以老版本展示
* @param $project
* @param $routerMap
* @param $old_domain_test
* @param $old_domain_online
* @param $language
* @return string
* @author Akun
* @date 2023/11/29 14:52
*/
public function getOldHtml($project, $routerMap, $old_domain_test, $old_domain_online, $language=''){
$collect_info = CollectTask::where('project_id',$project->id)->where('language',$language)->where('source',$routerMap->source)->where('source_id',$routerMap->source_id)->where('status',CollectTask::STATUS_COM)->first();
if($collect_info){
$html = $collect_info->html;
if(strpos($html,'404 Not Found') !== false){
return '';
}
//替换域名
$html = str_replace("http://".$old_domain_test,"",$html);
$html = str_replace("https://".$old_domain_test,"",$html);
$html = str_replace("http://".$old_domain_online,"",$html);
$html = str_replace("https://".$old_domain_online,"",$html);
// //暂时隐藏小语种
// $html = str_replace('<div class="change-language ensemble">','<div class="change-language ensemble" style="display: none">',$html);
// $html = str_replace('<div class="language_more">','<div class="language_more" style="display: none">',$html);
//处理搜索
preg_match_all('/<form\s+[^>]*?action\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', $html, $result_search);
$search = $result_search[2] ?? [];
foreach ($search as $vc) {
if((strpos($vc,'search.php') !== false) || (strpos($vc,'index.php') !== false)){
$html = str_replace($vc,'/search/',$html);
}
}
//增加统计代码
$html = str_replace('</body>','<script src="https://ecdn6.globalso.com/public/customerVisit.min.js"></script></body>',$html);
return $html;
}else{
return '';
}
}
/**
* 更新获取路由
*/
public function getRouters($updateNotifyData,$pageNum): array
{
$routers = null;
$perPage = 100;
$offset = ($pageNum - 1) * $perPage;
$updateNotifyQuery = UpdateHtmlModel::where("project_id",$updateNotifyData->project_id);
if ($updateNotifyData->route == Notify::ROUTE_ALL){
//所有更新
if ($updateNotifyData->type == Notify::TYPE_MASTER){
$updateNotifyQuery->where("status","<",2)->update(['status' => 2]);
$routers = RouteMap::where("project_id",$updateNotifyData->project_id)->offset($offset)->limit($perPage)->get()->sortBy(function($item) {
return array_search($item->source, ['page', 'product_category', 'product', 'news_category', 'news', 'blog_category', 'blog', 'product_keyword']);
});
}else{
$updateNotifyQuery->where("minor_languages_status","<",2)->update(['minor_languages_status' => 2]);
$routers = RouteMap::where("project_id",$updateNotifyData->project_id)->where("source","!=","product_keyword")->offset($offset)->limit($perPage)->get()->sortBy(function($item) {
return array_search($item->source, ['page', 'product_category', 'product', 'news_category', 'news', 'blog_category', 'blog']);
});
}
}else if($updateNotifyData->route == Notify::ROUTE_PRODUCT_KEYWORD){
//产品聚合页更新
$routers = RouteMap::where("project_id",$updateNotifyData->project_id)->where("source","product_keyword")->offset($offset)->limit($perPage)->get();
}else if($updateNotifyData->route == Notify::ROUTE_PRODUCT_VIDEO_KEYWORD){
//产品视频聚合页更新
$videoKeywordIdList = Keyword::where("project_id",$updateNotifyData->project_id)->where("status",1)->whereNotNull("route")->whereNotNull("video")->pluck("id")->toArray();
if (!empty($videoKeywordIdList)){
$routers = RouteMap::where("project_id",$updateNotifyData->project_id)->where("source","product_keyword")->whereIn("source_id",$videoKeywordIdList)->offset($offset)->limit($perPage)->get();
}
}else if($updateNotifyData->route == Notify::ROUTE_NOT_TRANSLATE){
//漏翻译
if ($updateNotifyData->type == Notify::TYPE_MINOR){
$routers = RouteMap::where("project_id",$updateNotifyData->project_id)->offset($offset)->limit($perPage)->get()->sortBy(function($item) {
return array_search($item->source, ['page', 'product_category', 'product', 'news_category', 'news', 'blog_category', 'blog', 'product_keyword']);
});
}
}else if($updateNotifyData->route == Notify::ROUTE_NEED){
//按需更新
if ($updateNotifyData->type == Notify::TYPE_MASTER){
$routers = $updateNotifyQuery->where("status","<",2)->offset($offset)->limit($perPage)->get();
$updateNotifyQuery->where("status","<",2)->update(['status' => 2]);
}else{
$routers = $updateNotifyQuery->where("minor_languages_status","<",2)->offset($offset)->limit($perPage)->get();
$updateNotifyQuery->where("minor_languages_status","<",2)->update(['minor_languages_status' => 2]);
}
}else{
//按url更新
$urlArrMap = [];
$dataJson = json_decode($updateNotifyData->data);
$urlArr = $dataJson->url;
if (!empty($urlArr)){
if (count($urlArr) != 0){
foreach ($urlArr as $key => $item){
if (strpos($item, 'http://') !== false || strpos($item, 'https://') !== false) {
$pathUrl = parse_url($item);
if (isset($pathUrl["path"])){
$pathUrl = $pathUrl["path"];
if ($pathUrl == "/"){
$urlArrMap[] = "index";
}
}else{
$urlArrMap[] = "index";
}
$pathInfo = urldecode($pathUrl);
$pageService = new PageService();
$analysisRouteArr = $pageService->analysisRoute($pathInfo);
if (isset($analysisRouteArr["router"])){
$urlArrMap[] = $analysisRouteArr["router"];
}
}else{
$urlArrMap[] = $item;
}
}
}
$pageNum = 0;
}
$routeNew = [];
if (!empty($urlArrMap)){
foreach ($urlArrMap as $v){
$routerItem = RouteMap::where("project_id",$updateNotifyData->project_id)->where("route",$v)->first();
if (!empty($routerItem)){
$routeNew[] = $v;
}
}
}
if (!empty($routeNew)){
$routeNew = array_values(array_unique(array_filter($routeNew)));
$routers = RouteMap::where("project_id",$updateNotifyData->project_id)->whereIn("route",$routeNew)->get();
}
}
$routersInfo["routers"] = $routers;
$routersInfo["pageNum"] = $pageNum;
return $routersInfo;
}
/**
* 数据详情入库数据处理
*/
public function htmlPageQueryDataHandle($routers,$updateNotifyData,$task_id,$isHasData = true)
{
$page = null;
$updateData = [];
$data = json_decode($updateNotifyData->data, true);
$updateNotifyData->domain = $data['domain'];
if ($updateNotifyData->route == Notify::ROUTE_ALL || $updateNotifyData->route == Notify::ROUTE_URL || $updateNotifyData->route == Notify::ROUTE_PRODUCT_KEYWORD || $updateNotifyData->route == Notify::ROUTE_NOT_TRANSLATE){
//全部更新
if ($isHasData && !empty($routers) && !$routers->isEmpty()){
foreach ($routers as $item){
$count = $this->isListAndGetCount($item,$updateNotifyData);
if ($count == 0 || $item->route == "index"){
$updateData['project_id'] = $updateNotifyData->project_id;
$updateData['id'] = $task_id;
$updateData['type'] = $item->source;
$updateData['route'] = $item->route;
$updateData['page'] = $page;
$updateData['domain'] =$updateNotifyData->domain;
$updateDataJson = json_encode($updateData);
//更新页面
$this->pushHtmlPage($updateNotifyData,$updateDataJson,$task_id);
}else{
for ($i = 1; $i <= $count; $i++) {
if ($i == 1){
$updateData['page'] = null;
}else{
$updateData['page'] = $i;
}
$updateData['project_id'] = $updateNotifyData->project_id;
$updateData['id'] = $task_id;
$updateData['type'] = $item->source;
$updateData['route'] = $item->route;
$updateData['domain'] =$updateNotifyData->domain;
$updateDataJson = json_encode($updateData);
//更新页面
$this->pushHtmlPage($updateNotifyData,$updateDataJson,$task_id);
}
}
}
}
if (!$isHasData){
//判断products,news,blog三个列表页是否存在路由,不存在主动更新
//手动更新所有关键词列表页(自定义top-search系列页面)
$this->checkProductsNewsBlogListAndGetCount($updateNotifyData,$task_id);
if ($updateNotifyData->type == Notify::TYPE_MASTER){
$this->productKeywordListAdnGetCount($updateNotifyData,$task_id);
}else{
if ($updateNotifyData->route == Notify::ROUTE_PRODUCT_KEYWORD){
$this->productKeywordListAdnGetCount($updateNotifyData,$task_id);
}
}
}
}else{
//按需更新
if ($isHasData && !empty($routers) && !$routers->isEmpty()){
foreach ($routers as $item){
$count = $this->isListAndGetCount($item,$updateNotifyData);
if ($count == 0 || $item->type == "index"){
$updateData['project_id'] = $updateNotifyData->project_id;
$updateData['id'] = $task_id;
if ($item->type == "index"){
$updateData['type'] = "page";
$updateData['route'] = "index";
}else{
$updateData['type'] = $item->type;
$updateData['route'] = $item->route;
}
$updateData['page'] = $page;
$updateData['domain'] =$updateNotifyData->domain;
$updateDataJson = json_encode($updateData);
//更新页面
$this->pushHtmlPage($updateNotifyData,$updateDataJson,$task_id);
}else{
for ($i = 1; $i <= $count; $i++) {
if ($i == 1){
$updateData['page'] = null;
}else{
$updateData['page'] = $i;
}
$updateData['project_id'] = $updateNotifyData->project_id;
$updateData['id'] = $task_id;
$updateData['type'] = $item->type;
$updateData['route'] = $item->route;
$updateData['domain'] =$updateNotifyData->domain;
$updateDataJson = json_encode($updateData);
//更新页面
$this->pushHtmlPage($updateNotifyData,$updateDataJson,$task_id);
}
}
}
}
if (!$isHasData){
//判断products,news,blog三个列表页是否存在路由,不存在主动更新
$this->checkProductsNewsBlogListAndGetCount($updateNotifyData,$task_id);
}
}
unset($routers);
}
/**
* 是否是列表,并返回页数
*/
public function isListAndGetCount($router,$updateNotifyData)
{
$count = 0;
$newsQuery = News::where("project_id",$updateNotifyData->project_id)->select("id")->where("status",1);
$blogQuery = Blog::where("project_id",$updateNotifyData->project_id)->select("id")->where("status",1);
$productsQuery = Product::where("project_id",$updateNotifyData->project_id)->select("id")->where("status",1)->whereNotNull('route');
if ($updateNotifyData->route == Notify::ROUTE_ALL || $updateNotifyData->route == Notify::ROUTE_URL){
if ($router->source == "news_category"){
if ($router->route == "news"){
$count = $newsQuery->count();
}else{
$count = $newsQuery->where("category_id","like","%".",".$router->source_id.","."%")->count();
}
}
if ($router->source == "blog_category"){
if ($router->route == "blog"){
$count = $blogQuery->count();
}else{
$count = $blogQuery->where("category_id","like","%".",".$router->source_id.","."%")->count();
}
}
if ($router->source == "product_category"){
if ($router->route == "products"){
$count =$productsQuery->count();
}else{
$ids = [];
$productCategoryList = Category::getAllSonCategoryById($updateNotifyData->project_id,(int)$router->source_id);
if (!empty($productCategoryList)){
$productList = CategoryRelated::whereIn("cate_id",$productCategoryList)->get();
if (!empty($productList)){
foreach ($productList as $productV){
$ids[] = $productV->product_id;
}
}
}
$count =$productsQuery->whereIn("id",$ids)->count();
}
}
}else{
$routerMap = RouteMap::where("project_id",$updateNotifyData->project_id)->where("route",$router->route)->first();
if (!empty($routerMap)){
if ($router->type == "news_category"){
if ($router->route == "news"){
$count = $newsQuery->count();
}else{
$count = $newsQuery->where("category_id","like","%".",".$routerMap->source_id.","."%")->count();
}
}
if ($router->type == "blog_category"){
if ($router->route == "blog"){
$count = $blogQuery->count();
}else{
$count = $blogQuery->where("category_id","like","%".",".$routerMap->source_id.","."%")->count();
}
}
if ($router->type == "product_category"){
if ($router->route == "products"){
$count = $productsQuery->count();
}else{
$count = $productsQuery->where("category_id","like","%,".(string)$routerMap->source_id.",%")->count();
}
}
}
}
if ($count != 0){
if ($router->type == "product_category"){
$webSettingNum = WebSettingNum::where("project_id",$updateNotifyData->project_id)->where("type",WebSettingNum::$productListType)->orderBy("id","desc")->first();
if (!empty($webSettingNum)){
$perPage = (int)$webSettingNum->num;
}else{
$perPage = Category::$productCategoryPagePercent; //产品每页条数
}
$total = (int)ceil($count / $perPage); //产品分类总页数
}elseif($router->type == "news_category"){
$webSettingNum = WebSettingNum::where("project_id",$updateNotifyData->project_id)->where("type",WebSettingNum::$newsListType)->orderBy("id","desc")->first();
if (!empty($webSettingNum)){
$perPage = (int)$webSettingNum->num;
}else{
$perPage = NewsCategory::$newsCategoryPagePercent; //新闻每页条数
}
$total = (int)ceil($count / $perPage); //新闻总页数
}else{
$webSettingNum = WebSettingNum::where("project_id",$updateNotifyData->project_id)->where("type",WebSettingNum::$blogListType)->orderBy("id","desc")->first();
if (!empty($webSettingNum)){
$perPage = (int)$webSettingNum->num;
}else{
$perPage = NewsCategory::$newsCategoryPagePercent; //博客每页条数
}
$total = (int)ceil($count / $perPage); //博客总页数
}
$count = $total;
}
return $count;
}
/**
* 需要更新的页面,主站页面或者小语种页面
*/
public function pushHtmlPage($updateNotifyData, $updateDataJson,$taskId)
{
//更新页面
$mysqlData["created_at"] = now();
$mysqlData["updated_at"] = now();
$mysqlData["data"] =$updateDataJson;
$mysqlData["task_id"] =$taskId;
$data = json_decode($updateDataJson);
if (!empty($data->page)){
$page =",分页:".$data->page;
}else{
$page = "";
}
echo "创建项目路由:任务ID:" . $taskId .",项目ID:".$data->project_id.",域名:".$data->domain.",路由:".$data->route.$page. PHP_EOL;
if ($updateNotifyData->type == Notify::TYPE_MASTER){
UpdateMasterWebsiteModel::insertGetId($mysqlData);
}else{
UpdateMinorLanguagesModel::insertGetId($mysqlData);
}
}
/**
* 判断products,news,blog三个列表页是否存在路由,不存在主动更新
*/
public function checkProductsNewsBlogListAndGetCount($updateNotifyData,$task_id)
{
$productsCount = 0;
$newsCount = 0;
$blogCount = 0;
//产品
$routerProductsMap = RouteMap::where("project_id",$updateNotifyData->project_id)->where("route","products")->first();
if (empty($routerProductsMap)){
$productsCount = Product::where("project_id",$updateNotifyData->project_id)->select("id")->where("status",1)->whereNotNull('route')->orderBy("id","DESC")->count();
if ($productsCount != 0){
$webSettingNum = WebSettingNum::where("project_id",$updateNotifyData->project_id)->where("type",WebSettingNum::$productListType)->orderBy("id","desc")->first();
if (!empty($webSettingNum)){
$perPage = (int)$webSettingNum->num;
}else{
$perPage = Category::$productCategoryPagePercent; //产品每页条数
}
$productsTotal = (int)ceil($productsCount / $perPage);
if ($productsTotal>=1){
for ($i = 1; $i <= $productsTotal; $i++) {
$updateData = [];
if ($i == 1){
$updateData['page'] = null;
}else{
$updateData['page'] = $i;
}
$updateData['project_id'] = $updateNotifyData->project_id;
$updateData['id'] = $task_id;
$updateData['type'] = "product_category";
$updateData['route'] = "products";
$updateData['domain'] =$updateNotifyData->domain;
$updateDataJson = json_encode($updateData);
//更新页面
$this->pushHtmlPage($updateNotifyData,$updateDataJson,$task_id);
}
}
}
}
//新闻
$routerNewsMap = RouteMap::where("project_id",$updateNotifyData->project_id)->where("route","news")->first();
if (empty($routerNewsMap)){
$newsCount = News::where("project_id",$updateNotifyData->project_id)->select("id")->where("status",1)->orderBy("id","DESC")->count();
$webSettingNum = WebSettingNum::where("project_id",$updateNotifyData->project_id)->where("type",WebSettingNum::$newsListType)->orderBy("id","desc")->first();
if (!empty($webSettingNum)){
$perPage = (int)$webSettingNum->num;
}else{
$perPage = NewsCategory::$newsCategoryPagePercent;
}
$NewsTotal = (int)ceil($newsCount / $perPage);
if ($NewsTotal>=1){
for ($i = 1; $i <= $NewsTotal; $i++) {
$updateData = [];
if ($i == 1){
$updateData['page'] = null;
}else{
$updateData['page'] = $i;
}
$updateData['project_id'] = $updateNotifyData->project_id;
$updateData['id'] = $task_id;
$updateData['type'] = "news_category";
$updateData['route'] = "news";
$updateData['domain'] =$updateNotifyData->domain;
$updateDataJson = json_encode($updateData);
//更新页面
$this->pushHtmlPage($updateNotifyData,$updateDataJson,$task_id);
}
}
}
//博客
$routerBlogMap = RouteMap::where("project_id",$updateNotifyData->project_id)->where("route","blog")->first();
if (empty($routerBlogMap)){
$blogCount = Blog::where("project_id",$updateNotifyData->project_id)->select("id")->where("status",1)->orderBy("id","DESC")->count();
$webSettingNum = WebSettingNum::where("project_id",$updateNotifyData->project_id)->where("type",WebSettingNum::$blogListType)->orderBy("id","desc")->first();
if (!empty($webSettingNum)){
$perPage = (int)$webSettingNum->num;
}else{
$perPage = NewsCategory::$newsCategoryPagePercent;
}
$BlogTotal = (int)ceil($blogCount / $perPage);
if ($BlogTotal>=1){
for ($i = 1; $i <= $BlogTotal; $i++) {
$updateData = [];
if ($i == 1){
$updateData['page'] = null;
}else{
$updateData['page'] = $i;
}
$updateData['project_id'] = $updateNotifyData->project_id;
$updateData['id'] = $task_id;
$updateData['type'] = "blog_category";
$updateData['route'] = "blog";
$updateData['domain'] =$updateNotifyData->domain;
$updateDataJson = json_encode($updateData);
//更新页面
$this->pushHtmlPage($updateNotifyData,$updateDataJson,$task_id);
}
}
}
}
/**
* 手动更新所有关键词列表页(自定义top-search系列页面)
*/
public function productKeywordListAdnGetCount($updateNotifyData,$task_id)
{
$productKeywordInfo = $this->projectProductKeywordsDataAndHandle($updateNotifyData->project_id);
if (isset($productKeywordInfo["productKeywordListInfo"]) && !empty($productKeywordInfo["productKeywordListInfo"])){
foreach ($productKeywordInfo["productKeywordListInfo"] as $productKeywordItem){
if ($productKeywordItem['total']>=1){
for ($i = 1; $i <= $productKeywordItem['total']; $i++) {
if ($i == 1){
$updateData['page'] = null;
}else{
$updateData['page'] = $i;
}
$updateData['project_id'] = $updateNotifyData->project_id;
$updateData['id'] = $task_id;
$updateData['type'] = "product_keyword_list";
$updateData['route'] = $productKeywordItem['route'];
$updateData['domain'] =$updateNotifyData->domain;
$updateDataJson = json_encode($updateData);
//更新页面
$this->pushHtmlPage($updateNotifyData,$updateDataJson,$task_id);
}
}
}
}
unset($productKeywordInfo);
}
/**
* 获取更新进度表
*/
public function getUpdateProgress($projectId,$type)
{
$updateProgressQuery = UpdateProgressModel::where("project_id",(int)$projectId)->orderBy("id","desc");
if ($type == "master_website"){
$updateProgressQuery = $updateProgressQuery->where("type",1)->first();
}else{
$updateProgressQuery = $updateProgressQuery->where("type",2)->first();
}
return $updateProgressQuery;
}
/**
* 项目产品关键词列表路由,及数据处理
*/
public function projectProductKeywordsDataAndHandle($projectId): array
{
$keywordsArr = [];
$keywordModel = new Keyword();
$keywords = $keywordModel->where("project_id",$projectId)->get();
if (!empty($keywords)){
foreach ($keywords->toArray() as $item){
$firstLetter = mb_strtolower(mb_substr($item['title'], 0, 1, 'utf-8'), 'utf-8');
$keywordsArr["top-search"][] = $item;
if (in_array($firstLetter, $keywordModel->routeZ)){
$keywordsArr["top-search-0"][] = $item;
}else{
$keywordsArr["top-search-".$firstLetter][] = $item;
}
}
}
return [
"productKeywordListInfo"=>$this->projectProductKeywordsDataAndTotalPageHandle($keywordsArr),
"productKeywords"=>$keywords,
];
}
/**
* 项目产品关键词列表路由数据及总页数
*/
public function projectProductKeywordsDataAndTotalPageHandle($data): array
{
$projectProjectKeywords = [];
$perPage = 80;
if (!empty($data)){
foreach ($data as $key => $item){
$count = count($item);
$total = (int)ceil($count / $perPage);
$projectProjectKeywords[$key]["route"] =$key;
$projectProjectKeywords[$key]["total"] =$total;
}
}
return $projectProjectKeywords;
}
/**
* 站点域名处理
*/
public function domainHandle($domain)
{
$langDomain = str_replace("http://","",$domain);
$langDomain = str_replace("https://","",$langDomain);
$langDomain = str_replace("/","",$langDomain);
return $langDomain;
}
/**
* 小语种自定义创建站点目录页面拷贝
*/
public function copyPageMinorWebsiteToCreateDomainDirectory($project)
{
$countryCustomInfo = CountryCustom::with("countryCustomLanguage")->where("language_id","!=",$project->main_lang_id)->where("project_id",$project->id)->where("status",1)->where("is_create",1)->get();
if (!empty($countryCustomInfo)){
$langDomain = $this->domainHandle($project->domain);
foreach ($countryCustomInfo as $countryCustomInfoItem){
$publicLangPath = public_path($langDomain."/".$countryCustomInfoItem->countryCustomLanguage->short);
$publicCreatePath = public_path($countryCustomInfoItem->custom_domain);
if (file_exists($publicLangPath)){
if (!file_exists($publicCreatePath)){
mkdir($publicCreatePath,0777);
}
File::copyDirectory($publicLangPath, $publicCreatePath);
}
}
}
}
}
... ...
此 diff 太大无法显示。
<?php
/**
* @remark :
* @name :CustomTemplateService.php
* @author :lyh
* @method :post
* @time :2024/3/11 16:15
*/
namespace App\Services\Html;
use App\Models\Project\PageSetting;
use App\Models\Service\Service as ServiceSettingModel;
use App\Models\Template\BTemplate;
use App\Models\Template\BTemplateCommon;
use App\Models\Template\Setting;
class CustomTemplateService
{
/**
* @remark :获取当前自定义界面详情
* @name :customTemplateInfo
* @author :lyh
* @method :post
* @time :2023/6/29 16:23
*/
public function getHtml($projectInfo,$custom_id){
$info = $this->model->read(['id'=>$custom_id]);
if($info === false){
return false;
}
if($info['is_visualization'] == 0 || $info['is_visualization'] == 1){
$html = $this->getBodyHeaderFooter($projectInfo,$info['html'],$info['html_style']);
$info['html'] = $this->getHeadFooter($html);
}
return ['html'=>$info['html']];
}
/**
* @remark :获取body的详情
* @name :getBodyHeaderFooter
* @author :lyh
* @method :post
* @time :2023/7/21 18:08
*/
public function getBodyHeaderFooter($projectInfo,$preg_html,$html_style){
if(empty($preg_html)){
$preg_html = "<main></main>";
$html_style = "<style id='globalsojs-styles'></style>";
}
//获取设置的默认模版
$bSettingModel = new Setting();
$info = $bSettingModel->read(['project_id'=>$projectInfo['id']]);
if($info === false){
return false;
}
//获取type类型
$commonInfo = $this->getCommonPage($projectInfo,$info['template_id']);
$html = $commonInfo['head_css'].$html_style.$commonInfo['footer_css'].$commonInfo['other'].
$commonInfo['head_html'].$preg_html.$commonInfo['footer_html'];
return ['html'=>$html];
}
/**
* @remark :根据类型获取公共头和底
* @name :getCommonPage
* @author :lyh
* @method :post
*/
public function getCommonPage($projectInfo,$template_id){
$is_head = $projectInfo['deploy_build']['configuration']['is_head'] ?? BTemplate::IS_NO_HEADER;
if(isset($is_head) && ($is_head != 0)) {
//查看页面是否设置自定义头部底部
$pageSettingModel = new PageSetting();
$pageInfo = $pageSettingModel->read(['project_id' => $projectInfo['id']]);
if ($pageInfo !== false) {
$commonTemplateModel = new BTemplateCommon();
if ($pageInfo['page_list'] != 0) {
//使用独立头和底
$commonInfo = $commonTemplateModel->read(['template_id' => $template_id, 'project_id' => $projectInfo['id'], 'type' => 9]);
}
}
}
if(!isset($commonInfo) || $commonInfo === false){
//获取首页公共的头部和底部
$commonTemplateModel = new BTemplateCommon();
$commonInfo = $commonTemplateModel->read(['template_id'=>$template_id,'project_id'=>$projectInfo['id'],'type'=>1]);
}
return $commonInfo;
}
/**
* @remark :拼接获取公共头部底部
* @name :getHeadFooter
* @author :lyh
* @method :post
*/
public function getHeadFooter($html = ''){
//获取公共主题头部底部
$serviceSettingModel = new ServiceSettingModel();
$list = $serviceSettingModel->list(['type'=>2],'created_at');
//拼接html
foreach ($list as $v){
if($v['key'] == 'head'){
$html = $v['values'].$html;
}
if($v['key'] == 'footer'){
$html = $html.$v['values'];
}
}
return $html;
}
}
<?php
namespace App\Services\Html;
use App\Models\Project\DeleteHtmlModel;
use App\Models\Project\DeployBuild;
use App\Models\Project\DeployOptimize;
use App\Models\Project\DomainInfo;
use App\Models\WebSetting\WebSetting;
use Illuminate\Support\Facades\Redis;
/**
* C端删除页面服务
*/
class DeletePageService{
/**
* 删除文件
*/
public function deleteDirectory($path): bool
{
if (!is_dir($path)) {
try {
unlink($path);
} catch (\Exception $e) {
return true;
}
return true;
}
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file) {
$filePath = $path . '/' . $file;
if (is_dir($filePath)) {
$this->deleteDirectory($filePath);
} else {
try {
unlink($filePath);
} catch (\Exception $e) {
return true;
}
}
}
rmdir($path);
return true;
}
/**
* 获取项目ID下正式+测试域名
*/
public function getAllProjectDomain($data)
{
if (Redis::get($data->project_id."_all_project_domain") != null){
$allProjectDomain =Redis::get($data->project_id."_all_project_domain");
}else{
$domainArr = [];
$onlineProject = DeployOptimize::where('project_id',$data->project_id)->first();
if (!empty($onlineProject)){
if ($onlineProject->domain != null){
$domainInfo = DomainInfo::where("id",$onlineProject->domain)->where("status",1)->first();
if (!empty($domainInfo)){
$domainArr[] = $domainInfo->domain;
}
}
}
$testProject = DeployBuild::where('project_id',$data->project_id)->first();
if (!empty($testProject)){
$testDomain = $testProject->test_domain;
if (strpos($testDomain, 'http://') !== false){
$testDomain = str_replace('http://', '', $testDomain);
}
if (strpos($testDomain, 'https://') !== false){
$testDomain = str_replace('https://', '', $testDomain);
}
$testDomain = str_replace('/', '', $testDomain);
$domainArr[] = $testDomain;
}
if (!empty($domainArr)){
$allProjectDomain = json_encode($domainArr);
Redis::set($data->project_id."_all_project_domain", $allProjectDomain);
Redis::expire($data->project_id."_all_project_domain", WebSetting::$redisExpireTime);
}
}
return $allProjectDomain;
}
/**
* 构造删除路径
*/
public function deleteHtmlItems($data): bool
{
$getAllProjectDomain = $this->getAllProjectDomain($data);
if ($getAllProjectDomain != null){
$getAllProjectDomain = json_decode($getAllProjectDomain);
$deleteHtml = DeleteHtmlModel::where("project_id",$data->project_id)->get();
foreach ($getAllProjectDomain as $domainItem){
if (!empty($deleteHtml)){
foreach ($deleteHtml as $v){
//国家
$pageService = new PageService();
$webCountry = $pageService->getCountryList($data->project_id);
if ($webCountry != null){
foreach ($webCountry as $item){
if ($v->route == "index"){
$path = public_path($domainItem."/".$item->alias."/index.html");
}else{
$path = public_path($domainItem."/".$item->alias."/".$v->route);
}
if (file_exists($path)){
$this->deleteDirectory($path);
}
}
}
if ($v->route == "index"){
$path = public_path($domainItem."/index.html");
}else{
$path = public_path($domainItem."/".$v->route);
}
if (file_exists($path)){
$this->deleteDirectory($path);
}
DeleteHtmlModel::where("project_id",$data->project_id)->where("route",$v->route)->delete();
}
}
//删除C端固定页面
$pageService = new PageService();
$webCountry = $pageService->getCountryList($data->project_id);
if ($webCountry != null){
foreach ($webCountry as $item) {
//删除C端固定小语种页面
$productsPath = public_path($domainItem . "/" . $item->alias . "/products");
$newsPath = public_path($domainItem . "/" . $item->alias . "/news");
$blogPath = public_path($domainItem . "/" . $item->alias . "/blog");
if (file_exists($productsPath)) {
$this->deleteDirectory($productsPath);
}
if (file_exists($newsPath)) {
$this->deleteDirectory($newsPath);
}
if (file_exists($blogPath)) {
$this->deleteDirectory($blogPath);
}
}
}
//删除C端固定主站页面
$productsPath = public_path($domainItem."/products");
$newsPath = public_path($domainItem."/news");
$blogPath = public_path($domainItem."/blog");
if (file_exists($productsPath)){
$this->deleteDirectory($productsPath);
}
if (file_exists($newsPath)){
$this->deleteDirectory($newsPath);
}
if (file_exists($blogPath)){
$this->deleteDirectory($blogPath);
}
}
}
return true;
}
}
... ...
<?php
/**
* @remark :
* @name :GeneratePageService.php
* @author :lyh
* @method :post
* @time :2024/2/19 15:54
*/
namespace App\Services\Html;
use App\Models\CustomModule\CustomModule;
use App\Models\CustomModule\CustomModuleCategory;
use App\Models\CustomModule\CustomModuleContent;
use App\Models\Project\PageSetting;
use App\Models\Project\Project;
use App\Models\RouteMap\RouteMap;
use App\Models\Template\BTemplate;
use App\Models\Template\BTemplateCommon;
use App\Models\Template\BTemplateMain;
use App\Models\Template\Setting;
use App\Models\Template\TemplateTypeMain;
use App\Services\ProjectServer;
use Illuminate\Support\Facades\DB;
class GeneratePageService
{
protected $route;
protected $param;
protected $project_id = 0;
/**
* @remark :生成单页数据
* @name :generateHtml
* @author :lyh
* @method :post
* @time :2024/2/19 16:57
*/
public function generateHtml($projectInfo,$routeInfo){
$this->project_id = $projectInfo['id'];
$this->route = $routeInfo['route'];
ProjectServer::useProject($this->project_id);
$this->handleParam($routeInfo);
$result = $this->getTemplateHtml($projectInfo);
DB::disconnect('custom_mysql');
return $this->success($result);
}
/**
* @remark :生成页面参数处理
* @name :generateHtml
* @author :lyh
* @method :post
* @time :2024/2/19 16:36
*/
public function handleParam($routeInfo){
switch ($routeInfo['source']){
case RouteMap::SOURCE_PRODUCT:
$this->param['source'] = BTemplate::SOURCE_PRODUCT;
$this->param['is_list'] = BTemplate::IS_DETAIL;
break;
case RouteMap::SOURCE_PRODUCT_CATE:
$this->param['source'] = BTemplate::SOURCE_PRODUCT;
$this->param['is_list'] = BTemplate::IS_LIST;
break;
case RouteMap::SOURCE_BLOG:
$this->param['source'] = BTemplate::SOURCE_BLOG;
$this->param['is_list'] = BTemplate::IS_DETAIL;
break;
case RouteMap::SOURCE_BLOG_CATE:
$this->param['source'] = BTemplate::SOURCE_BLOG;
$this->param['is_list'] = BTemplate::IS_LIST;
break;
case RouteMap::SOURCE_NEWS:
$this->param['source'] = BTemplate::SOURCE_NEWS;
$this->param['is_list'] = BTemplate::IS_DETAIL;
break;
case RouteMap::SOURCE_NEWS_CATE:
$this->param['source'] = BTemplate::SOURCE_NEWS;
$this->param['is_list'] = BTemplate::IS_LIST;
break;
case RouteMap::SOURCE_MODULE:
$this->param['is_custom'] = BTemplate::IS_CUSTOM;
//TODO::获取对应模块数据
$moduleModel = new CustomModuleContent();
$moduleInfo = $moduleModel->read(['id'=>$routeInfo['source_id']],['module_id']);
$this->param['source'] = $moduleInfo['id'] ?? 0;
$this->param['is_list'] = BTemplate::IS_DETAIL;
break;
case RouteMap::SOURCE_MODULE_CATE:
$this->param['is_custom'] = BTemplate::IS_CUSTOM;
//TODO::获取对应模块数据
$moduleModel = new CustomModuleCategory();
$moduleInfo = $moduleModel->read(['id'=>$routeInfo['source_id']],['module_id']);
$this->param['source'] = $moduleInfo['id'] ?? 0;
$this->param['is_list'] = BTemplate::IS_LIST;
break;
default:
$this->param['source'] = BTemplate::SOURCE_HOME;
$this->param['is_list'] = BTemplate::IS_DETAIL;
break;
return true;
}
}
/**
* @notes: 请简要描述方法功能
* @param array $data
* @return array
*/
public function success($data = [])
{
return $data;
}
/**
* @remark :获取html
* @name :getTemplateHtml
* @author :lyh
* @method :post
*/
public function getTemplateHtml($projectInfo){
$is_custom = $this->param['is_custom'] ?? 0;//是否为扩展模块
$is_list = $this->param['is_list'] ?? 0;//是否为列表页
$template_id = $this->getSettingTemplate($projectInfo,$this->param['source'],$is_list,$is_custom);//设置的模版id
if($template_id === false){
return false;
}
$templateInfo = $this->webTemplateInfo($this->param['source'],$this->param['source_id'],$template_id,$is_custom,$is_list);
if($templateInfo === false){
if($projectInfo['is_customized'] == BTemplate::IS_VISUALIZATION){//处理定制页面初始数据
$html = $this->customizedReturnHtml($projectInfo,$this->param['source'],$template_id,$is_custom,$is_list);
if($html !== false){
return $this->success($html);
}
}
//非定制初始中间部分
$mainInfo = $this->getMAinHtml($this->param['source'],$is_custom,$is_list);//获取中间部分代码
}else{
if($templateInfo['type'] == BTemplate::ALL_HTML){//返回整个html代码
return $this->getCustomizeAllHtml($templateInfo,$template_id,$is_custom,$is_list);
}
$mainInfo = ['main_html'=>$templateInfo['main_html'], 'main_css'=>$templateInfo['main_css']];
}
$commonInfo = $this->getCommonHtml($projectInfo,$this->param['source'],$is_list,$template_id,$is_custom);//获取非定制头部
$html = $commonInfo['head_css'].$mainInfo['main_css'].$commonInfo['footer_css'].$commonInfo['other']. $commonInfo['head_html'].$mainInfo['main_html'].$commonInfo['footer_html'];
$html = $this->getHeadFooter($html);
$result = ['html'=>$html];
return $this->success($result);
}
/**
* @remark :获取整个html代码
* @name :getCustomizeAllHtml
* @author :lyh
* @method :post
* @time :2024/1/10 14:15
*/
public function getCustomizeAllHtml($templateInfo,$template_id,$is_custom,$is_list){
if($is_custom == BTemplate::IS_CUSTOM){
$commonInfo = $this->getCustomizedCommonHtml($this->param['source'],$is_custom,$is_list);//获取定制头部
$html = $this->handleAllHtml($commonInfo,$templateInfo['html']);
}else{
$type = $this->getCustomizedType($this->param['source'],$is_list);
$commonInfo = $this->getCustomizedCommonHtml($type,$is_custom,$is_list);//获取定制头部
$html = $this->handleAllHtml($commonInfo,$templateInfo['html']);
}
return $this->success(['html'=>$html,'template_id'=>$template_id]);
}
/**
* @remark :获取装修详情
* @name :webTemplateInfo
* @author :lyh
* @method :post
* @time :2024/1/10 13:43
*/
public function webTemplateInfo($source,$source_id,$template_id,$is_custom,$is_list){
$templateInfo = $this->model->read([
'template_id'=>$template_id, 'source'=>$source,
'project_id'=>$this->project_id, 'source_id'=>$source_id,
'is_custom'=>$is_custom, 'is_list'=>$is_list
]);
return $this->success($templateInfo);
}
/**
* @remark :定制页面获取html
* @name :customizedReturnHtml
* @author :lyh
* @method :post
* @time :2024/1/10 13:46
*/
public function customizedReturnHtml($projectInfo,$source,$template_id,$is_custom,$is_list){
//TODO::扩展模块定制单独处理
if($is_custom == BTemplate::IS_CUSTOM){
$customModuleModel = new CustomModule();
$info = $customModuleModel->read(['id'=>$source]);
if($info === false){
return false;
}
//扩展模块定制
if($is_list == BTemplate::IS_LIST && $info['list_customized'] == BTemplate::IS_VISUALIZATION){
$html = $this->customModuleCustomizeHtml($source,$is_list,$is_custom);
if($html === false){
return false;
}
return $this->success(['html'=>$html]);
}
if($is_list == BTemplate::IS_DETAIL && $info['detail_customized'] == BTemplate::IS_VISUALIZATION){
$html = $this->customModuleCustomizeHtml($source,$is_list,$is_custom);
if($html === false){
return false;
}
return $this->success(['html'=>$html]);
}
return false;
}
//TODO::默认模块定制
$html = $this->isCustomizedPage($projectInfo,$source,$is_list,$is_custom);//获取定制页面的html
if($html !== false){
return $this->success(['html'=>$html]);
}
return false;
}
/**
* @remark :扩展模块定制html
* @name :customModuleInfo
* @author :lyh
* @method :post
* @time :2024/1/10 9:20
*/
public function customModuleCustomizeHtml($source,$is_list,$is_custom){
$bTemplateMainModel = new BTemplateMain();
//TODO::获取初始代码
$customHtmlInfo = $bTemplateMainModel->read(['type'=>$source,'is_list'=>$is_list,'is_custom'=>$is_custom]);
if($customHtmlInfo === false){
return false;
}
$commonInfo = $this->getCustomizedCommonHtml($source,$is_custom,$is_list);//获取定制头部
if($commonInfo !== false){
$customHtmlInfo['main_html'] = $this->handleAllHtml($commonInfo,$customHtmlInfo['main_html']);
}
return $customHtmlInfo['main_html'];
}
/**
* @remark :获取中间部分的html
* @name :getMAinHtml
* @author :lyh
* @method :post
* @time :2023/12/27 15:00
*/
public function getMAinHtml($type,$is_custom,$is_list){
//获取设置的默认中间部分
$bTemplateMainModel = new BTemplateMain();
$mainInfo = $bTemplateMainModel->read(['type'=>$type,'is_list'=>$is_list,'is_custom'=>$is_custom]);
if($mainInfo === false){
$main_html = $this->getInitModule($type,$is_custom,$is_list);
$main_css = "<style id='globalsojs-styles'></style>";
}else{
$main_html = $mainInfo['main_html'];
$main_css = $mainInfo['main_css'];
}
return ['main_html'=>$main_html,'main_css'=>$main_css];
}
/**
* @remark :默认复合页数据
* @name :getProductModule
* @author :lyh
* @method :post
* @time :2023/7/27 15:08
*/
public function getInitModule($type,$is_custom,$is_list){
if($is_custom == BTemplate::IS_CUSTOM) {
$type = BTemplate::SOURCE_CUSTOM;
}
$mainModel = new TemplateTypeMain();
$info = $mainModel->read(['type'=>$type,'is_list'=>$is_list]);
return $info['main_html'];
}
/**
* @remark :返回整个html截取代码
* @name :handleAllHtml
* @author :lyh
* @method :post
* @time :2023/12/13 15:39
*/
public function handleAllHtml($commonInfo,$html){
if(!empty($commonInfo)){
$html = preg_replace('/<header\b[^>]*>(.*?)<\/header>/s', $commonInfo['head_html'], $html);
$html = preg_replace('/<footer\b[^>]*>(.*?)<\/footer>/s', $commonInfo['footer_html'], $html);
$html = preg_replace('/<style id="globalsojs-header">(.*?)<\/style>/s', $commonInfo['head_css'], $html);
$html = preg_replace('/<style id="globalsojs-footer">(.*?)<\/style>/s', $commonInfo['footer_css'], $html);
}
return $html;
}
/**
* @remark :页面是否为定制页面获取初始代码
* @name :watchProjectIsCustomized
* @author :lyh
* @method :post
* @time :2023/12/13 10:55
*/
public function isCustomizedPage($projectInfo,$source,$is_list,$is_custom)
{
$type = $this->getCustomizedType($source, $is_list);//获取定制界面类型
//查看当前页面是否定制,是否开启可视化
$page_array = (array)$projectInfo['is_visualization']->page_array;//获取所有定制界面
if (in_array($type, $page_array)) {//是定制界面
//TODO::获取初始代码
$bTemplateMainModel = new BTemplateMain();
$customHtmlInfo = $bTemplateMainModel->read(['type'=>$source,'is_custom'=>$is_custom,'is_list'=>$is_list]);
if($customHtmlInfo === false){
return false;
}
$commonInfo = $this->getCustomizedCommonHtml($type,$is_custom,$is_list);//获取定制头部
if($commonInfo !== false){
$customHtmlInfo['main_html'] = $this->handleAllHtml($commonInfo,$customHtmlInfo['main_html']);
}
return $customHtmlInfo['main_html'];
}
return false;
}
/**
* @remark :定制项目获取头部底部
* @name :getCustomizedCommonHtml
* @author :lyh
* @method :post
* @time :2023/12/29 13:13
*/
public function getCustomizedCommonHtml($type,$is_custom = 0,$is_list = 0){
$data = [
'template_id' => 0,
'project_id' => $this->project_id,
'type'=>$type,
'is_custom'=>$is_custom,
'is_list'=>$is_list
];
$commonTemplateModel = new BTemplateCommon();
return $commonTemplateModel->read($data);
}
/**
* @remark :定制页面头部类型---根据source获取type类型
* @name :getType
* @author :lyh
* @method :post
* @time :2023/11/16 11:20
*/
public function getCustomizedType($source,$is_list){
$type = BTemplate::TYPE_HOME;
if($source == BTemplate::SOURCE_PRODUCT){
if($is_list == BTemplate::IS_LIST){
$type = BTemplate::TYPE_PRODUCT_LIST;
}else{
$type = BTemplate::TYPE_PRODUCT_DETAIL;
}
}
if($source == BTemplate::SOURCE_BLOG){
if($is_list == BTemplate::IS_LIST){
$type = BTemplate::TYPE_BLOG_LIST;
}else{
$type = BTemplate::TYPE_BLOG_DETAIL;
}
}
if($source == BTemplate::SOURCE_NEWS){
if($is_list == BTemplate::IS_LIST){
$type = BTemplate::TYPE_NEWS_LIST;
}else{
$type = BTemplate::TYPE_NEWS_DETAIL;
}
}
return $type;
}
/**
* @remark :获取当前项目设置的模版
* @name :getSettingTemplate
* @author :lyh
* @method :post
* @time :2023/12/13 10:48
*/
public function getSettingTemplate($projectInfo,$source,$is_list,$is_custom){
$template_id = 0;
if($projectInfo['is_customized'] == BTemplate::IS_VISUALIZATION) {//定制项目
if($is_custom == BTemplate::IS_CUSTOM){
$customModuleModel = new CustomModule();
$info = $customModuleModel->read(['id'=>$source]);
if($info === false){
return false;
}
if($info['list_customized'] == BTemplate::IS_VISUALIZATION && $is_list == BTemplate::IS_LIST){
return $this->success($template_id);
}
if($info['detail_customized'] == BTemplate::IS_VISUALIZATION && $is_list == BTemplate::IS_DETAIL){
return $this->success($template_id);
}
}else{
$type = $this->getCustomizedType($source, $is_list);//获取定制界面类型
//查看当前页面是否定制,是否开启可视化
$page_array = (array)$projectInfo['is_visualization']->page_array;//获取所有定制界面
if (in_array($type, $page_array)) {//是定制界面
return $this->success($template_id);
}
}
}
$bSettingModel = new Setting();
$info = $bSettingModel->read(['project_id'=>$this->project_id]);
if($info === false){
return false;
}
$template_id = $info['template_id'];
return $this->success($template_id);
}
/**
* @remark :根据类型获取公共头和底
* @name :getCommonPage
* @author :lyh
* @method :post
* @time :2023/10/21 16:55
*/
public function getCommonHtml($ProjectInfo,$source,$is_list,$template_id,$is_custom = 0,){
$type = $this->getType($ProjectInfo,$source,$is_list,$is_custom);
$data = [
'template_id' => $template_id,
'project_id' => $this->project_id,
'type'=>$type,
'is_custom'=>0,
];
$commonTemplateModel = new BTemplateCommon();
$commonInfo = $commonTemplateModel->read($data);
if($commonInfo === false){
$data['type'] = BTemplate::SOURCE_HOME;
$commonInfo = $commonTemplateModel->read($data);
}
return $this->success($commonInfo);
}
/**
* @remark :(非定制)保存时获取获取设置的类型
* @name :getType
* @author :lyh
* @method :post
* @time :2023/10/21 17:29
*/
public function getType($projectInfo,$source,$is_list,$is_custom = 0){
$type = BTemplate::SOURCE_HOME;//首页公共头部底部
$is_head = $projectInfo['deploy_build']['configuration']['is_head'] ?? BTemplate::IS_NO_HEADER;
if($is_custom == BTemplate::IS_CUSTOM){//拓展模块为首页头部
return $this->success($type);
}
//查看页面是否设置自定义头部底部
if($is_head != BTemplate::IS_NO_HEADER) {
$pageSettingModel = new PageSetting();
$pageInfo = $pageSettingModel->read(['project_id' => $projectInfo['id']]);
if ($pageInfo === false) {
return $this->success($type);
}
if ($source == BTemplate::SOURCE_PRODUCT) {if ($is_list != BTemplate::IS_LIST) {if ($pageInfo['product_details'] != 0) {$type = BTemplate::TYPE_PRODUCT_DETAIL;}}
else {if ($pageInfo['product_list'] != 0) {$type = BTemplate::TYPE_PRODUCT_LIST;}}}
if ($source == BTemplate::SOURCE_BLOG) {if ($is_list != BTemplate::IS_LIST) {if ($pageInfo['blog_details'] != 0) {$type = BTemplate::TYPE_BLOG_DETAIL;}}
else {if ($pageInfo['blog_list'] != 0) {$type = BTemplate::TYPE_BLOG_LIST;}}}
if ($source == BTemplate::SOURCE_NEWS) {if ($is_list != BTemplate::IS_LIST) {if ($pageInfo['news_details'] != 0) {$type = BTemplate::TYPE_NEWS_DETAIL;}}
else {if ($pageInfo['news_list'] != 0) {$type = BTemplate::TYPE_NEWS_LIST;}}}
if ($source == BTemplate::SOURCE_KEYWORD) {if ($pageInfo['polymerization'] != 0) {$type = BTemplate::TYPE_CUSTOM_PAGE;}}
}
return $this->success($type);
}
}
此 diff 太大无法显示。
<?php
namespace App\Services;
namespace App\Services\Html;
use App\Models\Blog\Blog;
use App\Models\Blog\BlogCategory;
use App\Models\CustomModule\CustomModule;
use App\Models\CustomModule\CustomModuleCategory;
use App\Models\Module\Module;
use App\Models\Module\ModuleCategory;
use App\Models\News\News;
use App\Models\News\NewsCategory;
use App\Models\Product\Category;
use App\Models\Product\Keyword;
use App\Models\RouteMap\RouteMap;
use App\Models\Template\BCustomTemplate;
use App\Models\WebSetting\WebCustom;
use App\Models\WebSetting\WebSetting;
use App\Models\WebSetting\WebSettingSeo;
use Illuminate\Support\Facades\Cache;
use App\Models\WebSetting\WebTemplateCommon;
use phpQuery;
/**
... ... @@ -27,52 +24,54 @@ class TdkService{
/**
* 页面TDK处理
*/
public function pageTdkHandle($projectInfo,$html,$type,$routerMapInfo=null): string
public function pageTdkHandle($project,$html,$type,$routerMap=null): string
{
$titleContent = "";
$descriptionContent = "";
$keywordsContent = "";
$phpQueryDom=phpQuery::newDocument($html);
//首页TDK设置
if ($type == RouteMap::SOURCE_INDEX){
$tdkInfo = $this->indexTDK($projectInfo);
if ($type == WebTemplateCommon::$indexName){
$tdkInfo = $this->indexTDK($project);
}
//单页面TDK设置
if ($type == RouteMap::SOURCE_PAGE){
$tdkInfo = $this->pageTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$pageName){
$tdkInfo = $this->pageTDK($project,$routerMap);
}
//自定义模块列表页TDK设置
if ($type == RouteMap::SOURCE_MODULE_CATE){
$tdkInfo = $this->moduleCategoryTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$extendCategoryName){
$tdkInfo = $this->moduleCategoryTDK($project,$routerMap);
}
//自定义模块详情页TDK设置
if ($type == RouteMap::SOURCE_MODULE){
$tdkInfo = $this->moduleDetailsTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$extendName){
$tdkInfo = $this->moduleDetailsTDK($project,$routerMap);
}
//新闻详情TDK设置
if ($type == RouteMap::SOURCE_NEWS){
$tdkInfo = $this->newsDetailsTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$newsName){
$tdkInfo = $this->newsDetailsTDK($project,$routerMap);
}
//博客详情TDK设置
if ($type == RouteMap::SOURCE_BLOG){
$tdkInfo = $this->blogDetailsTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$blogName){
$tdkInfo = $this->blogDetailsTDK($project,$routerMap);
}
//聚合页TDK设置
if ($type == RouteMap::SOURCE_PRODUCT_KEYWORD){
$tdkInfo = $this->productKeywordsTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$productKeywordName){
$tdkInfo = $this->productKeywordsTDK($project,$routerMap);
}
//新闻列表页TDK设置
if ($type == RouteMap::SOURCE_NEWS_CATE){
$tdkInfo = $this->newsCategoryTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$newsCategoryName){
$tdkInfo = $this->newsCategoryTDK($project,$routerMap);
}
//博客列表页TDK设置
if ($type == RouteMap::SOURCE_BLOG_CATE){
$tdkInfo = $this->blogCategoryTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$blogCategoryName){
$tdkInfo = $this->blogCategoryTDK($project,$routerMap);
}
//产品列表页TDK设置
if ($type == RouteMap::SOURCE_PRODUCT_CATE){
$tdkInfo = $this->productCategoryTDK($projectInfo,$routerMapInfo);
if ($type == WebTemplateCommon::$productCategoryName){
$tdkInfo = $this->productCategoryTDK($project,$routerMap);
}
if (!empty($tdkInfo)){
$titleContent = strip_tags($tdkInfo["titleContent"]);
$descriptionContent = strip_tags($tdkInfo["descriptionContent"]);
... ... @@ -84,6 +83,7 @@ class TdkService{
$phpQueryDom->find('head')->append("<meta property='og:title' content='".$titleContent."'/>");
$phpQueryDom->find('head')->append("<meta property='og:type' content='site'/>");
$phpQueryDom->find('head')->append("<meta property='og:site_name' content='".$titleContent."'/>");
$content = $phpQueryDom->htmlOuter();
unset($html,$tdkInfo,$phpQueryDom);
phpQuery::unloadDocuments();
... ... @@ -93,14 +93,14 @@ class TdkService{
/**
* 首页TDK
*/
public function indexTDK($projectInfo): array
public function indexTDK($project): array
{
$tdkInfo = [];
$webSettingInfo = $this->getWebSetting($projectInfo);
if (!empty($webSettingInfo)){
$titleContent = strip_tags($webSettingInfo['title']);
$descriptionContent = strip_tags($webSettingInfo['remark']);
$keywordsContent = strip_tags($webSettingInfo['keyword']);
$webSetting = WebSetting::getWebSetting($project);
if (!empty($webSetting)){
$titleContent = strip_tags($webSetting->title);
$descriptionContent = strip_tags($webSetting->remark);
$keywordsContent = strip_tags($webSetting->keyword);
$tdkInfo["titleContent"] = $titleContent;
$tdkInfo["descriptionContent"] = $descriptionContent;
$tdkInfo["keywordsContent"] = $keywordsContent;
... ... @@ -109,56 +109,37 @@ class TdkService{
}
/**
* 网站设置
*/
public function getWebSetting($projectInfo)
{
if (Cache::get("project_".$projectInfo['id']."_web_setting") == null) {
$webSettingModel = new WebSetting();
$webSettingInfo = $webSettingModel->read(['project_id'=>$projectInfo['id']]);
if ($webSettingInfo !== false) {
Cache::add("project_".$projectInfo['id']."_web_setting", json_encode($webSettingInfo));
return $webSettingInfo;
}
return [];
}
return (array)json_decode(Cache::get("project_".$projectInfo['id']."_web_setting"));
}
/**
* 新闻列表页TDK
*/
public function newsCategoryTDK($projectInfo,$routerMapInfo): array
public function newsCategoryTDK($project,$routerMap): array
{
$tdkInfo = [];
$pageSuffix = "";
$webSetting = $this->getWebSetting($projectInfo);
$newsCategoryModel = new NewsCategory();
$newsCategoryInfo = $newsCategoryModel->read(['project_id'=>$projectInfo['id'],'id'=>$routerMapInfo['source_id']]);
$webSetting = WebSetting::getWebSetting($project);
$newsCategory = NewsCategory::where("project_id",$project->id)->where("id",$routerMap->source_id)->first();
//seo拼接
$webSeoModel = new WebSettingSeo();
$webSeoInfo = $webSeoModel->read(['project_id'=>$projectInfo['id']]);
if ($webSeoInfo !== false){
$pageSuffix = !empty($webSeoInfo['single_page_suffix']) ? " ".$webSeoInfo['single_page_suffix'] : "";
$webSeo = WebSettingSeo::where("project_id",$project->id)->first();
if (!empty($webSeo)){
$pageSuffix = !empty($webSeo->single_page_suffix) ? " ".$webSeo->single_page_suffix : "";
}
if ($newsCategoryInfo !== false){
if (!empty($newsCategory)){
//title
if (!empty($newsCategoryInfo['seo_title'])){
$titleContent = $newsCategoryInfo['seo_title'].$pageSuffix;
if (!empty($newsCategory->seo_title)){
$titleContent = $newsCategory->seo_title.$pageSuffix;
}else{
$titleContent = $newsCategoryInfo['name'].$pageSuffix;
$titleContent = $newsCategory->name.$pageSuffix;
}
//description
if (!empty($newsCategoryInfo['seo_des'])){
$descriptionContent = $newsCategoryInfo['seo_des'];
if (!empty($newsCategory->seo_des)){
$descriptionContent = $newsCategory->seo_des;
}else{
$descriptionContent = !empty($webSetting['remark']) ? $webSetting['remark'] : "";
$descriptionContent = !empty($webSetting->remark) ? $webSetting->remark : "";
}
//keyword
if (!empty($newsCategoryInfo['seo_keywords'])){
$keywordsContent = $newsCategoryInfo['seo_keywords'];
if (!empty($newsCategory->seo_keywords)){
$keywordsContent = $newsCategory->seo_keywords;
}else{
$keywordsContent = !empty($webSetting['keyword']) ? $webSetting['keyword'] : "";
$keywordsContent = !empty($webSetting->keyword) ? $webSetting->keyword : "";
}
$tdkInfo["titleContent"] = $titleContent;
$tdkInfo["descriptionContent"] = $descriptionContent;
... ... @@ -170,37 +151,35 @@ class TdkService{
/**
* 博客列表页TDK
*/
public function blogCategoryTDK($projectInfo,$routerMapInfo): array
public function blogCategoryTDK($project,$routerMap): array
{
$tdkInfo = [];
$pageSuffix = "";
$webSetting = $this->getWebSetting($projectInfo);
$blogCategoryModel = new BlogCategory();
$blogCategoryInfo = $blogCategoryModel->read(['project_id'=>$projectInfo['id'],'id'=>$routerMapInfo['source_id']]);
$webSetting = WebSetting::getWebSetting($project);
$newsCategory = BlogCategory::where("project_id",$project->id)->where("id",$routerMap->source_id)->first();
//seo拼接
$webSeoModel = new WebSettingSeo();
$webSeoInfo = $webSeoModel->read(['project_id'=>$projectInfo['id']]);
if ($webSeoInfo !== false){
$pageSuffix = !empty($webSeoInfo['single_page_suffix']) ? " ".$webSeoInfo['single_page_suffix'] : "";
$webSeo = WebSettingSeo::where("project_id",$project->id)->first();
if (!empty($webSeo)){
$pageSuffix = !empty($webSeo->single_page_suffix) ? " ".$webSeo->single_page_suffix : "";
}
if ($blogCategoryInfo !== false){
if (!empty($newsCategory)){
//title
if (!empty($blogCategoryInfo['seo_title'])){
$titleContent = $blogCategoryInfo['seo_title'].$pageSuffix;
if (!empty($newsCategory->seo_title)){
$titleContent = $newsCategory->seo_title.$pageSuffix;
}else{
$titleContent = $blogCategoryInfo['name'].$pageSuffix;
$titleContent = $newsCategory->name.$pageSuffix;
}
//description
if (!empty($blogCategoryInfo['seo_des'])){
$descriptionContent = $blogCategoryInfo['seo_des'];
if (!empty($newsCategory->seo_des)){
$descriptionContent = $newsCategory->seo_des;
}else{
$descriptionContent = !empty($webSetting['remark']) ? $webSetting['remark'] : "";
$descriptionContent = !empty($webSetting->remark) ? $webSetting->remark : "";
}
//keyword
if (!empty($blogCategoryInfo['seo_keywords'])){
$keywordsContent = $blogCategoryInfo['seo_keywords'];
if (!empty($newsCategory->seo_keywords)){
$keywordsContent = $newsCategory->seo_keywords;
}else{
$keywordsContent = !empty($webSetting['keyword']) ? $webSetting['keyword'] : "";
$keywordsContent = !empty($webSetting->keyword) ? $webSetting->keyword : "";
}
$tdkInfo["titleContent"] = $titleContent;
$tdkInfo["descriptionContent"] = $descriptionContent;
... ... @@ -212,45 +191,46 @@ class TdkService{
/**
* 产品列表页TDK
*/
public function productCategoryTDK($projectInfo,$routerMapInfo): array
public function productCategoryTDK($project,$routerMap): array
{
$tdkInfo = [];
$prefix = "";
$suffix = "";
$pageSuffix = "";
$webSettingTitle = "";
$webSettingDescription = "";
$webSettingKeyword = "";
$projectCategoryModel = new Category();
$projectCategoryInfo = $projectCategoryModel->read(['project_id'=>$projectInfo['id'],'id'=>$routerMapInfo['source_id']]);
$webSetting = $this->getWebSetting($projectInfo);
$productCategory = Category::where("project_id",$project->id)->where("id",$routerMap->source_id)->first();
$webSetting = WebSetting::getWebSetting($project);
//seo拼接
$webSeoModel = new WebSettingSeo();
$webSeoInfo = $webSeoModel->read(['project_id'=>$projectInfo['id']]);
if ($webSeoInfo !== false){
$prefix = !empty($webSeoInfo['product_cate_prefix']) ? $webSeoInfo['product_cate_prefix']." " : "";
$suffix = !empty($webSeoInfo['product_cate_suffix']) ? " ".$webSeoInfo['product_cate_suffix'] : "";
$webSeo = WebSettingSeo::where("project_id",$project->id)->first();
if (!empty($webSeo)){
$prefix = !empty($webSeo->product_cate_prefix) ? $webSeo->product_cate_prefix." " : "";
$suffix = !empty($webSeo->product_cate_suffix) ? " ".$webSeo->product_cate_suffix : "";
$pageSuffix = !empty($webSeo->single_page_suffix) ? " ".$webSeo->single_page_suffix : "";
}
if ($webSetting !== false){
$webSettingTitle = !empty($webSetting['title']) ? $webSetting['title'] : "";
$webSettingDescription = !empty($webSetting['remark']) ? $webSetting['remark'] : "";
$webSettingKeyword = !empty($webSetting['keyword']) ? $webSetting['keyword'] : "";
if (!empty($webSetting)){
$webSettingTitle = !empty($webSetting->title) ? $webSetting->title : "";
$webSettingDescription = !empty($webSetting->remark) ? $webSetting->remark : "";
$webSettingKeyword = !empty($webSetting->keyword) ? $webSetting->keyword : "";
}
if ($projectCategoryInfo !== false){
if (!empty($productCategory)){
//title
if (!empty($projectCategoryInfo['seo_title'])){
$titleContent = $prefix.$projectCategoryInfo['seo_title'].$suffix;
if (!empty($productCategory->seo_title)){
$titleContent = $prefix.$productCategory->seo_title.$suffix;
}else{
$titleContent = $prefix.$webSettingTitle.$suffix;
}
//description
if (!empty($projectCategoryInfo['seo_des'])){
$descriptionContent = $projectCategoryInfo['seo_des'];
if (!empty($productCategory->seo_des)){
$descriptionContent = $productCategory->seo_des;
}else{
$descriptionContent = $webSettingDescription;
}
//keywords
if (!empty($projectCategoryInfo['seo_keywords'])){
$keywordsContent = $projectCategoryInfo['seo_keywords'];
if (!empty($productCategory->seo_keywords)){
$keywordsContent = $productCategory->seo_keywords;
}else{
$keywordsContent = $webSettingKeyword;
}
... ... @@ -268,22 +248,22 @@ class TdkService{
/**
* 产品聚合页TDK
*/
public function productKeywordsTDK($projectInfo,$routerMapInfo): array
public function productKeywordsTDK($project,$routerMap): array
{
$tdkInfo = [];
$keywordModel = new Keyword();
$keywordInfo = $keywordModel->read(['project_id'=>$projectInfo['id'],'id'=>$routerMapInfo['source_id']]);
if ($keywordInfo !== false){
$keyword = Keyword::where("project_id",$project->id)->where("status",1)->where("id",$routerMap->source_id)->first();
if (!empty($keyword)){
//处理title
$title = $keywordInfo['seo_title'] ?: $keywordInfo['title'];
$title = $keyword->seo_title ?: $keyword->title;
//seo拼接
$webSeoModel = new WebSettingSeo();
$webSeoInfo = $webSeoModel->read(['project_id'=>$projectInfo['id']]);
$titleContent = $webSeoInfo ? $webSeoInfo['tab_prefix'] . " " . $title . " " . $webSeoInfo['tab_suffix'] : $title;
$webSeo = WebSettingSeo::where("project_id",$project->id)->first();
$titleContent = $webSeo ? $webSeo->tab_prefix . " " . $title . " " . $webSeo->tab_suffix : $title;
//处理description
$descriptionContent = $keywordInfo['seo_description'] ?: $keywordInfo['title'];
$descriptionContent = $keyword->seo_description ?: $keyword->title;
//处理keywords
$keywordsContent = $keywordInfo['seo_keywords'] ?: $keywordInfo['title'];
$keywordsContent = $keyword->seo_keywords ?: $keyword->title;
$tdkInfo["titleContent"] = $titleContent;
$tdkInfo["descriptionContent"] = $descriptionContent;
... ... @@ -295,51 +275,49 @@ class TdkService{
/**
* 新闻详情页TDK
*/
public function newsDetailsTDK($projectInfo,$routerMapInfo): array
public function newsDetailsTDK($project,$routerMap): array
{
$tdkInfo = [];
$titleContent = "";
$keywordsContent = "";
$descriptionContent = "";
$newsModel = new News();
$newsInfo = $newsModel->read(['project_id'=>$projectInfo['id'],'id'=>$routerMapInfo['source_id'],'status'=>1]);
return $this->newsBlogTdk($newsInfo, $projectInfo, $titleContent, $descriptionContent, $keywordsContent, $tdkInfo);
$data = News::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->first();
return $this->newsBlogTdk($data, $project, $titleContent, $descriptionContent, $keywordsContent, $tdkInfo);
}
/**
* 新闻详情页TDK
*/
public function blogDetailsTDK($projectInfo,$routerMapInfo): array
public function blogDetailsTDK($project,$routerMap): array
{
$tdkInfo = [];
$titleContent = "";
$keywordsContent = "";
$descriptionContent = "";
$blogMode = new Blog();
$blogInfo = $blogMode->read(['project_id'=>$projectInfo['id'],'id'=>$routerMapInfo['source_id'],'status'=>1]);
return $this->newsBlogTdk($blogInfo, $projectInfo, $titleContent, $descriptionContent, $keywordsContent, $tdkInfo);
$data = Blog::where("project_id",$project->id)->where("id",$routerMap->source_id)->where("status",1)->first();
return $this->newsBlogTdk($data, $project, $titleContent, $descriptionContent, $keywordsContent, $tdkInfo);
}
/**
* 自定义模块列表页TDK
*/
public function moduleDetailsTDK($projectInfo,$routerMapInfo): array
public function moduleDetailsTDK($project,$routerMap): array
{
$tdkInfo = [];
$moduleModel = new CustomModule();
$moduleInfo = $moduleModel->read(['project_id'=>$projectInfo['id'],'id'=>$routerMapInfo['source_id'],'status'=>0]);
$webSetting = $this->getWebSetting($projectInfo);
if ($moduleInfo !== false){
$moduleInfo = Module::where("project_id",$project->id)->where("status",0)->where("id",$routerMap->source_id)->first();
$webSetting = WebSetting::getWebSetting($project);
if (!empty($moduleInfo)){
//title
$webSettingTitle = !empty($webSetting['title']) ? $webSetting['title'] : "";
$titleContent = !empty($moduleInfo['seo_title']) ? $moduleInfo['seo_title'] : $webSettingTitle;
$webSettingTitle = !empty($webSetting->title) ? $webSetting->title : "";
$titleContent = !empty($moduleInfo->seo_title) ? $moduleInfo->seo_title : $webSettingTitle;
//description
$webSettingDescription = !empty($webSetting['remark']) ? $webSetting['remark'] : "";
$descriptionContent = !empty($moduleInfo['seo_description']) ? $moduleInfo['seo_description'] : $webSettingDescription;
$webSettingDescription = !empty($webSetting->remark) ? $webSetting->remark : "";
$descriptionContent = !empty($moduleInfo->seo_description) ? $moduleInfo->seo_description : $webSettingDescription;
//keywords
$webSettingKeyword = !empty($webSetting['keyword']) ? $webSetting['keyword'] : "";
$keywordsContent = !empty($moduleInfo['seo_keywords']) ? $moduleInfo['seo_keywords'] : $webSettingKeyword;
$webSettingKeyword = !empty($webSetting->keyword) ? $webSetting->keyword : "";
$keywordsContent = !empty($moduleInfo->seo_keywords) ? $moduleInfo->seo_keywords : $webSettingKeyword;
$tdkInfo["titleContent"] = $titleContent;
$tdkInfo["descriptionContent"] = $descriptionContent;
$tdkInfo["keywordsContent"] = $keywordsContent;
... ... @@ -350,24 +328,23 @@ class TdkService{
/**
* 自定义模块列表页TDK
*/
public function moduleCategoryTDK($projectInfo,$routerMapInfo): array
public function moduleCategoryTDK($project,$routerMap): array
{
$tdkInfo = [];
$moduleCategoryModel = new CustomModuleCategory();
$moduleCategoryInfo = $moduleCategoryModel->read(['project_id'=>$projectInfo['id'],'id'=>$routerMapInfo['source_id']]);
$webSetting = $this->getWebSetting($projectInfo);
if ($moduleCategoryInfo !== false){
$moduleCategoryInfo = ModuleCategory::getModuleCategoryAndExtendByRoute($project->id,$routerMap->route);
$webSetting = WebSetting::getWebSetting($project);
if (!empty($moduleCategoryInfo)){
//title
$webSettingTitle = !empty($webSetting['title']) ? $webSetting['title'] : "";
$titleContent = !empty($moduleCategoryInfo['seo_title']) ? $moduleCategoryInfo['seo_title'] : $webSettingTitle;
$webSettingTitle = !empty($webSetting->title) ? $webSetting->title : "";
$titleContent = !empty($moduleCategoryInfo->seo_title) ? $moduleCategoryInfo->seo_title : $webSettingTitle;
//description
$webSettingDescription = !empty($webSetting['remark']) ? $webSetting['remark'] : "";
$descriptionContent = !empty($moduleCategoryInfo['seo_description']) ? $moduleCategoryInfo['seo_description'] : $webSettingDescription;
$webSettingDescription = !empty($webSetting->remark) ? $webSetting->remark : "";
$descriptionContent = !empty($moduleCategoryInfo->seo_description) ? $moduleCategoryInfo->seo_description : $webSettingDescription;
//keywords
$webSettingKeyword = !empty($webSetting['keyword']) ? $webSetting['keyword'] : "";
$keywordsContent = !empty($moduleCategoryInfo['seo_keywords']) ? $moduleCategoryInfo['seo_keywords'] : $webSettingKeyword;
$webSettingKeyword = !empty($webSetting->keyword) ? $webSetting->keyword : "";
$keywordsContent = !empty($moduleCategoryInfo->seo_keywords) ? $moduleCategoryInfo->seo_keywords : $webSettingKeyword;
$tdkInfo["titleContent"] = $titleContent;
$tdkInfo["descriptionContent"] = $descriptionContent;
$tdkInfo["keywordsContent"] = $keywordsContent;
... ... @@ -378,49 +355,48 @@ class TdkService{
/**
* 单页面TDK
*/
public function pageTDK($projectInfo,$routerMapInfo): array
public function pageTDK($project,$routerMap): array
{
$tdkInfo = [];
if (!empty($routerMap)){
$customModel = new BCustomTemplate();
$webCustomInfo = $customModel->read(['id'=>$routerMapInfo['source_id'],'status'=>1]);
$webCustom = WebCustom::where("id",$routerMap->source_id)->where("status",1)->first();
//seo拼接
$webSeoModel = new WebSettingSeo();
$webSeoInfo = $webSeoModel->read(['project_id'=>$projectInfo['id']]);
$webSeo = WebSettingSeo::where("project_id",$project->id)->first();
//网站设置
$webSetting = $this->getWebSetting($projectInfo);
$webSetting = WebSetting::getWebSetting($project);
$titleContent = "";
$descriptionContent = "";
$keywordsContent = "";
if ($webCustomInfo !== false){
if (!empty($webCustom)){
//title
if ($webCustomInfo['title'] == null){
if ($webCustom->title == null){
if (!empty($webSeo)){
$titleContent = $webCustomInfo['name']." ".$webSeoInfo['single_page_suffix'];
$titleContent = $webCustom->name." ".$webSeo->single_page_suffix;
}else{
$titleContent = $webCustomInfo['name'];
$titleContent = $webCustom->name;
}
}else{
if (!empty($webSeo)){
$titleContent = $webCustomInfo['title']." ".$webSeoInfo['single_page_suffix'];
$titleContent = $webCustom->title." ".$webSeo->single_page_suffix;
}else{
$titleContent = $webCustomInfo['title'];
$titleContent = $webCustom->title;
}
}
//keywords
if ($webCustomInfo['keywords'] == null){
if ($webCustom->keywords == null){
if (!empty($webSetting)){
$keywordsContent = $webSetting['keyword'];
$keywordsContent = $webSetting->keyword;
}
}else{
$keywordsContent = $webSetting['keywords'];
$keywordsContent = $webCustom->keywords;
}
//description
if ($webCustomInfo['description'] == null){
if ($webCustom->description == null){
if (!empty($webSetting)) {
$descriptionContent = $webSetting['remark'];
$descriptionContent = $webSetting->remark;
}
}else{
$descriptionContent = $webCustomInfo['description'];
$descriptionContent = $webCustom->description;
}
$tdkInfo["titleContent"] = $titleContent;
$tdkInfo["descriptionContent"] = $descriptionContent;
... ... @@ -433,33 +409,33 @@ class TdkService{
/**
* 新闻博客详情通用版块
*/
public function newsBlogTdk($info, $projectInfo, $titleContent, $descriptionContent, $keywordsContent, array $tdkInfo): array
public function newsBlogTdk($data, $project, string $titleContent, $descriptionContent, $keywordsContent, array $tdkInfo): array
{
if (!empty($info)) {
if (!empty($data)) {
//处理title
//seo拼接
$pageSuffix = "";
$webSeoModel = new WebSettingSeo();
$webSeoInfo = $webSeoModel->read(['project_id'=>$projectInfo['id']]);
$webSetting = $this->getWebSetting($projectInfo);
if (!empty($webSeoInfo)) {
$pageSuffix = !empty($webSeo['single_page_suffix']) ? " " . $webSeo['single_page_suffix'] : "";
$webSeo = WebSettingSeo::where("project_id", $project->id)->first();
$webSetting = WebSetting::getWebSetting($project);
if (!empty($webSeo)) {
$pageSuffix = !empty($webSeo->single_page_suffix) ? " " . $webSeo->single_page_suffix : "";
}
if ($info['seo_title'] == null) {
$titleContent = !empty($info['name']) ? $info['name'] . $pageSuffix : "";
if ($data->seo_title == null) {
$titleContent = !empty($data->name) ? $data->name . $pageSuffix : "";
} else {
$titleContent = $info['seo_title'] . $pageSuffix;
$titleContent = $data->seo_title . $pageSuffix;
}
//处理description
if ($info['seo_description'] == null) {
$descriptionContent = !empty($webSetting['remark']) ? $webSetting['remark'] : "";
if ($data->seo_description == null) {
$descriptionContent = !empty($webSetting->remark) ? $webSetting->remark : "";
} else {
$descriptionContent = $info['seo_description'];
$descriptionContent = $data->seo_description;
}
//处理keywords
if ($info['seo_keywords'] == null) {
$keywordsContent = !empty($webSetting['keyword']) ? $webSetting['keyword'] : "";
if ($data->seo_keywords == null) {
$keywordsContent = !empty($webSetting->keyword) ? $webSetting->keyword : "";
} else {
$keywordsContent = $info['seo_keywords'];
$keywordsContent = $data->seo_keywords;
}
$tdkInfo["titleContent"] = $titleContent;
$tdkInfo["descriptionContent"] = $descriptionContent;
... ...
<?php
namespace App\Services\Html;
use App\Models\Project\UpdateLog;
use App\Models\Project\UpdateOldInfo;
class UpdateService
{
/**
* 获取项目升级情况
* @param $project_id
* @param $domain
* @return array
* @author Akun
* @date 2023/12/01 10:32
*/
public static function getUpdateInfo($project_id)
{
$is_update = 0;
$is_language_update = 0;
$old_domain_online = $old_domain_test = '';
$update_info = UpdateLog::where('project_id', $project_id)->whereNotIn('api_type', ['category', 'website_info', 'tag', 'category_news'])->get();
if ($update_info->count() > 0) {
$is_update = 1;
$is_language_update = 1;
foreach ($update_info as $value) {
if ($value->collect_status != 1) {
$is_language_update = 0;
}
if ($value->collect_status == 0) {
$is_update = 0;
}
}
$old_domain_arr = parse_url($update_info[0]['api_url']);
$old_info = self::getOldInfo($project_id, $old_domain_arr['host']);
$old_domain_test = $old_info['old_domain_test'];
$old_domain_online = $old_info['old_domain_online'];
}
return [
'is_update' => $is_update,
'is_language_update' => $is_language_update,
'old_domain_test' => $old_domain_test,
'old_domain_online' => $old_domain_online
];
}
public static function getOldInfo($project_id, $domain)
{
$return = [
'old_domain_test' => $domain,
'old_domain_online' => $domain
];
$info = UpdateOldInfo::where('project_id', $project_id)->first();
if (!$info) {
$url_web_config = 'https://' . $domain . '/wp-content/cache/user_config.text';
$data_config = [];
try {
$data_config = self::curlGet($url_web_config);
} catch (\Exception $e) {
}
if ($data_config) {
$link_type = $data_config['link_type'] ?? 0;
$home_url_arr = parse_url($data_config['home_url'] ?? '');
$old_domain_test = $home_url_arr['host'] ?? '';
$web_url_arr = parse_url($data_config['web_url_domain'] ?? '');
$old_domain_online = $web_url_arr['host'] ?? '';
if ($old_domain_test || $old_domain_online) {
$info = new UpdateOldInfo();
$info->project_id = $project_id;
$info->link_type = $link_type;
$info->old_domain_test = $old_domain_test ?: $domain;
$info->old_domain_online = $old_domain_online ?: $domain;
$info->save();
}
$old_domain_test && $return['old_domain_test'] = $old_domain_test;
$old_domain_online && $return['old_domain_test'] = $old_domain_online;
}
} else {
$return['old_domain_test'] = $info['old_domain_test'];
$return['old_domain_online'] = $info['old_domain_online'];
}
return $return;
}
/**
* 远程请求
* @param $url
* @return mixed
* @author Akun
* @date 2023/11/29 14:23
*/
public static function curlGet($url)
{
$header = array(
'Expect:',
'Content-Type: application/json; charset=utf-8'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246');
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSLVERSION, 'all');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$content = curl_exec($ch);
curl_close($ch);
return json_decode($content, true);
}
}
... ...
<?php
namespace App\Services\Html;
use App\Console\Commands\ProjectService;
use App\Helper\Str;
use App\Helper\Translate;
use App\Models\Devops\ServerConfig;
use App\Models\Project\DeployOptimize;
use App\Models\Project\DomainInfo;
use App\Models\Project\Project;
use App\Models\Project\UpdateMasterWebsiteModel;
use App\Models\Project\UpdateMinorLanguagesModel;
use App\Models\Project\UpdateProgressModel;
use App\Models\RouteMap;
use App\Models\WebSetting\WebSetting;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* WebInfo服务
*/
class WebInfoService{
const SUCCESS = 200;
const ERROR = 400;
protected $header = [];//设置请求头参数
/**
* 手动清除网站缓存
*/
public function clearCache(Request $request,$domain='')
{
$project = null;
if ($domain == ''){
$domain = $request->getHost();
}
$projectDomain = Project::getProjectByDomain($domain);
if (!empty($projectDomain)){
$project = Project::where("id",$projectDomain->project_id)->first();
if (isset($projectDomain->test_domain)){
$project->domain = $projectDomain->test_domain;
}
if (empty($project)){
return $this->response("success",WebSetting::$errStatus,"no project");
}
}
if(Str::contains($domain, 'globalso.site')){
$domainTop = $domain;
}else{
$domainTop = Str::getTopDomain($domain);
$domain = 'www.'.$domainTop;
}
$cache_key = $domainTop."_project_info";
Cache::forget($cache_key);
//dump("已清除项目缓存");
Redis::del($domain."_project");
// dump("已清除项目缓存");
Redis::del($domain."_public_template");
// dump("已清除公共模板缓存");
Redis::del($project->id."_project_origin_head_footer");
// dump("已清除原始公共head+footer缓存");
Redis::del($domain."_project_mysql_config");
// dump("已清除mysql配置缓存");
Redis::del("project_".$project->id."_web_setting");
// dump("已清除网站设置缓存");
Redis::del($project->id."_header_nav");
// dump("已清除顶部导航缓存");
Redis::del($domain."_footer_nav");
// dump("已清除顶部底部缓存");
Redis::del($domain."_all_nav");
// dump("已清除顶部底部缓存");
Redis::del("project_".$project->id."_country");
// dump("已清除项目国家缓存");
Redis::del($project->id . "_recommend_and_hot_products");
// dump("已清除关键词聚合页推荐和热门产品");
Redis::del($project->id."_products_keyword_default");
// dump("已清除关键词聚合页默认产品产品");
Redis::del($project->id."_product_keywords_blog");
// dump("已清除关键词聚合页博客数据");
Redis::del("project_".$project->id."_third_party_code");
// dump("已清除第三方代码缓存");
Redis::del("project_".$project->id."_web_setting_text");
// dump("已清除网站锚文本缓存");
Redis::del($project->id."_product_category");
// dump("已清除网站产品分类缓存");
Redis::del($project->id."_news_category");
// dump("已清除网站新闻分类缓存");
Redis::del($project->id."_blog_category");
// dump("已清除网站博客分类缓存");
Redis::del("project_".$project->id."_all_project_domain");
// dump("已清除网站所有项目域名缓存");
Redis::del($domain."_translation_proofread");
// dump("已清除网站翻译校对缓存");
}
/**
* 清空站点所有页面
*/
public function clearWebsite($request,$data)
{
$project = $request->get("project");
$domainInfo = DomainInfo::where("project_id",$project->id)->first();
$this->response("error",WebSetting::$errStatus,"api not used");
// if (!empty($domainInfo) && $project->id != 1){
// $this->response("error",WebSetting::$errStatus,"The project has been launched!");
// }
$domain = $request->getHost();
$this->clearCache($request,$domain);
$path = public_path($domain);
if (file_exists($path)){
$deletePageService = new DeletePageService();
$deletePageService->deleteDirectory($path);
}
$this->response("success",WebSetting::$okStatus,"clear website success , please visit again !");
}
/**
* 翻译测试
*/
public function fanYi($request,$data)
{
$data = $request->all();
$res = Translate::tran($data["text"], $data["lang"]);
$this->response("success",WebSetting::$okStatus,$res);
}
public function getProject($request,$data)
{
$domain = $request->getHost();
//项目
if (Redis::get($domain."_project") != null){
$project = json_decode(Redis::get($domain."_project"));
}else{
$projectDomain = Project::getProjectByDomain($domain);
$project = Project::where("id",$projectDomain->project_id)->first();
if (isset($projectDomain->test_domain)){
$project->domain = $projectDomain->test_domain;
}else{
$project->domain = $projectDomain->domain;
}
if (empty($project)){
return $this->response("error",WebSetting::$errStatus,"no project");
}
Redis::set($domain."_project", json_encode($project->toArray()));
Redis::expire($domain."_project", WebSetting::$redisExpireTime);
}
dump($project);
}
/**
* 获取国家语言
*/
public function getCountryLang($request,$data)
{
$project = $request->get('project');
$pageService = new PageService();
$webCountry = $pageService->getCountryList($project->id);
foreach ($webCountry as $item){
dump($item);
}
}
/**
* 根据域名创建sitemap
*/
public function createSitemap($request): \Illuminate\Http\JsonResponse
{
$domain = $request->getHost();
Redis::lpush('create_sitemap',$domain);
return $this->response("success",WebSetting::$okStatus);
}
/**
* 创建所有上线sitemap
*/
public function createAllSitemap()
{
$project = DomainInfo::where(['status' => 1])->pluck('domain', 'project_id')->toArray();
foreach ($project as $k=>$v) {
Redis::lpush('create_sitemap',$v);
dump("sitemap生成提供成功:".$v);
}
dd("全部提交成功");
}
/**
* 响应
* @throws HttpResponseException
*/
public function response($msg = null,string $code = self::SUCCESS,$data = [],$result_code = 200,$type = 'application/json'): JsonResponse
{
$result = [
'msg' => $msg,
'code' => $code,
'data' => $data,
];
$this->header['Content-Type'] = $type;
$response = response($result,$result_code,$this->header);
throw new HttpResponseException($response);
}
/**
* 检查所有项目更新进度并处理
*/
public function checkProgressHandle()
{
//所有项目
$projectInfo = $this->getTotalProject();
//链接对应项目的数据库,并查找需要处理的产品关键词的数据
if (!empty($projectInfo)){
foreach ($projectInfo as $item){
//连接数据库
$this->connectMysql($item);
//主站
$updateProgressModel = UpdateProgressModel::where("project_id",$item["project_id"])->where("type",1)->orderBy("id","desc")->first();
if (!empty($updateProgressModel)){
$totalNum = $updateProgressModel->total_num;
$currentNum = $updateProgressModel->current_num;
if ((int)$currentNum < (int)$totalNum){
UpdateProgressModel::where('id', $updateProgressModel->id)->update(['current_num' => $totalNum]);
}
}
//小语种
$updateProgressModel = UpdateProgressModel::where("project_id",$item["project_id"])->where("type",2)->orderBy("id","desc")->first();
if (!empty($updateProgressModel)){
$totalNum = $updateProgressModel->total_num;
$currentNum = $updateProgressModel->current_num;
if ((int)$currentNum < (int)$totalNum){
UpdateProgressModel::where('id', $updateProgressModel->id)->update(['current_num' => $totalNum]);
}
}
UpdateMasterWebsiteModel::select("id")->delete();
UpdateMinorLanguagesModel::select("id")->delete();
//关闭数据库连接
DB::disconnect('custom_mysql');
}
}
$this->response("success",WebSetting::$okStatus,"success");
}
/**
* 根据域名创建sitemap
*/
public function createSitemapZhiFang($domain): bool
{
$projectInfo = [];
//获取项目
$projectByDomain = Project::getProjectByDomain($domain);
if (!empty($projectByDomain)){
$projectService = new ProjectService();
$projectInfo["domain"] = $domain;
$projectInfo["project_id"] = $projectByDomain->project_id;
$project = Project::where("id",$projectByDomain->project_id)->first();
if (!empty($project)){
$projectInfo["mysql_id"] = $project->mysql_id;
$projectInfo["main_lang_id"] = $project->main_lang_id;
$serverConfig = ServerConfig::where("id",$project->mysql_id)->first();
if (!empty($serverConfig)){
$projectInfo["host"] = $serverConfig->host;
$projectInfo["port"] = (int)$projectService::unlock_url($serverConfig->port);
$projectInfo["database"] = "gl_data_".$projectByDomain->project_id;
$projectInfo["username"] = $projectService::unlock_url($serverConfig->user);
$projectInfo["password"] = $projectService::unlock_url($serverConfig->password);
}
}
}
//连数据库
if (!empty($projectInfo)){
//连接数据库
$this->connectMysql($projectInfo);
//数据处理
$routeMapQuery = RouteMap::where("project_id",$projectInfo["project_id"]);
$routerCount = $routeMapQuery->count();
if ($routerCount > 0){
//获取所有路由,分类,生成sitemap
//获取各类型路由及分页信息
$createSitemapService = new CreateSitemapService();
$allTypeRouteCountAndPageInfo = $createSitemapService->getAllTypeRouteCountAndPageInfo($projectInfo["project_id"]);
//生成sitemap.xml页面
$createSitemapService->createSitemapPage($projectInfo,$allTypeRouteCountAndPageInfo);
}
//关闭数据库连接
DB::disconnect('custom_mysql');
}
return true;
}
/**
* 查询所有项目(所有)
*/
public function getTotalProject(): array
{
$projectInfo = [];
//正式项目
$allProject = Project::get();
$projectService = new ProjectService();
if (!empty($allProject)){
foreach ($allProject as $key => $item){
$projectInfo[$key]["project_id"] = $item->id;
//查数据库信息
$projectInfo[$key]["mysql_id"] = $item->mysql_id;
$serverConfig = ServerConfig::where("id",$item->mysql_id)->first();
if (!empty($serverConfig)){
$projectInfo[$key]["host"] = $serverConfig->host;
$projectInfo[$key]["port"] = (int)$projectService::unlock_url($serverConfig->port);
$projectInfo[$key]["database"] = "gl_data_".$item->project_id;
$projectInfo[$key]["username"] = $projectService::unlock_url($serverConfig->user);
$projectInfo[$key]["password"] = $projectService::unlock_url($serverConfig->password);
}
}
}
return $projectInfo;
}
/**
* 连接数据库
*/
public function connectMysql($data)
{
// 设置 database.connections.custom_mysql 配置
config(['database.connections.custom_mysql.host' => $data['host']]);
config(['database.connections.custom_mysql.port' => $data['port']]);
config(['database.connections.custom_mysql.database' => $data['database']]);
config(['database.connections.custom_mysql.username' => $data['username']]);
config(['database.connections.custom_mysql.password' => $data['password']]);
}
/**
* 查询所有项目,包括数据库信息
*/
public function getAllProject(): array
{
$projectInfo = [];
//正式项目
$onlineProject = DeployOptimize::whereNotNull("domain")->get();
$projectService = new ProjectService();
if (!empty($onlineProject)){
foreach ($onlineProject as $key => $item){
//查域名信息
$domainInfo = DomainInfo::where("id",$item->domain)->first();
if (!empty($domainInfo)){
$projectInfo[$key]["domain"] = $domainInfo->domain;
$projectInfo[$key]["project_id"] = $item->project_id;
}
//查数据库信息
$project = Project::where("id",$item->project_id)->first();
if (!empty($project)){
$projectInfo[$key]["mysql_id"] = $project->mysql_id;
$projectInfo[$key]["main_lang_id"] = (int)$project->main_lang_id;
$serverConfig = ServerConfig::where("id",$project->mysql_id)->first();
if (!empty($serverConfig)){
$projectInfo[$key]["host"] = $serverConfig->host;
$projectInfo[$key]["port"] = (int)$projectService::unlock_url($serverConfig->port);
$projectInfo[$key]["database"] = "gl_data_".$item->project_id;
$projectInfo[$key]["username"] = $projectService::unlock_url($serverConfig->user);
$projectInfo[$key]["password"] = $projectService::unlock_url($serverConfig->password);
}
}
}
}
return $projectInfo;
}
}
... ...