feat: 上线前安全加固与发布工程化;appmall 由插件迁移为独立应用

安全(P0)
- 发布包签名:新增 scripts/package_keygen.php、scripts/package_verify.php、
  ywxapp\service\PackageVerifier;FrameworkService::apply() 解压前强制验签
  (ywxapp.framework_package_verify,默认开启)
- JWT 收紧:config/jwt.php 移除公开默认密钥,JwtService::assertStrongSecret()
  校验非空 / 长度≥32 / 已知弱值;.env.production.example 键名由 JWT_SECRET_KEY 修正为 JWT_SECRET
- /api/v1/Article:免登录白名单收窄为只读接口,写操作字段白名单 + assertOwner() 越权校验
- 开发者令牌:查找接口不再回显明文、统一失败文案 + 限流
- TemplateInstaller:文件名白名单 + realpath 归一化 + 目录内断言,修复 Zip Slip;补 use ZipArchive
- 后台登录:接入验证码、失败锁定与登录限流(config/ratelimit.php)
- 缓存 / Session 驱动可由 .env 覆盖(CACHE_DRIVER / SESSION_TYPE),集群部署改 redis
- paycenter 支付日志开关改为 PAY_LOG,不再跟随 APP_DEBUG

工程化 / 交付
- 新增 CHANGELOG.md 与 .env.production.example;composer.lock 入库锁定依赖版本
- 插件离线安装 CLI 增加 --uid,后台上传安装透传 uid,付费插件授权校验可通过
- 授权拒绝文案区分「未携带 uid」与「未找到有效授权」,便于排障
- .gitignore 放行 .env.production.example / .env.addon.example / .gitattributes / public/.htaccess

结构
- appmall 由 addon/appmall 迁移为独立应用 app/appmall(市场 / 开发者中心 / 审核 / 分润)
This commit is contained in:
yangwx committed 2026-10-22 00:53:39 +08:00
1 parent 1d49e6f5ee
commit 18101cf11a
636 files changed
+58517 -9519

No files matched your search

