yunzer/app/index/controller/ArticlesController.php

1402 lines
44 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
/**
* 文章控制器
*/
namespace app\index\controller;
use app\index\controller\BaseController;
use app\index\model\Users;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use app\index\model\Articles\Articles;
use app\index\model\Articles\ArticlesCategory;
use app\index\model\Authors\Authors;
use app\index\model\Resources\Resources;
class ArticlesController extends BaseController
{
// 获取siteinformation分类
public function getSiteInformationCategory()
{
// 获取名为 '站点资讯' 的分类
$siteInfoCategory = ArticlesCategory::where('name', '站点资讯')
->where('delete_time', null)
->where('status', 1)
->field('id,cid,name,image,sort')
->find();
if (!$siteInfoCategory) {
return json([
'code' => 1,
'msg' => '未找到站点资讯分类'
]);
}
// 只返回其子分类cid等于'站点资讯'的id
$children = ArticlesCategory::where('cid', $siteInfoCategory['id'])
->where('delete_time', null)
->where('status', 1)
->field('id,cid,name,image,sort')
->select()
->toArray();
return json([
'code' => 0,
'msg' => '获取站点资讯子分类成功',
'data' => $children
]);
}
// 获取siteinformation内容传参
public function getSiteInformationLists()
{
try {
// 获取前端传递的分类ID
$cateid = input('cateid/d', 0);
// 验证分类ID
if ($cateid <= 0) {
return json([
'code' => 1,
'msg' => '分类ID不能为空'
]);
}
// 检查分类是否存在且有效
$category = ArticlesCategory::where('id', $cateid)
->where('delete_time', null)
->where('status', 1)
->find();
if (!$category) {
return json([
'code' => 1,
'msg' => '分类不存在或已禁用'
]);
}
// 获取分页参数
$page = input('page/d', 1);
$limit = input('limit/d', 10);
// 获取该分类下的所有子分类ID包括自身
$subCategoryIds = [$cateid];
// 查找所有子分类
$subCategories = ArticlesCategory::where('cid', $cateid)
->where('delete_time', null)
->where('status', 1)
->column('id');
if (!empty($subCategories)) {
$subCategoryIds = array_merge($subCategoryIds, $subCategories);
}
// 构建查询条件
$where = [
['delete_time', '=', null],
['status', '=', 2], // 已发布的文章
['cate', 'in', $subCategoryIds]
];
// 查询文章总数
$total = Articles::where($where)->count();
// 查询文章列表
$articles = Articles::where($where)
->field('id,title,cate,image,desc,author,content,publishdate,views,likes,is_trans,transurl,push,create_time')
->order('sort DESC, id DESC')
->page($page, $limit)
->select()
->toArray();
// 处理文章数据
foreach ($articles as &$article) {
// 如果文章没有封面图,使用分类封面图
if (empty($article['image'])) {
$article['image'] = $category['image'] ?? '';
}
// 格式化时间
$article['publishdate'] = date('Y-m-d H:i:s', strtotime($article['publishdate']));
$article['create_time'] = date('Y-m-d H:i:s', strtotime($article['create_time']));
// 获取分类名称
$articleCategory = ArticlesCategory::where('id', $article['cate'])->find();
$article['category_name'] = $articleCategory ? $articleCategory['name'] : '';
}
// 返回数据
return json([
'code' => 0,
'msg' => '获取成功',
'data' => [
'category' => [
'id' => $category['id'],
'name' => $category['name'],
'desc' => $category['desc'],
'image' => $category['image']
],
'articles' => $articles,
'total' => $total,
'page' => $page,
'limit' => $limit,
'total_pages' => ceil($total / $limit)
]
]);
} catch (\Exception $e) {
return json([
'code' => 1,
'msg' => '获取失败:' . $e->getMessage()
]);
}
}
// 获取technicalArticles分类
public function getTechnicalArticlesCategory()
{
// 获取名为 '技术文章' 的分类
$siteInfoCategory = ArticlesCategory::where('name', '技术文章')
->where('delete_time', null)
->where('status', 1)
->field('id,cid,name,image,sort')
->find();
if (!$siteInfoCategory) {
return json([
'code' => 1,
'msg' => '未找到技术文章分类'
]);
}
// 只返回其子分类cid等于'技术文章'的id
$children = ArticlesCategory::where('cid', $siteInfoCategory['id'])
->where('delete_time', null)
->where('status', 1)
->field('id,cid,name,image,sort')
->select()
->toArray();
return json([
'code' => 0,
'msg' => '获取技术文章子分类成功',
'data' => $children
]);
}
// 获取technicalArticles内容传参
public function getTechnicalArticlesLists()
{
try {
// 获取前端传递的分类ID
$cateid = input('cateid/d', 0);
// 验证分类ID
if ($cateid <= 0) {
return json([
'code' => 1,
'msg' => '分类ID不能为空'
]);
}
// 检查分类是否存在且有效
$category = ArticlesCategory::where('id', $cateid)
->where('delete_time', null)
->where('status', 1)
->find();
if (!$category) {
return json([
'code' => 1,
'msg' => '分类不存在或已禁用'
]);
}
// 获取分页参数
$page = input('page/d', 1);
$limit = input('limit/d', 10);
// 获取该分类下的所有子分类ID包括自身
$subCategoryIds = [$cateid];
// 查找所有子分类
$subCategories = ArticlesCategory::where('cid', $cateid)
->where('delete_time', null)
->where('status', 1)
->column('id');
if (!empty($subCategories)) {
$subCategoryIds = array_merge($subCategoryIds, $subCategories);
}
// 构建查询条件
$where = [
['delete_time', '=', null],
['status', '=', 2], // 已发布的文章
['cate', 'in', $subCategoryIds]
];
// 查询文章总数
$total = Articles::where($where)->count();
// 查询文章列表
$articles = Articles::where($where)
->field('id,title,cate,image,desc,author,content,publishdate,views,likes,is_trans,transurl,push,create_time')
->order('sort DESC, id DESC')
->page($page, $limit)
->select()
->toArray();
// 处理文章数据
foreach ($articles as &$article) {
// 如果文章没有封面图,使用分类封面图
if (empty($article['image'])) {
$article['image'] = $category['image'] ?? '';
}
// 格式化时间
$article['publishdate'] = date('Y-m-d H:i:s', strtotime($article['publishdate']));
$article['create_time'] = date('Y-m-d H:i:s', strtotime($article['create_time']));
// 获取分类名称
$articleCategory = ArticlesCategory::where('id', $article['cate'])->find();
$article['category_name'] = $articleCategory ? $articleCategory['name'] : '';
}
// 返回数据
return json([
'code' => 0,
'msg' => '获取成功',
'data' => [
'category' => [
'id' => $category['id'],
'name' => $category['name'],
'desc' => $category['desc'],
'image' => $category['image']
],
'articles' => $articles,
'total' => $total,
'page' => $page,
'limit' => $limit,
'total_pages' => ceil($total / $limit)
]
]);
} catch (\Exception $e) {
return json([
'code' => 1,
'msg' => '获取失败:' . $e->getMessage()
]);
}
}
// 获取articleDetail详情
public function getArticleDetail()
{
try {
// 获取前端传递的ID
$id = input('id/d', 0);
// 验证ID
if ($id <= 0) {
return json([
'code' => 1,
'msg' => 'ID参数错误'
]);
}
// 构建查询条件
$where = [
['a.id', '=', $id],
['a.delete_time', '=', null],
['a.status', '=', 2], // 已发布的文章
];
// 查询文章详情,联查分类信息
$article = Articles::where($where)
->field('a.id,a.title,a.cate,a.image,a.desc,a.author,a.content,a.publishdate,a.views,a.likes,a.is_trans,a.transurl,a.push,a.create_time,ac.name as cate_name')
->alias('a')
->join('articles_category ac', 'a.cate = ac.id', 'LEFT')
->find();
if (!$article) {
return json([
'code' => 1,
'msg' => '文章不存在或已删除'
]);
}
// 转换为数组并处理数据
$article = $article->toArray();
// 获取当前文章的分类ID和作者用于查询相关内容
$currentCateId = $article['cate'];
$currentAuthor = $article['author'];
// 查询上一篇同分类ID更小的按ID倒序取第一个
$prevArticle = Articles::where([
['id', '<', $id],
['cate', '=', $currentCateId],
['delete_time', '=', null],
['status', '=', 2]
])
->field('id,title,image')
->order('id', 'desc')
->find();
// 查询下一篇同分类ID更大的按ID正序取第一个
$nextArticle = Articles::where([
['id', '>', $id],
['cate', '=', $currentCateId],
['delete_time', '=', null],
['status', '=', 2]
])
->field('id,title,image')
->order('id', 'asc')
->find();
// 查询相关文章同分类排除当前文章按发布时间倒序取5个
$relatedArticles = Articles::where([
['a.id', '<>', $id],
['a.cate', '=', $currentCateId],
['a.delete_time', '=', null],
['a.status', '=', 2]
])
->field('a.id,a.title,IF(a.image IS NULL OR a.image = \'\', ac.image, a.image) as image,a.views,a.likes,a.publishdate')
->alias('a')
->join('articles_category ac', 'a.cate = ac.id', 'LEFT')
->order('publishdate', 'desc')
->limit(5)
->select();
// 查询当前作者的文章发布数量
$articleCount = Articles::where([
['author', '=', $currentAuthor],
['delete_time', '=', null],
['status', '=', 2]
])->count();
// 查询当前作者的资源发布数量
$resourceCount = Resources::where([
['delete_time', '=', null],
['status', '=', 1],
['push', '=', 1]
])->count();
// 格式化时间
$article['publishdate'] = date('Y-m-d H:i:s', strtotime($article['publishdate']));
$article['create_time'] = date('Y-m-d H:i:s', strtotime($article['create_time']));
// 分类名称
$article['category_name'] = $article['cate_name'] ?? '';
unset($article['cate_name']);
// 添加作者统计信息
$article['articlecount'] = $articleCount;
$article['resourcecount'] = $resourceCount;
// 处理相关文章数据
$relatedData = [];
if ($relatedArticles) {
foreach ($relatedArticles as $related) {
$relatedData[] = [
'id' => $related['id'],
'title' => $related['title'],
'image' => $related['image'],
'views' => $related['views'],
'likes' => $related['likes'],
'publishdate' => date('Y-m-d H:i:s', strtotime($related['publishdate']))
];
}
}
// 返回数据
return json([
'code' => 0,
'msg' => '获取成功',
'data' => [
'article' => $article,
'prev_article' => $prevArticle ? [
'id' => $prevArticle['id'],
'title' => $prevArticle['title']
] : null,
'next_article' => $nextArticle ? [
'id' => $nextArticle['id'],
'title' => $nextArticle['title']
] : null,
'related_articles' => $relatedData
]
]);
} catch (\Exception $e) {
return json([
'code' => 1,
'msg' => '获取失败:' . $e->getMessage()
]);
}
}
//文章中心
public function index()
{
// 获取前端传来的分类ID
$cateid = input('cateid/d', 0); // 使用input助手函数获取参数并转换为整数
$page = input('page/d', 1);
$limit = input('limit/d', 10);
// 获取所有顶级分类
$categories = ArticlesCategory::where('cid', 0)
->where('delete_time', null)
->where('status', 1)
->select()
->toArray();
// 获取顶级分类信息
$category = null;
if ($cateid > 0) {
$category = ArticlesCategory::where('id', $cateid)
->where('delete_time', null)
->where('status', 1)
->find();
}
// 获取所有子分类
$subCategories = [];
if ($cateid > 0) {
$subCategories = ArticlesCategory::where('cid', $cateid)
->where('delete_time', null)
->where('status', 1)
->select()
->toArray();
}
// 获取所有子分类ID
$subCategoryIds = array_column($subCategories, 'id');
if ($cateid > 0) {
$subCategoryIds[] = $cateid;
}
// 构建文章查询条件
$where = [
['delete_time', '=', null],
['status', '=', 2]
];
if (!empty($subCategoryIds)) {
$where[] = ['cate', 'in', $subCategoryIds];
}
// 查询文章
$articles = Articles::where($where)
->order('id DESC')
->page($page, $limit)
->select()
->toArray();
// 按子分类分组文章
$groupedArticles = [];
foreach ($subCategories as $subCategory) {
$groupedArticles[$subCategory['id']] = [
'id' => $subCategory['id'],
'name' => $subCategory['name'],
'desc' => $subCategory['desc'],
'image' => $subCategory['image'],
'list' => []
];
}
// 将文章分配到对应的子分类
foreach ($articles as $article) {
if (isset($groupedArticles[$article['cate']])) {
// 如果文章图片为空,使用分类图片
if (empty($article['image'])) {
$article['image'] = $groupedArticles[$article['cate']]['image'];
}
$groupedArticles[$article['cate']]['list'][] = $article;
}
}
// 获取总数
$total = Articles::where($where)->count();
// 准备返回数据
$data = [
'cate' => [
'id' => $cateid,
'name' => $category ? $category['name'] : '',
'desc' => $category ? $category['desc'] : '',
'image' => $category ? $category['image'] : '',
'subCategories' => array_values($groupedArticles),
'total' => $total,
'page' => $page,
'limit' => $limit
]
];
// 根据请求方式返回不同的输出
if (request()->isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => $data
]);
} else {
// 为视图准备数据
$viewData = [
'categories' => $categories,
'cate' => $data['cate']
];
return view('index', $viewData);
}
}
// 文章列表页
public function list()
{
// 获取分类ID
$cateId = Request::param('cate/d', 0);
// 构建查询条件
$where = [
['a.delete_time', '=', null],
['a.status', '=', 2]
];
if ($cateId > 0) {
$where[] = ['a.cate', '=', $cateId];
}
// 获取文章列表
$articles = Articles::alias('a')
->join('articles_category c', 'a.cate = c.id')
->where($where)
->field([
'a.*',
'IF(a.image IS NULL OR a.image = "", c.image, a.image) as image'
])
->order('a.id DESC')
->paginate([
'list_rows' => 10,
'query' => Request::instance()->param()
]);
// 获取分类信息
$category = null;
if ($cateId > 0) {
$category = ArticlesCategory::where('id', $cateId)
->where('delete_time', null)
->where('status', 3)
->find();
}
// 获取所有分类
$categories = ArticlesCategory::where('delete_time', null)
->where('status', 3)
->select()
->toArray();
// 根据请求方式返回不同的输出
if (request()->isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'articles' => $articles->items(),
'category' => $category,
'categories' => $categories,
'total' => $articles->total(),
'current_page' => $articles->currentPage(),
'per_page' => $articles->listRows()
]
]);
} else {
// 将变量传递给视图
View::assign([
'articles' => $articles,
'category' => $category,
'categories' => $categories
]);
return view('list');
}
}
// 文章详情页
public function detail()
{
$id = Request::param('id/d', 0);
$article = Articles::where('id', $id)->find();
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在或已被删除']);
}
// 获取分类名称
$cateName = ArticlesCategory::where('id', $article['cate'])
->value('name');
// 获取作者信息
$authorInfo = Users::where('name', $article['author'])->find();
if ($authorInfo) {
// 统计作者的文章数
$articleCount = Articles::where('author', $article['author'])->count();
// 统计作者的资源数
$resourceCount = Resources::where('uploader', $article['author'])->count();
$authorData = [
'avatar' => $authorInfo['avatar'] ?: '/static/images/avatar.png',
'name' => $authorInfo['name'],
'resource_count' => $resourceCount,
'article_count' => $articleCount
];
} else {
$authorData = [
'avatar' => '/static/images/avatar.png',
'name' => $article['author'],
'resource_count' => 0,
'article_count' => 0
];
}
// 获取上一篇和下一篇文章
$prevArticle = Articles::where('id', '<', $id)
->where('delete_time', null)
->where('status', '<>', 3)
->where('cate', $article['cate'])
->field(['id', 'title'])
->order('id DESC')
->find();
$nextArticle = Articles::where('id', '>', $id)
->where('delete_time', null)
->where('status', '<>', 3)
->where('cate', $article['cate'])
->field(['id', 'title'])
->order('id ASC')
->find();
// 获取相关文章(同分类的其他文章)
$relatedArticles = Articles::alias('a')
->join('articles_category c', 'a.cate = c.id')
->where('a.cate', $article['cate'])
->where('a.id', '<>', $id)
->where('a.delete_time', null)
->where('a.status', '=', 2)
->field([
'a.id',
'a.title',
'IF(a.image IS NULL OR a.image = "", c.image, a.image) as image'
])
->order('a.id DESC')
->limit(3)
->select()
->toArray();
// 如果是 POST 请求,返回 JSON 数据
if (Request::isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'authorInfo' => $authorData,
'article' => $article,
'cateName' => $cateName,
'prevArticle' => $prevArticle,
'nextArticle' => $nextArticle,
'relatedArticles' => $relatedArticles
]
]);
}
// GET 请求返回视图
View::assign([
'authorInfo' => $authorData,
'article' => $article,
'cateName' => $cateName,
'prevArticle' => $prevArticle,
'nextArticle' => $nextArticle,
'relatedArticles' => $relatedArticles
]);
return view('detail');
}
// 文章点赞
public function like()
{
if (!Request::isAjax()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::param('id/d', 0);
// 检查文章是否存在
$article = Articles::where('id', $id)
->where('delete_time', null)
->where('status', 2)
->find();
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在或已被删除']);
}
// 更新点赞数
$result = Articles::where('id', $id)
->where('delete_time', null)
->inc('likes', 1)
->update();
if ($result) {
// 返回更新后的点赞数
$newLikes = $article['likes'] + 1;
return json([
'code' => 1,
'msg' => '点赞成功',
'data' => [
'likes' => $newLikes
]
]);
} else {
return json(['code' => 0, 'msg' => '点赞失败']);
}
}
// 提交评论
public function comment()
{
if (!Request::isAjax() || !Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$articleId = Request::param('article_id/d', 0);
$content = Request::param('content/s', '');
$parentId = Request::param('parent_id/d', 0);
if (empty($content)) {
return json(['code' => 0, 'msg' => '评论内容不能为空']);
}
// 检查文章是否存在
$article = Articles::where('id', $articleId)
->where('delete_time', null)
->where('status', 3)
->find();
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在或已被删除']);
}
// 添加评论
// $data = [
// 'article_id' => $articleId,
// 'content' => $content,
// 'parent_id' => $parentId,
// 'user_id' => $this->getUserId(),
// 'user_name' => $this->getUserName(),
// 'status' => 1,
// 'create_time' => time()
// ];
// $result = Db::table('yz_article_comment')->insert($data);
// if ($result) {
// return json(['code' => 1, 'msg' => '评论成功']);
// } else {
// return json(['code' => 0, 'msg' => '评论失败']);
// }
}
// 获取当前用户ID示例方法实际应根据您的用户系统实现
private function getUserId()
{
// 这里应该返回当前登录用户的ID
return 1; // 示例返回值
}
// 获取当前用户名(示例方法,实际应根据您的用户系统实现)
private function getUserName()
{
// 这里应该返回当前登录用户的用户名
return '游客'; // 示例返回值
}
// 获取访问统计
public function viewStats()
{
$id = Request::param('id/d', 0);
// 获取总访问量
$totalViews = Articles::where('id', $id)
->value('views');
return json([
'code' => 1,
'data' => [
'total' => $totalViews
]
]);
}
//更新文章访问次数
public function updateViews()
{
if (!Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::post('id');
if (!$id) {
return json(['code' => 0, 'msg' => '参数错误']);
}
try {
// 更新访问次数
$article = Articles::where('id', $id)->find();
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在']);
}
// 更新访问次数
Articles::where('id', $id)->inc('views')->update();
// 获取更新后的访问次数
$newViews = Articles::where('id', $id)->value('views');
return json(['code' => 1, 'msg' => '更新成功', 'data' => ['views' => $newViews]]);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '更新失败:' . $e->getMessage()]);
}
}
//获取作者信息
public function getAuthorInfo()
{
if (!Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$authorName = Request::post('name');
if (empty($authorName)) {
return json(['code' => 0, 'msg' => '作者名称不能为空']);
}
try {
// 获取作者基本信息
$author = Db::name('users')
->where('name', $authorName)
->field('id, name, avatar')
->find();
if (!$author) {
return json(['code' => 0, 'msg' => '作者不存在']);
}
// 获取作者发布的资源数量
$resourceCount = Db::name('resources')
->where('user_id', $author['id'])
->where('delete_time', null)
->where('status', 2) // 假设2是已发布状态
->count();
// 获取作者发布的文章数量
$articleCount = Db::name('articles')
->where('author', $authorName)
->where('delete_time', null)
->where('status', 2) // 假设2是已发布状态
->count();
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'avatar' => $author['avatar'],
'name' => $author['name'],
'resource_count' => $resourceCount,
'article_count' => $articleCount
]
]);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '获取作者信息失败:' . $e->getMessage()]);
}
}
//获取用户文章列表
public function getUserArticleList()
{
try {
// 获取前端传递的用户ID
$userId = input('uid/d', 0);
// 验证用户ID
if ($userId <= 0) {
return json([
'code' => 1,
'msg' => '用户ID参数错误'
]);
}
// 根据用户ID获取用户名
$user = Users::where('uid', $userId)->field('uid, name')->find();
if (!$user) {
return json([
'code' => 1,
'msg' => '用户不存在'
]);
}
// 获取用户文章的分类ID列表用于批量查询分类信息
$cateIds = Articles::where([
['publisher', '=', $user['uid']],
['delete_time', '=', null],
['status', '=', 2] // 已发布的文章
])->column('cate');
// 批量查询分类信息避免N+1查询问题
$categories = [];
if (!empty($cateIds)) {
$categories = ArticlesCategory::where('id', 'in', array_unique($cateIds))
->column('id,name,image', 'id');
}
// 查询用户的文章列表
$articles = Articles::where([
['publisher', '=', $user['uid']],
['delete_time', '=', null],
['status', '=', 2] // 已发布的文章
])
->field('id, title, cate, image, author, publisher, publishdate, views, likes, update_time')
->order('publishdate', 'desc')
->select();
// 处理文章数据
$articleList = [];
if ($articles) {
foreach ($articles as $article) {
$articleData = $article->toArray();
// 格式化时间
$articleData['publishdate'] = date('Y-m-d H:i:s', strtotime($articleData['publishdate']));
// 从预加载的分类数据中获取信息
$cateId = $articleData['cate'];
if (isset($categories[$cateId])) {
$category = $categories[$cateId];
// 如果文章图片为空,使用分类图片
if (empty($articleData['image'])) {
$articleData['image'] = !empty($category['image']) ? $category['image'] : '/static/images/default.jpg';
}
// 设置分类名称
$articleData['category_name'] = $category['name'];
} else {
// 如果没有找到分类信息
if (empty($articleData['image'])) {
$articleData['image'] = '/static/images/default.jpg';
}
$articleData['category_name'] = '未分类';
}
$articleList[] = $articleData;
}
}
return json([
'code' => 0,
'msg' => '获取成功',
'data' => [
'articles' => $articleList,
'total' => count($articleList)
]
]);
} catch (\Exception $e) {
return json([
'code' => 1,
'msg' => '获取失败:' . $e->getMessage()
]);
}
}
//获取文章分类
public function getArticleCategory()
{
try {
// 获取所有顶级分类cid=0
$topCategories = ArticlesCategory::where('cid', 0)
->where('delete_time', null)
->where('status', 1)
->field('id, cid, name, image, sort')
->order('sort', 'asc')
->select()
->toArray();
$categories = [];
// 为每个顶级分类获取其子分类
foreach ($topCategories as $topCategory) {
$category = [
'id' => $topCategory['id'],
'name' => $topCategory['name'],
'image' => $topCategory['image'],
'sort' => $topCategory['sort'],
'children' => []
];
// 获取子分类
$children = ArticlesCategory::where('cid', $topCategory['id'])
->where('delete_time', null)
->where('status', 1)
->field('id, cid, name, image, sort')
->order('sort', 'asc')
->select()
->toArray();
// 为每个子分类获取文章数量
foreach ($children as &$child) {
$child['article_count'] = Articles::where('cate', $child['id'])
->where('delete_time', null)
->where('status', 2)
->count();
}
$category['children'] = $children;
$categories[] = $category;
}
return json([
'code' => 0,
'msg' => '获取文章分类成功',
'data' => $categories
]);
} catch (\Exception $e) {
return json([
'code' => 1,
'msg' => '获取文章分类失败:' . $e->getMessage()
]);
}
}
//发布文章
public function publishArticle()
{
try {
// 获取前端传递的数据
$data = [];
// 标题(必需)
$title = input('title', '');
if (empty($title)) {
return json([
'code' => 1,
'msg' => '文章标题不能为空'
]);
}
$data['title'] = $title;
// 分类ID必需
$cate = input('cate/d', 0);
if ($cate <= 0) {
return json([
'code' => 1,
'msg' => '请选择文章分类'
]);
}
//发布者
$publisher = input('user_id', '');
$data['publisher'] = $publisher;
// 验证分类是否存在
$category = ArticlesCategory::where('id', $cate)
->where('delete_time', null)
->where('status', 1)
->find();
if (!$category) {
return json([
'code' => 1,
'msg' => '选择的分类不存在'
]);
}
$data['cate'] = $cate;
// 内容(必需)
$content = input('content', '');
if (empty($content)) {
return json([
'code' => 1,
'msg' => '文章内容不能为空'
]);
}
$data['content'] = $content;
// 作者(必需)
$author = input('author', '');
if (empty($author)) {
return json([
'code' => 1,
'msg' => '作者不能为空'
]);
}
$data['author'] = $author;
// 图片(可选)
$image = input('image', '');
if (!empty($image)) {
$data['image'] = $image;
}
// 描述(可选)
$desc = input('desc', '');
if (!empty($desc)) {
$data['desc'] = $desc;
}
// 发布者(可选)
$publisher = input('publisher', '');
if (!empty($publisher)) {
$data['publisher'] = $publisher;
}
// 状态默认为2-已发布)
$status = input('status/d', 1);
if ($status >= 0 && $status <= 2) {
$data['status'] = $status;
} else {
$data['status'] = 2; // 默认已发布
}
// 发布日期(默认为当前时间)
$publishdate = input('publishdate', '');
if (!empty($publishdate)) {
// 验证日期格式
if (!strtotime($publishdate)) {
return json([
'code' => 1,
'msg' => '发布日期格式错误'
]);
}
$data['publishdate'] = $publishdate;
} else {
$data['publishdate'] = date('Y-m-d H:i:s');
}
// 是否翻译(可选)
$is_trans = input('is_trans/d', 0);
$data['is_trans'] = $is_trans ? 1 : 0;
// 翻译链接(可选)
$transurl = input('transurl', '');
if (!empty($transurl)) {
$data['transurl'] = $transurl;
}
// 推送状态(可选)
$push = input('push/d', 0);
$data['push'] = $push ? 1 : 0;
// 浏览量和点赞数默认为0
$data['views'] = 0;
$data['likes'] = 0;
// 创建时间和更新时间
$data['create_time'] = date('Y-m-d H:i:s');
// 执行插入
$result = Articles::insert($data);
if (!$result) {
return json([
'code' => 1,
'msg' => '发布失败'
]);
}
// 获取新插入的文章ID
$articleId = Articles::getLastInsID();
return json([
'code' => 0,
'msg' => '文章发布成功',
'data' => [
'article_id' => $articleId
]
]);
} catch (\Exception $e) {
return json([
'code' => 1,
'msg' => '发布失败:' . $e->getMessage()
]);
}
}
//编辑文章
public function updateArticle()
{
try {
// 获取文章ID
$id = input('id/d', 0);
// 验证ID
if ($id <= 0) {
return json([
'code' => 1,
'msg' => '文章ID参数错误'
]);
}
// 检查文章是否存在
$article = Articles::where('id', $id)
->where('delete_time', null)
->find();
if (!$article) {
return json([
'code' => 1,
'msg' => '文章不存在'
]);
}
// 获取要更新的数据
$data = [];
// 标题
$title = input('title', '');
if (!empty($title)) {
$data['title'] = $title;
}
// 分类ID
$cate = input('cate/d', 0);
if ($cate > 0) {
// 验证分类是否存在
$category = ArticlesCategory::where('id', $cate)
->where('delete_time', null)
->where('status', 1)
->find();
if (!$category) {
return json([
'code' => 1,
'msg' => '选择的分类不存在'
]);
}
$data['cate'] = $cate;
}
// 图片
$image = input('image', '');
if ($image !== '') {
$data['image'] = $image;
}
// 描述
$desc = input('desc', '');
if ($desc !== '') {
$data['desc'] = $desc;
}
// 内容
$content = input('content', '');
if ($content !== '') {
$data['content'] = $content;
}
// 作者
$author = input('author', '');
if (!empty($author)) {
$data['author'] = $author;
}
// 状态
$status = input('status/d', -1);
if ($status >= 0 && $status <= 2) {
$data['status'] = $status;
}
// 发布日期
$publishdate = input('publishdate', '');
if (!empty($publishdate)) {
// 验证日期格式
if (!strtotime($publishdate)) {
return json([
'code' => 1,
'msg' => '发布日期格式错误'
]);
}
$data['publishdate'] = $publishdate;
}
// 是否翻译
$is_trans = input('is_trans/d', -1);
if ($is_trans >= 0 && $is_trans <= 1) {
$data['is_trans'] = $is_trans;
}
// 翻译链接
$transurl = input('transurl', '');
if ($transurl !== '') {
$data['transurl'] = $transurl;
}
// 推送状态
$push = input('push/d', -1);
if ($push >= 0 && $push <= 1) {
$data['push'] = $push;
}
// 如果没有任何要更新的数据
if (empty($data)) {
return json([
'code' => 1,
'msg' => '没有要更新的内容'
]);
}
// 添加更新时间
$data['update_time'] = date('Y-m-d H:i:s');
// 执行更新
$result = Articles::where('id', $id)->update($data);
if ($result === false) {
return json([
'code' => 1,
'msg' => '更新失败'
]);
}
return json([
'code' => 0,
'msg' => '文章更新成功'
]);
} catch (\Exception $e) {
return json([
'code' => 1,
'msg' => '更新失败:' . $e->getMessage()
]);
}
}
}