├── README.md
├── LICENSE
└── api.php
/README.md:
--------------------------------------------------------------------------------
1 | # typechoapi
2 |
3 | Typecho 接口 API,包括发布文章、搜索文章、获取文章、备份数据、获取文章评论、获取网站信息、获取分类、获取标签等接口,持续更新中……
4 |
5 | ## 使用教程
6 |
7 | 上传 `api.php` 文件到 Typecho 博客(只支持正式版1.2.1,其他版本不支持,包括开发版本)根目录,使用前请务必修改自定义 `token`(为了安全考虑,不修改无法使用接口)。
8 |
9 | ## 近期新增
10 |
11 | 搜索文章、获取分类、获取标签、备份数据、删除备份
12 |
13 | ## 项目地址
14 |
15 | - [GitHub 地址](https://github.com/smcloudcat/typechoapi)
16 | - [Gitee 地址](https://gitee.com/ximami/typechoapi)
17 |
18 | ---
19 |
20 | ## 接口文档
21 |
22 | ### [文档地址](https://lwcat.cn/markdown/typechoapi/)
23 |
24 | ### 1. 发布文章 (release)
25 |
26 | #### 请求方法
27 | `POST/GET`
28 |
29 | #### 请求参数
30 |
31 | | 参数 | 类型 | 必填 | 说明 |
32 | |--------|--------|------|------------------------------------|
33 | | token | string | 是 | 请求的认证 Token,必填,正确的 token |
34 | | title | string | 是 | 文章标题 |
35 | | content| string | 是 | 文章内容 |
36 | | slug | string | 否 | 文章的 URL slug (可选) |
37 | | tags | string | 否 | 文章标签,多个标签用逗号分隔 (可选) |
38 |
39 | #### 示例请求
40 |
41 | ```bash
42 | POST https://example.com/api.php
43 | Content-Type: application/json
44 |
45 | {
46 | "method": "release",
47 | "token": "123456",
48 | "title": "文章标题",
49 | "content": "文章内容",
50 | "slug": "article-slug",
51 | "tags": "PHP,Typecho"
52 | }
53 | ```
54 |
55 | #### 响应示例
56 |
57 | 成功响应:
58 |
59 | ```json
60 | {
61 | "success": true,
62 | "message": "文章发布成功",
63 | "cid": 123
64 | }
65 | ```
66 |
67 | 失败响应:
68 |
69 | ```json
70 | {
71 | "success": false,
72 | "message": "无效的 token"
73 | }
74 | ```
75 |
76 | ---
77 |
78 | ### 2. 获取文章 (getarticle)
79 |
80 | #### 请求方法
81 | `POST/GET`
82 |
83 | #### 请求参数
84 |
85 | | 参数 | 类型 | 必填 | 说明 |
86 | |----------|--------|------|-----------------------------------------|
87 | | token | string | 是 | 请求的认证 Token,必填,正确的 token |
88 | | page | int | 否 | 页码,默认为 1 |
89 | | pageSize | int | 否 | 每页数量,默认为 10,最大值为 50 |
90 |
91 | #### 示例请求
92 |
93 | ```bash
94 | GET https://example.com/api.php?method=getarticle&token=123456&page=1&pageSize=10
95 | ```
96 |
97 | #### 响应示例
98 |
99 | 成功响应:
100 |
101 | ```json
102 | {
103 | "success": true,
104 | "data": [
105 | {
106 | "cid": "134",
107 | "title": "测试标题",
108 | "slug": "测试",
109 | "created": "2024-12-25 22:26:14",
110 | "authorId": "1",
111 | "tags": [],
112 | "summary": "测试内容..."
113 | },
114 | {
115 | "cid": "132",
116 | "title": "通过c计算一元二次方程的根",
117 | "slug": "132",
118 | "created": "2024-12-08 23:45:08",
119 | "authorId": "1",
120 | "tags": [],
121 | "summary": "```c\r\n#include \r\n#include \r\n\r\nvoid xiao(int a,int b,int c){\r\n int d;\r\n float real,noreal;\r\n d=b*b-4.0*a*c;\r\n real=(-b)\/2*a;\r\n noreal=sqrt(-(b*b-4*a*c));\r\n printf(\"这个方程有两个复数根:x1=%f+%f..."
122 | }
123 | ],
124 | "pagination": {
125 | "total": "65",
126 | "page": 1,
127 | "pageSize": 2
128 | }
129 | }
130 | ```
131 |
132 | ---
133 |
134 | ### 3. 获取文章评论 (getcomments)
135 |
136 | #### 请求方法
137 | `POST/GET`
138 |
139 | #### 请求参数
140 |
141 | | 参数 | 类型 | 必填 | 说明 |
142 | |------|--------|------|---------------------------------------|
143 | | token| string | 是 | 请求的认证 Token,必填,正确的 token |
144 | | cid | int | 是 | 文章 ID |
145 |
146 | #### 示例请求
147 |
148 | ```bash
149 | GET https://example.com/api.php?method=getcomments&token=123456&cid=123
150 | ```
151 |
152 | #### 响应示例
153 |
154 | 成功响应:
155 |
156 | ```json
157 | {
158 | "success": true,
159 | "data": [
160 | {
161 | "coid": 456,
162 | "author": "评论者",
163 | "content": "这是评论内容",
164 | "created": "2024-12-26 10:05:00",
165 | "parent": 0
166 | }
167 | ]
168 | }
169 | ```
170 |
171 | ---
172 |
173 | ### 4. 获取网站信息 (getbloginfo)
174 |
175 | #### 请求方法
176 | `POST/GET`
177 |
178 | #### 请求参数
179 |
180 | | 参数 | 类型 | 必填 | 说明 |
181 | |------|--------|------|---------------------------------------|
182 | | token| string | 是 | 请求的认证 Token,必填,正确的 token |
183 |
184 | #### 示例请求
185 |
186 | ```bash
187 | GET https://example.com/api.php?method=getbloginfo&token=123456
188 | ```
189 |
190 | #### 响应示例
191 |
192 | 成功响应:
193 |
194 | ```json
195 | {
196 | "success": true,
197 | "data": {
198 | "title": "CC的小窝",
199 | "description": "CC的小窝,记录生活的点点滴滴,分享自己的学习过程和心得。",
200 | "keywords": "小猫咪博客,小猫咪blog,CC的小窝",
201 | "theme": "handsome",
202 | "siteUrl": "https:\/\/lwcat.cn",
203 | "timezone": "28800",
204 | "charset": "UTF-8",
205 | "postCount": "65"
206 | }
207 | }
208 | ```
209 |
210 | ---
211 |
212 | ### 5. 删除文章 (delete)
213 |
214 | #### 请求方法
215 | `POST`
216 |
217 | #### 请求参数
218 |
219 | | 参数 | 类型 | 必填 | 说明 |
220 | |--------|--------|------|-------------------------------------|
221 | | token | string | 是 | 请求的认证 Token,必填,正确的 token |
222 | | cid | int | 是 | 要删除的文章 ID |
223 |
224 | #### 示例请求
225 |
226 | ```bash
227 | POST https://example.com/api.php
228 | Content-Type: application/json
229 |
230 | {
231 | "method": "delete",
232 | "token": "123456",
233 | "cid": 123
234 | }
235 | ```
236 |
237 | #### 响应示例
238 |
239 | 成功响应:
240 |
241 | ```json
242 | {
243 | "success": true,
244 | "message": "文章删除成功"
245 | }
246 | ```
247 |
248 | 失败响应:
249 |
250 | ```json
251 | {
252 | "success": false,
253 | "message": "无效的 token"
254 | }
255 | ```
256 |
257 | ---
258 |
259 | ## 错误响应
260 |
261 | 所有接口都会返回如下格式的错误响应:
262 |
263 | ```json
264 | {
265 | "success": false,
266 | "message": "错误信息"
267 | }
268 | ```
269 |
270 | ### 错误码
271 |
272 | | 错误信息 | 描述 |
273 | |---------------|---------------------------------------|
274 | | `请先到文件设置 token` | Token 未设置或文件为空 |
275 | | `无效的 token` | 请求中携带的 token 不匹配或无效 |
276 | | `文章ID不能为空` | 请求缺少 `cid` 或 `cid` 为无效值 |
277 | | `不支持的请求方法` | 请求方法不支持 |
278 | | `标题和内容不能为空` | 发布文章时,标题和内容不能为空 |
279 |
280 | ---
281 |
282 | ### 6. 备份管理
283 |
284 | #### 6.1 数据库备份 (backup_db)
285 | #### 6.2 文件备份 (backup_files)
286 | #### 6.3 完整备份 (backup_all)
287 |
288 | ##### 请求方法
289 | `GET/POST`
290 |
291 | ##### 请求参数
292 | | 参数 | 类型 | 必填 | 说明 |
293 | |--------|--------|------|------------------------------------|
294 | | token | string | 是 | 请求的认证 Token |
295 | | method | string | 是 | 备份类型:backup_db/backup_files/backup_all |
296 |
297 | ##### 示例请求
298 | ```bash
299 | GET https://example.com/api.php?method=backup_db&token=123456
300 | ```
301 |
302 | ##### 响应示例
303 | ```json
304 | {
305 | "success": true,
306 | "message": "备份完成",
307 | "download_links": [
308 | {
309 | "name": "backup_202308201530_abcd1234.sql",
310 | "url": "https://example.com/backups/backup_202504201530_abcd1234.sql"
311 | }
312 | ]
313 | }
314 | ```
315 |
316 | ---
317 |
318 | ### 7. 标签管理
319 |
320 | #### 7.1 获取全部标签 (getalltags)
321 |
322 | ##### 请求方法
323 | `GET`
324 |
325 | ##### 请求参数
326 | | 参数 | 类型 | 必填 | 说明 |
327 | |--------|--------|------|---------------|
328 | | token | string | 是 | 认证 Token |
329 |
330 | ##### 响应示例
331 | ```json
332 | {
333 | "success": true,
334 | "data": [
335 | {"name": "PHP", "slug": "php"},
336 | {"name": "教程", "slug": "tutorial"}
337 | ]
338 | }
339 | ```
340 |
341 | ---
342 |
343 | ### 8. 分类管理
344 |
345 | #### 8.1 获取全部分类 (getallcategories)
346 |
347 | ##### 请求方法
348 | `GET`
349 |
350 | ##### 请求参数
351 | | 参数 | 类型 | 必填 | 说明 |
352 | |--------|--------|------|---------------|
353 | | token | string | 是 | 认证 Token |
354 |
355 | ##### 响应示例
356 | ```json
357 | {
358 | "success": true,
359 | "data": [
360 | {"name": "技术文章", "slug": "tech", "post_count": 15},
361 | {"name": "生活随笔", "slug": "life", "post_count": 8}
362 | ]
363 | }
364 | ```
365 |
366 | #### 8.2 获取分类文章 (getcategoryposts)
367 |
368 | ##### 请求参数
369 | | 参数 | 类型 | 必填 | 说明 |
370 | |----------|--------|------|------------------------------|
371 | | token | string | 是 | 认证 Token |
372 | | category | string | 是 | 分类名称或缩略名 |
373 | | page | int | 否 | 页码(默认1) |
374 | | pageSize | int | 否 | 每页数量(默认10,最大100) |
375 |
376 | ##### 响应示例
377 | ```json
378 | {
379 | "success": true,
380 | "category_info": {
381 | "name": "技术文章",
382 | "slug": "tech",
383 | "total_posts": 25
384 | },
385 | "data": [
386 | {
387 | "cid": 123,
388 | "title": "PHP编程技巧",
389 | "slug": "php-tips",
390 | "created": "2025-04-20 10:30:00",
391 | "authorId": 1,
392 | "tags": ["PHP", "后端"],
393 | "summary": "本文分享10个实用的PHP编程技巧..."
394 | }
395 | ],
396 | "pagination": {
397 | "total": 25,
398 | "page": 1,
399 | "pageSize": 10,
400 | "totalPages": 3
401 | }
402 | }
403 | ```
404 |
405 | ---
406 |
407 | ### 9. 文章搜索 (search)
408 |
409 | ##### 请求参数
410 | | 参数 | 类型 | 必填 | 说明 |
411 | |----------|--------|------|------------------------------|
412 | | token | string | 是 | 认证 Token |
413 | | keyword | string | 是 | 搜索关键词 |
414 | | page | int | 否 | 页码(默认1) |
415 | | pageSize | int | 否 | 每页数量(默认10,最大100) |
416 |
417 | ##### 响应示例
418 | ```json
419 | {
420 | "success": true,
421 | "keyword": "API",
422 | "data": [
423 | {
424 | "cid": 123,
425 | "title": "TypechoAPI开发指南",
426 | "highlight_title": "Typecho API开发指南",
427 | "slug": "typecho-api",
428 | "created": "2025-04-20 14:30:00",
429 | "authorId": 1,
430 | "tags": ["教程", "开发"],
431 | "summary": "本文详细介绍如何开发Typecho API接口...",
432 | "highlight_summary": "本文详细介绍如何开发Typecho API接口..."
433 | }
434 | ],
435 | "pagination": {
436 | "total": 5,
437 | "page": 1,
438 | "pageSize": 10,
439 | "totalPages": 1
440 | }
441 | }
442 | ```
443 |
444 | ---
445 |
446 | ### 10. 删除备份 (delete_backups)
447 |
448 | ##### 请求方法
449 | `POST`
450 |
451 | ##### 请求参数
452 | | 参数 | 类型 | 必填 | 说明 |
453 | |--------|--------|------|---------------|
454 | | token | string | 是 | 认证 Token |
455 |
456 | ##### 响应示例
457 | ```json
458 | {
459 | "success": true,
460 | "message": "已删除所有备份文件"
461 | }
462 | ```
463 |
464 | ---
465 |
466 | ## 错误码(新增)
467 |
468 | | 错误信息 | 描述 |
469 | |---------------------|-------------------------------|
470 | | `分类不存在` | 指定的分类名称/缩略名不存在 |
471 | | `搜索关键词不能为空` | 未提供搜索关键词 |
472 | | `数据库备份失败` | 执行数据库备份时出现错误 |
473 |
474 | ---
475 |
476 | ## 其他说明
477 |
478 | 1. **Token 设置**
479 | Token 存储在文件中的第 9 行,请按要求修改,禁止为 "123456",确保文件中存在有效的 token,且在请求中正确传递。
480 | 如果文件为空,接口将返回 `请先到文件设置 token` 错误信息。为了你的网站安全,请设置安全的 token 并且妥善保管!
481 |
482 | 2. **分页与限制**
483 | 获取文章列表的接口 (`getarticle`) 支持分页,`page` 和 `pageSize` 参数允许控制返回数据的页码和每页数量。`pageSize` 最大为 50。
484 |
485 | 3. **错误处理**
486 | 所有接口都会返回标准的错误格式,确保你能够捕获并处理错误信息。
487 |
488 | 4. **备份管理注意事项**
489 | - 备份目录位于 `/backups/` 需要777写权限,可在文件中修改地址(建议修改)
490 | - 建议在服务器配置禁止直接访问备份目录
491 | - 大文件备份建议设置 `set_time_limit(0)`,否则容易出现超时问题,尤其是把图片文件都放在博客服务器中的
492 |
493 | 5. **搜索功能优化建议**
494 | - 在MySQL中为contents表创建全文索引
495 | ```sql
496 | CREATE FULLTEXT INDEX idx_search ON typecho_contents(title, text);
497 | ```
498 | - 中文搜索建议使用MySQL 5.7+的ngram分词器
499 |
500 | 6. **分类文章排序逻辑**
501 | - 默认按创建时间倒序排列
502 | - 可通过修改`order`参数实现不同排序方式:
503 | ```php
504 | ->order($table.'.created', Typecho_Db::SORT_DESC) // 修改此处排序条件
505 | ```
506 |
507 | ---
508 |
509 | ## 关于项目
510 |
511 | 最近在搞机器人,就顺手写了这个,接口目前还不多,持续更新中。如果在使用过程中发现问题,欢迎反馈 [yuncat@email.lwcat.cn](mailto:yuncat@email.lwcat.cn)
512 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/api.php:
--------------------------------------------------------------------------------
1 | false,
19 | 'message' => '请先到文件设置 token'
20 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
21 | exit;
22 | }
23 |
24 | $backupDir = __DIR__ . '/backups/';//这个是备份文件保持地址,请自行修改
25 | if (!file_exists($backupDir)) {
26 | mkdir($backupDir, 0755, true);
27 | }
28 |
29 | if (empty($requestToken) || $requestToken !== $token) {
30 | echo json_encode([
31 | 'success' => false,
32 | 'message' => '无效的 token'
33 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
34 | exit;
35 | }
36 |
37 | try {
38 | $db = Typecho_Db::get();
39 | $prefix = $db->getPrefix();
40 | $table = $prefix . 'contents';
41 |
42 | $method = $_REQUEST['method'] ?? '';
43 |
44 | if ($method == 'release') { // 发布文章
45 | $title = isset($_REQUEST['title']) ? trim($_REQUEST['title']) : '';
46 | $content = isset($_REQUEST['content']) ? trim($_REQUEST['content']) : '';
47 | $slug = isset($_REQUEST['slug']) ? trim($_REQUEST['slug']) : '';
48 | $tags = isset($_REQUEST['tags']) ? trim($_REQUEST['tags']) : '';
49 |
50 | if (empty($title) || empty($content)) {
51 | throw new Exception('标题和内容不能为空');
52 | }
53 |
54 | $insertData = [
55 | 'title' => $title,
56 | 'slug' => $slug ?: Typecho_Common::slug($title),
57 | 'created' => time(),
58 | 'modified' => time(),
59 | 'text' => $content,
60 | 'type' => 'post',
61 | 'status' => 'publish',
62 | 'authorId' => 1,
63 | 'allowComment' => 1,
64 | 'allowPing' => 1,
65 | 'allowFeed' => 1,
66 | 'password' => ''
67 | ];
68 |
69 | $db->query($db->insert($table)->rows($insertData));
70 | $cid = $db->lastInsertId();
71 |
72 | if (!empty($tags)) {
73 | $tagList = explode(',', $tags);
74 | foreach ($tagList as $tag) {
75 | $tag = trim($tag);
76 | if (empty($tag)) continue;
77 |
78 | $termQuery = $db->select('mid')->from($prefix . 'metas')
79 | ->where('type = ?', 'tag')
80 | ->where('name = ?', $tag);
81 |
82 | $term = $db->fetchRow($termQuery);
83 |
84 | if (!$term) {
85 | $db->query($db->insert($prefix . 'metas')->rows([
86 | 'name' => $tag,
87 | 'slug' => Typecho_Common::slug($tag),
88 | 'type' => 'tag',
89 | 'count' => 1
90 | ]));
91 | $mid = $db->lastInsertId();
92 | } else {
93 | $mid = $term['mid'];
94 |
95 | $db->query($db->update($prefix . 'metas')
96 | ->rows(['count' => new Typecho_Db_Expression('count + 1')])
97 | ->where('mid = ?', $mid));
98 | }
99 |
100 | $db->query($db->insert($prefix . 'relationships')->rows([
101 | 'cid' => $cid,
102 | 'mid' => $mid
103 | ]));
104 | }
105 | }
106 |
107 | echo json_encode(['success' => true, 'message' => '文章发布成功', 'cid' => $cid],
108 | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
109 |
110 | } elseif ($method == 'getarticle') { // 获取文章
111 | $page = max(1, intval($_REQUEST['page'] ?? 1));
112 | $pageSize = max(1, min(50, intval($_REQUEST['pageSize'] ?? 10)));
113 | $offset = ($page - 1) * $pageSize;
114 |
115 | $totalQuery = $db->select('COUNT(*) AS count')->from($table)
116 | ->where('type = ?', 'post')
117 | ->where('status = ?', 'publish');
118 | $total = $db->fetchRow($totalQuery)['count'];
119 |
120 | $query = $db->select('cid', 'title', 'slug', 'created', 'authorId', 'text')
121 | ->from($table)
122 | ->where('type = ?', 'post')
123 | ->where('status = ?', 'publish')
124 | ->order('created', Typecho_Db::SORT_DESC)
125 | ->limit($pageSize)
126 | ->offset($offset);
127 |
128 | $articles = $db->fetchAll($query);
129 |
130 | if (empty($articles)) {
131 | echo json_encode([
132 | 'success' => true,
133 | 'data' => [],
134 | 'pagination' => [
135 | 'total' => $total,
136 | 'page' => $page,
137 | 'pageSize' => $pageSize
138 | ]
139 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
140 | exit;
141 | }
142 |
143 | $result = [];
144 | foreach ($articles as $article) {
145 | $tagQuery = $db->select('name')->from($prefix . 'metas')
146 | ->join($prefix . 'relationships', $prefix . 'relationships.mid = ' . $prefix . 'metas.mid')
147 | ->where($prefix . 'relationships.cid = ?', $article['cid'])
148 | ->where('type = ?', 'tag');
149 | $tags = $db->fetchAll($tagQuery);
150 |
151 | $result[] = [
152 | 'cid' => $article['cid'],
153 | 'title' => $article['title'],
154 | 'slug' => $article['slug'],
155 | 'created' => date('Y-m-d H:i:s', $article['created']),
156 | 'authorId' => $article['authorId'],
157 | 'tags' => array_column($tags, 'name'),
158 | 'summary' => mb_substr(strip_tags($article['text']), 0, 200) . '...'
159 | ];
160 | }
161 |
162 | echo json_encode([
163 | 'success' => true,
164 | 'data' => $result,
165 | 'pagination' => [
166 | 'total' => $total,
167 | 'page' => $page,
168 | 'pageSize' => $pageSize
169 | ]
170 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
171 |
172 | } elseif ($method == 'getcomments') { // 获取文章评论
173 | $cid = intval($_REQUEST['cid'] ?? 0);
174 | if (!$cid) {
175 | throw new Exception('文章ID不能为空');
176 | }
177 |
178 | $query = $db->select('coid', 'author', 'text', 'created', 'parent')
179 | ->from($prefix . 'comments')
180 | ->where('cid = ?', $cid)
181 | ->where('status = ?', 'approved')
182 | ->order('created', Typecho_Db::SORT_ASC);
183 |
184 | $comments = $db->fetchAll($query);
185 |
186 | $result = [];
187 | foreach ($comments as $comment) {
188 | $result[] = [
189 | 'coid' => $comment['coid'],
190 | 'author' => $comment['author'],
191 | 'content' => $comment['text'],
192 | 'created' => date('Y-m-d H:i:s', $comment['created']),
193 | 'parent' => $comment['parent']
194 | ];
195 | }
196 |
197 | echo json_encode([
198 | 'success' => true,
199 | 'data' => $result
200 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
201 |
202 | } elseif ($method == 'getbloginfo') { // 获取网站信息
203 | $optionsTable = $prefix . 'options';
204 | $options = $db->fetchAll($db->select()->from($optionsTable));
205 |
206 | $optionsMap = [];
207 | foreach ($options as $option) {
208 | $optionsMap[$option['name']] = $option['value'];
209 | }
210 |
211 | $result = [
212 | 'title' => $optionsMap['title'] ?? '',
213 | 'description' => $optionsMap['description'] ?? '',
214 | 'keywords' => $optionsMap['keywords'] ?? '',
215 | 'theme' => $optionsMap['theme'] ?? '',
216 | 'siteUrl' => $optionsMap['siteUrl'] ?? '',
217 | 'timezone' => $optionsMap['timezone'] ?? '',
218 | 'charset' => $optionsMap['charset'] ?? '',
219 | 'postCount' => $db->fetchObject($db->select(['COUNT(*)' => 'num'])
220 | ->from($prefix . 'contents')
221 | ->where('type = ?', 'post')
222 | ->where('status = ?', 'publish'))->num
223 | ];
224 |
225 | echo json_encode([
226 | 'success' => true,
227 | 'data' => $result
228 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
229 |
230 | } elseif ($method == 'delete') { // 删除文章
231 | $cid = intval($_REQUEST['cid'] ?? 0);
232 | if (!$cid) {
233 | throw new Exception('文章ID不能为空');
234 | }
235 |
236 | $deleteArticleQuery = $db->delete($table)->where('cid = ?', $cid);
237 | $db->query($deleteArticleQuery);
238 |
239 | $db->query($db->delete($prefix . 'relationships')->where('cid = ?', $cid));
240 |
241 | $db->query($db->delete($prefix . 'comments')->where('cid = ?', $cid));
242 |
243 | $db->query($db->delete($prefix . 'metas')->where('mid = ?', $cid));
244 |
245 | echo json_encode(['success' => true, 'message' => '文章删除成功'],
246 | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
247 |
248 | } elseif (in_array($method, ['backup_db', 'backup_files', 'backup_all'])) { //备份功能
249 | $backupType = $method;
250 | $timestamp = date('YmdHis');
251 | $randomStr = bin2hex(random_bytes(4));
252 | $backupName = "backup_{$timestamp}_{$randomStr}";
253 |
254 | $backupFiles = [];
255 |
256 | // 备份数据库
257 | if ($backupType == 'backup_db' || $backupType == 'backup_all') {
258 | $dbBackupFile = "{$backupDir}{$backupName}.sql";
259 |
260 | $dbConfig = $db->getConfig(Typecho_Db::READ);
261 | $command = "mysqldump -h{$dbConfig['host']} -u{$dbConfig['user']} -p{$dbConfig['password']} {$dbConfig['database']} > {$dbBackupFile}";
262 | exec($command, $output, $returnVar);
263 |
264 | if ($returnVar !== 0) {
265 | throw new Exception('数据库备份失败');
266 | }
267 | $backupFiles[] = $dbBackupFile;
268 | }
269 |
270 | // 备份文件
271 | if ($backupType == 'backup_files' || $backupType == 'backup_all') {
272 | $zip = new ZipArchive();
273 | $fileBackup = "{$backupDir}{$backupName}.zip";
274 |
275 | if ($zip->open($fileBackup, ZipArchive::CREATE) !== TRUE) {
276 | throw new Exception('无法创建压缩文件');
277 | }
278 |
279 | $files = new RecursiveIteratorIterator(
280 | new RecursiveDirectoryIterator(__DIR__),
281 | RecursiveIteratorIterator::LEAVES_ONLY
282 | );
283 |
284 | foreach ($files as $name => $file) {
285 | if (!$file->isDir() && !str_contains($file->getRealPath(), $backupDir)) {
286 | $filePath = $file->getRealPath();
287 | $relativePath = substr($filePath, strlen(__DIR__) + 1);
288 | $zip->addFile($filePath, $relativePath);
289 | }
290 | }
291 |
292 | $zip->close();
293 | $backupFiles[] = $fileBackup;
294 | }
295 |
296 | $downloadLinks = [];
297 | foreach ($backupFiles as $file) {
298 | $downloadLinks[] = [
299 | 'name' => basename($file),
300 | 'url' => $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . str_replace($_SERVER['DOCUMENT_ROOT'], '', $file)
301 | ];
302 | }
303 |
304 | echo json_encode([
305 | 'success' => true,
306 | 'message' => '备份完成',
307 | 'download_links' => $downloadLinks
308 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
309 |
310 | } elseif ($method == 'delete_backups') { // 删除所有备份
311 | $files = glob($backupDir . '*');
312 | foreach ($files as $file) {
313 | if (is_file($file)) {
314 | unlink($file);
315 | }
316 | }
317 |
318 | echo json_encode([
319 | 'success' => true,
320 | 'message' => '已删除所有备份文件'
321 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
322 |
323 | } elseif ($method == 'getalltags') { // 获取全部标签
324 | $query = $db->select('name', 'slug')
325 | ->from($prefix . 'metas')
326 | ->where('type = ?', 'tag')
327 | ->order('name', Typecho_Db::SORT_ASC);
328 |
329 | $tags = $db->fetchAll($query);
330 |
331 | if (empty($tags)) {
332 | echo json_encode([
333 | 'success' => true,
334 | 'data' => []
335 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
336 | exit;
337 | }
338 |
339 | $result = [];
340 | foreach ($tags as $tag) {
341 | $result[] = [
342 | 'name' => $tag['name'],
343 | 'slug' => $tag['slug']
344 | ];
345 | }
346 |
347 | echo json_encode([
348 | 'success' => true,
349 | 'data' => $result
350 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
351 |
352 | } elseif ($method == 'getallcategories') { // 获取全部分类
353 | $query = $db->select('name', 'slug', 'count')
354 | ->from($prefix . 'metas')
355 | ->where('type = ?', 'category')
356 | ->order('order', Typecho_Db::SORT_ASC)
357 | ->order('name', Typecho_Db::SORT_ASC);
358 |
359 | $categories = $db->fetchAll($query);
360 |
361 | $result = [];
362 | foreach ($categories as $category) {
363 | $result[] = [
364 | 'name' => $category['name'],
365 | 'slug' => $category['slug'],
366 | 'post_count' => (int)$category['count']
367 | ];
368 | }
369 |
370 | echo json_encode([
371 | 'success' => true,
372 | 'data' => $result
373 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
374 | } elseif ($method == 'getcategoryposts') { // 获取分类下文章
375 | $category = trim($_REQUEST['category'] ?? '');
376 | if (empty($category)) {
377 | throw new Exception('分类名称/缩略名不能为空');
378 | }
379 |
380 | $metaQuery = $db->select('mid', 'name', 'slug')
381 | ->from($prefix . 'metas')
382 | ->where('type = ?', 'category')
383 | ->where('(name = ? OR slug = ?)', $category, $category);
384 |
385 | $categoryInfo = $db->fetchRow($metaQuery);
386 |
387 | if (empty($categoryInfo)) {
388 | throw new Exception('指定分类不存在');
389 | }
390 |
391 | $page = max(1, intval($_REQUEST['page'] ?? 1));
392 | $pageSize = max(1, min(100, intval($_REQUEST['pageSize'] ?? 10)));
393 | $offset = ($page - 1) * $pageSize;
394 |
395 | $totalQuery = $db->select(['COUNT(*)' => 'num'])
396 | ->from($table)
397 | ->join($prefix.'relationships', $table.'.cid = '.$prefix.'relationships.cid', Typecho_Db::INNER_JOIN)
398 | ->where($prefix.'relationships.mid = ?', $categoryInfo['mid'])
399 | ->where($table.'.type = ?', 'post')
400 | ->where($table.'.status = ?', 'publish');
401 |
402 | $total = $db->fetchObject($totalQuery)->num;
403 |
404 | $postQuery = $db->select(
405 | $table.'.cid',
406 | $table.'.title',
407 | $table.'.slug',
408 | $table.'.created',
409 | $table.'.authorId',
410 | $table.'.text'
411 | )
412 | ->from($table)
413 | ->join($prefix.'relationships', $table.'.cid = '.$prefix.'relationships.cid', Typecho_Db::INNER_JOIN)
414 | ->where($prefix.'relationships.mid = ?', $categoryInfo['mid'])
415 | ->where($table.'.type = ?', 'post')
416 | ->where($table.'.status = ?', 'publish')
417 | ->order($table.'.created', Typecho_Db::SORT_DESC)
418 | ->limit($pageSize)
419 | ->offset($offset);
420 |
421 | $articles = $db->fetchAll($postQuery);
422 |
423 | $result = [];
424 | foreach ($articles as $article) {
425 | $tagQuery = $db->select('name')
426 | ->from($prefix . 'metas')
427 | ->join($prefix . 'relationships', $prefix . 'relationships.mid = ' . $prefix . 'metas.mid')
428 | ->where($prefix . 'relationships.cid = ?', $article['cid'])
429 | ->where('type = ?', 'tag');
430 | $tags = $db->fetchAll($tagQuery);
431 |
432 | $result[] = [
433 | 'cid' => $article['cid'],
434 | 'title' => $article['title'],
435 | 'slug' => $article['slug'],
436 | 'created' => date('Y-m-d H:i:s', $article['created']),
437 | 'authorId' => $article['authorId'],
438 | 'tags' => array_column($tags, 'name'),
439 | 'summary' => mb_substr(strip_tags($article['text']), 0, 200) . '...'
440 | ];
441 | }
442 |
443 | echo json_encode([
444 | 'success' => true,
445 | 'category_info' => [
446 | 'name' => $categoryInfo['name'],
447 | 'slug' => $categoryInfo['slug'],
448 | 'total_posts' => $total
449 | ],
450 | 'data' => $result,
451 | 'pagination' => [
452 | 'total' => $total,
453 | 'page' => $page,
454 | 'pageSize' => $pageSize,
455 | 'totalPages' => ceil($total / $pageSize)
456 | ]
457 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
458 |
459 | } elseif ($method == 'search') { // 文章搜索功能
460 | $keyword = trim($_REQUEST['keyword'] ?? '');
461 | if (empty($keyword)) {
462 | throw new Exception('搜索关键词不能为空');
463 | }
464 |
465 | $page = max(1, intval($_REQUEST['page'] ?? 1));
466 | $pageSize = max(1, min(100, intval($_REQUEST['pageSize'] ?? 10)));
467 | $offset = ($page - 1) * $pageSize;
468 |
469 | $searchTerm = '%' . str_replace(['%', '_'], ['\%', '\_'], $keyword) . '%';
470 |
471 | $totalQuery = $db->select(['COUNT(*)' => 'num'])
472 | ->from($table)
473 | ->where('type = ?', 'post')
474 | ->where('status = ?', 'publish')
475 | ->where('(title LIKE ? OR text LIKE ?)', $searchTerm, $searchTerm);
476 |
477 | $total = $db->fetchObject($totalQuery)->num;
478 |
479 | $postQuery = $db->select(
480 | 'cid',
481 | 'title',
482 | 'slug',
483 | 'created',
484 | 'authorId',
485 | 'text'
486 | )
487 | ->from($table)
488 | ->where('type = ?', 'post')
489 | ->where('status = ?', 'publish')
490 | ->where('(title LIKE ? OR text LIKE ?)', $searchTerm, $searchTerm)
491 | ->order('created', Typecho_Db::SORT_DESC)
492 | ->limit($pageSize)
493 | ->offset($offset);
494 |
495 | $articles = $db->fetchAll($postQuery);
496 |
497 | $result = [];
498 | foreach ($articles as $article) {
499 | $tagQuery = $db->select('name')
500 | ->from($prefix . 'metas')
501 | ->join($prefix . 'relationships', $prefix . 'relationships.mid = ' . $prefix . 'metas.mid')
502 | ->where($prefix . 'relationships.cid = ?', $article['cid'])
503 | ->where('type = ?', 'tag');
504 | $tags = $db->fetchAll($tagQuery);
505 |
506 | $highlightTitle = str_ireplace(
507 | $keyword,
508 | "{$keyword}",
509 | $article['title']
510 | );
511 |
512 | $summary = mb_substr(strip_tags($article['text']), 0, 200) . '...';
513 | $highlightSummary = preg_replace(
514 | "/$keyword/i",
515 | "$0",
516 | $summary
517 | );
518 |
519 | $result[] = [
520 | 'cid' => $article['cid'],
521 | 'title' => $article['title'],
522 | 'highlight_title' => $highlightTitle,
523 | 'slug' => $article['slug'],
524 | 'created' => date('Y-m-d H:i:s', $article['created']),
525 | 'authorId' => $article['authorId'],
526 | 'tags' => array_column($tags, 'name'),
527 | 'summary' => $summary,
528 | 'highlight_summary' => $highlightSummary
529 | ];
530 | }
531 |
532 | echo json_encode([
533 | 'success' => true,
534 | 'keyword' => $keyword,
535 | 'data' => $result,
536 | 'pagination' => [
537 | 'total' => $total,
538 | 'page' => $page,
539 | 'pageSize' => $pageSize,
540 | 'totalPages' => ceil($total / $pageSize)
541 | ]
542 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
543 |
544 | }else {
545 | throw new Exception('不支持的请求方法');
546 | }
547 |
548 | } catch (Exception $e) {
549 | echo json_encode([
550 | 'success' => false,
551 | 'message' => $e->getMessage()
552 | ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
553 | }
--------------------------------------------------------------------------------