+94 -2
View File
@@ -10,39 +10,79 @@ declare (strict_types = 1);
namespace addon\articles;
use addon\articles\library\ArticleSchema;
use think\facade\Db;
use ywxapp\AddonBase;
use ywxapp\service\AddonService;
/**
* 文章CMS插件启动类
*/
class Addon extends AddonBase
{
// 插件基本信息
/** 插件私有表(不含表前缀) */
private const TABLES = [
'articles_article',
'articles_article_tag',
'articles_category',
'articles_tag',
'articles_comment',
];
// 插件基本信息(版本号须与 info.php 保持一致)
public $info = [
'name' => 'articles',
'title' => '文章CMS',
'description' => '完整文章类 CMS 插件:文章、分类、标签、评论',
'status' => 1,
'author' => 'ywxapp',
'version' => '1.0.0',
'version' => '1.0.1',
'type' => 1,
];
// 插件安装
public function install()
{
// install.sql 由框架导入(白名单仅 CREATE TABLE / INSERT);
// 这里再兜底一次,确保表齐备且不缺列。
ArticleSchema::repair();
return true;
}
// 插件卸载
public function uninstall()
{
$prefix = $this->prefix();
foreach (self::TABLES as $table) {
try {
// 用配置前缀拼接,勿硬编码 wxapp_
Db::execute("DROP TABLE IF EXISTS `{$prefix}{$table}`");
} catch (\Throwable $e) {
// 单表删除失败不阻断整体卸载
}
}
// 菜单由框架 deleteMenu() 清理;这里补清「配置残留」
// (框架卸载默认不清配置,重装会继承旧值)
try {
Db::name('common_addonconf')->where('addon', 'articles')->delete();
} catch (\Throwable $e) {
// 表不存在时忽略
}
AddonService::clearConfigCache('articles');
// 清理静态资源:框架卸载只删 public/static/addon/<name>/,
// 而本插件资源实际在 public/static/articles/,需自行清理。
$this->deleteDirectory(public_path() . 'static' . DIRECTORY_SEPARATOR . 'articles');
return true;
}
// 插件启用
public function enable()
{
// 启用时做一次轻量建表兜底(不补列,避免线上长耗时)
ArticleSchema::repair(false);
return true;
}
@@ -51,4 +91,56 @@ class Addon extends AddonBase
{
return true;
}
/**
* 插件升级(覆盖升级 / addon:manage 时由框架回调)
*
* 注意:install.sql 的 ALTER 会被 importsql 白名单跳过,
* 因此「老库补列 + 补索引」必须放在这里(ArticleSchema::repair)。
*
* @param string $currentVersion 已安装版本号
*/
public function upgrade($currentVersion = '')
{
ArticleSchema::repair();
return true;
}
/**
* 递归删除目录(卸载时清理静态资源)
*/
private function deleteDirectory(string $dir): void
{
if (!is_dir($dir)) {
return;
}
$items = scandir($dir);
if (!is_array($items)) {
return;
}
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path)) {
$this->deleteDirectory($path);
} else {
@unlink($path);
}
}
@rmdir($dir);
}
/**
* 当前数据库表前缀
*/
private function prefix(): string
{
$default = (string) config('database.default', 'mysql');
return (string) config("database.connections.{$default}.prefix", '');
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
// | 文章CMS插件公共文件
// |
// | 由 MultiApp::loadApp() 在请求命中 articles 应用时自动 include_once,
// | 这里负责加载插件语言包(模板中可用 {:L('Articles')} / L('Articles') 取值)。
// +----------------------------------------------------------------------
declare (strict_types = 1);
\think\facade\Lang::load(
dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . 'zh-cn.php'
);
+46
View File
@@ -0,0 +1,46 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
// | 文章CMS插件「后台配置表单」字段定义
// |
// | 框架自带通用配置页会自动按本文件渲染表单并保存:
// | /backend/addon/setting?addon=articles
// | 读取:AddonService::config('articles') 或 get_addon_config('articles')
// +----------------------------------------------------------------------
return [
[
'name' => 'comment_audit',
'title' => '评论审核',
'type' => 'select',
'value' => '0',
'options' => ['0' => '直接显示', '1' => '先审后发'],
'tip' => '开启「先审后发」后,新评论默认待审核,需在后台评论管理中审核后才公开显示',
],
[
'name' => 'comment_interval',
'title' => '评论间隔(秒)',
'type' => 'number',
'value' => '10',
'tip' => '同一用户两次评论的最小间隔,用于防灌水/刷屏,0 表示不限',
],
[
'name' => 'page_size',
'title' => '前台每页条数',
'type' => 'number',
'value' => '10',
'tip' => '前台列表每页显示的文章数量',
],
[
'name' => 'search_fulltext',
'title' => '全文搜索',
'type' => 'select',
'value' => '0',
'options' => ['0' => '关闭(LIKE 模糊匹配)', '1' => '开启(FULLTEXT 索引)'],
'tip' => '文章量大时开启可显著提速;需 MySQL 支持全文索引,索引不存在时会自动降级为 LIKE',
],
];
+204 -18
View File
@@ -17,9 +17,14 @@ declare (strict_types = 1);
namespace addon\articles\controller;
use think\facade\Db;
use think\facade\Cache;
use addon\articles\model\Article as ArticleModel;
use addon\articles\model\ArticleComment;
use addon\articles\model\ArticleLike;
use addon\articles\service\ContentRenderService;
use addon\articles\service\FavoriteService;
use addon\articles\service\LikeService;
use ywxapp\service\AddonService;
class Article extends ArticlesFrontend
{
@@ -27,24 +32,77 @@ class Article extends ArticlesFrontend
{
$article = ArticleModel::getDetail((int) $id);
if (!$article) {
$this->result->error('文章不存在或已删除');
// 软 404 会被搜索引擎收录:显式返回 HTTP 404
return $this->result->setStatusCode(404)->error('文章不存在或已删除', 404);
}
// 浏览量 +1
ArticleModel::where('id', $id)->inc('view_count')->update();
// 浏览量 +1(同访客 5 分钟内去重)
$this->bumpViews((int) $article->id);
// 评论:分页只取顶层评论,回复整体带出(避免分页把父子评论切断)
$commentsPage = ArticleComment::getByArticle((int) $id, (int) input('page', 1), 10);
$topComments = $commentsPage->items();
$replyMap = ArticleComment::repliesOf(array_column($topComments, 'id'));
$tree = [];
foreach ($topComments as $c) {
$c->replies = $replyMap[$c->id] ?? [];
$tree[] = $c;
}
$comments = [
'data' => $commentsPage->items(),
'data' => $tree,
'render' => $commentsPage->render(),
];
// 当前用户对本文的点赞状态
$uid = (int) ($this->auth && $this->auth->isLogin ? ($this->auth->info['uid'] ?? 0) : 0);
// 输出期增强(不改动入库内容):图片懒加载 + WebP(浏览器支持时)+ 内链(本文标签)
$useWebp = strpos((string) $this->request->header('Accept', ''), 'image/webp') !== false;
$keywords = [];
foreach ($article->tags as $t) {
$keywords[$t->name] = (string) url('articles/search/index', ['keyword' => $t->name]);
}
$contentHtml = ContentRenderService::render((string) $article->content, $keywords, $useWebp);
// SEO 结构化数据(JSON-LD):Article + BreadcrumbList,供搜索引擎/富摘要识别
$canonical = request()->domain() . (string) url('articles/read/' . $article->id);
$jsonLd = json_encode([
'@context' => 'https://schema.org',
'@type' => 'Article',
'headline' => (string) $article->title,
'description' => mb_substr((string) (strip_tags((string) ($article->summary ?: $article->content))), 0, 150),
'author' => ['@type' => 'Person', 'name' => (string) ($article->author ?: 'admin')],
'datePublished' => date('c', self::toTs($article->create_at)),
'dateModified' => date('c', self::toTs($article->update_at) ?: self::toTs($article->create_at)),
'mainEntityOfPage' => ['@type' => 'WebPage', '@id' => $canonical],
'articleSection' => (string) ($article->category_name ?? ''),
'image' => (string) ($article->cover_image ?: ''),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$breadcrumb = json_encode([
'@context' => 'https://schema.org',
'@type' => 'BreadcrumbList',
'itemListElement' => [
['@type' => 'ListItem', 'position' => 1, 'name' => '首页', 'item' => request()->domain() . (string) url('articles/index/index')],
['@type' => 'ListItem', 'position' => 2, 'name' => (string) ($article->category_name ?: '未分类'),
'item' => request()->domain() . (string) url('articles/category/index', ['id' => $article->cid])],
['@type' => 'ListItem', 'position' => 3, 'name' => (string) $article->title, 'item' => $canonical],
],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$this->view->assign([
'article' => $article,
'prev' => ArticleModel::prev($article->id, $article->cid),
'next' => ArticleModel::next($article->id, $article->cid),
'contentHtml' => $contentHtml,
'favorited' => FavoriteService::isFavorited($uid, (int) $article->id),
'related' => ArticleModel::related($article->id, $article->cid, 5),
'hot' => ArticleModel::hot(10),
'comments'=> $comments,
'liked' => LikeService::isLiked($uid, (int) $article->id, ArticleLike::TYPE_ARTICLE),
'jsonLd' => $jsonLd,
'breadcrumbLd' => $breadcrumb,
'nav_active' => $article->cid,
]);
return $this->fetch('article/detail');
@@ -77,22 +135,150 @@ class Article extends ArticlesFrontend
if (!$this->auth || !$this->auth->isLogin) {
$this->result->error('请先登录后再评论');
}
$aid = (int) input('aid', 0);
$content = trim(input('content', ''));
if (!$aid || !$content) {
$aid = (int) input('aid', 0);
$pid = (int) input('pid', 0);
$content = trim((string) input('content', ''));
if (!$aid || $content === '') {
$this->result->error('参数错误');
}
$uid = $this->auth->info['uid'] ?? 0;
// 长度校验:过短视为灌水,过长直接拒绝
$len = mb_strlen($content, 'UTF-8');
if ($len < 2) {
$this->result->error('评论内容太短');
}
if ($len > 500) {
$this->result->error('评论内容不能超过 500 字');
}
// 目标文章必须存在且已发布,否则可给任意 aid 灌评论
$article = ArticleModel::where('id', $aid)
->where('status', 1)
->where('delete_at', 0)
->find();
if (!$article) {
$this->result->error('文章不存在或未发布');
}
// 楼层回复:父评论必须存在且属于同一篇文章
if ($pid > 0) {
$parent = ArticleComment::where('id', $pid)
->where('aid', $aid)
->where('delete_at', 0)
->find();
if (!$parent) {
$this->result->error('父评论不存在');
}
}
$uid = (int) ($this->auth->info['uid'] ?? 0);
// 评论策略取自插件配置(后台「插件管理 → 配置」可改)
$cfg = AddonService::config('articles');
$needAudit = !empty($cfg['comment_audit']);
$interval = max(0, (int) ($cfg['comment_interval'] ?? 10));
// 限流:同一用户 N 秒内只发 1 条,防灌水/刷屏(N=0 表示不限)
$lockKey = 'articles_comment_lock:' . $uid;
if ($interval > 0 && Cache::get($lockKey, 0)) {
$this->result->error('评论太频繁,请稍后再试');
}
ArticleComment::create([
'uid' => $uid,
'aid' => $aid,
'pid' => 0,
'content' => $content,
'status' => 1,
'create_at' => time(),
'update_at' => time(),
'uid' => $uid,
'aid' => $aid,
'pid' => $pid,
'content' => $content,
// 「先审后发」时为 0(待审核),由后台评论管理审核通过后再公开
'status' => $needAudit ? 0 : 1,
'ip' => (string) $this->request->ip(),
'user_agent' => mb_substr((string) $this->request->header('user-agent', ''), 0, 255),
'create_at' => time(),
'update_at' => time(),
]);
ArticleModel::where('id', $aid)->inc('comment_count')->update();
$this->result->success('评论成功');
// 只有直接显示的评论才累加计数(待审核的等审核通过时再加)
if (!$needAudit) {
ArticleModel::where('id', $aid)->inc('comment_count')->update();
}
if ($interval > 0) {
Cache::set($lockKey, 1, $interval);
}
$this->result->success($needAudit ? '评论已提交,等待审核' : '评论成功');
}
/**
* 点赞 / 取消点赞(文章或评论)
*
* POST: id=目标ID target=1(文章)|2(评论)
* 返回:{liked: bool, count: int}
*/
public function like()
{
if (!$this->auth || !$this->auth->isLogin) {
$this->result->error('请先登录后再点赞');
}
$uid = (int) ($this->auth->info['uid'] ?? 0);
$targetId = (int) input('id', 0);
$type = (int) input('target', 1);
if ($targetId <= 0) {
$this->result->error('参数错误');
}
$res = $type === ArticleLike::TYPE_COMMENT
? LikeService::toggleComment($uid, $targetId)
: LikeService::toggleArticle($uid, $targetId);
// 计数为 0 且未点赞,说明目标不存在或不可见
if (!$res['liked'] && $res['count'] === 0) {
$this->result->error('点赞失败:内容不存在或不可见');
}
$this->result->success($res, $res['liked'] ? '已点赞' : '已取消点赞');
}
/**
* 收藏 / 取消收藏
*
* POST: id=文章ID
* 返回:{favorited: bool}
*/
public function favorite()
{
if (!$this->auth || !$this->auth->isLogin) {
$this->result->error('请先登录后再收藏');
}
$uid = (int) ($this->auth->info['uid'] ?? 0);
$targetId = (int) input('id', 0);
if ($targetId <= 0) {
$this->result->error('参数错误');
}
$res = FavoriteService::toggle($uid, $targetId);
if (!$res['favorited'] && !FavoriteService::isFavorited($uid, $targetId)) {
// 目标文章不存在/不可收藏时,toggle 会返回未收藏
if (!\addon\articles\model\Article::where('id', $targetId)->where('status', 1)->count()) {
$this->result->error('收藏失败:文章不存在或未发布');
}
}
$this->result->success($res, $res['favorited'] ? '已收藏' : '已取消收藏');
}
/**
* 时间字段转时间戳(模型可能返回日期字符串,取决于类型配置)
*/
private static function toTs($value): int
{
if (is_numeric($value)) {
return (int) $value;
}
$ts = strtotime((string) $value);
return $ts ?: 0;
}
}
+36 -2
View File
@@ -18,6 +18,7 @@ declare (strict_types = 1);
namespace addon\articles\controller;
use ywxapp\controller\FrontendBase;
use think\facade\Cache;
use addon\articles\model\Article;
use addon\articles\model\ArticleCategory;
use addon\articles\model\ArticleTag;
@@ -38,13 +39,46 @@ class ArticlesFrontend extends FrontendBase
$isLogin = $this->auth && $this->auth->isLogin;
$loginUser = $isLogin ? $this->auth->info : null;
// 分类/标签变动频率低,缓存 5 分钟(缓存数组,避免序列化模型集合)
$categories = Cache::remember('articles:categories', function () {
return ArticleCategory::allEnable()->toArray();
}, 300);
$tags = Cache::remember('articles:tags', function () {
return ArticleTag::where('delete_at', 0)->order('id', 'desc')->limit(20)->select()->toArray();
}, 300);
$this->view->assign([
'categories' => ArticleCategory::allEnable(),
'tags' => ArticleTag::where('delete_at', 0)->order('id', 'desc')->limit(20)->select(),
'categories' => $categories,
'tags' => $tags,
'hot' => Article::hot(10),
'is_login' => $isLogin,
'member' => $loginUser,
'nav_active' => '',
]);
}
/**
* 浏览量计数(同一访客同一文章 5 分钟内只算 1 次)
*
* 用缓存节流而非 Session:前台对游客开放,游客请求未必启动 Session,
* 且浏览量属统计类数据,不应强依赖会话。
*
* @param int $id 文章ID
*/
protected function bumpViews(int $id): void
{
if ($id <= 0) {
return;
}
$fingerprint = md5($this->request->ip() . '|' . (string) $this->request->header('user-agent', ''));
$key = 'articles_view:' . $id . ':' . $fingerprint;
if (Cache::get($key, 0)) {
return; // 5 分钟内已计过
}
Article::where('id', $id)->inc('view_count')->update();
Cache::set($key, 1, 300);
}
}
+2 -1
View File
@@ -17,7 +17,8 @@ class Category extends ArticlesFrontend
{
$category = ArticleCategory::getById((int) $id);
if (!$category) {
$this->result->error('分类不存在');
// 软 404 会被搜索引擎收录:显式返回 HTTP 404
return $this->result->setStatusCode(404)->error('分类不存在', 404);
}
$page = (int) input('page', 1);
$list = Article::listArticles(['cid' => $id], $page, 10);
-2
View File
@@ -24,8 +24,6 @@ class Index extends ArticlesFrontend
{
public function index()
{
// dump($this->app->route);die;
$page = (int) input('page', 1);
$list = Article::listArticles([], $page, 10);
+166
View File
@@ -0,0 +1,166 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\controller;
use addon\articles\model\Article;
use addon\articles\model\ArticleCategory;
use addon\articles\model\ArticleTopic;
use think\facade\Request;
/**
* 站点地图(前台 SEO 用)
*
* 文章数 ≤ 5000:sitemap.xml 直接输出全部 URL(urlset)
* 文章数 > 5000:sitemap.xml 输出 sitemap index,文章拆到 sitemap-<n>.xml 分片
* (单文件 URL 上限 5 万条、体积 50MB,这里按 5000 条分片留足余量)
*
* 收录范围:插件首页 / 分类 / 专题 / 已发布且未删除的文章(草稿与待审不收录)
*
* @author ywxapp <admin@ywxapp.cn>
*/
class Sitemap extends ArticlesFrontend
{
/** 单个 sitemap 文件最多包含的 URL 数 */
const MAX_PER_FILE = 5000;
/**
* /articles/sitemap.xml
*/
public function index()
{
$base = Request::domain();
$total = Article::scope('normal')->count();
// 首页 / 分类 / 专题(条目少,始终放在索引或主文件中)
$static = [
['loc' => $base . (string) url('articles/index/index'), 'priority' => '1.0', 'lastmod' => date('Y-m-d')],
['loc' => $base . (string) url('articles/topic/index'), 'priority' => '0.7'],
];
foreach (ArticleCategory::allEnable() as $c) {
$static[] = [
'loc' => $base . (string) url('articles/category/index', ['id' => $c->id]),
'priority' => '0.6',
];
}
foreach (ArticleTopic::scope('enable')->select() as $t) {
$static[] = [
'loc' => $base . (string) url('articles/topic/' . $t->id),
'priority' => '0.7',
];
}
// 文章过多 → 输出 sitemap index(静态条目放主文件,文章分片)
if ($total > self::MAX_PER_FILE) {
$pages = (int) ceil($total / self::MAX_PER_FILE);
$maps = $static;
for ($i = 1; $i <= $pages; $i++) {
// 分片文件 URL 手工拼接:url() 会追加 .html 后缀,不能用于 .xml
$maps[] = [
'loc' => $base . '/articles/sitemap-' . $i . '.xml',
'lastmod' => date('Y-m-d'),
'priority' => '0.8',
];
}
return response(self::renderIndex($maps), 200, ['Content-Type' => 'application/xml; charset=utf-8']);
}
// 常规:单文件输出(静态 + 全部文章)
$items = $static;
foreach (Article::scope('normal')->field('id,update_at')->order('id', 'desc')->select() as $a) {
$items[] = [
'loc' => $base . (string) url('articles/read/' . $a->id),
'lastmod' => date('Y-m-d', (int) $a->update_at ?: time()),
'priority' => '0.8',
];
}
return response(self::renderUrlset($items), 200, ['Content-Type' => 'application/xml; charset=utf-8']);
}
/**
* 文章分片:/articles/sitemap-<page>.xml
*/
public function chunk($page = 1)
{
$page = max(1, (int) $page);
$base = Request::domain();
$total = Article::scope('normal')->count();
$pages = max(1, (int) ceil($total / self::MAX_PER_FILE));
if ($page > $pages) {
// 越界分片返回空 urlset,避免搜索引擎误判为错误
return response(self::renderUrlset([]), 200, ['Content-Type' => 'application/xml; charset=utf-8']);
}
$articles = Article::scope('normal')
->field('id,update_at')
->order('id', 'desc')
->page($page, self::MAX_PER_FILE)
->select();
$items = [];
foreach ($articles as $a) {
$items[] = [
'loc' => $base . (string) url('articles/read/' . $a->id),
'lastmod' => date('Y-m-d', (int) $a->update_at ?: time()),
'priority' => '0.8',
];
}
return response(self::renderUrlset($items), 200, ['Content-Type' => 'application/xml; charset=utf-8']);
}
/**
* 渲染 urlset
*/
private static function renderUrlset(array $items): string
{
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n"
. '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($items as $item) {
$xml .= " <url>\n";
$xml .= ' <loc>' . self::esc($item['loc'] ?? '') . "</loc>\n";
if (!empty($item['lastmod'])) {
$xml .= ' <lastmod>' . $item['lastmod'] . "</lastmod>\n";
}
$xml .= ' <priority>' . ($item['priority'] ?? '0.5') . "</priority>\n";
$xml .= " </url>\n";
}
return $xml . '</urlset>';
}
/**
* 渲染 sitemap index
*/
private static function renderIndex(array $items): string
{
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n"
. '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($items as $item) {
$xml .= " <sitemap>\n";
$xml .= ' <loc>' . self::esc($item['loc'] ?? '') . "</loc>\n";
if (!empty($item['lastmod'])) {
$xml .= ' <lastmod>' . $item['lastmod'] . "</lastmod>\n";
}
$xml .= " </sitemap>\n";
}
return $xml . '</sitemapindex>';
}
private static function esc(string $value): string
{
return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}
}
+2 -1
View File
@@ -17,7 +17,8 @@ class Tag extends ArticlesFrontend
{
$tag = ArticleTag::where('delete_at', 0)->find($id);
if (!$tag) {
$this->result->error('标签不存在');
// 软 404 会被搜索引擎收录:显式返回 HTTP 404
return $this->result->setStatusCode(404)->error('标签不存在', 404);
}
$page = (int) input('page', 1);
$list = Article::listArticles(['tid' => $id], $page, 10);
+92
View File
@@ -0,0 +1,92 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\controller;
use addon\articles\model\Article;
use addon\articles\model\ArticleTopic;
use addon\articles\model\ArticleTopicArticle;
use think\facade\Cache;
/**
* 前台专题聚合页
*
* /articles/topic 专题列表
* /articles/topic/<id> 专题详情(专题内文章列表)
*/
class Topic extends ArticlesFrontend
{
/**
* 专题列表
*/
public function index()
{
$topics = Cache::remember('articles:topics', function () {
$list = ArticleTopic::scope('enable')
->order('sort', 'desc')
->order('id', 'desc')
->select();
$rows = [];
foreach ($list as $t) {
$rows[] = [
'id' => $t->id,
'title' => $t->title,
'alias' => $t->alias,
'description' => $t->description,
'cover' => $t->cover,
'count' => ArticleTopicArticle::where('tid', $t->id)->count(),
];
}
return $rows;
}, 300);
$this->view->assign([
'topics' => $topics,
'nav_active' => '',
]);
return $this->fetch('topic/index');
}
/**
* 专题详情(文章聚合)
*/
public function detail($id = 0)
{
$topic = ArticleTopic::scope('enable')->find((int) $id);
if (!$topic) {
return $this->result->setStatusCode(404)->error('专题不存在或已下线', 404);
}
$page = (int) input('page', 1);
$ids = ArticleTopicArticle::articleIdsOf((int) $topic->id);
$list = [];
if ($ids) {
// 只取已发布且到点的文章,并保持专题内排序
$list = Article::with(['category'])
->field(Article::listFields())
->whereIn('id', $ids)
->scope('normal')
->orderRaw('FIELD(id,' . implode(',', $ids) . ')')
->paginate(['list_rows' => 10, 'page' => $page]);
}
$this->view->assign([
'topic' => $topic,
'list' => $list ? $list->items() : [],
'page' => $list ? $list->render() : '',
'nav_active' => '',
]);
return $this->fetch('topic/detail');
}
}
+229
View File
@@ -0,0 +1,229 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\controller\api;
// 注意:本类就叫 Article,模型必须起别名,否则「类名已被占用」致命错误
use addon\articles\model\Article as ArticleModel;
use addon\articles\model\ArticleCategory;
use addon\articles\model\ArticleComment;
use addon\articles\model\ArticleTag;
use think\facade\Cache;
use ywxapp\controller\ApiBase;
use ywxapp\service\AddonService;
/**
* 文章CMS 对外 API
*
* 鉴权:继承 ApiBase(默认需登录);列表/详情/分类/标签/搜索放行游客,
* 评论必须登录($noNeedLogin 未包含 comment)。
*
* URL:/articles/api/articles 等(见 route/app.php)
*/
class Article extends ApiBase
{
/** 免登录方法(评论不在其中,必须登录) */
protected $noNeedLogin = ['index', 'read', 'categories', 'tags', 'search'];
/**
* 文章列表
* 参数:page / cid / tid
*/
public function index()
{
$page = (int) input('page/d', 1);
$cid = (int) input('cid/d', 0);
$tid = (int) input('tid/d', 0);
$where = [];
if ($cid > 0) {
$where['cid'] = $cid;
}
if ($tid > 0) {
$where['tid'] = $tid;
}
$list = ArticleModel::listArticles($where, $page, $this->pageSize());
$rows = [];
foreach ($list->items() as $a) {
$rows[] = [
'id' => $a->id,
'title' => $a->title,
'summary' => $a->summary,
'cover_image' => $a->cover_image,
'cid' => $a->cid,
'category' => $a->category_name ?? '',
'view_count' => (int) $a->view_count,
'comment_count' => (int) $a->comment_count,
'create_at' => $a->create_at,
];
}
$this->apiSuccess($rows, 'success', $list->total());
}
/**
* 文章详情(正文已在入库时做过白名单净化,可安全下发)
*/
public function read($id = 0)
{
$id = (int) ($id ?: input('id/d', 0));
$article = ArticleModel::getDetail($id);
if (!$article) {
$this->apiError('文章不存在或已下线', 404, null, 404);
}
ArticleModel::where('id', $id)->inc('view_count')->update();
$tags = [];
foreach ($article->tags as $t) {
$tags[] = ['id' => $t->id, 'name' => $t->name];
}
$this->apiSuccess([
'id' => $article->id,
'title' => $article->title,
'content' => $article->content,
'summary' => $article->summary,
'cover_image' => $article->cover_image,
'author' => $article->author,
'cid' => $article->cid,
'category' => $article->category_name ?? '',
'view_count' => (int) $article->view_count,
'comment_count' => (int) $article->comment_count,
'create_at' => $article->create_at,
'tags' => $tags,
]);
}
/**
* 分类列表
*/
public function categories()
{
$rows = [];
foreach (ArticleCategory::allEnable() as $c) {
$rows[] = [
'id' => $c->id,
'name' => $c->name,
'alias' => $c->alias,
'description' => $c->description,
];
}
$this->apiSuccess($rows, 'success', count($rows));
}
/**
* 标签列表
*/
public function tags()
{
$rows = [];
foreach (ArticleTag::where('delete_at', 0)->order('id', 'desc')->select() as $t) {
$rows[] = ['id' => $t->id, 'name' => $t->name, 'alias' => $t->alias];
}
$this->apiSuccess($rows, 'success', count($rows));
}
/**
* 搜索
*/
public function search()
{
$keyword = trim((string) input('keyword/s', ''));
$page = (int) input('page/d', 1);
$list = ArticleModel::listArticles(['keyword' => $keyword], $page, $this->pageSize());
$rows = [];
foreach ($list->items() as $a) {
$rows[] = [
'id' => $a->id,
'title' => $a->title,
'summary' => $a->summary,
'cid' => $a->cid,
'category' => $a->category_name ?? '',
'create_at' => $a->create_at,
];
}
$this->apiSuccess($rows, 'success', $list->total());
}
/**
* 发表评论(需登录)
*/
public function comment()
{
$aid = (int) input('aid/d', 0);
$content = trim((string) input('content/s', ''));
if ($aid <= 0 || $content === '') {
$this->apiError('参数错误');
}
$len = mb_strlen($content, 'UTF-8');
if ($len < 2) {
$this->apiError('评论内容太短');
}
if ($len > 500) {
$this->apiError('评论内容不能超过 500 字');
}
// 目标文章必须存在且已发布
$article = ArticleModel::where('id', $aid)->where('status', 1)->where('delete_at', 0)->find();
if (!$article) {
$this->apiError('文章不存在或未发布');
}
$cfg = AddonService::config('articles');
$needAudit = !empty($cfg['comment_audit']);
$interval = max(0, (int) ($cfg['comment_interval'] ?? 10));
$uid = (int) $this->uid();
$lockKey = 'articles_comment_lock:' . $uid;
if ($interval > 0 && Cache::get($lockKey, 0)) {
$this->apiError('评论太频繁,请稍后再试');
}
ArticleComment::create([
'uid' => $uid,
'aid' => $aid,
'pid' => 0,
'content' => $content,
'status' => $needAudit ? 0 : 1,
'ip' => (string) $this->request->ip(),
'user_agent' => mb_substr((string) $this->request->header('user-agent', ''), 0, 255),
'create_at' => time(),
'update_at' => time(),
]);
if (!$needAudit) {
ArticleModel::where('id', $aid)->inc('comment_count')->update();
}
if ($interval > 0) {
Cache::set($lockKey, 1, $interval);
}
$this->apiSuccess(null, $needAudit ? '评论已提交,等待审核' : '评论成功');
}
/**
* 每页条数(取自插件配置)
*/
private function pageSize(): int
{
$cfg = AddonService::config('articles');
$size = (int) ($cfg['page_size'] ?? 10);
return $size > 0 ? min($size, 50) : 10;
}
}
+146 -23
View File
@@ -14,13 +14,16 @@ use think\Validate;
use ywxapp\controller\BackendBase;
use addon\articles\model\Article as ArticleModel;
use addon\articles\model\ArticleCategory;
use addon\articles\model\ArticleComment;
use addon\articles\model\ArticleTag;
use addon\articles\model\ArticleArticleTag;
use addon\articles\library\ArticleSchema;
use addon\articles\library\HtmlSanitizer;
class Article extends BackendBase
{
protected $noNeedVerify = ['*'];
// 后台写操作走菜单权限节点校验,不放开免校验白名单
protected $noNeedVerify = [];
protected function initialize()
{
@@ -36,7 +39,8 @@ class Article extends BackendBase
$limit = Request::param('limit', 15);
if (Request::isAjax()) {
$query = ArticleModel::with(['category']);
// 列表排除正文(longtext),字段由 listFields() 动态生成
$query = ArticleModel::with(['category'])->field(ArticleModel::listFields());
if ($status !== 'all') {
$query->where('status', $status);
}
@@ -59,10 +63,17 @@ class Article extends BackendBase
'view_count' => (int) $a->view_count,
'comment_count' => (int) $a->comment_count,
'create_at' => $a->create_at,
'edit_url' => (string) url('articles/backend.article/edit', ['id' => $a->id]),
'edit_url' => (string) url('articles/backend/article/edit', ['id' => $a->id]),
];
}
return json(['code' => 0, 'msg' => '', 'count' => $paginator->total(), 'data' => $rows]);
// ↓↓↓ 临时诊断标记(确认 Web 实际加载的是不是本文件 + 真实 SQL),定位后移除
$diag = [
'mtime' => date('Y-m-d H:i:s', filemtime(__FILE__)),
'sql' => (string) ArticleModel::fetchSql(true)->order('id', 'desc')->limit(1)->select(),
];
// ↑↑↑ 临时诊断标记
return json(['code' => 0, 'msg' => '', 'count' => $paginator->total(), 'data' => $rows, '__diag' => $diag]);
}
return View::fetch('article/index', ['status' => $status, 'keyword' => $keyword]);
@@ -88,7 +99,8 @@ class Article extends BackendBase
{
$article = ArticleModel::with(['tags'])->find($id);
if (!$article) {
return redirect('/articles/backend/article');
// 用 url() 生成:绑定独立域名后自动切换,不要硬编码 '/articles/backend/...'
return redirect((string) url('articles/backend/article/index'));
}
$categories = ArticleCategory::where('delete_at', 0)->where('status', 1)->select();
$tags = ArticleTag::where('delete_at', 0)->select();
@@ -121,6 +133,28 @@ class Article extends BackendBase
return json(['code' => 0, 'msg' => $validate->getError()]);
}
// 定时发布:前端传 "Y-m-d H:i" 字符串,统一转时间戳(0 = 立即发布)
if (!empty($data['publish_time'])) {
$ts = strtotime((string) $data['publish_time']);
$data['publish_time'] = $ts ?: 0;
}
// 正文白名单净化:正文在前台是 |raw 直出(富文本必须原样输出),
// 所以必须在入库前净化,防止来源不可信时形成存储型 XSS。
if (!empty($data['content'])) {
$data['content'] = HtmlSanitizer::clean((string) $data['content']);
}
// 封面图地址校验:必须是 http(s):// 或 / 开头的 URL,避免填成裸字符串导致坏图
if (!empty($data['cover_image']) && !preg_match('#^(https?://|/)#i', (string) $data['cover_image'])) {
return json(['code' => 0, 'msg' => '封面图地址格式不正确(须为 http(s):// 或 / 开头)']);
}
// 字段白名单:防止通过表单注入 uid / view_count / delete_at 等非表单字段
$allow = ['title', 'content', 'summary', 'cover_image', 'uid', 'author',
'cid', 'status', 'is_top', 'is_recommend', 'publish_time',
'create_at', 'update_at'];
// 处理标签
$tagIds = [];
if (!empty($data['tags'])) {
@@ -130,31 +164,48 @@ class Article extends BackendBase
if ($name === '') {
continue;
}
$tag = ArticleTag::where('delete_at', 0)->where('name', $name)->find()
?: ArticleTag::create(['name' => $name, 'alias' => $name, 'create_at' => time(), 'update_at' => time()]);
$tag = ArticleTag::where('delete_at', 0)->where('name', $name)->find();
if (!$tag) {
// alias 用作 URL 标识:中文名不能直接当别名,用稳定的短哈希兜底
$tag = ArticleTag::create([
'name' => $name,
'alias' => 'tag-' . substr(md5($name), 0, 8),
'create_at' => time(),
'update_at' => time(),
]);
}
$tagIds[] = $tag->id;
}
}
if ($id) {
$article = ArticleModel::find($id);
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在']);
try {
if ($id) {
$article = ArticleModel::find($id);
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在']);
}
$article->allowField($allow)->save($data);
} else {
if (empty($data['uid'])) {
$data['uid'] = $this->auth->info['uid'] ?? 0;
}
if (empty($data['author'])) {
$data['author'] = $this->auth->info['nickname'] ?? '';
}
$data['create_at'] = time();
$article = ArticleModel::create($data, $allow);
$id = $article->id;
}
$article->save($data);
} else {
if (empty($data['uid'])) {
$data['uid'] = $this->auth->info['uid'] ?? 0;
}
if (empty($data['author'])) {
$data['author'] = $this->auth->info['nickname'] ?? '';
}
$data['create_at'] = time();
$article = ArticleModel::create($data);
$id = $article->id;
} catch (\Throwable $e) {
return json(['code' => 0, 'msg' => '保存失败:' . $e->getMessage()]);
}
ArticleArticleTag::syncTags($id, $tagIds);
return json(['code' => 1, 'msg' => '保存成功', 'url' => '/articles/backend/article']);
return json([
'code' => 1,
'msg' => '保存成功',
'url' => (string) url('articles/backend/article/index'),
]);
}
public function delete($id = 0)
@@ -163,11 +214,83 @@ class Article extends BackendBase
$article = ArticleModel::find($id);
if ($article) {
$article->delete();
// 一并清理标签关联与评论,避免孤儿数据
ArticleArticleTag::where('aid', $id)->delete();
ArticleComment::where('aid', $id)->delete();
return json(['code' => 1, 'msg' => '已删除']);
}
return json(['code' => 0, 'msg' => '文章不存在']);
}
/**
* 批量删除(软删 + 清理标签关联与评论)
*/
public function batchDelete()
{
$ids = (array) Request::post('ids/a', []);
$ids = array_values(array_filter(array_map('intval', $ids)));
if (!$ids) {
return json(['code' => 0, 'msg' => '请选择要删除的文章']);
}
$count = 0;
foreach ($ids as $id) {
$article = ArticleModel::find($id);
if (!$article) {
continue;
}
$article->delete();
ArticleArticleTag::where('aid', $id)->delete();
ArticleComment::where('aid', $id)->delete();
$count++;
}
return json(['code' => 1, 'msg' => '已删除 ' . $count . ' 篇']);
}
/**
* 批量设置状态(1=发布 0=草稿)
*/
public function batchStatus()
{
$ids = (array) Request::post('ids/a', []);
$ids = array_values(array_filter(array_map('intval', $ids)));
$status = (int) Request::post('status', 1);
if (!$ids) {
return json(['code' => 0, 'msg' => '请选择文章']);
}
if (!in_array($status, [0, 1], true)) {
return json(['code' => 0, 'msg' => '状态值不合法']);
}
$count = ArticleModel::whereIn('id', $ids)
->update(['status' => $status, 'update_at' => time()]);
return json(['code' => 1, 'msg' => '已更新 ' . $count . ' 篇']);
}
/**
* 审核前台投稿(pass=1 通过并发布 / pass=0 拒绝并退回草稿)
*/
public function audit()
{
$id = (int) Request::post('id', 0);
$pass = (int) Request::post('pass', 1);
$article = ArticleModel::find($id);
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在']);
}
if ((int) $article->status !== 2) {
return json(['code' => 0, 'msg' => '该文章不是待审核状态']);
}
$article->save(['status' => $pass ? 1 : 0, 'update_at' => time()]);
return json(['code' => 1, 'msg' => $pass ? '审核通过,已发布' : '已拒绝,退回草稿']);
}
public function recyclebin()
{
$page = Request::param('page', 1);
@@ -0,0 +1,153 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\controller\backend;
use addon\articles\library\ArticleSchema;
use addon\articles\model\ArticleAttachment;
use think\facade\Request;
use think\facade\View;
use ywxapp\controller\BackendBase;
use ywxapp\service\FileStorageService;
/**
* 附件管理
*
* 上传走框架 FileStorageService(与 /upload 同源),这里额外做:
* - 后台专用:类型白名单 + 大小限制
* - 落库记录,便于统一查看与清理
*/
class Attachment extends BackendBase
{
protected $noNeedVerify = [];
/** 允许的文件类型 */
private const ALLOW_EXT = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp',
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
'zip', 'rar', 'txt', 'csv'];
/** 单文件上限(字节) */
private const MAX_SIZE = 10485760; // 10MB
protected function initialize()
{
parent::initialize();
ArticleSchema::ensure();
}
public function index()
{
if (Request::isAjax()) {
$page = Request::param('page', 1);
$limit = Request::param('limit', 15);
$aid = (int) Request::param('aid', 0);
$query = ArticleAttachment::order('id', 'desc');
if ($aid > 0) {
$query->where('aid', $aid);
}
$paginator = $query->paginate(['list_rows' => $limit, 'page' => $page]);
$rows = [];
foreach ($paginator->items() as $f) {
$rows[] = [
'id' => $f->id,
'name' => $f->name,
'url' => $f->url,
'ext' => $f->ext,
'size_text' => $f->size_text,
'aid' => (int) $f->aid,
'create_at' => $f->create_at,
];
}
return json(['code' => 0, 'msg' => '', 'count' => $paginator->total(), 'data' => $rows]);
}
return View::fetch('attachment/index');
}
/**
* 上传并记录
*/
public function upload()
{
$file = Request::file('file');
if (!$file || !$file->isValid()) {
return json(['code' => 0, 'msg' => '未获取到上传文件']);
}
$ext = strtolower($file->extension());
if (!in_array($ext, self::ALLOW_EXT, true)) {
return json(['code' => 0, 'msg' => '不支持的文件类型:' . $ext]);
}
if ($file->getSize() > self::MAX_SIZE) {
return json(['code' => 0, 'msg' => '文件不能超过 ' . (self::MAX_SIZE / 1048576) . 'MB']);
}
// 真实 MIME 二次校验(防改扩展名)
$mime = (string) $file->getMime();
if ($mime !== '' && preg_match('#^text/(x-)?php#i', $mime)) {
return json(['code' => 0, 'msg' => '危险文件类型']);
}
try {
$storage = new FileStorageService();
$result = $storage->upload($file, 'articles/' . date('Ymd'));
$record = ArticleAttachment::record(
is_array($result) ? $result : ['url' => (string) $result],
(int) ($this->auth->info['uid'] ?? 0),
(int) Request::post('aid', 0)
);
return json([
'code' => 1,
'msg' => '上传成功',
'data' => ['id' => $record->id, 'url' => $record->url],
]);
} catch (\Throwable $e) {
return json(['code' => 0, 'msg' => '上传失败:' . $e->getMessage()]);
}
}
/**
* 删除记录并尝试清理物理文件
*/
public function delete($id = 0)
{
$id = (int) ($id ?: Request::post('id', 0));
$att = ArticleAttachment::find($id);
if (!$att) {
return json(['code' => 0, 'msg' => '记录不存在']);
}
// 删除物理文件(限定在 public 目录内,防目录穿越)
$rel = ltrim((string) $att->path, '/');
$url = ltrim((string) $att->url, '/');
$root = rtrim((string) public_path(), DIRECTORY_SEPARATOR);
foreach ([$rel, $url] as $candidate) {
if ($candidate === '' || strpos($candidate, '..') !== false) {
continue;
}
$full = $root . DIRECTORY_SEPARATOR . $candidate;
if (is_file($full)) {
@unlink($full);
break;
}
}
$att->delete();
return json(['code' => 1, 'msg' => '已删除']);
}
}
+34 -25
View File
@@ -8,6 +8,7 @@ declare(strict_types=1);
namespace addon\articles\controller\backend;
use think\facade\Cache;
use think\facade\Request;
use think\facade\View;
use think\Validate;
@@ -51,35 +52,26 @@ class Category extends BackendBase
'page' => $page,
'list_rows' => $size,
]);
$this->result->success($data->items());
// 必须回传 count,否则 layui 表格分页失效
return json(['code' => 0, 'msg' => '', 'count' => $data->total(), 'data' => $data->items()]);
}
$this->view->assign('title', '登录');
return $this->view->fetch('category/index');
}
public function save()
{
if (Request::isPost()) {
$data = Request::post();
$data['status'] = isset($data['status']) ? 1 : 0;
$validate = new Validate([
'name|名称' => 'require|max:50',
'alias|别名' => 'require|max:50',
]);
if (!$validate->check($data)) {
$this->result->error($validate->getError());
}
ArticleCategory::create($data);
$this->result->success();
return $this->update(0);
}
// GET:渲染新增表单(原实现无返回值,会输出空白页)
return View::fetch('category/edit', ['category' => null]);
}
public function edit($id = null)
{
$category = ArticleCategory::find($id);
if (!$category) {
return redirect('/articles/backend/category');
return redirect((string) url('articles/backend/category/index'));
}
return View::fetch('category/edit', ['category' => $category]);
}
@@ -99,17 +91,33 @@ class Category extends BackendBase
return json(['code' => 0, 'msg' => $validate->getError()]);
}
if ($id) {
$category = ArticleCategory::find($id);
if (!$category) {
return json(['code' => 0, 'msg' => '分类不存在']);
// 字段白名单(category 表实际列)
$allow = ['name', 'alias', 'description', 'cover', 'sort', 'status', 'create_at', 'update_at'];
try {
if ($id) {
$category = ArticleCategory::find($id);
if (!$category) {
return json(['code' => 0, 'msg' => '分类不存在']);
}
$category->allowField($allow)->save($data);
} else {
$data['create_at'] = time();
ArticleCategory::create($data, $allow);
}
$category->save($data);
} else {
$data['create_at'] = time();
ArticleCategory::create($data);
} catch (\Throwable $e) {
// alias 上有唯一键 uk_alias,重复会抛异常,转友好提示
return json(['code' => 0, 'msg' => '保存失败:别名可能已存在']);
}
return json(['code' => 0, 'msg' => '保存成功', 'url' => '/articles/backend/category']);
// 前台侧边栏分类有 5 分钟缓存,写操作后立即失效
Cache::delete('articles:categories');
return json([
'code' => 1,
'msg' => '保存成功',
'url' => (string) url('articles/backend/category/index'),
]);
}
public function delete($id = 0)
@@ -121,7 +129,8 @@ class Category extends BackendBase
return json(['code' => 0, 'msg' => '该分类下还有文章,无法删除']);
}
$category->delete();
return json(['code' => 0, 'msg' => '已删除']);
Cache::delete('articles:categories');
return json(['code' => 1, 'msg' => '已删除']);
}
return json(['code' => 0, 'msg' => '分类不存在']);
}
@@ -17,7 +17,8 @@ use addon\articles\library\ArticleSchema;
class Comment extends BackendBase
{
protected $noNeedVerify = ['*'];
// 后台操作走菜单权限节点校验,不放开免校验白名单
protected $noNeedVerify = [];
protected function initialize()
{
@@ -64,9 +65,13 @@ class Comment extends BackendBase
$id = $id ?: (int) Request::post('id', 0);
$comment = ArticleComment::find($id);
if ($comment) {
// 只在「未通过 → 通过」时累加计数:重复审核不会把评论数刷高
$wasPending = (int) $comment->status !== 1;
$comment->status = 1;
$comment->save();
Article::where('id', $comment->aid)->inc('comment_count')->update();
if ($wasPending) {
Article::where('id', $comment->aid)->inc('comment_count')->update();
}
return json(['code' => 1, 'msg' => '审核通过']);
}
return json(['code' => 0, 'msg' => '评论不存在']);
@@ -78,6 +83,8 @@ class Comment extends BackendBase
$comment = ArticleComment::find($id);
if ($comment) {
$comment->delete();
// 同步回退文章评论数,保持计数准确
Article::where('id', $comment->aid)->where('comment_count', '>', 0)->dec('comment_count')->update();
return json(['code' => 1, 'msg' => '已删除']);
}
return json(['code' => 0, 'msg' => '评论不存在']);
@@ -0,0 +1,75 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\controller\backend;
use addon\articles\library\ArticleSchema;
use addon\articles\model\Article as ArticleModel;
use addon\articles\model\ArticleCategory;
use addon\articles\model\ArticleComment;
use ywxapp\controller\BackendBase;
/**
* 文章CMS 后台仪表盘(统计概览)
*/
class Dashboard extends BackendBase
{
protected $noNeedVerify = [];
protected function initialize()
{
parent::initialize();
ArticleSchema::ensure();
}
public function index()
{
$today = strtotime('today');
$stats = [
'total' => ArticleModel::count(),
'published' => ArticleModel::where('status', 1)->count(),
'draft' => ArticleModel::where('status', 0)->count(),
'pending' => ArticleModel::scope('pending')->count(),
'today' => ArticleModel::where('create_at', '>=', $today)->count(),
'views' => (int) ArticleModel::sum('view_count'),
'comments' => ArticleComment::count(),
'pending_comments' => ArticleComment::where('status', 0)->count(),
'trashed' => ArticleModel::onlyTrashed()->count(),
];
// 分类分布(Top 10)
$dist = [];
foreach (ArticleCategory::where('delete_at', 0)->order('sort', 'desc')->select() as $c) {
$dist[] = [
'id' => $c->id,
'name' => $c->name,
'count' => ArticleModel::where('cid', $c->id)->count(),
];
}
usort($dist, function ($a, $b) {
return $b['count'] <=> $a['count'];
});
$dist = array_slice($dist, 0, 10);
// 热门文章 Top 10
$hot = ArticleModel::where('status', 1)
->field('id,title,view_count,comment_count')
->order('view_count', 'desc')
->limit(10)
->select();
return $this->view->fetch('dashboard/index', [
'stats' => $stats,
'dist' => $dist,
'hot' => $hot,
]);
}
}
+151
View File
@@ -0,0 +1,151 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\controller\backend;
use addon\articles\library\ArticleSchema;
use addon\articles\model\Article as ArticleModel;
use addon\articles\model\ArticleTopic;
use addon\articles\model\ArticleTopicArticle;
use think\facade\Cache;
use think\facade\Request;
use think\facade\View;
use think\Validate;
use ywxapp\controller\BackendBase;
/**
* 文章专题管理(运营聚合页)
*/
class Topic extends BackendBase
{
protected $noNeedVerify = [];
protected function initialize()
{
parent::initialize();
ArticleSchema::ensure();
}
public function index()
{
if (Request::isAjax()) {
$page = Request::param('page', 1);
$limit = Request::param('limit', 15);
$paginator = ArticleTopic::order('sort', 'desc')->order('id', 'desc')
->paginate(['list_rows' => $limit, 'page' => $page]);
$rows = [];
foreach ($paginator->items() as $t) {
$rows[] = [
'id' => $t->id,
'title' => $t->title,
'alias' => $t->alias,
'sort' => (int) $t->sort,
'status' => $t->status,
'article_count' => ArticleTopicArticle::where('tid', $t->id)->count(),
'create_at' => $t->create_at,
'edit_url' => (string) url('articles/backend/topic/edit', ['id' => $t->id]),
];
}
return json(['code' => 0, 'msg' => '', 'count' => $paginator->total(), 'data' => $rows]);
}
return View::fetch('topic/index');
}
public function save()
{
if (Request::isPost()) {
return $this->update(0);
}
return View::fetch('topic/edit', ['topic' => null, 'picked' => []]);
}
public function edit($id = null)
{
$topic = ArticleTopic::find($id);
if (!$topic) {
return redirect((string) url('articles/backend/topic/index'));
}
$ids = ArticleTopicArticle::articleIdsOf((int) $topic->id);
$picked = $ids
? ArticleModel::whereIn('id', $ids)->field('id,title')->select()->toArray()
: [];
return View::fetch('topic/edit', ['topic' => $topic, 'picked' => $picked]);
}
public function update($id = 0)
{
$data = Request::post();
$id = $id ?: (int) ($data['id'] ?? 0);
$data['update_at'] = time();
$data['status'] = isset($data['status']) ? 1 : 0;
$validate = new Validate([
'title|标题' => 'require|max:100',
'alias|别名' => 'require|max:50',
]);
if (!$validate->check($data)) {
return json(['code' => 0, 'msg' => $validate->getError()]);
}
// 关联文章:逗号分隔的文章ID(顺序即专题内排序)
$articleIds = array_values(array_filter(array_map('intval', explode(',', (string) ($data['article_ids'] ?? '')))));
$allow = ['title', 'alias', 'description', 'cover', 'sort', 'status', 'create_at', 'update_at'];
try {
if ($id) {
$topic = ArticleTopic::find($id);
if (!$topic) {
return json(['code' => 0, 'msg' => '专题不存在']);
}
$topic->allowField($allow)->save($data);
} else {
$data['create_at'] = time();
$topic = ArticleTopic::create($data, $allow);
$id = $topic->id;
}
} catch (\Throwable $e) {
// alias 上有唯一键 uk_alias
return json(['code' => 0, 'msg' => '保存失败:别名可能已存在']);
}
ArticleTopicArticle::syncArticles((int) $id, $articleIds);
// 前台专题聚合页有缓存,写操作后立即失效
Cache::delete('articles:topics');
return json([
'code' => 1,
'msg' => '保存成功',
'url' => (string) url('articles/backend/topic/index'),
]);
}
public function delete($id = 0)
{
$id = (int) ($id ?: Request::post('id', 0));
$topic = ArticleTopic::find($id);
if (!$topic) {
return json(['code' => 0, 'msg' => '专题不存在']);
}
$topic->delete();
ArticleTopicArticle::where('tid', $id)->delete();
Cache::delete('articles:topics');
return json(['code' => 1, 'msg' => '已删除']);
}
}
@@ -0,0 +1,150 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\controller\member;
use addon\articles\library\HtmlSanitizer;
use addon\articles\model\Article as ArticleModel;
use addon\articles\model\ArticleCategory;
use think\Validate;
use ywxapp\controller\MemberBase;
/**
* 会员中心 · 我的投稿
*
* 投稿统一写入 status=2(待审核),由后台审核通过后(status=1)才对前台可见。
* 会员只能查看/编辑/删除【自己】的文章。
*/
class Article extends MemberBase
{
/** 投稿必须登录 */
protected $noNeedLogin = [];
/**
* 我的投稿列表
*/
public function index()
{
$uid = $this->uid();
$list = ArticleModel::where('uid', $uid)
->field(ArticleModel::listFields())
->order('id', 'desc')
->paginate(['list_rows' => 10, 'page' => (int) input('page', 1)]);
return $this->fetch('article/index', ['list' => $list]);
}
/**
* 写新稿件
*/
public function add()
{
return $this->fetch('article/edit', [
'article' => null,
'categories' => $this->categories(),
]);
}
/**
* 编辑自己的稿件
*/
public function edit($id = 0)
{
$article = ArticleModel::where('id', (int) $id)->where('uid', $this->uid())->find();
if (!$article) {
$this->result->error('文章不存在或不属于你');
}
return $this->fetch('article/edit', [
'article' => $article,
'categories' => $this->categories(),
]);
}
/**
* 保存投稿(新增或编辑,保存后一律置为待审核)
*/
public function save()
{
if (!$this->request->isPost()) {
return redirect((string) url('articles/member/article/index'));
}
$uid = $this->uid();
$data = $this->request->post();
$id = (int) ($data['id'] ?? 0);
$validate = new Validate([
'title|标题' => 'require|max:255',
'content|内容' => 'require',
'cid|分类' => 'require|number',
]);
if (!$validate->check($data)) {
$this->result->error($validate->getError());
}
// 正文必须净化(前台来源不可信)
$data['content'] = HtmlSanitizer::clean((string) $data['content']);
$data['status'] = 2; // 待审核
$data['uid'] = $uid;
$data['author'] = $this->auth->info['nickname'] ?? '';
$data['is_top'] = 0;
$data['is_recommend'] = 0;
$data['update_at'] = time();
$allow = ['title', 'content', 'summary', 'cover_image', 'uid', 'author',
'cid', 'status', 'is_top', 'is_recommend', 'create_at', 'update_at'];
if ($id) {
$article = ArticleModel::where('id', $id)->where('uid', $uid)->find();
if (!$article) {
$this->result->error('文章不存在或不属于你');
}
$article->allowField($allow)->save($data);
} else {
$data['create_at'] = time();
ArticleModel::create($data, $allow);
}
$this->result->success(null, '投稿已提交,等待管理员审核');
}
/**
* 删除自己的稿件(软删)
*/
public function delete($id = 0)
{
$id = (int) ($id ?: input('id', 0));
$article = ArticleModel::where('id', $id)->where('uid', $this->uid())->find();
if (!$article) {
$this->result->error('文章不存在或不属于你');
}
$article->delete();
$this->result->success(null, '已删除');
}
/**
* 当前会员UID
*/
private function uid(): int
{
return (int) ($this->auth->info['uid'] ?? 0);
}
/**
* 可选分类
*/
private function categories()
{
return ArticleCategory::where('delete_at', 0)->where('status', 1)->select();
}
}
+4 -1
View File
@@ -3,12 +3,15 @@
return [
'name' => 'articles',
'title' => '文章CMS',
// intro 为 AddonBase::checkInfo() 校验的六项之一(name/title/intro/author/version/state)
'intro' => '完整文章类 CMS 插件:文章、分类、标签、评论,前台套用 layuiSimpleNews 模板',
'description' => '完整文章类 CMS 插件:文章、分类、标签、评论,前台套用 layuiSimpleNews 模板',
'status' => 1,
'author' => 'ywxapp',
'version' => '1.0.1',
'type' => 1,
'state' => 0,
// state=1 启用:框架按 info.php 的 state 过滤加载(路由/事件/配置预热),禁用时全部不生效
'state' => 1,
'install_time' => 1786348115,
'update_time' => 1786366229,
];
+105 -5
View File
@@ -4,9 +4,10 @@
-- (仅允许 CREATE TABLE / INSERT,见 importsql 白名单)。
-- 表名须为 __PREFIX__articles_*,与插件名一致。
-- 时间字段统一:create_at / update_at / delete_at(int 时间戳,0=未删)
--
-- 注意:不要写 SET NAMES / SET FOREIGN_KEY_CHECKS / DROP / ALTER / UPDATE / DELETE,
-- 这些语句会被框架白名单跳过(只记 Log::warning),写了等于没执行。
-- ============================================================
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
CREATE TABLE IF NOT EXISTS `__PREFIX__articles_article` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
@@ -17,7 +18,8 @@ CREATE TABLE IF NOT EXISTS `__PREFIX__articles_article` (
`uid` int NOT NULL DEFAULT 0 COMMENT '作者ID(member_user.uid)',
`author` varchar(50) DEFAULT '' COMMENT '作者名(冗余)',
`cid` int NOT NULL DEFAULT 0 COMMENT '分类ID',
`status` tinyint(1) DEFAULT 1 COMMENT '状态:1发布 0草稿',
`status` tinyint(1) DEFAULT 1 COMMENT '状态:1发布 0草稿 2待审核',
`publish_time` int NOT NULL DEFAULT 0 COMMENT '定时发布时间(0=立即发布)',
`is_top` tinyint(1) DEFAULT 0 COMMENT '是否置顶',
`is_recommend` tinyint(1) DEFAULT 0 COMMENT '是否推荐',
`view_count` int DEFAULT 0 COMMENT '浏览次数',
@@ -30,7 +32,13 @@ CREATE TABLE IF NOT EXISTS `__PREFIX__articles_article` (
KEY `idx_uid` (`uid`),
KEY `idx_cid` (`cid`),
KEY `idx_status_create` (`status`,`create_at`),
KEY `idx_delete` (`delete_at`)
KEY `idx_delete` (`delete_at`),
-- 前台列表:status + delete_at 过滤后按 create_at 排序
KEY `idx_list` (`status`,`delete_at`,`create_at`),
-- 后台列表:order is_top / is_recommend
KEY `idx_top` (`is_top`,`is_recommend`),
-- 热门文章:order view_count desc
KEY `idx_view` (`view_count`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章表';
CREATE TABLE IF NOT EXISTS `__PREFIX__articles_category` (
@@ -69,6 +77,17 @@ CREATE TABLE IF NOT EXISTS `__PREFIX__articles_article_tag` (
KEY `idx_tid` (`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章标签关联表';
CREATE TABLE IF NOT EXISTS `__PREFIX__articles_like` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`uid` int NOT NULL DEFAULT 0 COMMENT '用户ID',
`target_id` int NOT NULL DEFAULT 0 COMMENT '目标ID(文章ID / 评论ID)',
`type` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=文章点赞 2=评论点赞',
`create_at` int NOT NULL DEFAULT 0 COMMENT '创建时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_user_target` (`uid`,`target_id`,`type`),
KEY `idx_target` (`target_id`,`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='点赞记录表(唯一键防重复点赞)';
CREATE TABLE IF NOT EXISTS `__PREFIX__articles_comment` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`uid` int NOT NULL DEFAULT 0 COMMENT '用户ID(member_user.uid)',
@@ -88,4 +107,85 @@ CREATE TABLE IF NOT EXISTS `__PREFIX__articles_comment` (
KEY `idx_delete` (`delete_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章评论表';
SET FOREIGN_KEY_CHECKS = 1;
CREATE TABLE IF NOT EXISTS `__PREFIX__articles_topic` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL DEFAULT '' COMMENT '专题标题',
`alias` varchar(50) NOT NULL DEFAULT '' COMMENT '别名(URL 标识,英文/数字)',
`description` varchar(500) DEFAULT '' COMMENT '专题描述',
`cover` varchar(255) DEFAULT '' COMMENT '封面图',
`sort` int DEFAULT 0 COMMENT '排序权重',
`status` tinyint(1) DEFAULT 1 COMMENT '状态:1启用 0禁用',
`create_at` int NOT NULL DEFAULT 0,
`update_at` int NOT NULL DEFAULT 0,
`delete_at` int NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_alias` (`alias`),
KEY `idx_delete` (`delete_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章专题表';
CREATE TABLE IF NOT EXISTS `__PREFIX__articles_topic_article` (
`tid` int NOT NULL COMMENT '专题ID',
`aid` int NOT NULL COMMENT '文章ID',
`sort` int DEFAULT 0 COMMENT '专题内排序',
PRIMARY KEY (`tid`,`aid`),
KEY `idx_aid` (`aid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='专题-文章关联表';
CREATE TABLE IF NOT EXISTS `__PREFIX__articles_favorite` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`uid` int NOT NULL DEFAULT 0 COMMENT '用户ID',
`aid` int NOT NULL DEFAULT 0 COMMENT '文章ID',
`create_at` int NOT NULL DEFAULT 0 COMMENT '收藏时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_user_article` (`uid`,`aid`),
KEY `idx_aid` (`aid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章收藏表';
CREATE TABLE IF NOT EXISTS `__PREFIX__articles_attachment` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`uid` int NOT NULL DEFAULT 0 COMMENT '上传者ID',
`name` varchar(255) DEFAULT '' COMMENT '原始文件名',
`url` varchar(255) DEFAULT '' COMMENT '访问地址',
`path` varchar(255) DEFAULT '' COMMENT '存储相对路径(删除文件用)',
`ext` varchar(20) DEFAULT '' COMMENT '扩展名',
`mime` varchar(100) DEFAULT '' COMMENT 'MIME类型',
`size` int unsigned DEFAULT 0 COMMENT '文件大小(字节)',
`aid` int NOT NULL DEFAULT 0 COMMENT '关联文章ID(0=未关联)',
`create_at` int NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `idx_aid` (`aid`),
KEY `idx_uid` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='附件表';
-- ============================================================
-- 种子数据:让新装站点有一份可直接查看的示例内容
-- 说明:框架会把 INSERT 改写为 INSERT IGNORE,且 category.alias /
-- tag.name 上有唯一键,重复导入安全;文章用 NOT EXISTS 判重。
-- ============================================================
INSERT INTO `__PREFIX__articles_category`
(`name`,`alias`,`description`,`sort`,`status`,`create_at`,`update_at`,`delete_at`)
VALUES
('资讯','news','站点动态与行业资讯',1,1,UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),0),
('教程','tutorial','使用教程与最佳实践',2,1,UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),0);
INSERT INTO `__PREFIX__articles_tag`
(`name`,`alias`,`description`,`create_at`,`update_at`,`delete_at`)
VALUES
('入门','getting-started','新手入门',UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),0),
('进阶','advanced','进阶技巧',UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),0);
INSERT INTO `__PREFIX__articles_article`
(`title`,`content`,`summary`,`cid`,`author`,`status`,`create_at`,`update_at`,`delete_at`)
SELECT
'欢迎使用文章CMS',
'<p>这是安装后自动生成的示例文章,可在后台「文章管理」中编辑或删除。</p>',
'安装后自动生成的示例文章',
(SELECT `id` FROM `__PREFIX__articles_category` WHERE `alias` = 'news' LIMIT 1),
'admin',
1,
UNIX_TIMESTAMP(),
UNIX_TIMESTAMP(),
0
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `__PREFIX__articles_article` WHERE `title` = '欢迎使用文章CMS');
+41
View File
@@ -0,0 +1,41 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
// | 文章CMS插件语言包(zh-cn)
// |
// | 由 addon/articles/common.php 在应用加载时自动载入。
// | 模板/代码中用 {:L('Articles')} 或 L('Articles') 取值;
// | 需要其它语种时新增 lang/<langset>.php 即可(键名保持一致)。
// +----------------------------------------------------------------------
return [
// ===== 前台通用 =====
'Articles' => '文章',
'Category' => '分类',
'Tag' => '标签',
'Search' => '搜索',
'Hot Articles' => '热门文章',
'Related Articles' => '相关阅读',
'Prev Article' => '上一篇',
'Next Article' => '下一篇',
'No data' => '暂无数据',
'Read more' => '阅读全文',
'Views' => '阅读',
'Comments' => '评论',
'Submit Comment' => '发表评论',
'Login to comment' => '请先登录后再评论',
'Comment pending' => '评论已提交,等待审核',
// ===== 后台 =====
'Article Manage' => '文章管理',
'New Article' => '新建文章',
'Recycle Bin' => '回收站',
'Publish' => '发布',
'Draft' => '草稿',
'Top' => '置顶',
'Recommend' => '推荐',
];
+183 -9
View File
@@ -2,27 +2,201 @@
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
// | 文章CMS插件数据表自愈聚合入口
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\library;
use addon\articles\model\Article;
use addon\articles\model\ArticleCategory;
use addon\articles\model\ArticleTag;
use addon\articles\model\ArticleComment;
use think\facade\Db;
/**
* 插件表结构自愈
*
* 背景(重要):
* - 框架 install.sql 导入有白名单,只执行 CREATE TABLE / INSERT,
* ALTER / DROP / UPDATE 会被跳过并记日志 → 老库升级缺列只能靠代码补。
* - 早期实现复用 BaseModel::ensureTableFromInstall(),它读的是**核心**
* public/install/install.sql(不含本插件表)→ 恒为空操作,还每请求
* 重复 file_get_contents + 正则解析大文件。
*
* 现方案:本类直接解析**插件自身** addon/articles/install.sql:
* - repair(false):只建表(轻量,首访兜底,同请求只跑一次)
* - repair(true) :建表 + 补列 + 补索引(install / upgrade 时调用)
*/
class ArticleSchema
{
/** 同一次请求内是否已检查过(避免每请求重复解析 SQL) */
private static bool $checked = false;
/** 需要补齐的性能索引:表名(不含前缀) => [索引名 => 列定义] */
private const INDEXES = [
'articles_article' => [
// 前台列表:status + delete_at 过滤后按 create_at 排序
'idx_list' => '`status`,`delete_at`,`create_at`',
// 后台列表:order is_top desc / is_recommend
'idx_top' => '`is_top`,`is_recommend`',
],
];
/**
* 插件启用/首访时调用,确保全部私有表存在
* 首访兜底:确保表存在(不补列,同请求只执行一次)
*/
public static function ensure(): void
{
Article::ensureSchema();
ArticleCategory::ensureSchema();
ArticleTag::ensureSchema();
ArticleComment::ensureSchema();
if (self::$checked) {
return;
}
self::$checked = true;
self::repair(false);
}
/**
* 完整自愈:建表(+ 补列 + 补索引)
*
* @param bool $withColumns 是否补列与补索引(升级场景传 true)
*/
public static function repair(bool $withColumns = true): void
{
$file = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'install.sql';
if (!is_file($file)) {
return;
}
$content = (string) file_get_contents($file);
$prefix = self::prefix();
// 解析 CREATE TABLE IF NOT EXISTS `__PREFIX__xxx` ( ... ) ENGINE=...;
preg_match_all(
'/CREATE TABLE IF NOT EXISTS\s+`__PREFIX__([a-z_]+)`\s*\((.*?)\)\s*ENGINE=[^;]*;/is',
$content,
$matches,
PREG_SET_ORDER
);
foreach ($matches as $m) {
$table = $prefix . $m[1];
self::ensureTable($table, str_replace('__PREFIX__', $prefix, $m[0]));
if ($withColumns) {
self::ensureColumns($table, $m[2]);
}
}
if ($withColumns) {
foreach (self::INDEXES as $table => $indexes) {
foreach ($indexes as $name => $cols) {
self::ensureIndex($prefix . $table, $name, $cols);
}
}
// 全文索引(可选):用于加速搜索,不支持时静默降级(搜索仍走 LIKE)
self::ensureFulltext($prefix . 'articles_article', 'ft_title_summary', '`title`,`summary`');
}
}
/**
* 当前数据库表前缀
*/
private static function prefix(): string
{
$default = (string) config('database.default', 'mysql');
return (string) config("database.connections.{$default}.prefix", '');
}
/**
* 表不存在则建表
*/
private static function ensureTable(string $table, string $ddl): void
{
try {
$exists = Db::query("SHOW TABLES LIKE '{$table}'");
if (empty($exists)) {
Db::execute($ddl);
}
} catch (\Throwable $e) {
// 建表失败不阻断访问,交由 install/upgrade 流程暴露
}
}
/**
* 按 install.sql 的列定义补列(SHOW COLUMNS 比对后 ALTER ADD COLUMN)
*/
private static function ensureColumns(string $table, string $body): void
{
$exists = [];
try {
foreach (Db::query("SHOW COLUMNS FROM `{$table}`") as $row) {
$exists[strtolower((string) $row['Field'])] = true;
}
} catch (\Throwable $e) {
return; // 表都还没有,交给 ensureTable
}
foreach (preg_split('/\r\n|\r|\n/', $body) as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
// 跳过键定义行
if (preg_match('/^(PRIMARY\s+KEY|UNIQUE\s+KEY|KEY|INDEX|CONSTRAINT|FULLTEXT)\b/i', $line)) {
continue;
}
if (!preg_match('/^`(\w+)`\s+(.+?),?$/s', $line, $m)) {
continue;
}
$col = $m[1];
if (isset($exists[strtolower($col)])) {
continue;
}
try {
Db::execute('ALTER TABLE `' . $table . '` ADD COLUMN `' . $col . '` ' . rtrim($m[2], ','));
} catch (\Throwable $e) {
// 单列补失败不影响其它列
}
}
}
/**
* 全文索引不存在则添加(中文优先用 ngram 解析器,失败退回默认解析器,再失败则忽略)
*/
private static function ensureFulltext(string $table, string $name, string $cols): void
{
try {
foreach (Db::query("SHOW INDEX FROM `{$table}`") as $row) {
if (($row['Key_name'] ?? '') === $name) {
return;
}
}
try {
Db::execute("ALTER TABLE `{$table}` ADD FULLTEXT INDEX `{$name}` ({$cols}) WITH PARSER ngram");
} catch (\Throwable $e) {
// 不支持 ngram(非 MySQL / 版本过旧):退回默认解析器
Db::execute("ALTER TABLE `{$table}` ADD FULLTEXT INDEX `{$name}` ({$cols})");
}
} catch (\Throwable $e) {
// 不支持全文索引:忽略,搜索自动降级为 LIKE
}
}
/**
* 索引不存在则添加
*/
private static function ensureIndex(string $table, string $name, string $cols): void
{
try {
foreach (Db::query("SHOW INDEX FROM `{$table}`") as $row) {
if (($row['Key_name'] ?? '') === $name) {
return;
}
}
Db::execute("ALTER TABLE `{$table}` ADD INDEX `{$name}` ({$cols})");
} catch (\Throwable $e) {
// 索引已存在或不支持时忽略
}
}
}
+226
View File
@@ -0,0 +1,226 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\library;
/**
* 文章正文 HTML 白名单净化器
*
* 用途:文章正文在前台是 {$article.content|raw} 直出(富文本必须原样输出),
* 因此必须在**入库前**做白名单净化,否则一旦内容来自不可信来源
* (前台投稿、Word/网页导入、编辑器被绕过)就是存储型 XSS。
*
* 实现说明:基于 PHP DOM 扩展做「标签白名单 + 属性白名单 + URL 协议白名单」,
* 不依赖外部组件(HTMLPurifier)。libxml 不可用时降级为 strip_tags 粗过滤。
*/
class HtmlSanitizer
{
/** 允许的标签(小写) */
private const ALLOW_TAGS = [
'p', 'br', 'div', 'span', 'section', 'article', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'blockquote', 'pre', 'code',
'strong', 'b', 'em', 'i', 'u', 's', 'del', 'ins', 'sub', 'sup', 'mark', 'small',
'a', 'img', 'figure', 'figcaption', 'hr',
'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'col',
];
/** 整块丢弃的标签(连同内部内容一起删除) */
private const DROP_TAGS = [
'script', 'style', 'iframe', 'frame', 'frameset', 'object', 'embed', 'applet',
'form', 'input', 'button', 'select', 'option', 'textarea', 'label',
'link', 'meta', 'base', 'noscript', 'svg', 'math', 'audio', 'video', 'source', 'track',
];
/** 允许保留的属性(小写) */
private const ALLOW_ATTR = [
'class', 'id', 'style', 'title', 'alt', 'src', 'href', 'target', 'rel',
'width', 'height', 'align', 'colspan', 'rowspan',
];
/**
* 净化 HTML
*
* @param string $html 原始富文本
* @return string 净化后的 HTML(可直接入库与直出)
*/
public static function clean(string $html): string
{
$html = trim($html);
if ($html === '') {
return '';
}
if (!class_exists('DOMDocument')) {
return self::fallback($html);
}
$prev = libxml_use_internal_errors(true);
$doc = new \DOMDocument('1.0', 'UTF-8');
// 加 XML 编码声明,避免中文被按 ISO-8859-1 解析
$loaded = $doc->loadHTML('<?xml encoding="UTF-8">' . $html);
libxml_clear_errors();
libxml_use_internal_errors($prev);
if (!$loaded) {
return self::fallback($html);
}
$body = $doc->getElementsByTagName('body')->item(0);
if (!$body) {
return self::fallback($html);
}
self::walk($body);
$out = '';
foreach ($body->childNodes as $child) {
$out .= $doc->saveHTML($child);
}
return trim($out);
}
/**
* 递归净化节点
*/
private static function walk(\DOMNode $node): void
{
$children = [];
foreach ($node->childNodes as $child) {
$children[] = $child;
}
foreach ($children as $child) {
// 注释节点一律删除(IE 条件注释可携带脚本)
if ($child->nodeType === XML_COMMENT_NODE) {
$node->removeChild($child);
continue;
}
if ($child->nodeType !== XML_ELEMENT_NODE) {
continue;
}
/** @var \DOMElement $child */
$tag = strtolower($child->nodeName);
// 危险标签:连同内容一起丢掉
if (in_array($tag, self::DROP_TAGS, true)) {
$node->removeChild($child);
continue;
}
// 非白名单标签:只拆掉外壳,保留内容(如 font/center 等富文本残留)
if (!in_array($tag, self::ALLOW_TAGS, true)) {
self::walk($child);
self::unwrap($child);
continue;
}
self::cleanAttrs($child);
self::walk($child);
}
}
/**
* 拆掉元素外壳,把子节点提到父级
*/
private static function unwrap(\DOMElement $el): void
{
$parent = $el->parentNode;
if (!$parent) {
return;
}
$children = [];
foreach ($el->childNodes as $c) {
$children[] = $c;
}
foreach ($children as $c) {
$parent->insertBefore($c, $el);
}
$parent->removeChild($el);
}
/**
* 属性白名单 + URL 协议校验
*/
private static function cleanAttrs(\DOMElement $el): void
{
$names = [];
foreach ($el->attributes as $attr) {
$names[] = $attr->nodeName;
}
foreach ($names as $name) {
$lname = strtolower($name);
$value = (string) $el->getAttribute($name);
// on* 事件属性一律删除(白名单里本来也没有,这里是双保险)
if (strpos($lname, 'on') === 0) {
$el->removeAttribute($name);
continue;
}
if (!in_array($lname, self::ALLOW_ATTR, true)) {
$el->removeAttribute($name);
continue;
}
// src / href 必须走安全协议
if (($lname === 'src' || $lname === 'href') && self::isUnsafeUrl($value)) {
$el->removeAttribute($name);
continue;
}
// style 里禁止 expression / javascript / url() 等可执行写法
if ($lname === 'style' && preg_match('/(expression|javascript|vbscript|url\s*\()/i', $value)) {
$el->removeAttribute($name);
continue;
}
}
// 链接统一加 rel:防 window.opener 劫持 + 不向站外传递权重
if (strtolower($el->nodeName) === 'a' && $el->getAttribute('href') !== '') {
$el->setAttribute('rel', 'nofollow noopener noreferrer');
}
}
/**
* URL 是否不安全
*/
private static function isUnsafeUrl(string $value): bool
{
$v = strtolower((string) preg_replace('/[\s\x00-\x1f]/', '', $value));
if ($v === '') {
return true;
}
// 可执行协议
if (preg_match('/^(javascript|vbscript|file|about|blob):/', $v)) {
return true;
}
// data: 仅允许图片
if (preg_match('/^data:/', $v) && !preg_match('/^data:image\//', $v)) {
return true;
}
return false;
}
/**
* 降级方案(DOM 不可用时):粗过滤危险标签
*/
private static function fallback(string $html): string
{
$html = (string) preg_replace('#<\s*(script|style|iframe|object|embed|form)\b[^>]*>.*?<\s*/\s*\1\s*>#is', '', $html);
$html = (string) preg_replace('/\son[a-z]+\s*=\s*(".*?"|\'.*?\'|[^\s>]+)/is', '', $html);
return strip_tags($html, '<p><br><div><span><h1><h2><h3><h4><h5><h6><ul><ol><li><blockquote><pre><code><strong><b><em><i><u><s><a><img><table><thead><tbody><tr><td><th><hr><figure><figcaption>');
}
}
+34 -1
View File
@@ -3,14 +3,28 @@
"backend": [
{
"name": "dashboard",
"title": "仪表盘",
"icon": "fa fa-dashboard",
"type": 2,
"sort": 5,
"route": "articles/backend/dashboard/index"
},
{
"name": "article/index",
"title": "文章列表",
"icon": "fa fa-list",
"type": 2,
"sort": 10,
"route": "articles/backend/article/index"
},
{
"name": "article/index/index",
"name": "category/index",
"title": "分类管理",
"icon": "fa fa-list",
"type": 2,
"sort": 20,
"route": "articles/backend/category/index",
"child": [
{ "name": "category:add", "title": "新增分类", "type": 4 },
@@ -23,9 +37,28 @@
"title": "标签管理",
"route": "articles/backend/tag/index"
},
{
"name": "topic/index",
"title": "专题管理",
"icon": "fa fa-th-large",
"type": 2,
"sort": 30,
"route": "articles/backend/topic/index"
},
{
"name": "attachment/index",
"title": "附件管理",
"icon": "fa fa-paperclip",
"type": 2,
"sort": 40,
"route": "articles/backend/attachment/index"
},
{
"name": "comment/index",
"title": "评论管理",
"icon": "fa fa-comments",
"type": 2,
"sort": 50,
"route": "articles/backend/comment/index"
}
+21
View File
@@ -0,0 +1,21 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
/**
* articles 插件应用中间件
*
* 插件被 MultiApp 解析为独立应用,主应用的 middleware.php 不覆盖插件,
* 因此后台写操作(文章/分类/标签/评论的增改删)默认没有 CSRF 防护。
* 这里注册 VerifyCsrfToken(默认同源校验,不强制 token),
* 并须同时把 'articles' 加入 config/csrf.php 的 session_apps 白名单。
*/
return [
\ywxapp\middleware\VerifyCsrfToken::class,
];
+193 -17
View File
@@ -8,6 +8,8 @@ declare (strict_types = 1);
namespace addon\articles\model;
use think\facade\Cache;
use think\facade\Db;
use think\model\concern\SoftDelete;
use ywxapp\model\BaseModel;
@@ -31,12 +33,61 @@ class Article extends BaseModel
'view_count' => 'integer',
'comment_count'=> 'integer',
'like_count' => 'integer',
'publish_time' => 'integer',
];
// 发布中(未删除、已发布)
/**
* 发布中:未删除 + 已发布 + 已到定时发布时间
*
* status 语义:1=发布 0=草稿 2=待审核(前台投稿)
*/
public function scopeNormal($query)
{
$query->where('delete_at', 0)->where('status', 1);
$query->where('delete_at', 0)
->where('status', 1)
->where(function ($q) {
// 定时发布:0 表示立即发布,否则到点后才对外可见
$q->where('publish_time', 0)->whereOr('publish_time', '<=', time());
});
}
/**
* 待审核(前台投稿后等待后台审核)
*/
public function scopePending($query)
{
$query->where('delete_at', 0)->where('status', 2);
}
/**
* 列表场景的字段列表(动态生成,排除 longtext content)
*
* 为什么不写死列名:
* 1. 排除式 field('content', true) 与 bind 关联组合时会生成 SELECT `content`,
* 列表所有字段变 null(实测踩过);
* 2. 写死列名(如 like_count)在线上老库缺列时直接 Unknown column 报错。
* 因此改为按 SHOW COLUMNS 动态取列并排除 content,结果缓存 1 小时。
*/
public static function listFields(): string
{
$cacheKey = 'articles:list_fields';
$fields = Cache::get($cacheKey);
if (!is_array($fields) || empty($fields)) {
$table = Db::name('articles_article')->getTable();
$cols = Db::query('SHOW COLUMNS FROM `' . $table . '`');
$fields = [];
foreach ($cols as $col) {
$name = $col['Field'] ?? '';
if ($name === '' || strtolower($name) === 'content') {
continue;
}
$fields[] = '`' . $name . '`';
}
Cache::set($cacheKey, $fields, 3600);
}
return implode(',', $fields);
}
public function category()
@@ -61,7 +112,8 @@ class Article extends BaseModel
*/
public static function listArticles(array $where = [], int $page = 1, int $size = 10, string $order = 'is_top desc, create_at desc')
{
$query = self::with(['category'])->scope('normal');
// 列表排除正文(longtext),字段由 listFields() 动态生成
$query = self::with(['category'])->field(self::listFields())->scope('normal');
if (!empty($where['cid'])) {
$query->where('cid', $where['cid']);
@@ -72,9 +124,14 @@ class Article extends BaseModel
}
if (!empty($where['keyword'])) {
$kw = $where['keyword'];
$query->where(function ($q) use ($kw) {
$q->whereLike('title', "%{$kw}%")->whereOr('summary', 'like', "%{$kw}%");
});
if (self::fulltextAvailable()) {
// 全文索引可用:走 MATCH AGAINST(布尔模式 + 前缀通配)
$query->whereRaw('MATCH(`title`,`summary`) AGAINST (? IN BOOLEAN MODE)', [$kw . '*']);
} else {
$query->where(function ($q) use ($kw) {
$q->whereLike('title', "%{$kw}%")->whereOr('summary', 'like', "%{$kw}%");
});
}
}
if (!empty($where['is_recommend'])) {
$query->where('is_recommend', 1);
@@ -86,6 +143,38 @@ class Article extends BaseModel
]);
}
/**
* 全文索引是否可用(配置开启 + 索引真实存在,结果缓存 1 小时)
*
* 不可用时搜索自动降级为 LIKE,不会报错。
*/
public static function fulltextAvailable(): bool
{
$cfg = \ywxapp\service\AddonService::config('articles');
if (empty($cfg['search_fulltext'])) {
return false;
}
$flag = Cache::get('articles:fulltext');
if ($flag === null) {
$flag = 0;
try {
$table = Db::name('articles_article')->getTable();
foreach (Db::query("SHOW INDEX FROM `{$table}`") as $row) {
if (($row['Index_type'] ?? '') === 'FULLTEXT') {
$flag = 1;
break;
}
}
} catch (\Throwable $e) {
$flag = 0;
}
Cache::set('articles:fulltext', $flag, 3600);
}
return (int) $flag === 1;
}
public static function getDetail(int $id)
{
return self::with(['category', 'tags', 'author'])
@@ -120,22 +209,109 @@ class Article extends BaseModel
->select();
}
public static function related(int $id, int $cid = 0, int $limit = 5)
/**
* 相关推荐(打分排序 + 缓存 10 分钟)
*
* 打分维度:
* - 标签重合:每个共同标签 +10(信号最强)
* - 同分类:+5
* - 新鲜度:30 天内线性衰减,最多 +5
* - 热度:浏览量轻微加成,最多 +3
*
* 候选池限制在「同分类最近 100 篇 + 有共同标签的最近 200 条关联」,
* 并一次性批量取标签(避免 N+1),保证大数据量下也可控。
*
* @return array 推荐文章数组(id/title/cid/view_count/score)
*/
public static function related(int $id, int $cid = 0, int $limit = 5): array
{
$query = self::scope('normal')->where('id', '<>', $id);
if ($cid) {
$query->where('cid', $cid);
$limit = max(1, min((int) $limit, 20));
$key = 'articles:related:' . $id . ':' . $limit;
$cached = Cache::get($key);
if (is_array($cached)) {
return $cached;
}
return $query->order('create_at', 'desc')
->limit($limit)
->field('id,title,cid')
->select();
$myTags = array_map('intval', ArticleArticleTag::where('aid', $id)->column('tid'));
// 1) 候选池
$pool = [];
$sameCat = self::scope('normal')
->where('id', '<>', $id)
->when($cid > 0, function ($q) use ($cid) {
$q->where('cid', $cid);
})
->field('id,title,cid,create_at,view_count')
->order('create_at', 'desc')
->limit(100)
->select()
->toArray();
foreach ($sameCat as $row) {
$pool[(int) $row['id']] = $row;
}
if ($myTags) {
$aids = ArticleArticleTag::whereIn('tid', $myTags)
->where('aid', '<>', $id)
->limit(200)
->column('aid');
if ($aids) {
$byTag = self::scope('normal')
->whereIn('id', $aids)
->field('id,title,cid,create_at,view_count')
->select()
->toArray();
foreach ($byTag as $row) {
$pool[(int) $row['id']] = $row;
}
}
}
if (empty($pool)) {
return [];
}
// 2) 批量取候选文章的标签(避免逐篇查询)
$tagMap = [];
foreach (ArticleArticleTag::whereIn('aid', array_keys($pool))->select()->toArray() as $row) {
$tagMap[(int) $row['aid']][] = (int) $row['tid'];
}
// 3) 打分
$now = time();
$scored = [];
foreach ($pool as $aid => $row) {
$common = $myTags ? count(array_intersect($myTags, $tagMap[$aid] ?? [])) : 0;
$created = $row['create_at'] ?? 0;
$ts = is_numeric($created) ? (int) $created : (int) strtotime((string) $created);
$days = max(0, ($now - $ts) / 86400);
$score = $common * 10;
$score += ($cid > 0 && (int) $row['cid'] === (int) $cid) ? 5 : 0;
$score += max(0, 30 - $days) / 30 * 5;
$score += min(((int) ($row['view_count'] ?? 0)) / 100, 3);
$row['score'] = round($score, 2);
$scored[] = $row;
}
usort($scored, function ($a, $b) {
return $b['score'] <=> $a['score'];
});
$result = array_slice($scored, 0, $limit);
Cache::set($key, $result, 600);
return $result;
}
public static function ensureSchema(): void
{
$prefix = self::currentPrefix();
self::ensureTableFromInstall($prefix, 'articles_article');
self::ensureTableFromInstall($prefix, 'articles_article_tag');
// 统一交给 ArticleSchema:它解析的是**插件自身** install.sql。
// 旧的 ensureTableFromInstall() 读的是核心 public/install/install.sql,
// 本插件表不在其中,等于空操作。
\addon\articles\library\ArticleSchema::ensure();
}
}
+14 -7
View File
@@ -24,14 +24,21 @@ class ArticleArticleTag extends Pivot
protected $name = 'articles_article_tag';
public $autoWriteTimestamp = false;
/**
* 同步文章标签(先删后插)
*
* 包事务:中途失败会回滚,避免出现「旧标签已删、新标签没插上」的半截状态。
*/
public static function syncTags(int $aid, array $tagIds): void
{
self::where('aid', $aid)->delete();
$data = array_map(function ($tid) use ($aid) {
return ['aid' => $aid, 'tid' => $tid];
}, $tagIds);
if ($data) {
self::insertAll($data);
}
\think\facade\Db::transaction(function () use ($aid, $tagIds) {
self::where('aid', $aid)->delete();
$data = array_map(function ($tid) use ($aid) {
return ['aid' => $aid, 'tid' => $tid];
}, $tagIds);
if ($data) {
self::insertAll($data);
}
});
}
}
@@ -0,0 +1,77 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\model;
use ywxapp\model\BaseModel;
/**
* 附件模型
*
* 记录通过上传接口产生的文件(图片/文档等),便于后台统一查看与清理。
* 文件本身由框架 FileStorageService 落盘,这里只存元数据。
*/
class ArticleAttachment extends BaseModel
{
protected $name = 'articles_attachment';
protected $autoWriteTimestamp = false;
protected $type = [
'uid' => 'integer',
'size' => 'integer',
'aid' => 'integer',
];
/**
* 记录一次上传
*
* @param array $file 上传结果(含 url/path/size/mime 等,字段缺失时自动降级)
* @param int $uid 上传者
* @param int $aid 关联文章ID(0=未关联)
*/
public static function record(array $file, int $uid = 0, int $aid = 0): self
{
$url = (string) ($file['url'] ?? $file['path'] ?? '');
$name = (string) ($file['name'] ?? basename($url));
return self::create([
'uid' => $uid,
'name' => $name,
'url' => $url,
'path' => (string) ($file['path'] ?? ''),
'ext' => strtolower(pathinfo($name, PATHINFO_EXTENSION)),
'mime' => (string) ($file['mime'] ?? ''),
'size' => (int) ($file['size'] ?? 0),
'aid' => $aid,
'create_at' => time(),
]);
}
/**
* 人类可读大小
*/
public function getSizeTextAttr(): string
{
$size = (int) ($this->size ?? 0);
if ($size < 1024) {
return $size . ' B';
}
if ($size < 1048576) {
return round($size / 1024, 1) . ' KB';
}
return round($size / 1048576, 2) . ' MB';
}
public static function ensureSchema(): void
{
\addon\articles\library\ArticleSchema::ensure();
}
}
+40 -1
View File
@@ -46,16 +46,55 @@ class ArticleComment extends BaseModel
->bind(['nickname', 'avatar']);
}
/**
* 所属文章(后台评论列表 with(['article']) 依赖此关联)
*/
public function article()
{
return $this->belongsTo(Article::class, 'aid', 'id');
}
/**
* 文章评论(只取顶层评论,回复由 repliesOf() 带出)
*/
public static function getByArticle(int $aid, int $page = 1, int $size = 10)
{
return self::with(['user'])
->where('delete_at', 0)
->where('aid', $aid)
->where('status', 1)
->order('id', 'asc')
->where('pid', 0)
->order('id', 'desc')
->paginate(['list_rows' => $size, 'page' => $page]);
}
/**
* 取指定父评论下的全部回复,按父评论ID分组
*
* @param array $parentIds 顶层评论ID数组
* @return array [父评论ID => 回复列表]
*/
public static function repliesOf(array $parentIds): array
{
$parentIds = array_values(array_filter(array_map('intval', $parentIds)));
if (empty($parentIds)) {
return [];
}
$rows = self::with(['user'])
->whereIn('pid', $parentIds)
->where('delete_at', 0)
->where('status', 1)
->order('id', 'asc')
->select();
$map = [];
foreach ($rows as $r) {
$map[(int) $r->pid][] = $r;
}
return $map;
}
public static function ensureSchema(): void
{
$prefix = self::currentPrefix();
+33
View File
@@ -0,0 +1,33 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\model;
use ywxapp\model\BaseModel;
/**
* 文章收藏模型(唯一键 uid+aid 防重复收藏)
*/
class ArticleFavorite extends BaseModel
{
protected $name = 'articles_favorite';
protected $autoWriteTimestamp = false;
protected $type = [
'uid' => 'integer',
'aid' => 'integer',
];
public static function ensureSchema(): void
{
\addon\articles\library\ArticleSchema::ensure();
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\model;
use ywxapp\model\BaseModel;
/**
* 点赞记录模型
*
* 唯一键 (uid, target_id, type) 保证同一用户对同一目标只能点一次赞;
* 计数冗余在 articles_article.like_count / articles_comment.like_count。
*/
class ArticleLike extends BaseModel
{
/** 文章点赞 */
const TYPE_ARTICLE = 1;
/** 评论点赞 */
const TYPE_COMMENT = 2;
protected $name = 'articles_like';
// 只需记录创建时间,且不自动维护时间戳(由 service 显式写入)
protected $autoWriteTimestamp = false;
protected $type = [
'uid' => 'integer',
'target_id' => 'integer',
'type' => 'integer',
];
public static function ensureSchema(): void
{
\addon\articles\library\ArticleSchema::ensure();
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\model;
use think\model\concern\SoftDelete;
use ywxapp\model\BaseModel;
/**
* 文章专题模型
*
* 专题 = 人工策划的聚合页:把若干文章归到一个主题下,
* 用于运营落地页(如「新手入门」「年度盘点」)。
*/
class ArticleTopic extends BaseModel
{
use SoftDelete;
protected $name = 'articles_topic';
protected $deleteTime = 'delete_at';
protected $defaultSoftDelete = 0;
protected $autoWriteTimestamp = true;
protected $createTime = 'create_at';
protected $updateTime = 'update_at';
protected $type = [
'status' => 'integer',
'sort' => 'integer',
];
/** 启用中 */
public function scopeEnable($query)
{
$query->where('delete_at', 0)->where('status', 1);
}
/**
* 专题下的文章(多对多)
*/
public function articles()
{
return $this->belongsToMany(Article::class, ArticleTopicArticle::class, 'aid', 'tid');
}
/**
* 按别名取启用专题
*/
public static function enabledByAlias(string $alias)
{
return self::scope('enable')->where('alias', $alias)->find();
}
public static function ensureSchema(): void
{
\addon\articles\library\ArticleSchema::ensure();
}
}
@@ -0,0 +1,73 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\model;
use think\facade\Db;
use think\model\Pivot;
use ywxapp\model\BaseModel;
/**
* 专题-文章关联模型
*/
class ArticleTopicArticle extends Pivot
{
protected $name = 'articles_topic_article';
public $autoWriteTimestamp = false;
/**
* 某专题下的文章ID(按专题内排序)
*/
public static function articleIdsOf(int $tid): array
{
if ($tid <= 0) {
return [];
}
return self::where('tid', $tid)->order('sort', 'asc')->order('aid', 'desc')->column('aid');
}
/**
* 某文章所属的专题ID
*/
public static function topicIdsOf(int $aid): array
{
if ($aid <= 0) {
return [];
}
return self::where('aid', $aid)->column('tid');
}
/**
* 同步专题下的文章(先删后插,事务保护)
*
* @param int $tid 专题ID
* @param array $aids 文章ID数组(顺序即专题内排序)
*/
public static function syncArticles(int $tid, array $aids): void
{
Db::transaction(function () use ($tid, $aids) {
self::where('tid', $tid)->delete();
$data = [];
$sort = 0;
foreach ($aids as $aid) {
$aid = (int) $aid;
if ($aid <= 0) {
continue;
}
$data[] = ['tid' => $tid, 'aid' => $aid, 'sort' => $sort++];
}
if ($data) {
self::insertAll($data);
}
});
}
}
+61 -7
View File
@@ -23,25 +23,69 @@ Route::get('category/:id', 'addon\articles\controller\Category@index');
Route::get('tag/index', 'addon\articles\controller\Tag@index');
Route::get('tag/:id', 'addon\articles\controller\Tag@index');
Route::get('search/index', 'addon\articles\controller\Article@search');
// 专题聚合页
Route::get('topic', 'addon\articles\controller\Topic@index');
Route::get('topic/index', 'addon\articles\controller\Topic@index');
Route::get('topic/:id', 'addon\articles\controller\Topic@detail');
Route::post('article/comment', 'addon\articles\controller\Article@comment');
Route::post('article/like', 'addon\articles\controller\Article@like');
Route::post('article/favorite', 'addon\articles\controller\Article@favorite');
// 后台(直接把 backend/ 写进 rule 路径,避免嵌套 Route::group('backend') 产生的歧义)
// 实测结论:无论用嵌套 Route::group('backend') 还是把 backend 写进 rule 路径,
// loadAddonRoutes 的外层 Route::group('articles') 都会把 backend 层级拼成「带点」形式
// → 真实 URL 固定为 /articles/backend.category/index.html(斜杠形式恒 404)。
// 故后台 URL 统一用带点,menu.json 的 jump 与视图 {:url('articles/backend.xxx/yyy')} 均须用带点。
// 注意:不能用 wxchat 的 ->prefix('backend/') 写法——articles 后台控制器在 controller/backend/ 子目录,
// prefix 会让 TP 解析成 backend/backend/Category 导致 500(实测)。
// SEO:站点地图(文章 > 5000 条时 sitemap.xml 输出 index,文章拆到 sitemap-<n>.xml)
Route::get('sitemap.xml', 'addon\articles\controller\Sitemap@index');
Route::get('sitemap-:page.xml', 'addon\articles\controller\Sitemap@chunk');
// 对外 API(/articles/api/...,继承 ApiBase,走 JWT 登录态;游客可访问列表/详情/搜索)
Route::group('api', function () {
Route::get('articles', 'api.Article/index');
Route::get('article/:id', 'api.Article/read');
Route::get('categories', 'api.Article/categories');
Route::get('tags', 'api.Article/tags');
Route::get('search', 'api.Article/search');
Route::post('comment', 'api.Article/comment');
});
// 会员中心投稿(/articles/member/article/...,必须登录,投稿后为待审核状态)
Route::group('member', function () {
Route::get('article/index', 'Article/index');
Route::get('article/add', 'Article/add');
Route::get('article/edit', 'Article/edit');
Route::post('article/save', 'Article/save');
Route::post('article/delete', 'Article/delete');
})->layer('member');
// 后台
// 实测结论(已校准,勿改回点号):
// 1. 真实 URL 是【斜杠】形式 —— /articles/backend/article/index.html
// (外层 Route::group('articles') 只补插件名前缀,不会把 backend 拼成带点形式)
// 2. 早期注释里"拼成带点形式 / 斜杠恒 404 / 必须用点号"的说法已过时。点号 URL
// (articles/backend.article/index)匹配不到已注册规则 → 走兜底控制器解析:
// Windows 下文件名大小写不敏感可能碰巧命中,Linux 必然 404;且兜底不校验 HTTP
// 方法,会让 Route::post('article/delete') 的方法限制失效(GET 即可删除)。
// 3. 故:menu.json 的 route、视图 {:url('articles/backend/xxx/yyy')}、
// 控制器的跳转/返回 url 一律用斜杠形式。
// 4. 不能用 wxchat 的 ->prefix('backend/') 写法——本插件后台控制器已在
// controller/backend/ 子目录,prefix 会让 TP 解析成 backend/backend/Category 导致 500。
// 5. ->layer('backend') 负责把 'Article/index' 解析到 controller/backend/Article.php。
Route::group('backend', function () {
// 无 index 段的等价形态(兼容控制器/模板里的 '/articles/backend/article' 旧跳转)
Route::get('article', 'Article/index');
Route::get('tag', 'Tag/index');
Route::get('category', 'Category/index');
Route::get('dashboard/index', 'Dashboard/index');
Route::get('dashboard', 'Dashboard/index');
Route::get('article/index', 'Article/index');
Route::any('article/save', 'Article/save');
Route::get('article/edit', 'Article/edit');
Route::post('article/update', 'Article/update');
Route::post('article/delete', 'Article/delete');
Route::post('article/batchDelete', 'Article/batchDelete');
Route::post('article/batchStatus', 'Article/batchStatus');
Route::post('article/audit', 'Article/audit');
Route::post('article/recyclebin', 'Article/recyclebin');
Route::post('article/restore', 'Article/restore');
@@ -55,6 +99,16 @@ Route::group('backend', function () {
Route::post('comment/audit', 'Comment/audit');
Route::post('comment/delete', 'Comment/delete');
Route::get('topic/index', 'Topic/index');
Route::any('topic/save', 'Topic/save');
Route::get('topic/edit', 'Topic/edit');
Route::post('topic/update', 'Topic/update');
Route::post('topic/delete', 'Topic/delete');
Route::get('attachment/index', 'Attachment/index');
Route::post('attachment/upload', 'Attachment/upload');
Route::post('attachment/delete', 'Attachment/delete');
Route::get('category/index', 'Category/index');
Route::any('category/save', 'Category/save');
Route::get('category/edit', 'Category/edit');
@@ -0,0 +1,163 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\service;
/**
* 正文渲染服务(输出期增强,不改动入库内容)
*
* 三件事:
* 1. 图片懒加载:给 <img> 加 loading="lazy" decoding="async"
* 2. WebP:浏览器支持时把站内图片替换为 .webp 副本(见 ImageService)
* 3. 内链:把命中的关键词(如本文标签)替换为站内链接,利于收录与导流
*
* 全部基于 DOM 操作,不会破坏原有 HTML 结构;DOM 不可用时原样返回。
*/
class ContentRenderService
{
/** 单篇文章最多生成的内链数 */
const MAX_LINKS = 5;
/**
* 渲染正文
*
* @param string $html 已净化的正文
* @param array $linkKeywords [关键词 => 链接地址]
* @param bool $useWebp 是否启用 WebP 替换
*/
public static function render(string $html, array $linkKeywords = [], bool $useWebp = false): string
{
$html = trim($html);
if ($html === '' || !class_exists('DOMDocument')) {
return $html;
}
$prev = libxml_use_internal_errors(true);
$doc = new \DOMDocument('1.0', 'UTF-8');
$loaded = $doc->loadHTML('<?xml encoding="UTF-8">' . $html);
libxml_clear_errors();
libxml_use_internal_errors($prev);
if (!$loaded) {
return $html;
}
$body = $doc->getElementsByTagName('body')->item(0);
if (!$body) {
return $html;
}
self::enhanceImages($doc, $useWebp);
if (!empty($linkKeywords)) {
self::linkKeywords($doc, $linkKeywords);
}
$out = '';
foreach ($body->childNodes as $child) {
$out .= $doc->saveHTML($child);
}
return trim($out);
}
/**
* 图片增强:懒加载 + WebP
*/
private static function enhanceImages(\DOMDocument $doc, bool $useWebp): void
{
$images = [];
foreach ($doc->getElementsByTagName('img') as $img) {
$images[] = $img;
}
foreach ($images as $img) {
$img->setAttribute('loading', 'lazy');
$img->setAttribute('decoding', 'async');
if (!$useWebp) {
continue;
}
$src = (string) $img->getAttribute('src');
$webp = ImageService::webpUrl($src);
if ($webp !== '') {
$img->setAttribute('src', $webp);
}
}
}
/**
* 内链替换(跳过已在 <a> 内的文本,避免链接套链接)
*/
private static function linkKeywords(\DOMDocument $doc, array $keywords): void
{
$xpath = new \DOMXPath($doc);
$nodes = $xpath->query('//text()[not(ancestor::a)]');
if (!$nodes || $nodes->length === 0) {
return;
}
// 先快照,避免替换过程中结构变化影响遍历
$list = [];
foreach ($nodes as $node) {
$list[] = $node;
}
$used = [];
$count = 0;
foreach ($list as $node) {
if ($count >= self::MAX_LINKS) {
break;
}
$text = (string) $node->nodeValue;
if (mb_strlen(trim($text), 'UTF-8') < 2) {
continue;
}
foreach ($keywords as $kw => $url) {
$kw = (string) $kw;
if ($count >= self::MAX_LINKS || isset($used[$kw]) || mb_strlen($kw, 'UTF-8') < 2) {
continue;
}
$pos = mb_stripos($text, $kw, 0, 'UTF-8');
if ($pos === false) {
continue;
}
$before = mb_substr($text, 0, $pos, 'UTF-8');
$after = mb_substr($text, $pos + mb_strlen($kw, 'UTF-8'), null, 'UTF-8');
$a = $doc->createElement('a', htmlspecialchars($kw, ENT_QUOTES, 'UTF-8'));
$a->setAttribute('href', (string) $url);
$a->setAttribute('class', 'article-inner-link');
$frag = $doc->createDocumentFragment();
$frag->appendChild($doc->createTextNode($before));
$frag->appendChild($a);
$frag->appendChild($doc->createTextNode($after));
$parent = $node->parentNode;
if (!$parent) {
continue;
}
$parent->replaceChild($frag, $node);
$used[$kw] = true;
$count++;
break; // 每个文本节点只处理一个关键词
}
}
}
}
@@ -0,0 +1,78 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\service;
use addon\articles\model\Article;
use addon\articles\model\ArticleFavorite;
/**
* 收藏服务
*/
class FavoriteService
{
/**
* 收藏 / 取消收藏
*
* @return array ['favorited' => bool]
*/
public static function toggle(int $uid, int $articleId): array
{
if ($uid <= 0 || $articleId <= 0) {
return ['favorited' => false];
}
// 只能收藏已发布且未删除的文章
$exists = Article::where('id', $articleId)->where('status', 1)->where('delete_at', 0)->count();
if (!$exists) {
return ['favorited' => false];
}
$record = ArticleFavorite::where('uid', $uid)->where('aid', $articleId)->find();
if ($record) {
$record->delete();
return ['favorited' => false];
}
ArticleFavorite::create([
'uid' => $uid,
'aid' => $articleId,
'create_at' => time(),
]);
return ['favorited' => true];
}
/**
* 是否已收藏
*/
public static function isFavorited(int $uid, int $articleId): bool
{
if ($uid <= 0 || $articleId <= 0) {
return false;
}
return (bool) ArticleFavorite::where('uid', $uid)->where('aid', $articleId)->count();
}
/**
* 我的收藏文章ID(按收藏时间倒序)
*/
public static function articleIds(int $uid, int $limit = 0): array
{
if ($uid <= 0) {
return [];
}
$query = ArticleFavorite::where('uid', $uid)->order('id', 'desc');
if ($limit > 0) {
$query->limit($limit);
}
return $query->column('aid');
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\service;
/**
* 图片服务(WebP 副本生成)
*
* 策略:**不覆盖原图**,只在同目录生成 `原文件名.webp` 副本;
* 浏览器 Accept 含 image/webp 时才使用副本,否则回落原图。
* 依赖 GD(imagewebp);不支持时自动回落,不影响页面。
*/
class ImageService
{
/** WebP 输出质量 */
const QUALITY = 80;
/**
* 取 WebP 版本地址(无副本且 GD 可用时现场生成)
*
* @param string $src 站内相对路径(如 /upload/2026/01/a.jpg)
* @return string WebP 地址;不可用返回空串(调用方应回落到原图)
*/
public static function webpUrl(string $src): string
{
// 只处理站内相对路径,跳过站外 URL、data:、已是 webp 的图
if ($src === '' || strpos($src, '/') !== 0) {
return '';
}
if (preg_match('#^data:#i', $src) || preg_match('#\.webp($|\?)#i', $src)) {
return '';
}
$root = rtrim((string) public_path(), DIRECTORY_SEPARATOR);
$srcFile = $root . $src;
$dst = $src . '.webp';
$dstFile = $root . $dst;
// 副本已存在直接用
if (is_file($dstFile)) {
return $dst;
}
if (!is_file($srcFile) || !function_exists('imagewebp')) {
return '';
}
return self::convert($srcFile, $dstFile) ? $dst : '';
}
/**
* 转换一张图为 WebP
*/
private static function convert(string $srcFile, string $dstFile): bool
{
$info = @getimagesize($srcFile);
if (!is_array($info) || empty($info['mime'])) {
return false;
}
$im = null;
switch ($info['mime']) {
case 'image/jpeg':
$im = @imagecreatefromjpeg($srcFile);
break;
case 'image/png':
$im = @imagecreatefrompng($srcFile);
if ($im) {
imagepalettetotruecolor($im);
imagealphablending($im, true);
imagesavealpha($im, true);
}
break;
case 'image/gif':
$im = @imagecreatefromgif($srcFile);
break;
case 'image/webp':
$im = @imagecreatefromwebp($srcFile);
break;
default:
return false;
}
if (!$im) {
return false;
}
$dir = dirname($dstFile);
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}
$ok = @imagewebp($im, $dstFile, self::QUALITY);
imagedestroy($im);
return $ok && is_file($dstFile);
}
}
+143
View File
@@ -0,0 +1,143 @@
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\articles\service;
use addon\articles\model\Article;
use addon\articles\model\ArticleComment;
use addon\articles\model\ArticleLike;
use think\facade\Db;
/**
* 点赞服务(文章 / 评论)
*
* 规则:
* - 必须登录(游客不允许点赞,避免刷量)
* - 同一用户对同一目标只能赞一次(唯一键保证),再次调用即取消
* - 计数冗余在目标表的 like_count,取消时用 dec 并保证不为负
*/
class LikeService
{
/**
* 文章点赞/取消
*
* @return array ['liked' => bool, 'count' => int]
*/
public static function toggleArticle(int $uid, int $articleId): array
{
if ($uid <= 0 || $articleId <= 0) {
return ['liked' => false, 'count' => 0];
}
// 文章必须存在且已发布
$exists = Article::where('id', $articleId)->where('status', 1)->where('delete_at', 0)->count();
if (!$exists) {
return ['liked' => false, 'count' => 0];
}
return self::toggle($uid, $articleId, ArticleLike::TYPE_ARTICLE, 'articles_article', $articleId);
}
/**
* 评论点赞/取消
*
* @return array ['liked' => bool, 'count' => int]
*/
public static function toggleComment(int $uid, int $commentId): array
{
if ($uid <= 0 || $commentId <= 0) {
return ['liked' => false, 'count' => 0];
}
$exists = ArticleComment::where('id', $commentId)->where('delete_at', 0)->count();
if (!$exists) {
return ['liked' => false, 'count' => 0];
}
return self::toggle($uid, $commentId, ArticleLike::TYPE_COMMENT, 'articles_comment', $commentId);
}
/**
* 是否已点赞
*/
public static function isLiked(int $uid, int $targetId, int $type): bool
{
if ($uid <= 0) {
return false;
}
return (bool) ArticleLike::where('uid', $uid)
->where('target_id', $targetId)
->where('type', $type)
->count();
}
/**
* 批量判断文章是否已赞(列表/详情页用,避免 N+1)
*
* @param array $ids 文章ID数组
* @return array 已赞的文章ID => true
*/
public static function likedArticleMap(int $uid, array $ids): array
{
if ($uid <= 0 || empty($ids)) {
return [];
}
$rows = ArticleLike::where('uid', $uid)
->where('type', ArticleLike::TYPE_ARTICLE)
->whereIn('target_id', $ids)
->column('target_id');
$map = [];
foreach ($rows as $id) {
$map[(int) $id] = true;
}
return $map;
}
/**
* 通用切换逻辑
*/
private static function toggle(int $uid, int $targetId, int $type, string $countTable, int $targetKey): array
{
$record = ArticleLike::where('uid', $uid)
->where('target_id', $targetId)
->where('type', $type)
->find();
if ($record) {
// 已赞 → 取消
$record->delete();
Db::name($countTable)->where('id', $targetKey)
->where('like_count', '>', 0)
->dec('like_count')
->update();
return ['liked' => false, 'count' => self::count($countTable, $targetKey)];
}
ArticleLike::create([
'uid' => $uid,
'target_id' => $targetId,
'type' => $type,
'create_at' => time(),
]);
Db::name($countTable)->where('id', $targetKey)->inc('like_count')->update();
return ['liked' => true, 'count' => self::count($countTable, $targetKey)];
}
/**
* 读取最新计数
*/
private static function count(string $table, int $id): int
{
return (int) Db::name($table)->where('id', $id)->value('like_count');
}
}
+53 -13
View File
@@ -31,10 +31,23 @@
<div class="layui-form-item">
<label class="layui-form-label">封面图</label>
<div class="layui-input-block">
<input type="text" name="cover_image" id="cover_image" value="{$article.cover_image|default=''}" class="layui-input">
<input type="text" name="cover_image" id="cover_image" value="{$article.cover_image|default=''}" class="layui-input" style="width:calc(100% - 120px);display:inline-block;" placeholder="图片地址,或点右侧上传">
<button type="button" class="layui-btn layui-btn-primary" id="cover_upload">上传</button>
<div style="margin-top:8px;">
<img id="cover_preview" src="{$article.cover_image|default=''}" alt="封面预览" style="max-height:120px;{if condition="empty($article['cover_image'])"}display:none;{/if}">
</div>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">定时发布</label>
<div class="layui-input-inline">
<input type="text" name="publish_time" id="publish_time" class="layui-input" placeholder="留空=立即发布"
value="{if isset($article['publish_time']) && $article['publish_time']}{:date('Y-m-d H:i', $article['publish_time'])}{/if}">
</div>
<div class="layui-form-mid layui-word-aux">到点后自动对前台可见(状态须为「发布」)</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">摘要</label>
<div class="layui-input-block">
@@ -66,7 +79,7 @@
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="save">保存</button>
<a href="{:url('articles/backend.article/index')}" class="layui-btn layui-btn-primary">返回</a>
<a href="{:url('articles/backend/article/index')}" class="layui-btn layui-btn-primary">返回</a>
</div>
</div>
</form>
@@ -77,8 +90,41 @@
<script src="/assets/library/ueditor/ueditor.config.js"></script>
<script src="/assets/library/ueditor/ueditor.all.js"></script>
<script>
layui.use(['form', 'jquery'], function () {
var form = layui.form, $ = layui.jquery;
layui.use(['form', 'jquery', 'upload', 'laydate', 'http', 'ywxapp'], function () {
var http = layui.http;
var form = layui.form, $ = layui.jquery, upload = layui.upload, laydate = layui.laydate;
laydate.render({ elem: '#publish_time', type: 'datetime' });
// 封面图上传:对接框架通用上传接口 /upload(字段名 file)
upload.render({
elem: '#cover_upload',
url: '/upload',
field: 'file',
accept: 'images',
acceptMime: 'image/*',
exts: 'jpg|jpeg|png|gif|webp',
size: 2048,
data: { type: 'articles' },
done: function (r) {
if (String(r.code) !== '0') {
layer.msg(r.message || r.msg || '上传失败');
return;
}
var d = r.data || {};
// 兼容不同驱动返回的字段名
var url = d.url || d.path || d.src || (typeof d === 'string' ? d : '');
if (!url) {
layer.msg('上传成功但未返回地址');
return;
}
$('#cover_image').val(url);
$('#cover_preview').attr('src', url).show();
},
error: function () {
layer.msg('上传失败');
}
});
var ue = UE.getEditor('editor', {
UEDITOR_HOME_URL: '/assets/library/ueditor/',
@@ -91,16 +137,10 @@ layui.use(['form', 'jquery'], function () {
form.on('submit(save)', function (data) {
data.field.content = ue.getContent();
$.ajax({
url: "{:url('articles/backend.article/update')}",
type: 'post',
data: data.field,
dataType: 'json',
success: function (r) {
http.post("{:url('articles/backend/article/update')}", data.field).then(function (r) {
layer.msg(r.msg);
if (r.code) { setTimeout(function () { location.href = r.url || "{:url('articles/backend.article/index')}"; }, 800); }
}
});
if (r.code) { setTimeout(function () { location.href = r.url || "{:url('articles/backend/article/index')}"; }, 800); }
});
return false;
});
});
+58 -5
View File
@@ -9,6 +9,7 @@
<option value="all">全部状态</option>
<option value="1">已发布</option>
<option value="0">草稿</option>
<option value="2">待审核</option>
</select>
</div>
<div class="layui-inline">
@@ -16,12 +17,18 @@
</div>
<div class="layui-inline">
<button class="layui-btn" lay-submit lay-filter="search">搜索</button>
<a href="{:url('articles/backend.article/save')}" class="layui-btn layui-btn-normal">新建文章</a>
<a href="{:url('articles/backend.article/recyclebin')}" class="layui-btn layui-btn-primary">回收站</a>
<a href="{:url('articles/backend/article/save')}" class="layui-btn layui-btn-normal">新建文章</a>
<a href="{:url('articles/backend/article/recyclebin')}" class="layui-btn layui-btn-primary">回收站</a>
</div>
</div>
</form>
<script type="text/html" id="batchbar">
<button class="layui-btn layui-btn-sm" lay-event="publish">批量发布</button>
<button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="draft">转为草稿</button>
<button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="batchdel">批量删除</button>
</script>
<table class="layui-table" id="table" lay-filter="table"></table>
</div>
</div>
@@ -29,19 +36,23 @@
<script type="text/html" id="toolbar">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="audit">审核</a>
<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
</script>
<script>
layui.use(['table', 'form'], function () {
layui.use(['table', 'form', 'http', 'ywxapp'], function () {
var http = layui.http;
var table = layui.table, form = layui.form, $ = layui.jquery;
var tableIns = table.render({
elem: '#table',
url: "{:url('articles/backend.article/index')}",
url: "{:url('articles/backend/article/index')}",
method: 'post',
where: { status: 'all' },
page: true,
toolbar: '#batchbar',
cols: [[
{ type: 'checkbox', fixed: 'left', width: 50 },
{ field: 'id', title: 'ID', width: 70 },
{ field: 'title', title: '标题', minWidth: 200 },
{ field: 'category', title: '分类', width: 100 },
@@ -63,14 +74,56 @@ layui.use(['table', 'form'], function () {
table.on('tool(table)', function (obj) {
if (obj.event === 'edit') {
location.href = obj.data.edit_url;
} else if (obj.event === 'audit') {
layer.confirm('通过选「确定」,拒绝选「取消」后可在列表里改为草稿', { title: '审核该投稿' }, function () {
http.post("{:url('articles/backend/article/audit')}", { id: obj.data.id, pass: 1 }).then(function (r) {
layer.msg(r.msg);
if (r.code) { setTimeout(function () { tableIns.reload(); }, 600); }
});
}, function () {
http.post("{:url('articles/backend/article/audit')}", { id: obj.data.id, pass: 0 }).then(function (r) {
layer.msg(r.msg);
if (r.code) { setTimeout(function () { tableIns.reload(); }, 600); }
});
});
} else if (obj.event === 'del') {
layer.confirm('确认删除该文章?', function () {
$.post("{:url('articles/backend.article/delete')}", { id: obj.data.id }, function (r) {
http.post("{:url('articles/backend/article/delete')}", { id: obj.data.id }).then(function (r) {
layer.msg(r.msg);
if (r.code) { obj.del(); }
});
});
}
});
// 批量操作(表头工具栏)
function selectedIds() {
var ids = [];
layui.each(table.checkStatus('table').data, function (i, row) { ids.push(row.id); });
return ids;
}
table.on('toolbar(table)', function (obj) {
var ids = selectedIds();
if (!ids.length) { layer.msg('请先勾选文章'); return; }
if (obj.event === 'publish' || obj.event === 'draft') {
var status = obj.event === 'publish' ? 1 : 0;
http.post("{:url('articles/backend/article/batchStatus')}", { ids: ids, status: status }).then(function (r) {
layer.msg(r.msg);
if (r.code) { setTimeout(function () { tableIns.reload(); }, 600); }
});
return;
}
if (obj.event === 'batchdel') {
layer.confirm('确认删除选中的 ' + ids.length + ' 篇文章?', function () {
http.post("{:url('articles/backend/article/batchDelete')}", { ids: ids }).then(function (r) {
layer.msg(r.msg);
if (r.code) { setTimeout(function () { tableIns.reload(); }, 600); }
});
});
}
});
});
</script>
@@ -12,11 +12,12 @@
</script>
<script>
layui.use(['table'], function () {
layui.use(['table', 'http', 'ywxapp'], function () {
var http = layui.http;
var table = layui.table;
var tableIns = table.render({
elem: '#table',
url: "{:url('articles/backend.article/recyclebin')}",
url: "{:url('articles/backend/article/recyclebin')}",
method: 'post',
page: true,
cols: [[
@@ -28,7 +29,7 @@ layui.use(['table'], function () {
});
table.on('tool(table)', function (obj) {
if (obj.event === 'restore') {
$.post("{:url('articles/backend.article/restore')}", { id: obj.data.id }, function (r) {
http.post("{:url('articles/backend/article/restore')}", { id: obj.data.id }).then(function (r) {
layer.msg(r.msg); if (r.code) { obj.del(); }
});
}
@@ -0,0 +1,68 @@
<div class="layui-fluid">
<div class="layui-card">
<div class="layui-card-header">
附件管理
<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="btnUpload" style="float:right;margin-top:6px;">上传附件</button>
</div>
<div class="layui-card-body">
<table class="layui-table" id="table" lay-filter="table"></table>
</div>
</div>
</div>
<script type="text/html" id="toolbar">
<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="view">查看</a>
<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
</script>
<script>
layui.use(['table', 'upload', 'jquery', 'http', 'ywxapp'], function () {
var http = layui.http;
var table = layui.table, upload = layui.upload, $ = layui.jquery;
var tableIns = table.render({
elem: '#table',
url: "{:url('articles/backend/attachment/index')}",
method: 'post',
page: true,
cols: [[
{ field: 'id', title: 'ID', width: 70 },
{ field: 'name', title: '文件名', minWidth: 220 },
{ field: 'ext', title: '类型', width: 90 },
{ field: 'size_text', title: '大小', width: 100 },
{ field: 'aid', title: '关联文章', width: 100 },
{ field: 'create_at', title: '上传时间', width: 170 },
{ title: '操作', width: 140, toolbar: '#toolbar' }
]]
});
upload.render({
elem: '#btnUpload',
url: "{:url('articles/backend/attachment/upload')}",
field: 'file',
accept: 'file',
exts: 'jpg|jpeg|png|gif|webp|bmp|pdf|doc|docx|xls|xlsx|ppt|pptx|zip|rar|txt|csv',
size: 10240,
done: function (r) {
layer.msg(r.msg || '');
if (r.code) { setTimeout(function () { tableIns.reload(); }, 600); }
},
error: function () { layer.msg('上传失败'); }
});
table.on('tool(table)', function (obj) {
if (obj.event === 'view') {
if (obj.data.url) { window.open(obj.data.url, '_blank'); }
return;
}
if (obj.event === 'del') {
layer.confirm('确认删除该附件?(会一并尝试删除物理文件)', function () {
http.post("{:url('articles/backend/attachment/delete')}", { id: obj.data.id }).then(function (r) {
layer.msg(r.msg);
if (r.code) { obj.del(); }
});
});
}
});
});
</script>
@@ -30,7 +30,7 @@
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="save">保存</button>
<a href="{:url('articles/backend.category/index')}" class="layui-btn layui-btn-primary">返回</a>
<a href="{:url('articles/backend/category/index')}" class="layui-btn layui-btn-primary">返回</a>
</div>
</div>
</form>
@@ -39,12 +39,13 @@
</div>
<script>
layui.use(['form', 'jquery'], function () {
layui.use(['form', 'jquery', 'http', 'ywxapp'], function () {
var http = layui.http;
var form = layui.form, $ = layui.jquery;
form.on('submit(save)', function (data) {
$.post("{:url('articles/backend.category/update')}", data.field, function (r) {
http.post("{:url('articles/backend/category/update')}", data.field).then(function (r) {
layer.msg(r.msg); if (r.code) { setTimeout(function () { location.href = r.url; }, 800); }
}, 'json');
});
return false;
});
});
@@ -30,11 +30,12 @@
</script>
<script>
layui.use(['table', 'form'], function () {
layui.use(['table', 'form', 'http', 'ywxapp'], function () {
var http = layui.http;
var table = layui.table, form = layui.form;
var tableIns = table.render({
elem: '#table',
url: "{:url('articles/backend.comment/index')}",
url: "{:url('articles/backend/comment/index')}",
method: 'post',
where: { status: 'all' },
page: true,
@@ -54,10 +55,10 @@ layui.use(['table', 'form'], function () {
});
table.on('tool(table)', function (obj) {
if (obj.event === 'audit') {
$.post("{:url('articles/backend.comment/audit')}", { id: obj.data.id }, function (r) { layer.msg(r.msg); if (r.code) { obj.update({ status: '已审核' }); } });
http.post("{:url('articles/backend/comment/audit')}", { id: obj.data.id }).then(function (r) { layer.msg(r.msg); if (r.code) { obj.update({ status: '已审核' }); } });
} else if (obj.event === 'del') {
layer.confirm('确认删除该评论?', function () {
$.post("{:url('articles/backend.comment/delete')}", { id: obj.data.id }, function (r) { layer.msg(r.msg); if (r.code) obj.del(); });
http.post("{:url('articles/backend/comment/delete')}", { id: obj.data.id }).then(function (r) { layer.msg(r.msg); if (r.code) obj.del(); });
});
}
});
@@ -0,0 +1,92 @@
<div class="layui-fluid">
<div class="layui-row layui-col-space15">
<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">文章总数</div>
<div class="layui-card-body" style="font-size:26px;">{$stats.total}</div>
</div>
</div>
<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">已发布</div>
<div class="layui-card-body" style="font-size:26px;color:#5FB878;">{$stats.published}</div>
</div>
</div>
<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">待审核</div>
<div class="layui-card-body" style="font-size:26px;color:#FFB800;">{$stats.pending}</div>
</div>
</div>
<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">草稿</div>
<div class="layui-card-body" style="font-size:26px;">{$stats.draft}</div>
</div>
</div>
<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">今日新增</div>
<div class="layui-card-body" style="font-size:26px;">{$stats.today}</div>
</div>
</div>
<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">总浏览</div>
<div class="layui-card-body" style="font-size:26px;">{$stats.views}</div>
</div>
</div>
<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">评论 / 待审</div>
<div class="layui-card-body" style="font-size:26px;">{$stats.comments} <span style="font-size:14px;color:#FF5722;">/ {$stats.pending_comments}</span></div>
</div>
</div>
<div class="layui-col-xs6 layui-col-sm4 layui-col-md3">
<div class="layui-card">
<div class="layui-card-header">回收站</div>
<div class="layui-card-body" style="font-size:26px;">{$stats.trashed}</div>
</div>
</div>
</div>
<div class="layui-row layui-col-space15" style="margin-top:10px;">
<div class="layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">分类分布(Top 10)</div>
<div class="layui-card-body">
<table class="layui-table">
<thead><tr><th>分类</th><th>文章数</th></tr></thead>
<tbody>
{volist name='dist' id='d'}
<tr><td>{$d.name}</td><td>{$d.count}</td></tr>
{/volist}
{empty name='dist'}
<tr><td colspan="2" style="text-align:center;color:#999;">暂无分类</td></tr>
{/empty}
</tbody>
</table>
</div>
</div>
</div>
<div class="layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">热门文章(按浏览)</div>
<div class="layui-card-body">
<table class="layui-table">
<thead><tr><th>标题</th><th>浏览</th><th>评论</th></tr></thead>
<tbody>
{volist name='hot' id='h'}
<tr><td>{$h.title}</td><td>{$h.view_count}</td><td>{$h.comment_count}</td></tr>
{/volist}
{empty name='hot'}
<tr><td colspan="3" style="text-align:center;color:#999;">暂无数据</td></tr>
{/empty}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
+5 -4
View File
@@ -19,7 +19,7 @@
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="save">保存</button>
<a href="{:url('articles/backend.tag/index')}" class="layui-btn layui-btn-primary">返回</a>
<a href="{:url('articles/backend/tag/index')}" class="layui-btn layui-btn-primary">返回</a>
</div>
</div>
</form>
@@ -28,12 +28,13 @@
</div>
<script>
layui.use(['form', 'jquery'], function () {
layui.use(['form', 'jquery', 'http', 'ywxapp'], function () {
var http = layui.http;
var form = layui.form, $ = layui.jquery;
form.on('submit(save)', function (data) {
$.post("{:url('articles/backend.tag/update')}", data.field, function (r) {
http.post("{:url('articles/backend/tag/update')}", data.field).then(function (r) {
layer.msg(r.msg); if (r.code) { setTimeout(function () { location.href = r.url; }, 800); }
}, 'json');
});
return false;
});
});
+3 -2
View File
@@ -13,7 +13,8 @@
</script>
<script>
layui.use(['table'], function () {
layui.use(['table', 'http', 'ywxapp'], function () {
var http = layui.http;
var table = layui.table;
table.render({
elem: '#table',
@@ -33,7 +34,7 @@ layui.use(['table'], function () {
if (obj.event === 'edit') { location.href = obj.data.edit_url; }
else if (obj.event === 'del') {
layer.confirm('确认删除该标签?', function () {
$.post("{:url('articles/backend.tag/delete')}", { id: obj.data.id }, function (r) {
http.post("{:url('articles/backend.tag/delete')}", { id: obj.data.id }).then(function (r) {
layer.msg(r.msg); if (r.code) { obj.del(); }
});
});
@@ -0,0 +1,94 @@
<div class="layui-fluid">
<div class="layui-card">
<div class="layui-card-header">
{if $topic}编辑专题{else/}新建专题{/if}
<a href="{:url('articles/backend/topic/index')}" class="layui-btn layui-btn-sm layui-btn-primary" style="float:right;margin-top:6px;">返回</a>
</div>
<div class="layui-card-body">
<form class="layui-form">
<input type="hidden" name="id" value="{$topic.id|default='0'}">
<div class="layui-form-item">
<label class="layui-form-label">专题名称</label>
<div class="layui-input-block">
<input type="text" name="title" value="{$topic.title|default=''}" required lay-verify="required" class="layui-input" placeholder="如:新手入门">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">别名</label>
<div class="layui-input-block">
<input type="text" name="alias" value="{$topic.alias|default=''}" required lay-verify="required" class="layui-input" placeholder="URL 标识,如 getting-started">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">描述</label>
<div class="layui-input-block">
<textarea name="description" class="layui-textarea" placeholder="专题简介(用于聚合页 SEO description)">{$topic.description|default=''}</textarea>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">封面图</label>
<div class="layui-input-block">
<input type="text" name="cover" value="{$topic.cover|default=''}" class="layui-input" placeholder="图片地址">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">包含文章</label>
<div class="layui-input-block">
<input type="text" name="article_ids" id="article_ids" class="layui-input"
value="{if isset($picked) && $picked}{:implode(',', array_column($picked, 'id'))}{/if}"
placeholder="文章ID,逗号分隔;顺序即专题内展示顺序">
<div style="margin-top:8px;color:#666;">
{volist name='picked' id='p'}
<span class="layui-badge layui-bg-gray">#{$p.id} {$p.title}</span>
{/volist}
{empty name='picked'}
<span style="color:#999;">尚未选择文章(可在文章列表查看 ID)</span>
{/empty}
</div>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">排序</label>
<div class="layui-input-inline">
<input type="number" name="sort" value="{$topic.sort|default='0'}" class="layui-input">
</div>
<div class="layui-form-mid">越大越靠前</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">状态</label>
<div class="layui-input-inline">
<input type="checkbox" name="status" value="1" {if isset($topic['status']) ? $topic['status'] : 1}checked{/if} title="启用" lay-skin="switch">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="save">保存</button>
<a href="{:url('articles/backend/topic/index')}" class="layui-btn layui-btn-primary">返回</a>
</div>
</div>
</form>
</div>
</div>
</div>
<script>
layui.use(['form', 'http', 'ywxapp'], function () {
var http = layui.http;
var form = layui.form;
form.on('submit(save)', function (data) {
http.post("{:url('articles/backend/topic/update')}", data.field).then(function (r) {
layer.msg(r.msg);
if (r.code) { setTimeout(function () { location.href = r.url || "{:url('articles/backend/topic/index')}"; }, 800); }
});
return false;
});
});
</script>
@@ -0,0 +1,53 @@
<div class="layui-fluid">
<div class="layui-card">
<div class="layui-card-header">
专题管理
<a href="{:url('articles/backend/topic/save')}" class="layui-btn layui-btn-sm layui-btn-normal" style="float:right;margin-top:6px;">新建专题</a>
</div>
<div class="layui-card-body">
<table class="layui-table" id="table" lay-filter="table"></table>
</div>
</div>
</div>
<script type="text/html" id="toolbar">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
</script>
<script>
layui.use(['table', 'jquery', 'http', 'ywxapp'], function () {
var http = layui.http;
var table = layui.table, $ = layui.jquery;
var tableIns = table.render({
elem: '#table',
url: "{:url('articles/backend/topic/index')}",
method: 'post',
page: true,
cols: [[
{ field: 'id', title: 'ID', width: 70 },
{ field: 'title', title: '专题名称', minWidth: 180 },
{ field: 'alias', title: '别名', width: 140 },
{ field: 'article_count', title: '文章数', width: 90 },
{ field: 'sort', title: '排序', width: 80 },
{ field: 'status', title: '状态', width: 80, templet: function (d) { return d.status ? '<span class="layui-badge layui-bg-green">启用</span>' : '<span class="layui-badge">禁用</span>'; } },
{ field: 'create_at', title: '创建时间', width: 170 },
{ title: '操作', width: 140, toolbar: '#toolbar' }
]]
});
table.on('tool(table)', function (obj) {
if (obj.event === 'edit') {
location.href = obj.data.edit_url;
} else if (obj.event === 'del') {
layer.confirm('确认删除该专题?(不会删除文章本身)', function () {
http.post("{:url('articles/backend/topic/delete')}", { id: obj.data.id }).then(function (r) {
layer.msg(r.msg);
if (r.code) { obj.del(); }
});
});
}
});
});
</script>
@@ -3,11 +3,26 @@
<head>
<meta charset="UTF-8">
<title>{$article.title} - 文章CMS</title>
<meta name="keywords" content="{$article.category_name|default=''}">
<meta name="description" content="{$article.summary|default=''|substr=0,150}">
<link rel="canonical" href="{:url('articles/read/' . $article.id)}">
{notempty name='$jsonLd'}
<script type="application/ld+json">{$jsonLd|raw}</script>
<script type="application/ld+json">{$breadcrumbLd|raw}</script>
{/notempty}
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" type="text/css" href="/assets/layui/css/layui.css">
<link rel="stylesheet" type="text/css" href="/static/articles/css/main.css">
</head>
<body class="micronews">
<!-- 阅读进度条 + 继续上次阅读 -->
<div id="readProgressBar" style="position:fixed;top:0;left:0;height:3px;background:#5FB878;width:0;z-index:9999;"></div>
<div id="readResume" style="display:none;position:fixed;right:16px;bottom:16px;background:#fff;border:1px solid #eee;padding:8px 12px;box-shadow:0 2px 8px rgba(0,0,0,.12);z-index:9999;font-size:13px;">
上次读到 <b id="readResumePct">0</b>% · <a href="javascript:;" id="readResumeGo" style="color:#5FB878;">继续阅读</a>
<a href="javascript:;" id="readResumeClose" style="margin-left:8px;color:#999;">×</a>
</div>
<div class="micronews-header-wrap">
<div class="micronews-header w1000 layui-clear">
<h1 class="logo">
@@ -29,8 +44,8 @@
<input type="text" name="keyword" placeholder="搜索你要的内容" autocomplete="off" class="layui-input">
<button class="layui-btn search-btn" formnovalidate><i class="layui-icon layui-icon-search"></i></button>
</div>
</div>-
</form>
</div>
</form>
</div>
<div class="login">
{if $is_login}
@@ -72,6 +87,14 @@
<b>{$article.comment_count}</b>条
</span>
</a>
<a href="javascript:;" id="btnLike" class="icon like {if $liked}liked{/if}" title="点赞">
<i class="layui-icon layui-icon-praise"></i>
<b id="likeCount">{$article.like_count|default='0'}</b>
</a>
<a href="javascript:;" id="btnFav" class="icon fav {if $favorited}on{/if}" title="收藏">
<i class="layui-icon layui-icon-star"></i>
<span id="favText">{if $favorited}已收藏{else/}收藏{/if}</span>
</a>
<span class="icon time">
<i class="layui-icon layui-icon-log"></i>
{$article.create_at}
@@ -79,7 +102,7 @@
</div>
</div>
<div class="article">
{$article.content|raw}
{if isset($contentHtml) && $contentHtml}{$contentHtml|raw}{else/}{$article.content|raw}{/if}
</div>
<div class="leave-message" id="message">
<div class="tit-box">
@@ -105,6 +128,16 @@
</div>
</form>
</div>
<!-- 楼层回复框:点击某条评论的「回复」后展开 -->
<div class="reply-box" id="replyBox" style="display:none;margin:10px 0;padding:10px;border:1px solid #eee;">
<div class="reply-tip" id="replyTip" style="margin-bottom:6px;color:#888;"></div>
<textarea id="replyContent" class="layui-textarea" placeholder="回复内容"></textarea>
<div style="text-align:right;margin-top:8px;">
<button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="replyCancel">取消</button>
<button type="button" class="layui-btn layui-btn-sm" id="replySubmit">提交回复</button>
</div>
</div>
<div class="ulCommentList">
{volist name='comments.data' id='cm'}
<div class="liCont">
@@ -113,7 +146,18 @@
<div class="cont">
<p><span class="name">{$cm.nickname|default='游客'}</span><span class="time">{$cm.create_at}</span></p>
<p class="text">{$cm.content}</p>
<p><a href="javascript:;" class="btn-reply" data-id="{$cm.id}" data-name="{$cm.nickname|default='游客'}">回复</a></p>
</div>
{notempty name='$cm.replies'}
<div class="reply-list" style="margin-left:52px;border-left:2px solid #f0f0f0;padding-left:10px;">
{volist name='$cm.replies' id='rp'}
<div class="reply-item">
<p><span class="name">{$rp.nickname|default='游客'}</span><span class="time">{$rp.create_at}</span></p>
<p class="text">{$rp.content}</p>
</div>
{/volist}
</div>
{/notempty}
</div>
</div>
{/volist}
@@ -186,5 +230,90 @@
index.arrowutil();
});
</script>
<script>
// 点赞 / 楼层回复(独立于模板自带 index 模块,避免冲突)
layui.use(['jquery', 'layer'], function () {
var $ = layui.jquery, layer = layui.layer;
var aid = "{$article.id}";
var likeUrl = "{:url('articles/article/like')}";
var commentUrl = "{:url('articles/article/comment')}";
$('#btnLike').on('click', function () {
$.post(likeUrl, { id: aid, target: 1 }, function (r) {
if (!r || !r.code) { layer.msg((r && r.message) || '操作失败'); return; }
var d = r.data || {};
$('#likeCount').text(d.count || 0);
$('#btnLike').toggleClass('liked', !!d.liked);
layer.msg(r.message || (d.liked ? '已点赞' : '已取消点赞'));
});
return false;
});
// 收藏
$('#btnFav').on('click', function () {
$.post("{:url('articles/article/favorite')}", { id: aid }, function (r) {
if (!r || !r.code) { layer.msg((r && r.message) || '请先登录'); return; }
var on = !!(r.data && r.data.favorited);
$('#btnFav').toggleClass('on', on);
$('#favText').text(on ? '已收藏' : '收藏');
layer.msg(r.message || '');
});
return false;
});
// 阅读进度(本地记录,无需登录)
var bar = document.getElementById('readProgressBar');
var pkey = 'articles_progress_' + aid;
function progress() {
var h = document.documentElement;
var top = h.scrollTop || document.body.scrollTop || 0;
var max = (h.scrollHeight - h.clientHeight) || 0;
return max > 0 ? Math.min(100, Math.round(top / max * 100)) : 0;
}
window.addEventListener('scroll', function () {
var p = progress();
if (bar) { bar.style.width = p + '%'; }
try { localStorage.setItem(pkey, p); } catch (e) {}
});
var saved = 0;
try { saved = parseInt(localStorage.getItem(pkey) || '0', 10); } catch (e) {}
if (saved >= 5 && saved <= 90) {
$('#readResumePct').text(saved);
$('#readResume').show();
$('#readResumeGo').on('click', function () {
var h = document.documentElement;
var max = (h.scrollHeight - h.clientHeight) || 0;
window.scrollTo({ top: Math.round(max * saved / 100), behavior: 'smooth' });
$('#readResume').hide();
});
$('#readResumeClose').on('click', function () { $('#readResume').hide(); });
}
var replyPid = 0;
$(document).on('click', '.btn-reply', function () {
replyPid = $(this).data('id');
$('#replyTip').text('回复 @' + ($(this).data('name') || ''));
$('#replyBox').show();
$('#replyContent').focus();
});
$('#replyCancel').on('click', function () {
replyPid = 0;
$('#replyBox').hide();
$('#replyContent').val('');
});
$('#replySubmit').on('click', function () {
var content = $.trim($('#replyContent').val());
if (!content) { layer.msg('请输入回复内容'); return; }
$.post(commentUrl, { aid: aid, pid: replyPid, content: content }, function (r) {
layer.msg((r && r.message) || '已提交');
if (r && r.code) { setTimeout(function () { location.reload(); }, 600); }
});
});
});
</script>
</body>
</html>
@@ -3,6 +3,8 @@
<head>
<meta charset="UTF-8">
<title>{$category.name|default='分类'} - 文章CMS</title>
<meta name="description" content="{$category.description|default=''|substr=0,150}">
<link rel="canonical" href="{:url('articles/category/index', ['id'=>$category.id])}">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" type="text/css" href="/assets/layui/css/layui.css">
<link rel="stylesheet" type="text/css" href="/static/articles/css/main.css">
@@ -3,6 +3,8 @@
<head>
<meta charset="UTF-8">
<title>文章CMS - 资讯中心</title>
<meta name="description" content="文章CMS 资讯中心">
<link rel="canonical" href="{:url('articles/index/index')}">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" type="text/css" href="/assets/layui/css/layui.css">
<link rel="stylesheet" type="text/css" href="/static/articles/css/main.css">
@@ -3,6 +3,8 @@
<head>
<meta charset="UTF-8">
<title>搜索:{$keyword|default=''} - 文章CMS</title>
{* 搜索结果页千变万化且无实质内容,禁止搜索引擎收录 *}
<meta name="robots" content="noindex,follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" type="text/css" href="/assets/layui/css/layui.css">
<link rel="stylesheet" type="text/css" href="/static/articles/css/main.css">
@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8">
<title>{$tag.name|default='标签'} - 文章CMS</title>
<link rel="canonical" href="{:url('articles/tag/index', ['id'=>$tag.id])}">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" type="text/css" href="/assets/layui/css/layui.css">
<link rel="stylesheet" type="text/css" href="/static/articles/css/main.css">
@@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{$topic.title} - 专题 - 文章CMS</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="{$topic.title}">
<meta name="description" content="{$topic.description|default=$topic.title|substr=0,150}">
<link rel="canonical" href="{:url('articles/topic/' . $topic.id)}">
<link rel="stylesheet" type="text/css" href="/assets/layui/css/layui.css">
<link rel="stylesheet" type="text/css" href="/static/articles/css/main.css">
</head>
<body class="micronews">
<div class="micronews-header-wrap">
<div class="micronews-header w1000 layui-clear">
<h1 class="logo">
<a href="{:url('articles/index/index')}">
<img src="/static/articles/img/LOGO.png" alt="logo">
<span class="layui-hide">LOGO</span>
</a>
</h1>
<p class="nav">
<a href="{:url('articles/index/index')}">最新</a>
<a href="{:url('articles/topic/index')}" class="active">专题</a>
{volist name='categories' id='c'}
<a href="{:url('articles/category/index', ['id'=>$c.id])}">{$c.name}</a>
{/volist}
</p>
<div class="search-bar">
<form class="layui-form" action="{:url('articles/search/index')}">
<div class="layui-form-item">
<div class="layui-input-block">
<input type="text" name="keyword" placeholder="搜索你要的内容" autocomplete="off" class="layui-input">
<button class="layui-btn search-btn" formnovalidate><i class="layui-icon layui-icon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="micronews-container w1000">
<div class="layui-card">
<div class="layui-card-header">
<h3>{$topic.title}</h3>
</div>
<div class="layui-card-body">
{notempty name='$topic.description'}
<p style="color:#666;margin-bottom:10px;">{$topic.description}</p>
{/notempty}
<ul class="list-box">
{volist name='list' id='a'}
<li class="list">
<a href="{:url('articles/read/' . $a.id)}">{$a.title}</a>
<span style="color:#999;font-size:12px;margin-left:8px;">{$a.category_name|default=''} · {$a.view_count} 次阅读</span>
</li>
{/volist}
{empty name='list'}
<li class="list" style="color:#999;">该专题下暂无已发布文章</li>
{/empty}
</ul>
<div class="page-wrap">{$page|raw}</div>
</div>
</div>
</div>
<div class="micronews-footer-wrap">
<div class="micronews-footer w1000">
<div class="Copyright">
<span>Copyright&nbsp;</span>&nbsp;&copy;<span>文章CMS&nbsp;&nbsp;</span><span>Powered by YwxApp</span>
</div>
</div>
</div>
<script type="text/javascript" src="/assets/layui/layui.js"></script>
</body>
</html>
@@ -0,0 +1,80 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>专题汇总 - 文章CMS</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="专题汇总">
<link rel="canonical" href="{:url('articles/topic/index')}">
<link rel="stylesheet" type="text/css" href="/assets/layui/css/layui.css">
<link rel="stylesheet" type="text/css" href="/static/articles/css/main.css">
</head>
<body class="micronews">
<div class="micronews-header-wrap">
<div class="micronews-header w1000 layui-clear">
<h1 class="logo">
<a href="{:url('articles/index/index')}">
<img src="/static/articles/img/LOGO.png" alt="logo">
<span class="layui-hide">LOGO</span>
</a>
</h1>
<p class="nav">
<a href="{:url('articles/index/index')}">最新</a>
<a href="{:url('articles/topic/index')}" class="active">专题</a>
{volist name='categories' id='c'}
<a href="{:url('articles/category/index', ['id'=>$c.id])}">{$c.name}</a>
{/volist}
</p>
<div class="search-bar">
<form class="layui-form" action="{:url('articles/search/index')}">
<div class="layui-form-item">
<div class="layui-input-block">
<input type="text" name="keyword" placeholder="搜索你要的内容" autocomplete="off" class="layui-input">
<button class="layui-btn search-btn" formnovalidate><i class="layui-icon layui-icon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="micronews-container w1000">
<div class="layui-card">
<div class="layui-card-header"><h3>专题汇总</h3></div>
<div class="layui-card-body">
<div class="layui-row layui-col-space15">
{volist name='topics' id='t'}
<div class="layui-col-md4 layui-col-sm6">
<div class="layui-card">
{notempty name='$t.cover'}
<div style="height:140px;overflow:hidden;">
<img src="{$t.cover}" alt="{$t.title}" style="width:100%;">
</div>
{/notempty}
<div class="layui-card-body">
<h3><a href="{:url('articles/topic/' . $t.id)}">{$t.title}</a></h3>
<p style="color:#666;margin:6px 0;">{$t.description|default=''|substr=0,60}</p>
<span class="layui-badge layui-bg-gray">{$t.count} 篇</span>
</div>
</div>
</div>
{/volist}
{empty name='topics'}
<div class="layui-col-md12" style="text-align:center;color:#999;padding:40px 0;">暂无专题</div>
{/empty}
</div>
</div>
</div>
</div>
<div class="micronews-footer-wrap">
<div class="micronews-footer w1000">
<div class="Copyright">
<span>Copyright&nbsp;</span>&nbsp;&copy;<span>文章CMS&nbsp;&nbsp;</span><span>Powered by YwxApp</span>
</div>
</div>
</div>
<script type="text/javascript" src="/assets/layui/layui.js"></script>
</body>
</html>
@@ -0,0 +1,92 @@
<div class="layui-card">
<div class="layui-card-header">
{if $article}编辑稿件{else/}写文章{/if}
<a href="{:url('articles/member/article/index')}" class="layui-btn layui-btn-sm layui-btn-primary" style="float:right;margin-top:6px;">返回列表</a>
</div>
<div class="layui-card-body">
<form class="layui-form" lay-filter="contribute">
<input type="hidden" name="id" value="{$article.id|default='0'}">
<div class="layui-form-item">
<label class="layui-form-label">标题</label>
<div class="layui-input-block">
<input type="text" name="title" value="{$article.title|default=''}" required lay-verify="required" placeholder="文章标题" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">分类</label>
<div class="layui-input-block">
<select name="cid" lay-verify="required">
{volist name='categories' id='c'}
<option value="{$c.id}" {if isset($article['cid']) && $article['cid'] == $c['id']}selected{/if}>{$c.name}</option>
{/volist}
</select>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">摘要</label>
<div class="layui-input-block">
<textarea name="summary" class="layui-textarea" placeholder="可选,列表页展示">{$article.summary|default=''}</textarea>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">封面图</label>
<div class="layui-input-block">
<input type="text" name="cover_image" value="{$article.cover_image|default=''}" class="layui-input" placeholder="图片地址(可留空)">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">正文</label>
<div class="layui-input-block">
<textarea id="content" name="content" style="display:none;">{$article.content|default=''}</textarea>
<script id="editor" type="text/plain" style="width:100%;height:380px;"></script>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="contribute">提交投稿</button>
<span style="color:#999;margin-left:10px;">提交后进入「待审核」,管理员通过后才会公开显示</span>
</div>
</div>
</form>
</div>
</div>
<script src="/assets/library/ueditor/ueditor.config.js"></script>
<script src="/assets/library/ueditor/ueditor.all.js"></script>
<script>
layui.use(['form', 'jquery'], function () {
var form = layui.form, $ = layui.jquery;
var ue = UE.getEditor('editor', {
UEDITOR_HOME_URL: '/assets/library/ueditor/',
serverUrl: '/ueditor'
});
ue.ready(function () {
var c = $('#content').val();
if (c) { ue.setContent(c); }
});
form.on('submit(contribute)', function (data) {
data.field.content = ue.getContent();
$.ajax({
url: "{:url('articles/member/article/save')}",
type: 'post',
data: data.field,
dataType: 'json',
success: function (r) {
layer.msg(r.message || r.msg || '');
if (r.code === 0 || r.code === '0') {
setTimeout(function () { location.href = "{:url('articles/member/article/index')}"; }, 800);
}
}
});
return false;
});
});
</script>
@@ -0,0 +1,54 @@
<div class="layui-card">
<div class="layui-card-header">
我的投稿
<a href="{:url('articles/member/article/add')}" class="layui-btn layui-btn-sm layui-btn-normal" style="float:right;margin-top:6px;">写文章</a>
</div>
<div class="layui-card-body">
<table class="layui-table">
<thead>
<tr><th>ID</th><th>标题</th><th>分类</th><th>状态</th><th>浏览</th><th>时间</th><th>操作</th></tr>
</thead>
<tbody>
{volist name='list' id='a'}
<tr>
<td>{$a.id}</td>
<td>{$a.title}</td>
<td>{$a.category_name|default='未分类'}</td>
<td>
{switch $a.status}
{case 1}<span class="layui-badge layui-bg-green">已发布</span>{/case}
{case 2}<span class="layui-badge layui-bg-orange">待审核</span>{/case}
{default /}<span class="layui-badge">草稿</span>
{/switch}
</td>
<td>{$a.view_count}</td>
<td>{$a.create_at}</td>
<td>
<a href="{:url('articles/member/article/edit', ['id'=>$a.id])}" class="layui-btn layui-btn-xs">编辑</a>
<a href="javascript:;" class="layui-btn layui-btn-xs layui-btn-danger btn-del" data-id="{$a.id}">删除</a>
</td>
</tr>
{/volist}
{empty name='list'}
<tr><td colspan="7" style="text-align:center;color:#999;">还没有投稿,点右上角「写文章」开始吧</td></tr>
{/empty}
</tbody>
</table>
<div>{$list->render()|raw}</div>
</div>
</div>
<script>
layui.use(['jquery', 'layer'], function () {
var $ = layui.jquery, layer = layui.layer;
$('.btn-del').on('click', function () {
var id = $(this).data('id');
layer.confirm('确认删除这篇稿件?', function () {
$.post("{:url('articles/member/article/delete')}", { id: id }, function (r) {
layer.msg(r.message || r.msg || '');
if (r.code === 0 || r.code === '0') { setTimeout(function () { location.reload(); }, 600); }
});
});
});
});
</script>