Files

2631 lines
91 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* TypechoToObsidian REST API 接口 - API Action
*
* @package TypechoToObsidian
* @author 石头厝
*/
namespace TypechoPlugin\TypechoToObsidian;
use ReflectionClass;
use ReflectionMethod;
use Typecho\Common;
use Typecho\Config;
use Typecho\Cookie;
use Typecho\Db;
use Typecho\Request as TypechoRequest;
use Typecho\Router;
use Typecho\Widget\Request;
use Utils\Markdown;
use Widget\ActionInterface;
use Widget\Base\Comments;
use Widget\Base\Contents;
use Widget\Base\Metas;
use Widget\Options;
use Widget\Upload;
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
class Action extends Request implements ActionInterface
{
/**
* @var Config
*/
private $config;
/**
* @var Db
*/
private $db;
/**
* @var Options
*/
private $options;
/**
* @var array
*/
private $httpParams;
protected \Typecho\Widget\Request $request;
protected \Typecho\Widget\Response $response;
/**
* @var array
* 指定路由短名在 POST 时跳过 JSON 解析报错
* 例如: ['upload', 'anotherRoute']
*/
private array $jsonParseSkipRoutes = array('upload');
/**
* buildPermalink() 的按 cid 缓存
*
* 评论列表一次几十条,同几篇文章的评论会反复取链接;
* 每个 cid 单独查 contents + 分类要 2 条 SQL,缓存后只算一次。
*
* @var array
*/
private array $permalinkCache = array();
public function __construct($request = null, $response = null, $params = null)
{
$typecho_request = TypechoRequest::getInstance();
parent::__construct($typecho_request, $params);
$this->db = Db::get();
$this->options = Options::alloc();
$this->config = $this->options->plugin('TypechoToObsidian');
$this->request = $request;
$this->response = $response;
}
/**
* 获取路由参数
*
* @return array
*/
public static function getRoutes()
{
$routes = array();
$reflectClass = new ReflectionClass(__CLASS__);
$prefix = defined('__TYPECHO_TO_OBSIDIAN_PREFIX__') ? __TYPECHO_TO_OBSIDIAN_PREFIX__ : '/api/';
foreach ($reflectClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectMethod) {
$methodName = $reflectMethod->getName();
preg_match('/(.*)Action$/', $methodName, $matches);
if (isset($matches[1])) {
$routes[] = array(
'action' => $matches[0],
'name' => 'tto_' . $matches[1],
'shortName' => $matches[1],
'uri' => $prefix . $matches[1],
'description' => trim(str_replace(
array('/', '*'),
'',
substr($reflectMethod->getDocComment(), 0, strpos($reflectMethod->getDocComment(), '@'))
)),
);
}
}
return $routes;
}
public function execute()
{
$this->sendCORS();
$this->parseRequest();
$prefix = defined('__TYPECHO_TO_OBSIDIAN_PREFIX__') ? __TYPECHO_TO_OBSIDIAN_PREFIX__ : '/api/';
$url = $this->request->getPathInfo();
$url = str_replace($prefix, '', $url);
$this->{$url . "Action"}();
}
public function action()
{
}
/**
* 发送跨域 HEADER
*/
private function sendCORS()
{
$httpOrigin = $this->request->getServer('HTTP_ORIGIN');
$this->response->setHeader('Access-Control-Allow-Credentials', 'true');
$allowedHttpOrigins = explode("\n", str_replace("\r", "", $this->config->offsetGet('origin')));
if (!$httpOrigin) {
$this->throwError('非法请求!');
}
if (in_array($httpOrigin, $allowedHttpOrigins)) {
$this->response->setHeader('Access-Control-Allow-Origin', $httpOrigin);
}
if (strtolower($this->request->getServer('REQUEST_METHOD')) == 'options') {
$this->response->setStatus(204);
$this->response->setHeader('Access-Control-Allow-Headers', 'Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type');
$this->response->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
exit;
}
}
/**
* 解析请求参数
*
* @return void
*/
private function parseRequest()
{
if ($this->request->isPost()) {
$pathInfo = (string)$this->request->getPathInfo();
$prefix = defined('__TYPECHO_TO_OBSIDIAN_PREFIX__') ? __TYPECHO_TO_OBSIDIAN_PREFIX__ : '/api/';
$shortRoute = trim(str_replace($prefix, '', $pathInfo), '/');
if (false !== ($pos = strpos($shortRoute, '/'))) {
$shortRoute = substr($shortRoute, 0, $pos);
}
$data = file_get_contents('php://input');
$data = json_decode($data, true);
if ($data !== '' && json_last_error() != JSON_ERROR_NONE) {
// 命中跳过列表则不抛错
if (in_array($shortRoute, $this->jsonParseSkipRoutes, true)) {
$this->httpParams = array();
return;
}
$this->throwError('Parse JSON error');
}
$this->httpParams = $data;
}
}
/**
* 获取 GET/POST 参数
*
* @param string $key 目标参数的 key
* @param mixed $default 返回的默认值
* @return mixed
*/
private function getParams($key, $default = null)
{
if ($this->request->isGet()) {
return $this->request->get($key, $default);
}
if (!isset($this->httpParams[$key])) {
return $default;
}
return $this->httpParams[$key];
}
/**
* 标题在数据库里的真实形态
*
* 核心写文章都会先 htmlspecialchars,所以库里存的是转义后的标题;
* 本插件更新文章用裸 UPDATE,不会自动转义,必须自己补上。
*
* @param string $title
* @return string
*/
private function storedTitle($title)
{
return htmlspecialchars((string) $title);
}
/**
* 给查询加「按标题匹配」条件
*
* 客户端发的是标题原文,库里存的是转义形态,只比原文永远查不到
* 刚插入的那篇(会被当成新文章重复插入)。旧版本插件裸 SQL 更新过的
* 文章可能留着未转义的标题,因此两种形态都算命中。
*
* @param \Typecho\Db\Query $query
* @param string $title
* @return \Typecho\Db\Query
*/
private function whereTitle($query, $title)
{
$forms = array();
foreach (array($this->storedTitle($title), (string) $title) as $form) {
if (!in_array($form, $forms, true)) {
$forms[] = $form;
}
}
$condition = '(' . implode(' OR ', array_fill(0, count($forms), 'title = ?')) . ')';
return call_user_func_array(array($query, 'where'), array_merge(array($condition), $forms));
}
/**
* 以 JSON 格式返回错误
*
* @param string $message 错误信息
* @param integer $status HTTP 状态码
* @return void
*/
private function throwError($message = 'unknown', $status = 400)
{
$this->response->setStatus($status);
$this->response->throwJson(array(
'status' => 'error',
'message' => $message,
'data' => null,
));
}
/**
* 以 JSON 格式响应请求的信息
*
* @param mixed $data 要返回给用户的内容
* @return void
*/
private function throwData($data)
{
$this->response->throwJson(array(
'status' => 'success',
'message' => '',
'data' => $data,
));
}
/**
* 锁定 API 请求方式
*
* @param string $method 请求方式 (get/post)
* @return void
*/
private function lockMethod($method)
{
$method = strtolower($method);
if (strtolower($this->request->getServer('REQUEST_METHOD')) != $method) {
$this->throwError('method not allowed', 405);
}
}
/**
* show errors when accessing a disabled API
*
* @param string $route
* @return void
*/
private function checkState($route, $defaultEnabled = false)
{
$state = $this->config->$route;
if ($state === null || $state === '') {
// 升级插件后新增的路由在旧配置里没有记录,按调用方给的默认值处理
$state = $defaultEnabled;
}
if (!$state) {
$this->throwError('This API has been disabled.', 403);
}
$token = $this->request->getHeader('token');
if ($this->config->apiToken && $token != $this->config->apiToken) {
$this->throwError('apiToken is invalid', 403);
}
}
/**
* 获取文章自定义字段内容
*
* @param int $cid
* @return array
*/
public function getCustomFields($cid)
{
$cfg = $this->config->fieldsPrivacy;
$filters = empty($cfg) ? array() : explode(',', $cfg);
$query = $this->db->select('*')->from('table.fields')
->where('cid = ?', $cid);
$rows = $this->db->fetchAll($query);
$result = array();
if (count($rows) > 0) {
foreach ($rows as $key => $value) {
if (in_array($value['name'], $filters)) {
continue;
}
$type = $value['type'];
$result[$value['name']] = array(
"name" => $value['name'],
"type" => $value['type'],
"value" => $value['str_value'],
);
}
}
return $result;
}
/**
* 获取文章列表、搜索文章的接口
*
* @return void
*/
public function postsAction()
{
$this->lockMethod('get');
$this->checkState('posts');
$pageSize = $this->getParams('pageSize', 5);
$page = $this->getParams('page', 1);
$page = is_numeric($page) ? $page : 1;
$offset = $pageSize * ($page - 1);
$filterType = trim($this->getParams('filterType', ''));
$filterSlug = trim($this->getParams('filterSlug', ''));
$showContent = trim($this->getParams('showContent', '')) === 'true';
$showDigest = trim($this->getParams('showDigest', ''));
if (in_array($filterType, array('category', 'tag', 'search'))) {
if ($filterSlug == '') {
$this->throwError('filter slug is empty');
}
if ($filterType != 'search') {
$select = $this->db->select('mid')
->from('table.metas')
->where('type = ?', $filterType)
->where('slug = ?', $filterSlug);
$row = $this->db->fetchRow($select);
if (!isset($row['mid'])) {
$this->throwError('unknown slug name');
}
$mid = $row['mid'];
$select = $this->db->select('cid')->from('table.relationships')
->where('mid = ?', $mid);
$cids = $this->db->fetchAll($select);
if (count($cids) == 0) {
$this->throwData(array(
'page' => (int)$page,
'pageSize' => (int)$pageSize,
'pages' => 0,
'count' => 0,
'dataSet' => array(),
));
} else {
foreach ($cids as $key => $cid) {
$cids[$key] = $cid['cid'];
}
}
}
}
$select = $this->db
->select('cid', 'title', 'created', 'modified', 'slug', 'commentsNum', 'text', 'type')
->from('table.contents')
->where('type = ?', 'post')
->where('status = ?', 'publish')
->where('created < ?', time())
->where('password IS NULL')
->order('created', Db::SORT_DESC);
if (isset($cids)) {
$cidStr = implode(',', $cids);
$select->where('cid IN (' . $cidStr . ')');
} elseif ($filterType == 'search') {
// 多个关键词按空格分词,每个词都要命中(标题或正文里出现即可)。
// 原来是把空格替换成 % 拼成一个 LIKE,等于要求「按顺序连续出现」,
// 搜「发布 500」这种不相邻的词直接搜不到。
$keywords = preg_split('/\s+/u', $filterSlug, -1, PREG_SPLIT_NO_EMPTY);
if (empty($keywords)) {
$keywords = array($filterSlug);
}
// 关键词太多没有意义,顺手挡住超长输入
$keywords = array_slice($keywords, 0, 8);
$conditions = array();
$params = array();
foreach ($keywords as $keyword) {
// 关键词里的 % _ 是 LIKE 通配符,得转义成字面量
$like = '%' . str_replace(
array('\\', '%', '_'),
array('\\\\', '\\%', '\\_'),
$keyword
) . '%';
// 整体加括号:Query::where 用 AND 拼接,不括号的话
// 「title LIKE ? OR text LIKE ?」里的 OR 会把上面
// type=post / status=publish 等条件一起短路,
// 草稿、页面、加密文章都会混进搜索结果
$conditions[] = '(title LIKE ? OR text LIKE ?)';
$params[] = $like;
$params[] = $like;
}
$searchWhere = '(' . implode(' AND ', $conditions) . ')';
// 客户端会把界面上的 #416 直接粘进搜索框,纯数字当成文章 ID 精确匹配。
// 单独 OR 出来,不和关键词条件混在一起(否则会变成「必须又含这串数字」)。
$idKeywords = array();
foreach ($keywords as $keyword) {
if (preg_match('/^#?(\d+)$/', $keyword, $matches)) {
$idKeywords[] = (int) $matches[1];
}
}
if (count($idKeywords) > 0) {
$placeholders = implode(',', array_fill(0, count($idKeywords), '?'));
$searchWhere = '(' . $searchWhere . ' OR cid IN (' . $placeholders . '))';
$params = array_merge($params, $idKeywords);
}
call_user_func_array(
array($select, 'where'),
array_merge(array($searchWhere), $params)
);
}
$count = count($this->db->fetchAll($select));
$select->offset($offset)
->limit($pageSize);
$result = $this->db->fetchAll($select);
foreach ($result as $key => $value) {
// digest has two types
if ($showDigest === 'more') {
// if you use 'more', plugin will truncate from <!--more-->
$result[$key]['digest'] = str_replace(
"<!--markdown-->",
"",
explode("<!--more-->", $result[$key]['text'])[0]
);
$result[$key] = $this->articleFilter($result[$key]);
} elseif ($showDigest === 'excerpt') {
// if you use 'excerpt', plugin will truncate for certain number of text
$limit = (int)trim($this->getParams('limit', '200'));
$result[$key] = $this->articleFilter($value);
$result[$key]['digest'] = mb_substr(
htmlspecialchars_decode(strip_tags($result[$key]['text'])),
0,
$limit,
'utf-8'
) . "...";
} else {
$result[$key] = $this->articleFilter($value);
}
if (!$showContent) {
unset($result[$key]['text']);
}
}
$this->throwData(array(
'page' => (int)$page,
'pageSize' => (int)$pageSize,
'pages' => ceil($count / $pageSize),
'count' => $count,
'dataSet' => $result,
));
}
/**
* 获取页面列表的接口
*
* @return void
*/
public function pagesAction()
{
$this->lockMethod('get');
$this->checkState('pages');
$select = $this->db
->select('cid', 'title', 'created', 'slug')
->from('table.contents')
->where('type = ?', 'page')
->where('status = ?', 'publish')
->where('created < ?', time())
->where('password IS NULL')
->order('order', Db::SORT_ASC);
$result = $this->db->fetchAll($select);
$count = count($result);
$this->throwData(array(
'count' => $count,
'dataSet' => $result,
));
}
/**
* 获取分类列表的接口
*
* @return void
*/
public function categoriesAction()
{
$this->lockMethod('get');
$this->checkState('categories');
// $categories = $this->db->fetchAll(Contents::alloc()->select('*')->where('type = ?', 'page'));
$categories = $this->db->fetchAll(Metas::alloc()->select('*')->where('type = ?', 'category'));
$this->throwData($categories);
}
/**
* 获取标签列表的接口
*
* @return void
*/
public function tagsAction()
{
$this->lockMethod('get');
$this->checkState('tags');
$tags = $this->db
->select('mid', 'name', 'slug', 'description', 'count', 'order', 'parent')
->from('table.metas')
->where("type = 'tag'");
$result = $this->db->fetchAll($tags);
$this->throwData($result);
}
/**
* 获取文章、独立页面详情的接口
*
* @return void
*/
public function postAction()
{
$this->lockMethod('get');
$this->checkState('post');
$slug = $this->getParams('slug', '');
$cid = $this->getParams('cid', '');
$select = $this->db
->select('title', 'cid', 'created', 'type', 'slug', 'commentsNum', 'text')
->from('table.contents')
->where('password IS NULL');
if (is_numeric($cid)) {
$select->where('cid = ?', $cid);
} else {
$select->where('slug = ?', $slug);
}
$result = $this->db->fetchRow($select);
if (!empty($result) && count($result) != 0) {
$result = $this->articleFilter($result);
$result['csrfToken'] = $this->generateCsrfToken($result['permalink']);
$this->throwData($result);
} else {
$this->throwError('post not exists', 404);
}
}
/**
* 获取最新(最近)评论的接口
*
* @return void
*/
public function recentCommentsAction()
{
$this->lockMethod('get');
$this->checkState('recentComments');
$size = $this->getParams('size', 9);
$query = $this->db
->select('coid', 'cid', 'author', 'text')
->from('table.comments')
->where('type = ? AND status = ?', 'comment', 'approved')
->order('created', Db::SORT_DESC)
->limit($size);
$result = $this->db->fetchAll($query);
$this->throwData(array(
'count' => count($result),
'dataSet' => $result
));
}
/**
* 获取文章、独立页面评论列表的接口
*
* @return void
*/
public function commentsAction()
{
$this->lockMethod('get');
$this->checkState('comments');
$pageSize = $this->getParams('pageSize', 5);
$page = $this->getParams('page', 1);
$page = is_numeric($page) ? $page : 1;
$offset = $pageSize * ($page - 1);
$slug = $this->getParams('slug', '');
$cid = $this->getParams('cid', '');
$order = strtolower($this->getParams('order', ''));
// 为带 cookie 请求的用户显示正在等待审核的评论
$author = Cookie::get('__typecho_remember_author');
$mail = Cookie::get('__typecho_remember_mail');
if (empty($cid) && empty($slug)) {
$this->throwError('No specified posts.', 404);
}
$select = $this->db
->select('table.comments.coid', 'table.comments.parent', 'table.comments.cid', 'table.comments.created', 'table.comments.author', 'table.comments.mail', 'table.comments.url', 'table.comments.text', 'table.comments.status')
->from('table.comments')
->join('table.contents', 'table.comments.cid = table.contents.cid', Db::LEFT_JOIN)
->where('table.comments.type = ?', 'comment')
->group('table.comments.coid')
->order('table.comments.created', $order === 'asc' ? Db::SORT_ASC : Db::SORT_DESC);
if (empty($author)) {
$select->where('table.comments.status = ?', 'approved');
} else {
$select
->where('table.comments.status = ? OR (table.comments.author = ? AND table.comments.mail = ?)', 'approved', $author, $mail);
}
if (is_numeric($cid)) {
$select->where('table.comments.cid = ?', $cid);
} else {
$select->where('table.contents.slug = ?', $slug);
}
$result = $this->db->fetchAll($select);
if (count($result) <= 0) {
$count = 0;
$finalResult = array();
} else {
$newResult = $this->buildNodes($result);
$count = count($newResult);
$finalResult = array_slice($newResult, $offset, $pageSize);
}
$this->throwData(array(
'page' => (int)$page,
'pageSize' => (int)$pageSize,
'pages' => ceil($count / $pageSize),
'count' => $count,
'dataSet' => $finalResult,
));
}
/**
* 发表评论的接口
*
* @return void
*/
public function commentAction()
{
$this->lockMethod('post');
$this->checkState('comment');
$comments = new Comments($this->request, $this->response);
$check_key = array(
'text', 'mail', 'author', 'token'
);
foreach ($check_key as $key) {
if (!$this->getParams($key, '')) {
$this->throwError('missing ' . $key);
}
}
if (!filter_var($this->getParams('mail'), FILTER_VALIDATE_EMAIL)) {
$this->throwError('邮箱地址不合法');
}
$slug = $this->getParams('slug', '');
$cid = $this->getParams('cid', '');
$token = $this->getParams('token', '');
$select = $this->db->select('cid', 'created', 'type', 'slug', 'commentsNum', 'text')
->from('table.contents')
->where('password IS NULL');
if (is_numeric($cid)) {
$select->where('cid = ?', $cid);
} else {
$select->where('slug = ?', $slug);
}
$result = $this->db->fetchRow($select);
if (count($result) != 0) {
$result = $this->articleFilter($result);
} else {
$this->throwError('post not exists', 404);
}
if (!$this->checkCsrfToken($result['permalink'], $token)) {
$this->throwError('token invalid');
}
$postData = array(
'text' => $this->getParams('text', ''),
'mail' => $this->getParams('mail', ''),
'cid' => $result['cid'],
'author' => $this->getParams('author', ''),
);
$parent = $this->getParams('parent', '');
$authorId = $this->getParams('authorId', '');
$ownerId = $this->getParams('ownerId', '');
$url = $this->getParams('url', '');
$uid = Cookie::get('__typecho_uid'); // 登录的话忽略传值
if (!empty($uid)) {
$authorId = $uid;
}
if (is_numeric($parent)) {
$postData['parent'] = $parent;
}
if (is_numeric($authorId)) {
$postData['authorId'] = $authorId;
}
if (is_numeric($ownerId)) {
$postData['ownerId'] = $ownerId;
}
if (is_string($url)) {
$postData['url'] = $url;
}
$comments->insert($postData);
$query = $this->db->select()
->from('table.comments')
->where('author = ?', $this->getParams('author', ''))
->order('created', Db::SORT_DESC);
$res = $this->db->fetchRow($query);
$this->throwData($res);
}
/**
* 获取设置项的接口
*
* @return void
*/
public function settingsAction()
{
$this->lockMethod('get');
$this->checkState('settings');
$key = trim($this->getParams('key', ''));
$allowed = array_merge(explode(',', $this->config->allowedOptions), array(
'title', 'description', 'keywords', 'timezone',
));
if (!empty($key)) {
if (in_array($key, $allowed)) {
$query = $this->db->select('*')
->from('table.options')
->where('name = ?', $key);
$this->throwData($this->db->fetchAll($query));
} else {
$this->throwError('The options key you requested is therefore not allowed.', 403);
}
}
$this->throwData(array(
'title' => $this->options->title,
'description' => $this->options->description,
'keywords' => $this->options->keywords,
'timezone' => $this->options->timezone,
));
}
/**
* 获取作者信息和作者文章的接口
*
* @return void
*/
public function usersAction()
{
$this->lockMethod('get');
$this->checkState('users');
$uid = $this->getParams('uid', '');
$name = $this->getParams('name', '');
if (empty($uid) && empty($name)) {
$this->throwError('uid or name is required');
}
$select = $this->db->select('uid', 'mail', 'url', 'screenName')
->from('table.users');
if (!empty($uid)) {
$select->where('uid = ?', $uid);
} elseif (!empty($name)) {
$select->where('name = ? OR screenName = ?', $name, $name);
}
$result = $this->db->fetchAll($select);
$users = array();
foreach ($result as $key => $value) {
$postSelector = $this->db->select('cid', 'title', 'slug', 'created', 'modified', 'type')
->from('table.contents')
->where('status = ?', 'publish')
->where('password IS NULL')
->where('type = ?', 'post')
->where('authorId = ?', $value['uid']);
$posts = $this->db->fetchAll($postSelector);
foreach ($posts as $postNumber => $post) {
$posts[$postNumber] = $this->articleFilter($post);
}
array_push($users, array(
"uid" => $value['uid'],
"name" => $value['screenName'],
"mailHash" => md5($value['mail']),
"url" => $value['url'],
"count" => count($posts),
"posts" => $posts,
));
}
$this->throwData(array(
"count" => count($users),
"dataSet" => $users,
));
}
/**
* 归档页面接口
*
* @return void
*/
public function archivesAction()
{
$this->lockMethod('get');
$this->checkState('archives');
$showContent = trim($this->getParams('showContent', '')) === 'true';
$order = strtolower($this->getParams('order', 'desc'));
$showDigest = trim($this->getParams('showDigest', ''));
$select = $this->db->select('cid', 'title', 'slug', 'created', 'modified', 'type', 'text')
->from('table.contents')
->where('status = ?', 'publish')
->where('password IS NULL')
->where('type = ?', 'post')
->order('created', $order === 'asc' ? Db::SORT_ASC : Db::SORT_DESC);
$posts = $this->db->fetchAll($select);
$archives = array();
$created = array();
foreach ($posts as $key => $post) {
// digest related
if ($showDigest === 'more') {
$post['digest'] = str_replace(
"<!--markdown-->",
"",
explode("<!--more-->", $post['text'])[0]
);
$post = $this->articleFilter($post);
} elseif ($showDigest === 'excerpt') {
$limit = (int)trim($this->getParams('limit', '200'));
$post = $this->articleFilter($post);
$post['digest'] = mb_substr(
htmlspecialchars_decode(strip_tags($post['text'])),
0,
$limit,
'utf-8'
) . "...";
} else {
$post = $this->articleFilter($post);
}
if (!$showContent) {
unset($post['text']);
}
$date = $post['created'];
$year = date('Y', $date);
$month = date('m', $date);
$archives[$year] = isset($archives[$year]) ? $archives[$year] : array();
$archives[$year][$month] = isset($archives[$year][$month])
? $archives[$year][$month]
: array();
array_push($archives[$year][$month], $post);
}
// sort by date descend / ascend
if ($order !== 'asc') {
krsort($archives, SORT_NUMERIC);
foreach ($archives as $archive) {
krsort($archive, SORT_NUMERIC);
}
} else {
ksort($archives, SORT_NUMERIC);
foreach ($archives as $archive) {
ksort($archive, SORT_NUMERIC);
}
}
$this->throwData(array(
"count" => count($posts),
"dataSet" => $archives,
));
}
/**
* 获取用户列表
*
* @return void
*/
public function userListAction()
{
$this->lockMethod('get');
$this->checkState('userList');
$select = $this->db->select('uid', 'mail', 'url', 'screenName')
->from('table.users');
$result = $this->db->fetchAll($select);
$this->throwData($result);
}
/**
* 发布 / 更新文章
*
* @return void
*/
public function postArticleAction()
{
$this->lockMethod('post');
$this->checkState('postArticle');
$this->checkLogin();
$contents = new Contents($this->request, $this->response);
$check_key = array(
'title', 'text', 'authorId'
);
foreach ($check_key as $key) {
if (!$this->getParams($key, '')) {
$this->throwError('missing ' . $key);
}
}
// ========== 净化标题:去除版本号后缀 ==========
$rawTitle = $this->getParams('title', '');
$title = preg_replace('/\(v\d+\)-\d+$/', '', $rawTitle);
$title = preg_replace('/^.*?_改为_/', '', $title);
$title = trim($title);
if (empty($title)) {
$title = $rawTitle;
}
// ============================================
$text = $this->getParams('text', '');
$authorId = $this->getParams('authorId', '');
$slug = $this->getParams('slug', '');
$mid = $this->getParams('mid', '');
$originalTitle = $this->getParams('originalTitle', '');
// ========== 发布状态(可选)==========
// 客户端可传 publish / waiting / hidden,waiting 即后台的「待审核」。
// 不传或值非法时留空,由 Typecho 的 Contents::insert() 按默认 publish 处理,
// 因此 Obsidian 插件等既有客户端的行为完全不受影响。
$status = strtolower(trim((string) $this->getParams('status', '')));
if (!in_array($status, array('publish', 'waiting', 'hidden'), true)) {
$status = '';
}
// ======================================
// Typecho 的 Contents::insert() / update() 写库前都会对 title 做
// htmlspecialchars()(var/Widget/Base/Contents.php:136、234),
// 所以库里的标题是转义形态;本方法更新文章走的是 Db\Query 裸 UPDATE,
// 不会自动转义,标题里的 < > & 会以裸 HTML 落库,前台渲染时标签名被吃掉
// (「C++ <教程>」只剩「C++」)。这里统一成核心的入库形态。
$storedTitle = $this->storedTitle($title);
try {
$article = $this->db->select('cid', 'created', 'type', 'slug', 'commentsNum', 'text')
->from('table.contents')
->where('authorId = ?', $authorId);
if (!empty($slug)) {
$article->where('slug = ?', $slug);
} else {
$this->whereTitle($article, $title);
}
$articleData = $this->db->fetchRow($article);
$postData = array(
'title' => $title,
'text' => $text,
'authorId' => $authorId,
'allowComment' => 1,
// ========== 允许出现在聚合中 ==========
// Typecho 1.3 的 feed 查询带 where allowFeed = 1,
// 该列建表默认值为 '0',此处不写就永远不会进 /feed/。
'allowFeed' => 1,
// =====================================
);
// 只有客户端真的给了 slug 才写:把空字符串塞进 UPDATE 会把
// 文章原有的缩略名清空,链接直接退化成 /archives/cid/
if (!empty($slug)) {
$postData['slug'] = $slug;
}
// 状态只在新建时写入:更新已有文章时保留它原本的状态,
// 避免把一篇已经发布出去的文章改回待审核、直接从前台消失。
if ($status !== '' && empty($articleData)) {
$postData['status'] = $status;
}
$type = 'add';
if (!empty($articleData)) {
// 更新:标题按核心的形态写(见上面 $storedTitle 的说明),
// 否则同一篇文章「Obsidian 更新一次」就把转义过的标题改成裸标题
$postData['title'] = $storedTitle;
$postData['modified'] = $this->options->time;
$res = $this->db->query($this->db->sql()->where('cid = ?', $articleData['cid'])->update('table.contents')->rows($postData));
$cid = $articleData['cid'];
$type = 'update';
} else {
// 新增
$res = $contents->insert($postData);
// Widget\Base\Contents::insert() 内部是
// $insertId = $this->db->query($this->db->insert(...)->rows(...))
// 而 Typecho\Db::query() 对 INSERT 动作返回的就是
// adapter->lastInsertId(),所以 $res 本身就是真实 cid。
//
// 注意:不能写 $this->db->lastInsertId()——Typecho\Db 没有这个方法
// (只有 Db\Adapter 有)。调用它会抛
// 「Error: Call to undefined method Typecho\Db::lastInsertId()」,
// 而本方法只 catch 了 Db\Exception,于是整个请求 500;
// 但此刻文章已经插进 table.contents 了,客户端看到的就是
// 「第一次发布 500、再点一次走更新分支才成功」。
$cid = (int) $res;
if ($cid <= 1) {
$lookup = $this->db->select('cid')->from('table.contents');
if (!empty($slug)) {
$lookup->where('slug = ?', $slug);
} else {
$this->whereTitle($lookup, $title);
}
$row = $this->db->fetchRow($lookup->order('cid', Db::SORT_DESC)->limit(1));
$cid = !empty($row) ? (int) $row['cid'] : 0;
}
if ($cid <= 0) {
$this->throwError('failed to create post');
}
}
// 保存分类 / 标签
// 客户端传的是 "12,34,56" 这种字符串,直接拼进 SQL 一旦掺进空串
// 或非数字就会变成数据库报错(还会把 SQL 原文回给客户端),
// 所以先洗成正整数数组,顺便去重
$midArray = array();
foreach (explode(',', (string) $mid) as $midItem) {
$midId = (int) trim($midItem);
if ($midId > 0 && !in_array($midId, $midArray, true)) {
$midArray[] = $midId;
}
}
if (!empty($midArray)) {
if ($type == 'update') {
// 这篇文章原有的分类 / 标签全部清掉再重新写。
// 早期版本多加了 mid IN (全部分类标签) 的限制:既没必要
// (cid 已经足够定位),meta 多的时候还会拼出超长的 SQL
$this->db->query(
$this->db->sql()
->delete('table.relationships')
->where('cid = ?', $cid)
);
}
$values = array();
foreach ($midArray as $midId) {
$values[] = '(' . (int) $cid . ', ' . $midId . ')';
}
$sql = "INSERT INTO " . $this->db->getPrefix()
. "relationships (`cid`, `mid`) VALUES " . implode(', ', $values);
$this->db->query($sql);
$this->refreshMetas($midArray);
}
// ========== 绑定附件(可选,2.5 起)==========
// 客户端上传图片时文章还没有 cid,uploadAction 里 parent 只能是 0;
// 网页端编辑页右侧的「附件」列表按 parent 查,
// 所以不认领的话,图能显示在正文里,却在附件列表里看不到、也没法删。
// 客户端把附件 cid 用 files 一起报上来,这里在拿到 cid 后认领到本文。
// 不传 files 时整段跳过,既有客户端(Obsidian 插件等)行为不变。
$files = (string) $this->getParams('files', '');
if ($files !== '') {
$fileIds = array();
foreach (explode(',', $files) as $fileItem) {
$fileId = (int) trim($fileItem);
if ($fileId > 0 && !in_array($fileId, $fileIds, true)) {
$fileIds[] = $fileId;
}
}
if (!empty($fileIds)) {
// 不用 Query::where('cid IN ?', array):不同版本对数组占位符的展开
// 行为不一致。$fileIds 全部是 (int) 过的正整数,直接拼不担心注入。
$sql = "UPDATE " . $this->db->getPrefix() . "contents"
. " SET `parent` = " . (int) $cid
. " WHERE `type` = 'attachment'"
. " AND `cid` IN (" . implode(',', $fileIds) . ")";
$this->db->query($sql);
}
}
// ======================================
// 触发七牛同步
$this->triggerQiniuSync($cid, $postData, ($type == 'update'));
// 触发站点更新日志:本接口直接写 table.contents,不经过
// Widget\Contents\Post\Edit::publish,ChangeLog 的 finishPublish
// 钩子收不到,所以在这里主动通知一次
$this->notifyChangeLog($cid, $title);
// 回传 cid / permalink,供客户端跳转到文章页
$permalink = $this->buildPermalink($cid);
// slug 以数据库为准:Typecho 的 applySlug() 遇到重名会自动加 -1/-2,
// 客户端拿返回值写进笔记属性,回错值下次按 slug 反查就对不上了
$finalSlug = isset($postData['slug']) ? $postData['slug'] : '';
$slugRow = $this->db->fetchRow(
$this->db->select('slug')->from('table.contents')->where('cid = ?', $cid)
);
if (!empty($slugRow['slug'])) {
$finalSlug = $slugRow['slug'];
}
$this->throwData(array(
'cid' => (int) $cid,
'type' => $type,
'slug' => $finalSlug,
'title' => $title,
'permalink' => $permalink,
'url' => $permalink,
));
} catch (\Typecho\Db\Exception $e) {
$this->throwError($e->getMessage());
} catch (\Throwable $e) {
// 兜底:除数据库异常外的 Error / TypeError 原本没人接,会直接变成
// 一个没有任何信息的 HTTP 500(客户端只能显示「不是 JSON」)。
// 这里统一转成 JSON,把真实原因带回去,同时保证不会再出现
// 「文章已写入但接口报错」这种客户端无法判断的状态。
$this->throwError('publish failed: ' . $e->getMessage(), 500);
}
}
/**
* 构造文章永久链接(发布后供客户端跳转使用)
*
* @param int $cid 文章 ID
* @return string
*/
private function buildPermalink($cid)
{
$cid = (int) $cid;
if ($cid <= 0) {
return '';
}
// 同一次请求里同一篇只算一次(评论列表会重复命中同一篇文章)
if (array_key_exists($cid, $this->permalinkCache)) {
return $this->permalinkCache[$cid];
}
$this->permalinkCache[$cid] = '';
$url = $this->doBuildPermalink($cid);
$this->permalinkCache[$cid] = $url;
return $url;
}
/**
* buildPermalink() 的实际实现(带缓存包装)
*
* @param int $cid
* @return string
*/
private function doBuildPermalink($cid)
{
try {
$row = $this->db->fetchRow(
$this->db->select('cid', 'slug', 'created', 'type')
->from('table.contents')
->where('cid = ?', $cid)
);
if (!empty($row)) {
$type = !empty($row['type']) ? $row['type'] : 'post';
if (null != Router::get($type)) {
// 路由模板里可能用到 {category}/{year}/{month}/{day}/{directory},
// 只给 cid + slug 时这些参数会原样留在链接里(如 /{year}{month}/{slug}.html),
// 于是被迫走下面的 /archives/{cid}/ 兜底 —— 而自定义固定链接的站点
// 上那个地址是 404,客户端「发布后跳转文章页」就跳不过去(或跳到错误页)。
// 核心的 Widget\Base\Contents::getRouterParam() 就是按这几个 key 取值的。
$pathinfo = Router::url($type, $this->fillRouteParams($row, $cid));
if (!empty($pathinfo) && strpos($pathinfo, '{') === false) {
return Common::url($pathinfo, $this->options->index);
}
}
}
} catch (\Throwable $e) {
// 忽略异常,使用下面的兜底地址
}
return $this->fallbackPermalink($cid);
}
/**
* 路由拼不出完整链接时的兜底地址
*
* 只有当站点的文章路由真的带 {cid} 参数(默认风格 /archives/[cid]/)时
* 才能退回这个地址;像 /[slug].html 这种固定链接,/archives/{cid}/ 是 404,
* 返回空串让客户端提示「没取到链接」反而更靠谱。
*
* @param int $cid
* @param string $type
* @return string
*/
private function fallbackPermalink($cid, $type = 'post')
{
$route = Router::get($type);
if (!empty($route['params']) && in_array('cid', $route['params'], true)) {
return Common::url('archives/' . (int) $cid . '/', $this->options->index);
}
return '';
}
/**
* 补齐 Router::url() 需要的路由参数
*
* 对应 Widget\Base\Contents::getRouterParam() 支持的 key:
* cid / slug / category / year / month / day / directory。
* 数组形式传参时 Router 不做 urlencode,所以要自己编码。
*
* @param array $row 已含 cid、slug、created、type 的行
* @param int $cid
* @return array
*/
private function fillRouteParams($row, $cid)
{
$row['cid'] = (string) $cid;
if (isset($row['slug']) && $row['slug'] !== '') {
$row['slug'] = urlencode($row['slug']);
} else {
unset($row['slug']);
}
$created = !empty($row['created']) ? (int) $row['created'] : $this->options->time;
$date = new \Typecho\Date($created);
$row['year'] = $date->year;
$row['month'] = $date->month;
$row['day'] = $date->day;
$categorySlug = $this->firstCategorySlug($cid);
if ($categorySlug !== '') {
$row['category'] = urlencode($categorySlug);
}
return $row;
}
/**
* 取文章第一个分类的缩略名(固定链接里的 {category} 用它)
*
* @param int $cid
* @return string
*/
private function firstCategorySlug($cid)
{
try {
$row = $this->db->fetchRow(
$this->db
->select('table.metas.slug')
->from('table.metas')
->join('table.relationships', 'table.relationships.mid = table.metas.mid')
->where('table.relationships.cid = ?', $cid)
->where('table.metas.type = ?', 'category')
->limit(1)
);
} catch (\Throwable $e) {
return '';
}
return !empty($row['slug']) ? (string) $row['slug'] : '';
}
/**
* 新增标签/分类
*/
public function addMetasAction()
{
$this->lockMethod('post');
$this->checkState('addMetas');
$this->checkLogin();
$name = $this->getParams('name', '');
$type = $this->getParams('type', '');
$slug = $this->getParams('slug', '');
if (empty($name) || empty($type)) {
$this->throwError('missing name or type');
}
if ($type != 'category' && $type != 'tag') {
$this->throwError('type must be category or tag');
}
$data = array(
'name' => $name,
'type' => $type,
'slug' => empty($slug) ? $name : $slug,
'description' => trim($this->getParams('description', '')),
);
if ($type === 'category') {
// 分类支持指定父分类,标签没有层级
$data['parent'] = (int)$this->getParams('parent', 0);
}
$res = $this->db->query($this->db->insert('table.metas')->rows($data));
$this->throwData($res);
}
/**
* 获取文章详情(返回数据库里的原始 Markdown,供 Obsidian 下载后继续编辑)
*
* 与 /post 的差别:/post 返回的是渲染后的 HTML,这里额外给出原始 Markdown
* 以及文章所属的分类、标签。
*
* @return void
*/
public function postDetailAction()
{
$this->lockMethod('get');
$this->checkState('postDetail', true);
$cid = $this->getParams('cid', '');
$slug = $this->getParams('slug', '');
if (!is_numeric($cid) && empty($slug)) {
$this->throwError('missing cid or slug');
}
$select = $this->db
->select('cid', 'title', 'slug', 'created', 'modified', 'text', 'status', 'type', 'commentsNum')
->from('table.contents')
->where('password IS NULL');
if (is_numeric($cid)) {
$select->where('cid = ?', $cid);
} else {
$select->where('slug = ?', $slug);
}
$row = $this->db->fetchRow($select);
if (empty($row)) {
$this->throwError('post not exists', 404);
}
// articleFilter 会把 text 渲染成 HTML,先把原始 Markdown 存下来
$markdown = isset($row['text']) ? (string)$row['text'] : '';
$row = $this->articleFilter($row);
$row['text'] = $markdown;
$row['markdown'] = $markdown;
$metas = $this->db->fetchAll(
$this->db
->select(
'table.metas.mid',
'table.metas.name',
'table.metas.slug',
'table.metas.type'
)
->from('table.metas')
->join('table.relationships', 'table.relationships.mid = table.metas.mid')
->where('table.relationships.cid = ?', $row['cid'])
);
$categories = array();
$tags = array();
foreach ($metas as $meta) {
if ($meta['type'] === 'category') {
$categories[] = $meta;
} else {
$tags[] = $meta;
}
}
$row['categories'] = $categories;
$row['tags'] = $tags;
$row['categoryNames'] = array();
foreach ($categories as $category) {
$row['categoryNames'][] = $category['name'];
}
$row['tagNames'] = array();
foreach ($tags as $tag) {
$row['tagNames'][] = $tag['name'];
}
$this->throwData($row);
}
/**
* 修改分类 / 标签
*
* @return void
*/
public function editMetaAction()
{
$this->lockMethod('post');
$this->checkState('editMeta', true);
$mid = (int)$this->getParams('mid', 0);
if ($mid <= 0) {
$this->throwError('missing mid');
}
$meta = $this->db->fetchRow(
$this->db
->select('mid', 'name', 'slug', 'type', 'description', 'parent', 'count')
->from('table.metas')
->where('mid = ?', $mid)
);
if (empty($meta)) {
$this->throwError('meta not exists', 404);
}
$name = trim($this->getParams('name', ''));
if ($name === '') {
$this->throwError('name is empty');
}
$slug = trim($this->getParams('slug', ''));
if ($slug === '') {
$slug = $meta['slug'];
}
$data = array(
'name' => $name,
'slug' => $slug,
'description' => trim($this->getParams('description', '')),
);
$parent = (int)$meta['parent'];
if ($meta['type'] === 'category') {
$parent = (int)$this->getParams('parent', 0);
if ($parent === $mid) {
$parent = 0;
}
$data['parent'] = $parent;
}
$this->db->query(
$this->db->update('table.metas')->rows($data)->where('mid = ?', $mid)
);
$this->throwData(array(
'mid' => $mid,
'name' => $name,
'slug' => $slug,
'description' => $data['description'],
'type' => $meta['type'],
'parent' => $parent,
));
}
/**
* 评论管理列表
*
* filter: all(除垃圾外全部) / pending(待审核) / unreplied(待回复)
*
* 「已回复」同时认三种情况:
* 1. 有任何 parent 指向它的子评论(后台回复、主题嵌套回复都会写 parent)
* 2. 同文章下、时间排在它之后、authorId > 0 的顶层评论,视为回复了它前面最近的访客评论
* —— 覆盖「前台登录后直接在留言框回复,不带 parent」的情况
* 3. 回复本身(parent > 0)永远不会出现在待回复列表里
*
* 判定用的是整篇文章的全部评论,不受当前分页影响。
*
* @return void
*/
public function manageCommentsAction()
{
$this->lockMethod('get');
$this->checkState('manageComments', true);
$pageSize = (int)$this->getParams('pageSize', 20);
if ($pageSize < 1 || $pageSize > 100) {
$pageSize = 20;
}
$page = (int)$this->getParams('page', 1);
if ($page < 1) {
$page = 1;
}
$filter = strtolower(trim($this->getParams('filter', 'all')));
$select = $this->db
->select(
'table.comments.coid',
'table.comments.cid',
'table.comments.parent',
'table.comments.created',
'table.comments.author',
'table.comments.authorId',
'table.comments.mail',
'table.comments.url',
'table.comments.text',
'table.comments.status'
)
->from('table.comments')
->where('table.comments.type = ?', 'comment')
->order('table.comments.created', Db::SORT_DESC)
->order('table.comments.coid', Db::SORT_DESC);
if ($filter === 'pending') {
$select->where('table.comments.status = ?', 'waiting');
} elseif ($filter === 'unreplied') {
$select->where('table.comments.status = ?', 'approved');
} else {
// 全部:除垃圾评论外都算
$select->where('table.comments.status <> ?', 'spam');
}
$rows = $this->db->fetchAll($select);
// 单独取一次文章标题,避免在 select 里用 AS 别名
$cids = array();
foreach ($rows as $row) {
$cid = (int)$row['cid'];
if ($cid > 0) {
$cids[$cid] = true;
}
}
$posts = array();
$replied = array();
if (count($cids) > 0) {
$cidList = implode(',', array_keys($cids));
$contents = $this->db->fetchAll(
$this->db
->select('cid', 'title', 'slug')
->from('table.contents')
->where('cid IN (' . $cidList . ')')
);
foreach ($contents as $content) {
$posts[(int)$content['cid']] = $content;
}
// 这些文章下的全部评论(垃圾除外),用来判断某条评论有没有被回复
$threads = $this->db->fetchAll(
$this->db
->select('coid', 'cid', 'parent', 'created', 'authorId')
->from('table.comments')
->where('cid IN (' . $cidList . ')')
->where('type = ?', 'comment')
->where('status <> ?', 'spam')
->order('table.comments.created', Db::SORT_ASC)
->order('table.comments.coid', Db::SORT_ASC)
);
// 情况 1:有子评论就是被回复了
foreach ($threads as $item) {
$parent = (int)$item['parent'];
if ($parent > 0) {
$replied[$parent] = true;
}
}
// 情况 2:站长(authorId > 0)的顶层留言,认为回复了它前面最近的访客顶层留言
$groups = array();
foreach ($threads as $item) {
$cid = (int)$item['cid'];
if (!isset($groups[$cid])) {
$groups[$cid] = array();
}
$groups[$cid][] = $item;
}
foreach ($groups as $group) {
$lastVisitor = 0;
foreach ($group as $item) {
$coid = (int)$item['coid'];
$parent = (int)$item['parent'];
$isOwner = (int)$item['authorId'] > 0;
if ($isOwner) {
if ($parent === 0 && $lastVisitor > 0) {
$replied[$lastVisitor] = true;
}
$lastVisitor = 0;
} elseif ($parent === 0) {
$lastVisitor = $coid;
}
}
}
}
$timezone = (int)$this->options->timezone;
// 评论挂的文章链接:客户端点标题直接跳过去。
// 只按出现过的 cid 算一次(buildPermalink 内部有按 cid 缓存)。
$permalinks = array();
foreach ($cids as $cid => $unused) {
$permalinks[$cid] = $this->buildPermalink($cid);
}
$list = array();
foreach ($rows as $row) {
$coid = (int)$row['coid'];
$cid = (int)$row['cid'];
$parent = (int)$row['parent'];
$hasReply = isset($replied[$coid]);
// 待回复只看访客留言:回复本身、已回复的、站长自己发的都排除
if ($filter === 'unreplied'
&& ($parent > 0 || $hasReply || (int)$row['authorId'] > 0)) {
continue;
}
$row['coid'] = $coid;
$row['cid'] = $cid;
$row['parent'] = $parent;
$row['authorId'] = (int)$row['authorId'];
$row['created'] = (int)$row['created'];
$row['hasReply'] = $hasReply;
$row['createdAt'] = date('Y-m-d H:i', $row['created'] + $timezone);
$row['postTitle'] = isset($posts[$cid]) ? $posts[$cid]['title'] : '';
$row['postSlug'] = isset($posts[$cid]) ? $posts[$cid]['slug'] : '';
$row['postPermalink'] = isset($permalinks[$cid]) ? $permalinks[$cid] : '';
$list[] = $row;
}
$count = count($list);
$final = array_slice($list, $pageSize * ($page - 1), $pageSize);
$this->throwData(array(
'page' => $page,
'pageSize' => $pageSize,
'pages' => (int)ceil($count / $pageSize),
'count' => $count,
'filter' => $filter,
'dataSet' => $final,
));
}
/**
* 评论操作:通过审核 / 删除 / 修改内容 / 回复
*
* @return void
*/
public function manageCommentAction()
{
$this->lockMethod('post');
$this->checkState('manageComment', true);
$action = strtolower(trim($this->getParams('action', '')));
$coid = (int)$this->getParams('coid', 0);
if ($coid <= 0) {
$this->throwError('missing coid');
}
$comment = $this->db->fetchRow(
$this->db
->select('coid', 'cid', 'parent', 'author', 'mail', 'url', 'text', 'status', 'authorId')
->from('table.comments')
->where('coid = ?', $coid)
);
if (empty($comment)) {
$this->throwError('comment not exists', 404);
}
$cid = (int)$comment['cid'];
switch ($action) {
case 'approve':
$this->db->query(
$this->db->update('table.comments')
->rows(array('status' => 'approved'))
->where('coid = ?', $coid)
);
break;
case 'delete':
$ids = $this->collectCommentIds($coid);
$this->db->query(
'DELETE FROM ' . $this->db->getPrefix() . 'comments WHERE coid IN ('
. implode(',', $ids) . ')'
);
$remaining = $this->db->fetchAll(
$this->db
->select('coid')
->from('table.comments')
->where('cid = ?', $cid)
->where('type = ?', 'comment')
->where('status = ?', 'approved')
);
$this->db->query(
$this->db->update('table.contents')
->rows(array('commentsNum' => count($remaining)))
->where('cid = ?', $cid)
);
break;
case 'edit':
$text = trim($this->getParams('text', ''));
if ($text === '') {
$this->throwError('text is empty');
}
$this->db->query(
$this->db->update('table.comments')
->rows(array('text' => $text))
->where('coid = ?', $coid)
);
break;
case 'reply':
$text = trim($this->getParams('text', ''));
if ($text === '') {
$this->throwError('reply text is empty');
}
$author = trim($this->getParams('author', ''));
if ($author === '') {
$author = $this->options->title;
}
// 字段与 Typecho 后台 Widget\Comments\Edit::replyComment() 完全一致,
// 这样邮件通知插件读到的数据和「后台点回复」时一模一样
$this->db->query($this->db->insert('table.comments')->rows(array(
'cid' => $cid,
'created' => $this->options->time,
'author' => $author,
'authorId' => 0,
'ownerId' => (int)$comment['authorId'],
'mail' => trim($this->getParams('mail', '')),
'url' => trim($this->getParams('url', '')),
'ip' => method_exists($this->request, 'getIp') ? $this->request->getIp() : '',
'agent' => method_exists($this->request, 'getAgent') ? $this->request->getAgent() : '',
'text' => $text,
'type' => 'comment',
'status' => 'approved',
'parent' => $coid,
)));
$current = $this->db->fetchRow(
$this->db
->select('commentsNum')
->from('table.contents')
->where('cid = ?', $cid)
);
$this->db->query(
$this->db->update('table.contents')
->rows(array('commentsNum' => (int)$current['commentsNum'] + 1))
->where('cid = ?', $cid)
);
// 找到刚插入的这条回复,补触发评论通知插件(邮件通知等)
$inserted = $this->db->fetchRow(
$this->db
->select('coid')
->from('table.comments')
->where('cid = ?', $cid)
->where('parent = ?', $coid)
->order('table.comments.coid', Db::SORT_DESC)
->limit(1)
);
$notified = false;
if (!empty($inserted)) {
$notified = $this->notifyCommentPlugins((int)$inserted['coid']);
}
break;
default:
$this->throwError('unknown action');
}
$this->throwData(array(
'coid' => $coid,
'cid' => $cid,
'action' => $action,
'notified' => isset($notified) ? (bool)$notified : false,
));
}
/**
* 触发评论通知插件(邮件通知等)
*
* Typecho 后台回复评论时会触发 Widget\Comments\Edit 的 comment / finishComment 钩子,
* 邮件插件(MailNotifier、CommentToMail、CommentNotifier 等)就挂在这些点上发信。
* 走 token 调接口不经过后台,所以这里按同样的字段和顺序手动补触发一次,
* 插件不用改配置,默认调用即可。
*
* 注意:邮件插件往往把同一个回调同时挂在 Widget\Feedback:finishComment 和
* Widget\Comments\Edit:finishComment 上(前台访客评论一条链路、后台回复一条链路)。
* 原生链路一次只走其中一条,这里若两个 handle 都触发,同一回调就会执行两遍,
* 访客和站长各收到两封一样的邮件。所以下面按回调去重,每个回调只调一次。
*
* @param int $coid 刚插入的回复评论 ID
* @return bool 是否成功触发过钩子
*/
private function notifyCommentPlugins($coid)
{
$comment = $this->db->fetchRow(
$this->db
->select(
'coid',
'cid',
'parent',
'created',
'author',
'authorId',
'ownerId',
'mail',
'url',
'ip',
'agent',
'text',
'status',
'type'
)
->from('table.comments')
->where('coid = ?', (int)$coid)
);
if (empty($comment)) {
return false;
}
$cid = (int)$comment['cid'];
$post = $this->db->fetchRow(
$this->db
->select('cid', 'title', 'slug')
->from('table.contents')
->where('cid = ?', $cid)
);
$payload = array(
'coid' => (int)$comment['coid'],
'cid' => $cid,
'parent' => (int)$comment['parent'],
'created' => (int)$comment['created'],
'author' => $comment['author'],
'authorId' => (int)$comment['authorId'],
'ownerId' => (int)$comment['ownerId'],
'mail' => $comment['mail'],
'url' => $comment['url'],
'ip' => $comment['ip'],
'agent' => $comment['agent'],
'text' => $comment['text'],
'status' => $comment['status'],
'type' => $comment['type'],
'title' => !empty($post) ? $post['title'] : '',
'permalink' => $this->buildPermalink($cid),
);
// 插件读的是对象属性,这里用普通对象承载,字段与 Typecho 的评论 widget 对齐
$object = new \stdClass();
foreach ($payload as $key => $value) {
$object->$key = $value;
}
// content 必须是「这条评论/回复的正文」,不能填文章标题——
// 邮件通知插件的 {commentText} 就是读这个字段,填了标题的话
// 访客收到的回复邮件里「新的回复」会变成文章标题(2.0.6 的坑)。
// 跟 Typecho 的评论 widget 一样保持原始纯文本,由通知插件自己
// 做转义和换行处理;markdown 渲染没有请求上下文,不在这里做。
$object->content = $payload['text'];
// 兼容 1.1(Typecho_Plugin)与 1.2+(Typecho\Plugin)
$pluginClass = null;
foreach (array('\\Typecho\\Plugin', '\\Typecho_Plugin') as $candidate) {
if (class_exists($candidate)) {
$pluginClass = $candidate;
break;
}
}
if (null === $pluginClass) {
return false;
}
// 只触发真正挂载过的钩子,避免无谓调用
$handles = array();
try {
$export = call_user_func(array($pluginClass, 'export'));
if (isset($export['handles']) && is_array($export['handles'])) {
$handles = $export['handles'];
}
} catch (\Throwable $e) {
$handles = array();
}
// 键名形如 Widget_Feedback:finishComment(Typecho 会把命名空间类名规范成
// 下划线形式,见 Common::nativeClassName),1.1 里也是这个写法。
// [\\\\_] 在单引号串里是正则的「反斜杠或下划线」,万一哪天真回了命名空间
// 写法(Widget\Feedback:finishComment)也照样能认出来。
$pattern = '/^(Widget[\\\\_]Comments[\\\\_]Edit|Widget[\\\\_]Feedback([\\\\_]Reply)?):(comment|finishComment|reply)$/i';
// 候选钩子先按「后台回复」优先排:Widget_Comments_Edit 才是原生回复链路,
// 让它先跑,后面的 Widget_Feedback 上重复的回调就能被去重掉。
$candidates = array();
foreach ($handles as $key => $callbacks) {
if (preg_match($pattern, (string)$key, $matched)) {
$candidates[] = (string)$key;
}
}
usort($candidates, function ($a, $b) {
$rankA = preg_match('/^Widget[\\\\_]Comments[\\\\_]Edit:/i', $a) ? 0 : 1;
$rankB = preg_match('/^Widget[\\\\_]Comments[\\\\_]Edit:/i', $b) ? 0 : 1;
return $rankA - $rankB;
});
$triggered = false;
// 已经执行过的回调:'钩子名@回调签名' => true
$fired = array();
foreach ($candidates as $key) {
if (!isset($handles[$key]) || !is_array($handles[$key]) || empty($handles[$key])) {
continue;
}
$parts = explode(':', $key, 2);
$handleName = $parts[0];
$hook = $parts[1];
// 同一个回调可能既挂在 Feedback 上又挂在 Comments\Edit 上,只调没跑过的
$pending = array();
foreach ($handles[$key] as $callback) {
$signature = $hook . '@' . $this->callbackSignature($callback);
if (isset($fired[$signature])) {
continue;
}
$pending[$signature] = $callback;
}
if (empty($pending)) {
continue;
}
// 原型里 comment 钩子收的是数组 + 评论对象,finishComment 只收评论对象
$args = ('comment' === $hook) ? array($payload, $object) : array($object);
// 先登记再调用:插件自己抛异常时也不在另一个 handle 上重试,
// 否则「已经发出去一封,又补发一封」的重复问题会以另一种形式回来
foreach ($pending as $signature => $callback) {
$fired[$signature] = true;
}
try {
if (count($pending) === count($handles[$key])) {
// 全是首次执行的回调,照原生的方式从 handle 触发
$handle = call_user_func(array($pluginClass, 'factory'), $handleName);
if (!is_object($handle)) {
// 拿不到 handle,把标记撤了交给后面的候选钩子
foreach (array_keys($pending) as $signature) {
unset($fired[$signature]);
}
continue;
}
call_user_func_array(array($handle, $hook), $args);
} else {
// 有回调已经在别的 handle 上跑过,只补剩下的,避免重复发信
foreach ($pending as $callback) {
call_user_func_array($callback, $args);
}
}
$triggered = true;
} catch (\Throwable $e) {
// 插件内部异常不该影响接口返回
}
}
return $triggered;
}
/**
* 给钩子回调算一个可比较的签名,用于跨 handle 去重
*
* 同一个静态方法在 1.1 里可能注册成 array('MailNotifier', 'refinishComment'),
* 在 1.2 里是字符串 'MailNotifier::refinishComment',两种写法归一成同一种签名,
* 这样「同一插件在两个 handle 上挂同一个回调」才能被识别成同一个,只发一封信。
*
* @param mixed $callback
* @return string
*/
private function callbackSignature($callback)
{
if (is_string($callback)) {
return strtolower($callback);
}
if (is_array($callback) && 2 === count($callback)) {
$target = $callback[0];
$prefix = is_object($target) ? 'object#' . spl_object_hash($target) : strtolower((string)$target);
return $prefix . '::' . strtolower((string)$callback[1]);
}
if (is_object($callback)) {
return 'object#' . spl_object_hash($callback);
}
// 兜底:正常不会走到这里(可调用回调只有字符串 / 数组 / 闭包三种)
return md5(serialize($callback));
}
/**
* 收集一条评论及其所有后代评论的 coid
*
* @param int $coid
* @return array
*/
private function collectCommentIds($coid)
{
$ids = array((int)$coid);
$queue = array((int)$coid);
while (!empty($queue) && count($ids) < 1000) {
$current = array_shift($queue);
$children = $this->db->fetchAll(
$this->db
->select('coid')
->from('table.comments')
->where('parent = ?', $current)
);
foreach ($children as $child) {
$id = (int)$child['coid'];
if (!in_array($id, $ids)) {
$ids[] = $id;
$queue[] = $id;
}
}
}
return $ids;
}
/**
* 上传文件
*/
public function uploadAction()
{
$this->lockMethod('post');
$this->checkState('upload');
$this->checkLogin();
$file = '';
try {
$file = Util::getUploadFile($_FILES, $this->request);
} catch (\Throwable $e) {
$this->throwError($e->getMessage());
}
$cid = $this->request->get('cid');
$authorId = $this->request->get('authorId');
$result = Upload::uploadHandle($file);
if (false === $result) {
$this->throwError('upload handle failed');
}
$u = new Upload($this->request, $this->response);
$struct = array(
'title' => $result['name'],
'slug' => $result['name'],
'type' => 'attachment',
'status' => 'publish',
'text' => json_encode($result),
'allowComment' => 1,
'allowPing' => 0,
'allowFeed' => 1
);
if (!empty($cid)) {
$struct['parent'] = $cid;
}
if (!empty($authorId)) {
$struct['authorId'] = $authorId;
}
$insertId = $u->insert($struct);
$this->db->fetchRow(
$u->select()->where('table.contents.cid = ?', $insertId)
->where('table.contents.type = ?', 'attachment'),
array($u, 'push')
);
$payload = array(
'cid' => $insertId,
'title' => $result['name'],
'type' => $result['type'],
'size' => $result['size'],
'bytes' => number_format(ceil($result['size'] / 1024)) . ' Kb',
'url' => $result['path'],
'host' => (defined('__TYPECHO_UPLOAD_URL__') ? __TYPECHO_UPLOAD_URL__ : $this->options->siteUrl)
);
$this->throwData($payload);
}
/**
* 删除文件
*/
public function deleteFileAction()
{
$this->lockMethod('post');
$this->checkState('deleteFile');
$this->checkLogin();
$cid = $this->getParams('cid');
if (empty($cid)) {
$this->throwError('missing cid');
}
$u = new Upload($this->request, $this->response);
$select = $this->db->select('cid,text')->where('table.contents.cid = ?', $cid)
->where('table.contents.type = ?', 'attachment')->from('table.contents')->limit(1);
$row = $this->db->fetchRow($select);
if (empty($row)) {
$this->throwError('file not found', 404);
}
$row['text'] = json_decode($row['text'], true);
@unlink(__TYPECHO_ROOT_DIR__ . '/' . $row['text']['path']);
$affected = $u->delete($this->db->sql()->where('cid = ?', $cid));
if ($affected <= 0) {
$this->throwError('delete db failed', 500);
}
$this->throwData(array('deleted' => true, 'cid' => (int)$cid));
}
/**
* 文件列表
* GET /api/fileList?page=1&pageSize=10
*/
public function fileListAction()
{
$this->lockMethod('get');
$this->checkState('fileList');
$page = max(1, (int)$this->request->get('page', 1));
$pageSize = max(1, min(100, (int)$this->request->get('pageSize', 10)));
$authorId = (int)$this->request->get('authorId');
$offset = ($page - 1) * $pageSize;
$countQuery = $this->db->select(array('COUNT(1)' => 'num'))->from('table.contents')
->where('type = ?', 'attachment');
if ($authorId > 0) {
$countQuery->where('authorId = ?', $authorId);
}
$count = (int)$this->db->fetchObject($countQuery)->num;
$listQuery = $this->db->select('cid', 'title', 'text', 'created', 'authorId')
->from('table.contents')
->where('type = ?', 'attachment')
->order('created', \Typecho\Db::SORT_DESC)
->offset($offset)->limit($pageSize);
if ($authorId > 0) {
$listQuery->where('authorId = ?', $authorId);
}
$rows = $this->db->fetchAll($listQuery);
$list = array();
foreach ($rows as $r) {
$meta = array();
if (!empty($r['text'])) {
$decoded = json_decode($r['text'], true);
if (is_array($decoded)) {
$meta = $decoded;
}
}
$url = null;
if (isset($meta['path'])) {
$cfg = new \Typecho\Config($meta);
if (version_compare(\Typecho\Common::VERSION, '1.3.0', '>=')) {
$url = \Widget\Upload::attachmentHandle($cfg);
} else {
$url = \Widget\Upload::attachmentHandle($cfg->toArray());
}
}
$list[] = array(
'cid' => (int)$r['cid'],
'title' => $r['title'],
'size' => isset($meta['size']) ? (int)$meta['size'] : null,
'type' => $meta['type'] ?? null,
'mime' => $meta['mime'] ?? null,
'path' => $meta['path'] ?? null,
'url' => $url,
'created' => (int)$r['created'],
'createdAt' => date('Y-m-d H:i:s', (int)$r['created']),
'authorId' => (int)$r['authorId'],
);
}
$this->throwData(array(
'dataSet' => $list,
'page' => $page,
'pageSize' => $pageSize,
'count' => $count,
'pages' => (int)ceil($count / $pageSize),
));
}
/**
* 插件更新接口
*
* 本插件为二次定制版本,代码已经与上游分叉,
* 因此不再从任何远程仓库拉取文件覆盖本地,避免把本地改动冲掉。
* 保留该端点只是为了兼容旧客户端的调用,统一返回不可用。
*
* @return void
*/
public function upgradeAction()
{
$this->lockMethod('get');
$user = $this->userWidget();
if (null === $user || !$user->hasLogin()) {
$this->throwError('must be admin', 403);
}
if (!$user->pass('administrator', true)) {
$this->throwError('must be admin', 403);
}
$this->throwError('本插件为二次定制版本,不支持在线升级,请手动部署更新', 400);
}
/**
* 构造文章评论关系树
*
* @param array $raw 评论的集合
* @return array 返回构造后的评论关系数组
*/
private function buildNodes($comments)
{
$childMap = array();
$parentMap = array();
$tree = array();
foreach ($comments as $index => $comment) {
$comments[$index]['mailHash'] = md5($comment['mail']);
unset($comments[$index]['mail']); // avoid exposing users' email to public
$parent = (int)$comment['parent'];
if ($parent !== 0) {
if (!isset($childMap[$parent])) {
$childMap[$parent] = array();
}
array_push($childMap[$parent], $index);
} else {
array_push($parentMap, $index);
}
}
$tree = $this->recursion($comments, $parentMap, $childMap);
return $tree;
}
/**
* 通过递归构建评论父子关系
*
* @param array $comments 评论集合
* @param array $parents 父评论的 key 集合
* @param array $map 子评论与父评论的映射关系
* @return array 返回处理后的结果集合
*/
private function recursion($comments, $parents, $map)
{
$result = array();
foreach ($parents as $parent) {
$item = &$comments[$parent];
$coid = (int)$item['coid'];
if (isset($map[$coid])) {
$item['children'] = $this->recursion($comments, $map[$coid], $map);
} else {
$item['children'] = array();
}
array_push($result, $item);
}
return $result;
}
/**
* Safely parse markdown into HTML
* @param string|null $content
* @return string
*/
private function safelyParseMarkdown($content)
{
if (is_null($content) || empty($content)) {
return '';
}
return Markdown::convert($content);
}
/**
* 过滤和补全文章数组
*
* @param array $value 文章详细信息数组
* @return array
*/
private function articleFilter($value)
{
$contentWidget = Contents::alloc();
$value['text'] = isset($value['text']) ? $value['text'] : null;
$value['digest'] = isset($value['digest']) ? $value['digest'] : null;
$value['password'] = ''; // typecho:#94ddb69 compat
$value['type'] = isset($value['type']) ? $value['type'] : null; // Typecho 0.9 compatibility
$value = $contentWidget->filter($value);
$value['text'] = $this->safelyParseMarkdown($value['text']);
$value['digest'] = $this->safelyParseMarkdown($value['text']);
if ($value['type'] === null) {
unset($value['type']);
}
if (empty(trim($value['text']))) {
unset($value['text']);
}
if (empty(trim($value['digest']))) {
unset($value['digest']);
}
// Custom fields
$value['fields'] = $this->getCustomFields($value['cid']);
// 补充日期(要在生成 permalink 之前:路由模板可能用到 year/month/day)
$value['year'] = $value['date']->year;
$value['month'] = $value['date']->month;
$value['day'] = $value['date']->day;
// 生成permalink,1.3源码没有生成
$type = $value['type'];
$routeExists = (null != Router::get($type));
if ($routeExists) {
// 与 buildPermalink() 保持一致:补齐 slug/category/日期等路由参数,
// 否则 /{year}{month}/{slug}.html 这类固定链接会残留 {year} 占位符
$routeValue = $this->fillRouteParams($value, (int) $value['cid']);
$pathinfo = Router::url($type, $routeValue);
if (strpos($pathinfo, '{') !== false) {
// 还有占位符没填上(例如文章 slug 为空),退回站点真实支持的形式
$pathinfo = $this->fallbackPermalink((int) $value['cid'], $type);
}
$value['pathinfo'] = $pathinfo !== '' ? $pathinfo : '#';
} else {
$value['pathinfo'] = '#';
}
$value['url'] = $value['permalink'] = Common::url($value['pathinfo'], $this->options->index);
return $value;
}
/**
* 生成 CSRF Token
*
* @param mixed $key
* @return string
*/
private function generateCsrfToken($key)
{
return base64_encode(
hash_hmac(
'sha256',
hash_hmac(
'sha256',
date('Ymd') . $this->request->getServer('REMOTE_ADDR') . $this->request->getServer('HTTP_USER_AGENT'),
hash('sha256', $key, true),
true
),
$this->config->csrfSalt,
true
)
);
}
/**
* 检查 CSRF Token 是否匹配
*
* @param mixed $key
* @param mixed $token
* @return boolean
*/
private function checkCsrfToken($key, $token)
{
return hash_equals($token, $this->generateCsrfToken($key));
}
/**
* 检测登录状态
*/
public function checkLogin()
{
if ($this->config->validateLogin != 1) {
return;
}
$user = $this->userWidget();
// 拿不到用户对象时按「未登录」处理:写操作宁可拒绝,也不能放行
if (null === $user || !$user->hasLogin()) {
$this->throwError('User must be logged in', 401);
}
}
/**
* 取当前登录用户的 widget
*
* 注意:Action 继承的是 Typecho\Widget\Request,它**没有** widget() 方法。
* 早先写的 $this->widget('Widget_User') 会抛
* 「Error: Call to undefined method」,只要后台把「验证登录」打开,
* 每个写接口都会 500。这里按版本分别取:
* 1.2+ 用 \Widget\User::alloc(),1.1 用 \Typecho_Widget::widget()。
*
* @return object|null
*/
private function userWidget()
{
try {
if (class_exists('\\Widget\\User')) {
return \Widget\User::alloc();
}
if (class_exists('\\Typecho_Widget')) {
return \Typecho_Widget::widget('Widget_User');
}
} catch (\Throwable $e) {
return null;
}
return null;
}
/**
* 刷新Metas数量
* @param array $midArray
* @return void
*/
private function refreshMetas(array $midArray)
{
$tags = $this->db
->select('*')
->from('table.metas')
->where('mid IN (' . implode(',', $midArray) . ')');
$result = $this->db->fetchAll($tags);
// 更新数量
foreach ($result as $tag) {
$count = $this->db->fetchObject($this->db->select(array('COUNT(cid)' => 'num'))
->from('table.relationships')
->where('mid = ?', $tag['mid']))->num;
$this->db->query($this->db->update('table.metas')
->rows(array('count' => $count))
->where('mid = ?', $tag['mid']));
}
}
/**
* 触发七牛云同步插件
*
* @param int $cid 文章ID
* @param array $postData 文章数据
* @param bool $isUpdate 是否为更新操作
*/
private function triggerQiniuSync($cid, $postData, $isUpdate = false)
{
// 检查七牛插件是否存在且激活
if (!class_exists('\ArticleToObsidian_Plugin')) {
return;
}
// 获取完整的文章数据
$select = $this->db->select('cid', 'title', 'text', 'created', 'modified', 'authorId', 'slug')
->from('table.contents')
->where('cid = ?', $cid);
$article = $this->db->fetchRow($select);
if (empty($article)) {
return;
}
// 构造类似 Typecho 发布时的数据格式
$contents = array(
'cid' => $article['cid'],
'title' => $article['title'],
'text' => $article['text'],
'created' => $article['created'],
'modified' => $article['modified'],
'authorId' => $article['authorId'],
'slug' => $article['slug'],
);
// 模拟一个简单的 widget 对象
$mockWidget = new \stdClass();
$mockWidget->cid = $article['cid'];
$mockWidget->title = $article['title'];
$mockWidget->text = $article['text'];
$mockWidget->created = $article['created'];
$mockWidget->modified = $article['modified'];
try {
if ($isUpdate) {
// 触发更新同步
\ArticleToObsidian_Plugin::autoSyncOnUpdate($contents, $mockWidget);
} else {
// 触发发布同步
\ArticleToObsidian_Plugin::autoSyncOnPublish($contents, $mockWidget);
}
} catch (\Throwable $e) {
// 记录错误到日志文件(连 Error/TypeError 一起接住,别让一个第三方
// 插件的类型错误把发文请求变成 500——文章此时其实已经写好了)
$logFile = dirname(__DIR__) . '/ArticleToObsidian/data/sync.log';
@file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] TypechoToObsidian 触发同步失败: " . $e->getMessage() . "\n", FILE_APPEND);
}
}
/**
* 通知更新日志插件:从 Obsidian 发布的文章也写入站点更新日志
*
* 本接口发文章是把内容直接写进 table.contents(Contents::insert),
* 不经过 Widget\Contents\Post\Edit::publish,所以 ChangeLog 挂在
* finishPublish 上的自动记录不会触发。这里按它公开的
* recordPublishedPost($contents, $widget) 主动补一次通知:
* 后台开关、同一 cid 去重、异常兜底都由 ChangeLog 自己处理。
*
* @param int $cid 文章 ID
* @param string $title 文章标题
* @return void
*/
private function notifyChangeLog($cid, $title)
{
$cid = (int) $cid;
if ($cid <= 0) {
return;
}
// 没装或没启用 ChangeLog 就安静跳过
if (!$this->isPluginActivated('ChangeLog')) {
return;
}
if (
!class_exists('\ChangeLog_Plugin')
|| !method_exists('\ChangeLog_Plugin', 'recordPublishedPost')
) {
return;
}
$payload = array(
'cid' => $cid,
'title' => (string) $title,
'type' => 'post',
'status' => 'publish',
);
// ChangeLog 读的是 widget 的属性,这里用普通对象承载,
// 字段与 Widget\Contents\Post\Edit 对齐
$widget = new \stdClass();
foreach ($payload as $key => $value) {
$widget->$key = $value;
}
try {
\ChangeLog_Plugin::recordPublishedPost($payload, $widget);
} catch (\Throwable $e) {
// 日志记录失败绝不能影响发文结果
}
}
/**
* 判断某个插件是否处于启用状态
*
* Typecho 的类自动加载只认「文件在不在」,停用的插件同样能被
* class_exists 命中,所以这里再查一次 activated 列表。
*
* @param string $name 插件目录名
* @return bool
*/
private function isPluginActivated($name)
{
foreach (array('\Typecho\Plugin', '\Typecho_Plugin') as $candidate) {
if (!class_exists($candidate)) {
continue;
}
try {
$export = $candidate::export();
} catch (\Throwable $e) {
return false;
}
return !empty($export['activated'][$name]);
}
return false;
}
}