master
ブランチ master
LittleBeast / src / Site / Controller / Comment.php
8.1 KB、217行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Site\Controller;
39
40use Site\Controller\BlogPost;
41use Site\Controller\Mods;
42use Std\Lib\Activitypub;
43use Std\Lib\Auth;
44use Std\Lib\Comments;
45use Std\Lib\Template;
46
47/**
48 * 記事のコメントの投稿・いいね・削除(POST)と通知のページ
49 */
50class Comment extends BlogPost {
51 use Mods;
52
53 private ?\stdClass $user;
54
55 public function __construct() {
56 $this->user = (new Auth())->getLoggedInUser();
57 }
58
59 /**
60 * コメントする(POST /comments)
61 * thread:スレッド、parent:返信先のコメント、body:本文(Markdown)
62 *
63 * @param array $params パラメータ配列
64 * @return void
65 */
66 public function post(array $params): void {
67 $user = $this->requireUser();
68 $thread = (string)($_POST['thread'] ?? '');
69 $parent = (string)($_POST['parent'] ?? '');
70 $body = (string)($_POST['body'] ?? '');
71
72 $title = $this->commentable($thread);
73 if ($title === null) $this->notFound();
74
75 if (!$this->csrfOk()) {
76 $error = 'セッションの有効期限が切れました。もう一度送信して下さい。';
77 } else {
78 $res = Comments::addLocal($thread, $title, $user, $body, $parent === '' ? null : $parent, $this->postNote($thread));
79 if ($res->isSuccess) $this->redirect('/'.$thread.'#c-'.$res->data['id']);
80 $error = $res->message;
81 }
82
83 // 失敗:入力した内容を残して表示する
84 $this->render('comment', 'コメント', [
85 'error' => $error,
86 'thread' => $thread,
87 'title' => $title,
88 'parent' => $parent,
89 'body' => $body,
90 'maxLength' => Comments::MAX_LENGTH,
91 ]);
92 }
93
94 /**
95 * いいね・いいねの取り消し(POST /comments/like)
96 *
97 * @param array $params パラメータ配列
98 * @return void
99 */
100 public function like(array $params): void {
101 [$user, $thread, $id] = $this->target();
102 $res = Comments::like($thread, $id, $user);
103 if (!$res->isSuccess) $this->message($res->message, '/'.$thread.'#comments');
104 $this->redirect('/'.$thread.'#c-'.$id);
105 }
106
107 /**
108 * コメントを削除する(POST /comments/delete、本人又は管理者)
109 *
110 * @param array $params パラメータ配列
111 * @return void
112 */
113 public function delete(array $params): void {
114 [$user, $thread, $id] = $this->target();
115 $res = Comments::delete($thread, $id, $user);
116 if (!$res->isSuccess) $this->message($res->message, '/'.$thread.'#comments');
117 $this->redirect('/'.$thread.'#comments');
118 }
119
120 /**
121 * 通知(GET /notifications)。管理者には新しいコメント、全員には自分のコメントへの返信といいね
122 *
123 * @param array $params パラメータ配列
124 * @return void
125 */
126 public function notifications(array $params): void {
127 $user = $this->requireUser();
128 $list = array_map(fn($n) => Comments::present($n), \Std\Lib\Notifications::list($user->username));
129 \Std\Lib\Notifications::markRead($user->username);
130 $this->render('notifications', '通知', ['list' => $list]);
131 }
132
133 //////
134
135 /**
136 * コメント出来る記事か(記事が存在し、このユーザーが読める)
137 *
138 * @param string $thread スレッド(「blog/記事」等)
139 * @return string|null 記事のタイトル、コメント出来なければnull
140 */
141 private function commentable(string $thread): ?string {
142 if (!Comments::validThread($thread)) return null;
143 $parts = explode('/', $thread);
144 if (count($parts) !== 2 || !isset(blogs()[$parts[0]])) return null;
145 foreach ($this->getPosts("/{$parts[0]}/", $this->user) as $post) {
146 // 会員限定等で読めない記事にはコメント出来ない
147 if ($post['slug'] === $parts[1]) return $post['preview'] === '未許可' ? null : (string)$post['title'];
148 }
149 return null;
150 }
151
152 /**
153 * 連合するブログの記事のNote(Fediverseのロールを持つユーザーのコメントを、記事への返信として送る為)
154 *
155 * @param string $thread スレッド
156 * @return array|null 連合しない記事(勉強会、会員限定等)ならnull
157 */
158 private function postNote(string $thread): ?array {
159 [$section, $slug] = array_pad(explode('/', $thread, 2), 2, '');
160 if (!ACTIVITYPUB_ENABLED || !(blogs()[$section]['federate'] ?? false)) return null;
161 foreach ($this->getPosts("/{$section}/", null) as $post) {
162 if ($post['slug'] !== $slug) continue;
163 $json = (new Activitypub([$post + ['section' => $section]]))->getObject((string)$post['uuid'], $section);
164 return $json !== '' ? json_decode($json, true) : null;
165 }
166 return null;
167 }
168
169 /** いいね・削除の対象(ログイン、CSRF、記事を確認する) */
170 private function target(): array {
171 $user = $this->requireUser();
172 $thread = (string)($_POST['thread'] ?? '');
173 $id = (string)($_POST['id'] ?? '');
174 if ($this->commentable($thread) === null) $this->notFound();
175 if (!$this->csrfOk()) $this->message('セッションの有効期限が切れました。前のページに戻って、もう一度お試し下さい。', '/'.$thread.'#comments');
176 return [$user, $thread, $id];
177 }
178
179 private function requireUser(): \stdClass {
180 if ($this->user === null) $this->redirect('/login');
181 return $this->user;
182 }
183
184 private function csrfOk(): bool {
185 return is_string($_POST['csrf_token'] ?? null) && verify_csrf_token($_POST['csrf_token']);
186 }
187
188 private function redirect(string $to): never {
189 header('Location: '.$to);
190 exit;
191 }
192
193 private function notFound(): never {
194 header('Location: /404');
195 exit;
196 }
197
198 private function message(string $msg, string $back): never {
199 $this->render('comment', 'コメント', ['error' => $msg, 'back' => $back]);
200 exit;
201 }
202
203 private function render(string $view, string $title, array $vars): void {
204 $tmpl = new Template('/');
205 $tmpl->assign('pagetit', $title);
206 $tmpl->assign('curPage', 'comments');
207 $tmpl->assign('custCss', false);
208 $tmpl->assign('menu', $this->getMenu());
209 $tmpl->assign('description', SITEINFO['description']);
210 $tmpl->assign('user', $this->user);
211 // クッキーはテンプレートの出力の前に設定する
212 $tmpl->assign('csrf', make_csrf_token());
213 foreach ($vars as $k => $v) $tmpl->assign($k, $v);
214 $tmpl->addCss('comments');
215 $tmpl->render($view);
216 }
217}