From 8b4295b5bb1b00461635ef48dac625489f4301eb Mon Sep 17 00:00:00 2001 From: XIGE <710062962@qq.com> Date: Thu, 26 Nov 2026 15:05:16 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=8F=92=E4=BB=B6=E6=BA=90?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=B9=B6=E8=A1=A5=E9=BD=90=E6=A0=87=E5=87=86?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 29 + Action.php | 2631 +++++++++++++++++++++++++++++++++++++++++++++++ CHANGELOG.md | 54 + CONTRIBUTING.md | 19 + LICENSE | 21 + Plugin.php | 1264 +++++++++++++++++++++++ README.md | 28 + Util.php | 98 ++ 8 files changed, 4144 insertions(+) create mode 100644 .gitignore create mode 100644 Action.php create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 Plugin.php create mode 100644 Util.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40fbae9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Dependencies and build output +node_modules/ +vendor/ +dist/ +build/ +out/ +main.js +*.apk + +# Build tools and IDE +.gradle/ +.idea/ +*.iml +gradle/ +gradlew +gradlew.bat + +# Environment and secrets +.env +.env.* +keystore.properties +*.jks +credentials*.json + +# Runtime data and backups +data/ +备份/ +*.log +.DS_Store diff --git a/Action.php b/Action.php new file mode 100644 index 0000000..a727c24 --- /dev/null +++ b/Action.php @@ -0,0 +1,2631 @@ +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 + $result[$key]['digest'] = str_replace( + "", + "", + explode("", $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( + "", + "", + explode("", $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; + } +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..6f88605 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,54 @@ +# TypechoToObsidian 更新日志 + +> 本文件记录本插件的所有修改与变化。本次整理(2026-11-22)为规范化记录起点。 + +## 插件信息 + +- 名称:TypechoToObsidian +- 版本:2.0.9 +- 作者:石头厝 +- 说明:文章、分类、标签、评论REST_API接口 + +## 记录格式约定 + +每次修改按如下格式在**最上方**追加一条记录(新的在上): + +``` +## YYYY-MM-DD · 版本号 —— 一句话概述 + +- 改动点 1 +- 改动点 2 +- 影响范围 / 注意事项(若有) +- 对应备份:备份/YYYY-MM-DD-修改内容简短说明修改前/ +``` + +## 2026-11-23 · 2.0.9 —— postArticle 支持 files,把客户端上传的附件认领到文章 + +- `Action.php`:`postArticleAction` 新增可选参数 `files`(逗号分隔的附件 cid) +- 写完文章拿到 cid 后,执行 `UPDATE ... table.contents SET parent = cid WHERE type='attachment' AND cid IN (...)`,把客户端上传时 `parent` 仍为 0 的附件挂到本文 +- 解决的问题:App 先传图再发文,图能在正文里显示,但网页端编辑页右侧「附件」列表按 `parent` 查,看不到这些图,也没法在后台删除或复用 +- 兼容性:不传 `files` 时整段跳过,Obsidian 插件等既有客户端行为完全不变;`$fileIds` 全部经 `(int)` 过滤后拼接,不引入注入面 +- 同日另有一处已在上方记录的改动:`postArticle` 支持可选 `status`(publish / waiting / hidden),App 用它把文章发成「待审核」 +- 对应备份:`备份/2026-11-23-postArticle绑定附件修改前/` +- 部署:只需覆盖上传 `usr/plugins/TypechoToObsidian/Action.php`,无需重新启用插件 + +## 2026-11-22 · 2.0.8 —— 补齐头部版本与链接 + +- `Plugin.php` 文件头注释(Typecho 后台插件信息读取的第一段)补齐 `@version 2.0.8`、`@link https://www.shitoucuo.com/` +- 版本号取自本插件更新日志既有版本(类注释中已有同值),后台插件列表版本显示不再为空 +- 对应备份:`备份/2026-11-22-补版本和链接修改前/` + +## 2026-11-22 · 2.0.8 —— 统一作者与链接 + +- `Plugin.php` 头部 `@author` 统一为「石头厝」 +- `@link` 统一为 `https://www.shitoucuo.com/` +- 影响范围:仅头部元信息,不涉及功能代码 +- 对应备份:`备份/2026-11-22-统一作者和链接修改前/` + +--- + +## 2026-11-22 · 2.0.8 —— 建立规范化备份与更新日志 + +- 建立 `备份/` 文件夹并生成本次整理前全量备份 `备份/2026-11-22-规范化整理修改前/` +- 创建本更新日志,作为后续所有修改的记录起点 +- 说明:本次仅做规范化整理,未改动插件功能代码 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..6ed8c08 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# 贡献指南 + +欢迎对本插件提出改进建议或提交代码。 + +## 提交前检查 + +- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。 +- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。 +- 涉及对外服务或凭据的配置不要写入代码或文档。 + +## 提交流程 + +1. Fork 仓库并创建功能分支。 +2. 完成修改后提交 Pull Request,说明改动目的与影响范围。 +3. 重要功能变更请同步更新 `CHANGELOG.md`。 + +## 问题反馈 + +请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7951bd8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 石头厝 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Plugin.php b/Plugin.php new file mode 100644 index 0000000..cbbad9d --- /dev/null +++ b/Plugin.php @@ -0,0 +1,1264 @@ + array( + 'title' => '内容读取', + 'note' => '只读,客户端拉取文章、分类、标签与评论时用到', + 'names' => array( + 'posts', 'post', 'postDetail', 'pages', 'categories', 'tags', + 'archives', 'recentComments', 'comments', 'settings', 'users', 'userList', + ), + ), + 'publish' => array( + 'title' => '发布与编辑', + 'note' => '从 Obsidian 写回文章、分类与标签', + 'names' => array('postArticle', 'addMetas', 'editMeta'), + ), + 'comment' => array( + 'title' => '评论管理', + 'note' => '发表、审核、回复与删除评论', + 'names' => array('comment', 'manageComments', 'manageComment'), + ), + 'file' => array( + 'title' => '文件管理', + 'note' => '附件上传、删除与列表', + 'names' => array('upload', 'deleteFile', 'fileList'), + ), + ); + + /** + * 接口在设置页里显示的一句话说明 + * + * 注释里的原文会被 getRoutes() 去掉斜杠、且大多带「的接口」尾巴, + * 这里单独给一份干净的展示文案;新增的接口没写在这里时自动回退到注释第一行。 + * + * @var array + */ + private const ROUTE_INFO = array( + 'posts' => '文章列表与搜索', + 'post' => '文章 / 独立页面详情(渲染后的 HTML)', + 'postDetail' => '文章详情(原始 Markdown,供下载后继续编辑)', + 'pages' => '独立页面列表', + 'categories' => '分类列表', + 'tags' => '标签列表', + 'archives' => '归档列表', + 'recentComments' => '最新评论', + 'comments' => '文章评论列表', + 'settings' => '站点设置项', + 'users' => '作者信息与作者文章', + 'userList' => '用户列表', + 'postArticle' => '发布 / 更新文章', + 'addMetas' => '新增分类 / 标签', + 'editMeta' => '修改分类 / 标签', + 'comment' => '发表评论', + 'manageComments' => '评论列表(管理用,可按状态筛选)', + 'manageComment' => '评论操作:审核 / 回复 / 删除 / 修改', + 'upload' => '上传附件', + 'deleteFile' => '删除附件', + 'fileList' => '附件列表', + ); + + /** + * 激活插件方法,如果激活失败,直接抛出异常 + * + * @access public + * @return string + * @throws Exception + */ + public static function activate() + { + $routes = call_user_func(array(self::ACTION_CLASS, 'getRoutes')); + foreach ($routes as $route) { + Helper::addRoute($route['name'], $route['uri'], self::ACTION_CLASS, $route['action']); + } + TypechoPlugin::factory('Widget_Feedback')->comment = array(__CLASS__, 'comment'); + + return 'TypechoToObsidian 已启用'; + } + + /** + * 禁用插件方法,如果禁用失败,直接抛出异常 + * + * @static + * @access public + * @return string + * @throws Exception + */ + public static function deactivate() + { + $routes = call_user_func(array(self::ACTION_CLASS, 'getRoutes')); + foreach ($routes as $route) { + Helper::removeRoute($route['name']); + } + + return 'TypechoToObsidian 已停用'; + } + + /** + * 获取插件配置面板 + * + * @access public + * @param Form $form 配置面板 + * @return void + */ + public static function config(Form $form) + { + $form->setAttribute('class', 'tto-form'); + + $routes = call_user_func(array(self::ACTION_CLASS, 'getRoutes')); + $methods = self::routeMethods(); + + /** 先按原有 name / 默认值把输入项建好,保证配置键名与提交逻辑完全不变 */ + $switches = array(); + foreach ($routes as $route) { + if ($route['shortName'] === 'upgrade') { + continue; + } + + $switch = new Radio( + $route['shortName'], + array(0 => _t('禁用'), 1 => _t('启用')), + 1, + self::switchLabel($route, $methods), + self::routeSummary($route) + ); + $switch->setAttribute('class', 'typecho-option tto-row tto-row--switch'); + $switch->setAttribute('data-tto-route', $route['shortName']); + $form->addInput($switch); + + $switches[$route['shortName']] = $switch; + } + + $fields = array(); + + $fields['apiToken'] = new Text( + 'apiToken', + null, + '123456', + _t('APITOKEN'), + _t('客户端请求时通过 token 请求头携带。留空则不校验,任何拿到接口地址的人都能读写。') + ); + $fields['apiToken']->input->setAttribute('placeholder', _t('例如 8f3c1d7a9b…(留空表示不校验)')); + + $fields['csrfSalt'] = new Text( + 'csrfSalt', + null, + '05faabd6637f7e30c797973a558d4372', + _t('CSRF 加密盐'), + _t('请务必改成你自己的随机字符串,用于签发和校验请求令牌。') + ); + $fields['csrfSalt']->input->setAttribute('placeholder', _t('一串随机字符,越长越好')); + + $fields['validateLogin'] = new Radio( + 'validateLogin', + array(0 => _t('否'), 1 => _t('是')), + 0, + _t('高敏接口校验后台登录'), + _t('开启后,高敏接口需要携带后台登录 Cookie 才能调用,只适合在浏览器里直接调试时使用。') + ); + + $fields['origin'] = new Textarea( + 'origin', + null, + null, + _t('跨域域名白名单'), + _t('一行一个来源域名,需带协议头,例如 https://blog.example.com。填 * 表示不限制跨域来源,不推荐。') + ); + $fields['origin']->input->setAttribute('placeholder', 'https://blog.example.com'); + + $fields['fieldsPrivacy'] = new Text( + 'fieldsPrivacy', + null, + null, + _t('自定义字段过滤'), + _t('获取文章时忽略的自定义字段名,半角英文逗号分隔,例如 fields1,fields2') + ); + $fields['fieldsPrivacy']->input->setAttribute('placeholder', 'fields1,fields2'); + + $fields['allowedOptions'] = new Text( + 'allowedOptions', + null, + null, + _t('设置项白名单'), + _t('/api/settings 默认只返回安全的站点设置。这里可以追加允许通过 ?key= 读取的 typecho_options 字段名,英文逗号分隔,例如 keywords,theme') + ); + $fields['allowedOptions']->input->setAttribute('placeholder', 'keywords,theme'); + + /* 这两项是开关样式,其余是输入框样式 */ + $switchStyleFields = array('validateLogin'); + + foreach ($fields as $name => $field) { + $field->setAttribute( + 'class', + 'typecho-option tto-row ' + . (in_array($name, $switchStyleFields, true) ? 'tto-row--switch' : 'tto-row--field') + ); + $form->addInput($field); + } + + self::buildLayout($form, $switches, $fields); + } + + /** + * 把建好的输入项重新组织进分组卡片里 + * + * 所有输入项都已通过 addInput 注册,这里只是把它们从表单顶层搬到卡片内部, + * 因此提交的字段名、默认值、校验逻辑都不受影响。 + * + * @param Form $form + * @param array $switches 接口开关 + * @param array $fields 其余配置项 + * @return void + */ + private static function buildLayout(Form $form, array $switches, array $fields) + { + $form->addItem(self::layout('style', array('id' => 'tto-config-style'), self::stylesheet())); + + /* 顶部说明 */ + $form->addItem(self::layout('div', array('class' => 'tto-hero'), self::heroHtml(count($switches)))); + + /* 接口开关 */ + $card = self::card( + _t('接口开关'), + _t('关闭后该接口对客户端立即失效,请求会返回 403。'), + '' . _t('已启用') . ' – / ' . count($switches) . '' + . '' + . '' + ); + + foreach (self::ROUTE_GROUPS as $group) { + $names = array(); + foreach ($group['names'] as $name) { + if (isset($switches[$name])) { + $names[] = $name; + } + } + if (!$names) { + continue; + } + + $card->addItem(self::layout( + 'div', + array('class' => 'tto-group-head'), + '' . _t($group['title']) . '' + . '' . _t($group['note']) . '' + . '' . count($names) . '' + )); + + foreach ($names as $name) { + $form->removeItem($switches[$name]); + $card->addItem($switches[$name]); + unset($switches[$name]); + } + } + + /* 以后新增但没写进分组的接口,兜底显示在最后,避免漏掉 */ + if ($switches) { + $card->addItem(self::layout( + 'div', + array('class' => 'tto-group-head'), + '' . _t('其他接口') . '' + . '' . count($switches) . '' + )); + foreach ($switches as $name => $switch) { + $form->removeItem($switch); + $card->addItem($switch); + } + } + + $form->addItem($card); + + /* 安全与访问 */ + $security = self::card( + _t('安全与访问'), + _t('这几项决定谁能调用本站接口,建议逐条确认。') + ); + foreach (array('apiToken', 'csrfSalt', 'validateLogin', 'origin') as $name) { + $form->removeItem($fields[$name]); + $security->addItem($fields[$name]); + } + $form->addItem($security); + + /* 高级设置 */ + $advanced = self::card( + _t('高级设置'), + _t('不确定用途的话保持默认即可。') + ); + foreach (array('fieldsPrivacy', 'allowedOptions') as $name) { + $form->removeItem($fields[$name]); + $advanced->addItem($fields[$name]); + } + $form->addItem($advanced); + + $form->addItem(self::layout('script', array(), self::script())); + } + + /** + * 顶部说明区 + * + * @param int $total 接口总数 + * @return string + */ + private static function heroHtml(int $total): string + { + $prefix = defined('__TYPECHO_TO_OBSIDIAN_PREFIX__') ? __TYPECHO_TO_OBSIDIAN_PREFIX__ : '/api/'; + + return '
' . _t('把本站文章、分类、标签与评论以 REST API 形式开放,供 Obsidian 客户端发布与同步使用。当前共 %d 个接口,可直接在下方逐个开关。', $total) . '
' + . '' . htmlspecialchars($prefix, ENT_QUOTES, 'UTF-8') . ''
+ . '' . _t('接口前缀') . ''
+ . '' . $desc . '
' : '') + . '' . htmlspecialchars($route['uri'], ENT_QUOTES, 'UTF-8') . '';
+ }
+
+ /**
+ * 接口说明只取注释第一行,避免把整段判定规则塞进设置页
+ *
+ * @param array $route
+ * @return string
+ */
+ private static function routeSummary(array $route): string
+ {
+ if (isset(self::ROUTE_INFO[$route['shortName']])) {
+ return htmlspecialchars(self::ROUTE_INFO[$route['shortName']], ENT_QUOTES, 'UTF-8');
+ }
+
+ $lines = preg_split('/\r\n|\r|\n/', (string) $route['description']);
+
+ foreach ((array) $lines as $line) {
+ $line = trim($line, " \t\n\r\0\x0B*/");
+ if ($line !== '') {
+ return htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
+ }
+ }
+
+ return '';
+ }
+
+ /**
+ * 从接口源码里读出每个接口限定的请求方法
+ *
+ * @return array action 名 => GET / POST
+ */
+ private static function routeMethods(): array
+ {
+ $map = array();
+
+ try {
+ $class = new \ReflectionClass(self::ACTION_CLASS);
+ $file = $class->getFileName();
+ $lines = $file ? @file($file) : null;
+ if (!$lines) {
+ return $map;
+ }
+
+ foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
+ if (!preg_match('/(.*)Action$/', $method->getName())) {
+ continue;
+ }
+ $start = $method->getStartLine() - 1;
+ $body = implode('', array_slice($lines, $start, $method->getEndLine() - $start));
+ $map[$method->getName()] = preg_match('/lockMethod\(\s*[\'"]post[\'"]/i', $body) ? 'POST' : 'GET';
+ }
+ } catch (\Throwable $e) {
+ /* 反射失败时按 GET 显示,不影响配置本身 */
+ }
+
+ return $map;
+ }
+
+ /**
+ * 当前插件版本,跟随文件头注释
+ *
+ * @return string
+ */
+ private static function version(): string
+ {
+ try {
+ $doc = (string) (new \ReflectionClass(__CLASS__))->getDocComment();
+ if (preg_match('/@version\s+([\w.\-]+)/', $doc, $matches)) {
+ return $matches[1];
+ }
+ } catch (\Throwable $e) {
+ }
+
+ return '2.0.1';
+ }
+
+ /**
+ * 设置页样式
+ *
+ * 全部限定在 .tto-form 内,不影响后台其他页面。
+ *
+ * @return string
+ */
+ private static function stylesheet(): string
+ {
+ return <<<'CSS'
+.tto-form {
+ /* ---------- 浅色(默认) ---------- */
+ --tto-accent: #467B96;
+ --tto-accent-soft: #EDF3F6;
+ --tto-accent-line: #C7D8E0;
+ --tto-accent-strong: #3C6A81;
+ --tto-ink: #363633;
+ --tto-ink-strong: #2E2E2B;
+ --tto-label: #33332F;
+ --tto-path-text: #33332F;
+ --tto-subtle: #5F5F58;
+ --tto-muted: #72726B;
+ --tto-dim: #8A8A82;
+ --tto-total: #898981;
+ --tto-line: #E3E3DD;
+ --tto-line-soft: #F1F1EC;
+ --tto-card: #FFFFFF;
+ --tto-card-head: #FCFCFA;
+ --tto-soft: #FAFAF7;
+ --tto-page: #F6F6F3;
+ --tto-input-bg: #FFFFFF;
+ --tto-input-line: #D9D9D3;
+ --tto-ctrl-text: #66665F;
+ --tto-ctrl-bg: #FFFFFF;
+ --tto-ctrl-line: #D9D9D3;
+ --tto-ctrl-hover: #F4F4EF;
+ --tto-seg-on-bg: #E4E4DB;
+ --tto-seg-on-line: #C4C4B9;
+ --tto-seg-on-text: #3D3D37;
+ --tto-count-text: #3C6A81;
+ --tto-get-text: #2E6F52;
+ --tto-get-bg: #E9F3EE;
+ --tto-post-text: #8F6220;
+ --tto-post-bg: #FAF0DE;
+ --tto-chip-text: #4A4A45;
+ --tto-chip-bg: #F4F4EF;
+ --tto-focus-ring: 0 0 0 3px rgba(70, 123, 150, .12);
+ --tto-bar-shadow: 0 -8px 14px -10px rgba(0, 0, 0, .18);
+ font-size: 14px;
+ color: var(--tto-ink);
+}
+
+/*
+ * 深色:脚本按 NewAdmin 的开关状态(#newadmin.dark / dark cookie / 系统偏好)
+ * 把 tto-dark 写到表单上,这里只换一套变量,其余规则不用复制一份。
+ */
+.tto-form.tto-dark {
+ --tto-accent: #7FBEDF;
+ --tto-accent-soft: rgba(127, 190, 223, .14);
+ --tto-accent-line: rgba(127, 190, 223, .34);
+ --tto-accent-strong: #2D578A;
+ --tto-ink: #D3DCE8;
+ --tto-ink-strong: #EAF1F8;
+ --tto-label: #DDE6F0;
+ --tto-path-text: #CBD6E4;
+ --tto-subtle: #BFCBDA;
+ --tto-muted: #9CABBC;
+ --tto-dim: #6C7B8E;
+ --tto-total: #8595A8;
+ --tto-line: #26354A;
+ --tto-line-soft: #1E2C3F;
+ --tto-card: #16202F;
+ --tto-card-head: #1A2635;
+ --tto-soft: #131C29;
+ --tto-page: #101928;
+ --tto-input-bg: #0E1723;
+ --tto-input-line: #2C3D54;
+ --tto-ctrl-text: #B4C1D2;
+ --tto-ctrl-bg: #1B2739;
+ --tto-ctrl-line: #2E4059;
+ --tto-ctrl-hover: #223148;
+ --tto-seg-on-bg: #3A424C;
+ --tto-seg-on-line: #4B545F;
+ --tto-seg-on-text: #E8EDF4;
+ --tto-count-text: #8FC4E4;
+ --tto-get-text: #82D8AC;
+ --tto-get-bg: rgba(130, 216, 172, .14);
+ --tto-post-text: #E8B76E;
+ --tto-post-bg: rgba(232, 183, 110, .14);
+ --tto-chip-text: #C2CDDC;
+ --tto-chip-bg: #1B2739;
+ --tto-focus-ring: 0 0 0 3px rgba(127, 190, 223, .18);
+ --tto-bar-shadow: 0 -8px 14px -10px rgba(0, 0, 0, .55);
+}
+
+/*
+ * 兜底:脚本没跑起来时跟随系统深浅色。
+ * 脚本正常时会显式加 tto-light / tto-dark,这里的规则不会误伤手动切到亮色的情况。
+ */
+@media (prefers-color-scheme: dark) {
+ .tto-form:not(.tto-light) {
+ --tto-accent: #7FBEDF;
+ --tto-accent-soft: rgba(127, 190, 223, .14);
+ --tto-accent-line: rgba(127, 190, 223, .34);
+ --tto-accent-strong: #2D578A;
+ --tto-ink: #D3DCE8;
+ --tto-ink-strong: #EAF1F8;
+ --tto-label: #DDE6F0;
+ --tto-path-text: #CBD6E4;
+ --tto-subtle: #BFCBDA;
+ --tto-muted: #9CABBC;
+ --tto-dim: #6C7B8E;
+ --tto-total: #8595A8;
+ --tto-line: #26354A;
+ --tto-line-soft: #1E2C3F;
+ --tto-card: #16202F;
+ --tto-card-head: #1A2635;
+ --tto-soft: #131C29;
+ --tto-page: #101928;
+ --tto-input-bg: #0E1723;
+ --tto-input-line: #2C3D54;
+ --tto-ctrl-text: #B4C1D2;
+ --tto-ctrl-bg: #1B2739;
+ --tto-ctrl-line: #2E4059;
+ --tto-ctrl-hover: #223148;
+ --tto-seg-on-bg: #3A424C;
+ --tto-seg-on-line: #4B545F;
+ --tto-seg-on-text: #E8EDF4;
+ --tto-count-text: #8FC4E4;
+ --tto-get-text: #82D8AC;
+ --tto-get-bg: rgba(130, 216, 172, .14);
+ --tto-post-text: #E8B76E;
+ --tto-post-bg: rgba(232, 183, 110, .14);
+ --tto-chip-text: #C2CDDC;
+ --tto-chip-bg: #1B2739;
+ --tto-focus-ring: 0 0 0 3px rgba(127, 190, 223, .18);
+ --tto-bar-shadow: 0 -8px 14px -10px rgba(0, 0, 0, .55);
+ }
+}
+
+.tto-form *,
+.tto-form *::before,
+.tto-form *::after {
+ box-sizing: border-box;
+}
+
+/* ---------------- 顶部说明 ---------------- */
+
+.tto-form .tto-hero {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ margin: 0 0 16px;
+ padding: 15px 18px;
+ background: var(--tto-card);
+ border: 1px solid var(--tto-line);
+ border-left: 3px solid var(--tto-accent);
+ border-radius: 5px;
+}
+
+.tto-form .tto-hero-main {
+ flex: 1 1 auto;
+ min-width: 0;
+}
+
+.tto-form .tto-hero-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 15px;
+ font-weight: 700;
+ color: var(--tto-ink-strong);
+}
+
+.tto-form .tto-hero-ver {
+ padding: 1px 7px;
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 1.6;
+ color: var(--tto-count-text);
+ background: var(--tto-accent-soft);
+ border-radius: 999px;
+}
+
+.tto-form .tto-hero-desc {
+ margin: 6px 0 0;
+ font-size: 12px;
+ line-height: 1.65;
+ color: var(--tto-muted);
+}
+
+.tto-form .tto-hero-side {
+ flex: 0 0 auto;
+ text-align: right;
+}
+
+.tto-form .tto-chip {
+ display: inline-block;
+ padding: 3px 9px;
+ font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+ font-size: 12px;
+ color: var(--tto-chip-text);
+ background: var(--tto-chip-bg);
+ border: 1px solid var(--tto-line);
+ border-radius: 4px;
+}
+
+.tto-form .tto-chip-label {
+ display: block;
+ margin-top: 4px;
+ font-size: 11px;
+ color: var(--tto-muted);
+}
+
+/* ---------------- 卡片 ---------------- */
+
+.tto-form .tto-card {
+ margin: 0 0 16px;
+ background: var(--tto-card);
+ border: 1px solid var(--tto-line);
+ border-radius: 5px;
+ overflow: hidden;
+ /* 让卡片按自身宽度决定是否折行,而不是跟着窗口宽度走 */
+ container-type: inline-size;
+}
+
+.tto-form .tto-card-head {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 11px 16px;
+ background: var(--tto-card-head);
+ border-bottom: 1px solid var(--tto-line);
+}
+
+.tto-form .tto-card-text {
+ flex: 1 1 auto;
+ min-width: 0;
+}
+
+.tto-form .tto-card-title {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 700;
+ color: var(--tto-ink-strong);
+}
+
+.tto-form .tto-card-desc {
+ margin: 3px 0 0;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--tto-muted);
+}
+
+.tto-form .tto-card-tools {
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.tto-form .tto-count {
+ padding: 3px 10px;
+ font-size: 11px;
+ color: var(--tto-count-text);
+ background: var(--tto-accent-soft);
+ border-radius: 999px;
+ white-space: nowrap;
+}
+
+.tto-form .tto-count b {
+ font-weight: 700;
+}
+
+.tto-form .tto-mini {
+ height: 26px;
+ padding: 0 10px;
+ font-size: 12px;
+ color: var(--tto-ctrl-text);
+ background: var(--tto-ctrl-bg);
+ border: 1px solid var(--tto-ctrl-line);
+ border-radius: 3px;
+ cursor: pointer;
+ transition: background-color .15s ease, border-color .15s ease, color .15s ease;
+}
+
+.tto-form .tto-mini:hover {
+ color: var(--tto-accent);
+ background: var(--tto-accent-soft);
+ border-color: var(--tto-accent-line);
+}
+
+/* ---------------- 分组标题 ---------------- */
+
+.tto-form .tto-group-head {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ padding: 10px 16px 7px;
+ background: var(--tto-soft);
+ border-bottom: 1px solid var(--tto-line-soft);
+}
+
+.tto-form .tto-group-title {
+ font-size: 12px;
+ font-weight: 700;
+ color: var(--tto-subtle);
+}
+
+.tto-form .tto-group-note {
+ flex: 1 1 auto;
+ min-width: 0;
+ font-size: 11px;
+ color: var(--tto-muted);
+}
+
+.tto-form .tto-group-total {
+ flex: 0 0 auto;
+ font-size: 11px;
+ color: var(--tto-total);
+}
+
+/* ---------------- 通用行 ---------------- */
+
+.tto-form ul.tto-row {
+ list-style: none;
+ margin: 0;
+ padding: 10px 16px;
+ border-bottom: 1px solid var(--tto-line-soft);
+}
+
+.tto-form ul.tto-row:last-child {
+ border-bottom: 0;
+}
+
+.tto-form ul.tto-row > li {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+/* ---------------- 开关行 ---------------- */
+
+.tto-form ul.tto-row--switch > li {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto auto;
+ align-items: center;
+ row-gap: 3px;
+ column-gap: 0;
+}
+
+.tto-form .tto-row--switch label.typecho-label {
+ grid-column: 1;
+ grid-row: 1;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ margin: 0;
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--tto-label);
+}
+
+.tto-form .tto-row--switch .description {
+ grid-column: 1;
+ grid-row: 2;
+ margin: 0;
+ font-size: 12px;
+ line-height: 1.55;
+ color: var(--tto-muted);
+}
+
+.tto-form .tto-row--switch > li > span {
+ display: flex;
+ grid-row: 1 / span 2;
+ margin: 0;
+}
+
+.tto-form .tto-row--switch > li > span:nth-of-type(1) {
+ grid-column: 2;
+}
+
+.tto-form .tto-row--switch > li > span:nth-of-type(2) {
+ grid-column: 3;
+}
+
+.tto-form .tto-row--switch input[type="radio"] {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ margin: 0;
+ opacity: 0;
+ pointer-events: none;
+}
+
+.tto-form .tto-row--switch span > label {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 46px;
+ height: 26px;
+ padding: 0 10px;
+ font-size: 12px;
+ line-height: 1;
+ color: var(--tto-ctrl-text);
+ background: var(--tto-ctrl-bg);
+ border: 1px solid var(--tto-ctrl-line);
+ cursor: pointer;
+ white-space: nowrap;
+ transition: background-color .15s ease, border-color .15s ease, color .15s ease;
+}
+
+.tto-form .tto-row--switch span:nth-of-type(1) > label {
+ border-radius: 3px 0 0 3px;
+}
+
+.tto-form .tto-row--switch span:nth-of-type(2) > label {
+ border-radius: 0 3px 3px 0;
+ border-left-width: 0;
+}
+
+.tto-form .tto-row--switch span > label:hover {
+ background: var(--tto-ctrl-hover);
+}
+
+.tto-form .tto-row--switch span:nth-of-type(1) input:checked + label {
+ color: var(--tto-seg-on-text);
+ font-weight: 600;
+ background: var(--tto-seg-on-bg);
+ border-color: var(--tto-seg-on-line);
+ box-shadow: inset 0 1px 2px rgba(0, 0, 0, .05);
+}
+
+.tto-form .tto-row--switch span:nth-of-type(2) input:checked + label {
+ color: #FFF;
+ font-weight: 600;
+ background: var(--tto-accent-strong);
+ border-color: var(--tto-accent-strong);
+}
+
+/* 关掉的接口把路径压淡,扫一眼就知道哪些没开 */
+.tto-form ul.tto-row--switch.is-off .tto-path {
+ color: var(--tto-dim);
+}
+
+.tto-form ul.tto-row--switch.is-off .tto-method {
+ opacity: .6;
+}
+
+.tto-form .tto-row--switch input[type="radio"]:focus-visible + label {
+ outline: 2px solid var(--tto-accent);
+ outline-offset: 1px;
+}
+
+/* 请求方法与路径 */
+
+.tto-form .tto-method {
+ flex: 0 0 auto;
+ min-width: 44px;
+ margin: 0;
+ padding: 1px 0;
+ font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 1.6;
+ letter-spacing: .04em;
+ text-align: center;
+ border-radius: 3px;
+}
+
+.tto-form .tto-method--get {
+ color: var(--tto-get-text);
+ background: var(--tto-get-bg);
+}
+
+.tto-form .tto-method--post {
+ color: var(--tto-post-text);
+ background: var(--tto-post-bg);
+}
+
+.tto-form .tto-path {
+ min-width: 0;
+ padding: 0;
+ font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+ font-size: 12.5px;
+ color: var(--tto-path-text);
+ background: none;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* ---------------- 输入行 ---------------- */
+
+.tto-form ul.tto-row--field {
+ padding: 14px 16px;
+}
+
+.tto-form .tto-row--field label.typecho-label {
+ display: block;
+ margin: 0 0 6px;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--tto-label);
+}
+
+.tto-form .tto-row--field .description {
+ margin: 6px 0 0;
+ font-size: 12px;
+ line-height: 1.65;
+ color: var(--tto-muted);
+}
+
+.tto-form .tto-row--field input.text {
+ display: block;
+ width: 100%;
+ height: 34px;
+ padding: 0 10px;
+ font-size: 13px;
+ color: var(--tto-ink);
+ background: var(--tto-input-bg);
+ border: 1px solid var(--tto-input-line);
+ border-radius: 3px;
+ transition: border-color .15s ease, box-shadow .15s ease;
+}
+
+.tto-form .tto-row--field textarea {
+ display: block;
+ width: 100%;
+ min-height: 92px;
+ padding: 8px 10px;
+ font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+ font-size: 12.5px;
+ line-height: 1.7;
+ color: var(--tto-ink);
+ background: var(--tto-input-bg);
+ border: 1px solid var(--tto-input-line);
+ border-radius: 3px;
+ resize: vertical;
+ transition: border-color .15s ease, box-shadow .15s ease;
+}
+
+.tto-form .tto-row--field input.text:focus,
+.tto-form .tto-row--field textarea:focus {
+ border-color: var(--tto-accent);
+ outline: none;
+ box-shadow: var(--tto-focus-ring);
+}
+
+/* ---------------- 保存 ---------------- */
+
+.tto-form .typecho-option-submit {
+ position: sticky;
+ bottom: 0;
+ z-index: 5;
+ margin: 0;
+ padding: 12px 0;
+ background: var(--tto-page);
+ border-top: 1px solid var(--tto-line);
+ box-shadow: var(--tto-bar-shadow);
+ text-align: center;
+}
+
+.tto-form .typecho-option-submit li {
+ border: 0;
+ text-align: center;
+}
+
+.tto-form .typecho-option-submit button[type="submit"] {
+ display: inline-block;
+ width: auto;
+ min-width: 132px;
+ height: 36px;
+ margin: 0 auto;
+ font-size: 13px;
+ font-weight: 600;
+ border-radius: 3px;
+}
+
+/* ---------------- 窄屏 ---------------- */
+
+/* 卡片本身变窄时(后台两栏、窄侧栏),工具按钮换到下一行,避免挤压标题 */
+@container (max-width: 560px) {
+ .tto-form .tto-card-head {
+ flex-wrap: wrap;
+ }
+
+ .tto-form .tto-card-tools {
+ width: 100%;
+ justify-content: flex-end;
+ }
+}
+
+@media (max-width: 620px) {
+ .tto-form .tto-hero {
+ flex-wrap: wrap;
+ }
+
+ .tto-form .tto-hero-side {
+ width: 100%;
+ text-align: left;
+ }
+
+ .tto-form ul.tto-row {
+ padding: 10px 12px;
+ }
+
+ .tto-form .tto-path {
+ font-size: 11.5px;
+ }
+}
+CSS;
+ }
+
+ /**
+ * 设置页里的小交互:统计已启用数量、一键全开/全关
+ *
+ * @return string
+ */
+ private static function script(): string
+ {
+ return <<<'JS'
+(function () {
+ /*
+ * 深色适配
+ * 后台主题(NewAdmin)把开关状态放在三处: #newadmin 上的 dark 类、
+ * dark=dark/light 的 cookie、以及 #darkcss 样式表的 disabled 状态。
+ * 按这个顺序判断,都没有时跟随系统偏好。
+ */
+ function isDark() {
+ var host = document.getElementById('newadmin');
+ if (host && host.classList.contains('dark')) {
+ return true;
+ }
+ if (document.body && document.body.classList.contains('dark')) {
+ return true;
+ }
+ var matched = document.cookie.match(/(?:^|;\s*)dark=([^;]+)/i);
+ if (matched) {
+ var value = decodeURIComponent(matched[1]).toLowerCase();
+ return value === 'dark' || value === 'true' || value === '1';
+ }
+ var sheet = document.getElementById('darkcss');
+ if (sheet) {
+ return !sheet.disabled;
+ }
+ return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
+ }
+
+ function syncTheme() {
+ var form = document.querySelector('form.tto-form');
+ if (!form) {
+ return;
+ }
+ var dark = isDark();
+ if (dark) {
+ form.classList.add('tto-dark');
+ form.classList.remove('tto-light');
+ } else {
+ form.classList.add('tto-light');
+ form.classList.remove('tto-dark');
+ }
+ }
+
+ /* 后台点太阳/月亮切换时不刷新页面,也要跟着变 */
+ function watchTheme() {
+ var host = document.getElementById('newadmin');
+ if (host && window.MutationObserver) {
+ new MutationObserver(syncTheme).observe(host, {
+ attributes: true,
+ attributeFilter: ['class']
+ });
+ }
+ if (window.matchMedia) {
+ var query = window.matchMedia('(prefers-color-scheme: dark)');
+ if (query.addEventListener) {
+ query.addEventListener('change', syncTheme);
+ } else if (query.addListener) {
+ query.addListener(syncTheme);
+ }
+ }
+ }
+
+ function init() {
+ var form = document.querySelector('form.tto-form');
+ if (!form) {
+ return;
+ }
+
+ syncTheme();
+ watchTheme();
+
+ var rows = form.querySelectorAll('[data-tto-route]');
+ var counter = form.querySelector('[data-tto="count"]');
+
+ function refresh() {
+ var enabled = 0;
+ for (var i = 0; i < rows.length; i++) {
+ var checked = rows[i].querySelector('input[type="radio"]:checked');
+ var on = !!checked && checked.value === '1';
+ if (on) {
+ enabled++;
+ }
+ rows[i].classList.toggle('is-off', !on);
+ }
+ if (counter) {
+ counter.textContent = String(enabled);
+ }
+ }
+
+ function setAll(value) {
+ for (var i = 0; i < rows.length; i++) {
+ var input = rows[i].querySelector('input[value="' + value + '"]');
+ if (input) {
+ input.checked = true;
+ }
+ }
+ refresh();
+ }
+
+ form.addEventListener('change', function (event) {
+ if (event.target && event.target.name) {
+ refresh();
+ }
+ });
+
+ var onButton = form.querySelector('[data-tto="all-on"]');
+ var offButton = form.querySelector('[data-tto="all-off"]');
+ if (onButton) {
+ onButton.addEventListener('click', function () { setAll('1'); });
+ }
+ if (offButton) {
+ offButton.addEventListener('click', function () { setAll('0'); });
+ }
+
+ refresh();
+ }
+
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+ } else {
+ init();
+ }
+})();
+JS;
+ }
+
+ /**
+ * 个人用户的配置面板
+ *
+ * @access public
+ * @param Form $form
+ * @return void
+ */
+ public static function personalConfig(Form $form)
+ {
+ }
+
+ /**
+ * 构造评论真实IP
+ *
+ * @return array
+ */
+ public static function comment($comment, $post)
+ {
+ $request = Request::getInstance();
+
+ $customIp = $request->getServer('HTTP_X_TYPECHO_TO_OBSIDIAN_IP');
+ if ($customIp != null) {
+ $comment['ip'] = $customIp;
+ }
+
+ return $comment;
+ }
+}
diff --git a/README.md b/README.md
index 0a93c65..c02fbd1 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,30 @@
# TypechoToObsidian
+> 仓库:`TypechoToObsidian` · 类型:Typecho 插件 · 版本:`2.0.9` · 作者:石头厝
+
+文章、分类、标签、评论 REST API 接口插件。
+
+本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。
+
+## 目录结构
+
+- `Action.php`
+- `Plugin.php`
+- `Util.php`
+
+## 安装与使用
+
+1. 将本仓库目录复制到 Typecho 站点的 `usr/plugins/<仓库名>/`。
+2. 在 Typecho 后台「插件」管理中启用并按站点配置。
+
+## 开发与贡献
+
+详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
+
+## 授权
+
+授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。
+
+## 变更记录
+
+详见 [CHANGELOG.md](CHANGELOG.md)。
diff --git a/Util.php b/Util.php
new file mode 100644
index 0000000..3694e8d
--- /dev/null
+++ b/Util.php
@@ -0,0 +1,98 @@
+get('file', null, $exists);
+ $fileNameParam = $request->get('fileName') ?: $request->get('name');
+
+ // 2) 若取不到,则尝试解析原始请求体(常见于 application/json)
+ if (!$exists || $postBytes === null) {
+ $raw = file_get_contents('php://input');
+ if (is_string($raw) && $raw !== '') {
+ $json = json_decode($raw, true);
+ if (json_last_error() === JSON_ERROR_NONE && is_array($json)) {
+ if (isset($json['file'])) {
+ $postBytes = $json['file'];
+ }
+ if (!$fileNameParam && isset($json['fileName'])) {
+ $fileNameParam = $json['fileName'];
+ } elseif (!$fileNameParam && isset($json['name'])) {
+ $fileNameParam = $json['name'];
+ }
+ }
+ }
+ }
+
+ if ($postBytes === null) {
+ throw new \Exception('missing file');
+ }
+
+ // 3) 处理可能的多种表示形式
+ // - 数字数组(Uint8Array)
+ // - base64 字符串(data:*;base64,xxx 或纯 base64)
+ // - 纯二进制字符串(不推荐,但做兜底)
+ $binary = null;
+ if (is_array($postBytes)) {
+ if (empty($postBytes)) {
+ throw new \Exception('missing file');
+ }
+ $bytes = array_map(static function ($v) {
+ $v = (int)$v;
+ if ($v < 0) {
+ $v = 0;
+ }
+ if ($v > 255) {
+ $v = 255;
+ }
+ return $v;
+ }, $postBytes);
+ $binary = pack('C*', ...$bytes);
+ } elseif (is_string($postBytes)) {
+ // data URL 或 base64
+ if (strpos($postBytes, 'base64,') !== false) {
+ $base64 = substr($postBytes, strpos($postBytes, 'base64,') + 7);
+ $binary = base64_decode($base64, true);
+ } else {
+ // 尝试按 base64 解码,不合法则当作原始二进制
+ $decoded = base64_decode($postBytes, true);
+ $binary = ($decoded !== false) ? $decoded : $postBytes;
+ }
+ } else {
+ throw new \Exception('missing file');
+ }
+
+ $name = $fileNameParam ?: 'upload.bin';
+ if ($request->isAjax() && $name) {
+ $name = urldecode($name);
+ }
+
+ $file = array(
+ 'name' => $name,
+ 'bytes' => $binary,
+ 'size' => strlen($binary),
+ );
+ } else {
+ $file = array_pop($files);
+ if (!isset($file['error']) || 0 !== (int)$file['error'] || !is_uploaded_file($file['tmp_name'])) {
+ throw new \Exception('upload failed');
+ }
+ if ($request->isAjax() && isset($file['name'])) {
+ $file['name'] = urldecode($file['name']);
+ }
+ }
+ return $file;
+ }
+}