| 1 | <?php |
| 2 | /************************************************************* |
| 3 | # 076 License |
| 4 | |
| 5 | Copyright (c) テクニカル諏訪子 |
| 6 | |
| 7 | Permission is hereby granted to any person obtaining a copy of the software |
| 8 | Little Beast (the "Software") to use, modify, merge, copy, publish, distribute, |
| 9 | sublicense, 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 | |
| 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 32 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 33 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 34 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE |
| 36 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | namespace Std\Lib\Fedi; |
| 39 | |
| 40 | use Std\Lib\Crypto\Rsa; |
| 41 | |
| 42 | /** |
| 43 | * ローカルのユーザーのアクター(鍵、プロフィール、WebFinger、コレクション) |
| 44 | */ |
| 45 | final class Actor { |
| 46 | /** |
| 47 | * ユーザーの秘密鍵(無ければ作る) |
| 48 | * |
| 49 | * @return Rsa|null 作れない・読めない場合はnull |
| 50 | */ |
| 51 | public static function privateKey(string $username): ?Rsa { |
| 52 | $file = Fedi::userPath($username, 'private.pem'); |
| 53 | if (!is_file($file)) { |
| 54 | $lock = fopen($file.'.lock', 'c'); |
| 55 | if ($lock) flock($lock, LOCK_EX); |
| 56 | try { |
| 57 | if (!is_file($file)) { |
| 58 | $key = Rsa::generate(2048); |
| 59 | file_put_contents($file, $key->toPem()); |
| 60 | @chmod($file, 0600); |
| 61 | file_put_contents(Fedi::userPath($username, 'public.pem'), $key->publicPem()); |
| 62 | } |
| 63 | } finally { |
| 64 | if ($lock) { |
| 65 | flock($lock, LOCK_UN); |
| 66 | fclose($lock); |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | try { |
| 71 | $key = Rsa::fromPem((string)file_get_contents($file)); |
| 72 | } catch (\InvalidArgumentException $e) { |
| 73 | logger(\LogType::ActivityPub, "「{$username}」の鍵を読めませんでした:".$e->getMessage()); |
| 74 | return null; |
| 75 | } |
| 76 | return $key->isPrivate() ? $key : null; |
| 77 | } |
| 78 | |
| 79 | public static function publicKeyPem(string $username): ?string { |
| 80 | $file = Fedi::userPath($username, 'public.pem'); |
| 81 | if (!is_file($file) && self::privateKey($username) === null) return null; |
| 82 | return is_file($file) ? (string)file_get_contents($file) : null; |
| 83 | } |
| 84 | |
| 85 | public static function keyId(string $username): string { |
| 86 | return Fedi::actorUrl($username).'#main-key'; |
| 87 | } |
| 88 | |
| 89 | /** ユーザーの設定(locked:フォローを承認制にする) */ |
| 90 | public static function settings(string $username): array { |
| 91 | return Fedi::read(Fedi::userPath($username, 'settings.json'), []) + ['locked' => false]; |
| 92 | } |
| 93 | |
| 94 | public static function saveSettings(string $username, array $settings): void { |
| 95 | Fedi::update(Fedi::userPath($username, 'settings.json'), fn($s) => array_merge($s, $settings)); |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * アクターのJSON-LD |
| 100 | * |
| 101 | * @param \stdClass $user ローカルのユーザー(Fedi::localActor()) |
| 102 | * @return array |
| 103 | */ |
| 104 | public static function document(\stdClass $user): array { |
| 105 | $url = Fedi::actorUrl($user->username); |
| 106 | $avatar = avatar_url($user); |
| 107 | $doc = [ |
| 108 | '@context' => Fedi::CONTEXT, |
| 109 | 'id' => $url, |
| 110 | 'type' => 'Person', |
| 111 | 'preferredUsername' => $user->username, |
| 112 | 'name' => ($user->displayname ?? '') !== '' ? $user->displayname : $user->username, |
| 113 | 'summary' => ($user->bio ?? '') !== '' ? Html::render($user->bio) : '', |
| 114 | 'url' => Fedi::base().'/microblog/user/'.$user->username, |
| 115 | 'inbox' => "{$url}/inbox", |
| 116 | 'outbox' => "{$url}/outbox", |
| 117 | 'followers' => "{$url}/followers", |
| 118 | 'following' => "{$url}/following", |
| 119 | 'endpoints' => ['sharedInbox' => Fedi::sharedInbox()], |
| 120 | 'manuallyApprovesFollowers' => (bool)self::settings($user->username)['locked'], |
| 121 | 'discoverable' => true, |
| 122 | 'published' => Fedi::now((int)($user->regDate ?? time())), |
| 123 | 'icon' => [ |
| 124 | 'type' => 'Image', |
| 125 | 'mediaType' => self::mediaTypeOf($avatar), |
| 126 | 'url' => preg_match('#^https?://#i', $avatar) ? $avatar : Fedi::base().$avatar, |
| 127 | ], |
| 128 | ]; |
| 129 | $pem = self::publicKeyPem($user->username); |
| 130 | if ($pem !== null) $doc['publicKey'] = ['id' => self::keyId($user->username), 'owner' => $url, 'publicKeyPem' => $pem]; |
| 131 | return $doc; |
| 132 | } |
| 133 | |
| 134 | /** |
| 135 | * WebFingerの応答 |
| 136 | * |
| 137 | * @param string $resource acct:ユーザー@ホスト又はアクターのURL |
| 138 | * @return array|null 見つからなければnull |
| 139 | */ |
| 140 | public static function webfinger(string $resource): ?array { |
| 141 | $username = null; |
| 142 | if (preg_match('/^(?:acct:)?@?([A-Za-z0-9]+)@(.+)$/', $resource, $m) && strtolower($m[2]) === strtolower(Fedi::host())) { |
| 143 | $username = $m[1]; |
| 144 | } else { |
| 145 | $username = Fedi::localUsername($resource); |
| 146 | } |
| 147 | if ($username === null || Fedi::localActor($username) === null) return null; |
| 148 | |
| 149 | return [ |
| 150 | 'subject' => "acct:{$username}@".Fedi::host(), |
| 151 | 'aliases' => [Fedi::actorUrl($username), Fedi::base().'/microblog/user/'.$username], |
| 152 | 'links' => [ |
| 153 | ['rel' => 'self', 'type' => 'application/activity+json', 'href' => Fedi::actorUrl($username)], |
| 154 | ['rel' => 'http://webfinger.net/rel/profile-page', 'type' => 'text/html', 'href' => Fedi::base().'/microblog/user/'.$username], |
| 155 | ], |
| 156 | ]; |
| 157 | } |
| 158 | |
| 159 | //////// フォロワーとフォロー |
| 160 | |
| 161 | /** フォロワー(アクターのURL => [inbox, sharedInbox, since]) */ |
| 162 | public static function followers(string $username): array { |
| 163 | return Fedi::read(Fedi::userPath($username, 'followers.json')); |
| 164 | } |
| 165 | |
| 166 | /** フォロー(アクターのURL => [state(pending/accepted), id, since]) */ |
| 167 | public static function following(string $username): array { |
| 168 | return Fedi::read(Fedi::userPath($username, 'following.json')); |
| 169 | } |
| 170 | |
| 171 | /** 承認待ちのフォローリクエスト(アクターのURL => [activity, at]) */ |
| 172 | public static function requests(string $username): array { |
| 173 | return Fedi::read(Fedi::userPath($username, 'requests.json')); |
| 174 | } |
| 175 | |
| 176 | public static function isFollowing(string $username, string $actor): bool { |
| 177 | return (self::following($username)[$actor]['state'] ?? '') === 'accepted'; |
| 178 | } |
| 179 | |
| 180 | public static function isFollowedBy(string $username, string $actor): bool { |
| 181 | return isset(self::followers($username)[$actor]); |
| 182 | } |
| 183 | |
| 184 | /** |
| 185 | * フォロワー・フォローのOrderedCollection(一覧は公開しない。数だけ) |
| 186 | */ |
| 187 | public static function collection(string $username, string $which): array { |
| 188 | $list = $which === 'followers' ? self::followers($username) |
| 189 | : array_filter(self::following($username), fn($f) => ($f['state'] ?? '') === 'accepted'); |
| 190 | return [ |
| 191 | '@context' => 'https://www.w3.org/ns/activitystreams', |
| 192 | 'id' => Fedi::actorUrl($username)."/{$which}", |
| 193 | 'type' => 'OrderedCollection', |
| 194 | 'totalItems' => count($list), |
| 195 | ]; |
| 196 | } |
| 197 | |
| 198 | //////// ブロック |
| 199 | |
| 200 | /** ブロック(actors:アクターのURL、domains:ドメイン) */ |
| 201 | public static function blocks(string $username): array { |
| 202 | return Fedi::read(Fedi::userPath($username, 'blocks.json')) + ['actors' => [], 'domains' => []]; |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * このユーザー(又はサイト全体)がブロックしているか |
| 207 | */ |
| 208 | public static function isBlocked(string $username, string $actor): bool { |
| 209 | if (self::isDomainBlocked($actor)) return true; |
| 210 | $b = self::blocks($username); |
| 211 | return in_array($actor, $b['actors'], true) || in_array(Fedi::domainOf($actor), $b['domains'], true); |
| 212 | } |
| 213 | |
| 214 | /** サイト全体でブロックしているドメイン(管理者) */ |
| 215 | public static function blockedDomains(): array { |
| 216 | return Fedi::read(Fedi::path('blocked_domains.json')); |
| 217 | } |
| 218 | |
| 219 | public static function isDomainBlocked(string $url): bool { |
| 220 | $d = Fedi::domainOf($url); |
| 221 | if ($d === '') return false; |
| 222 | foreach (self::blockedDomains() as $b) { |
| 223 | if ($d === $b || str_ends_with($d, '.'.$b)) return true; |
| 224 | } |
| 225 | return false; |
| 226 | } |
| 227 | |
| 228 | //////// 通知 |
| 229 | |
| 230 | /** |
| 231 | * 通知を追加する(新しい順、200件まで) |
| 232 | * |
| 233 | * @param string $username ユーザー |
| 234 | * @param string $type follow, follow_request, mention, reply, like, boost |
| 235 | * @param string $actor 誰から |
| 236 | * @param string|null $object 対象の投稿 |
| 237 | */ |
| 238 | public static function notify(string $username, string $type, string $actor, ?string $object = null): void { |
| 239 | Fedi::update(Fedi::userPath($username, 'notifications.json'), function(array $list) use ($type, $actor, $object): array { |
| 240 | // 同じ通知を重複させない |
| 241 | foreach ($list as $n) { |
| 242 | if ($n['type'] === $type && $n['actor'] === $actor && ($n['object'] ?? null) === $object && $n['at'] > time() - 3600) return $list; |
| 243 | } |
| 244 | array_unshift($list, ['type' => $type, 'actor' => $actor, 'object' => $object, 'at' => time(), 'read' => false]); |
| 245 | return array_slice($list, 0, 200); |
| 246 | }); |
| 247 | } |
| 248 | |
| 249 | public static function notifications(string $username): array { |
| 250 | return Fedi::read(Fedi::userPath($username, 'notifications.json')); |
| 251 | } |
| 252 | |
| 253 | public static function unreadCount(string $username): int { |
| 254 | return count(array_filter(self::notifications($username), fn($n) => !$n['read'])); |
| 255 | } |
| 256 | |
| 257 | public static function markRead(string $username): void { |
| 258 | Fedi::update(Fedi::userPath($username, 'notifications.json'), fn($l) => array_map(fn($n) => ['read' => true] + $n, $l)); |
| 259 | } |
| 260 | |
| 261 | ////// |
| 262 | |
| 263 | private static function mediaTypeOf(string $path): string { |
| 264 | return match (strtolower(pathinfo($path, PATHINFO_EXTENSION))) { |
| 265 | 'png' => 'image/png', |
| 266 | 'gif' => 'image/gif', |
| 267 | 'webp' => 'image/webp', |
| 268 | default => 'image/jpeg', |
| 269 | }; |
| 270 | } |
| 271 | } |