user = (new Auth())->getLoggedInUser();
if ($this->user && can_federate($this->user) && (($this->user->verified ?? true) !== false)) $this->me = $this->user->username;
}
//////// タイムライン
public function home(array $params): void {
if ($this->me === null) $this->redirect('/microblog/local');
$this->timeline('home', 'ホーム');
}
public function local(array $params): void {
$this->timeline('local', 'ローカル');
}
public function federated(array $params): void {
$this->timeline('federated', '連合');
}
public function tag(array $params): void {
$tag = mb_strtolower((string)($params['tag'] ?? ''));
[$items, $next] = Timeline::query('tag', $this->me, ['tag' => $tag, 'before' => $this->before()]);
$this->render('microblog/timeline', "#{$tag}", [
'scope' => 'tag',
'heading' => "#{$tag}",
'items' => $this->present($items),
'next' => $next !== null ? "/microblog/tag/".rawurlencode($tag)."?before={$next}" : null,
]);
}
private function timeline(string $scope, string $title): void {
[$items, $next] = Timeline::query($scope, $this->me, ['before' => $this->before()]);
$path = $scope === 'home' ? '/microblog' : "/microblog/{$scope}";
$this->render('microblog/timeline', $title, [
'scope' => $scope,
'heading' => $title,
'items' => $this->present($items),
'next' => $next !== null ? "{$path}?before={$next}" : null,
'replyTo' => null,
]);
}
//////// プロフィール
/** ローカルのユーザーの投稿(/microblog/user/{name}) */
public function user(array $params): void {
$name = (string)($params['name'] ?? '');
$u = Fedi::localActor($name);
if (!$u) $this->notFound();
$url = Fedi::actorUrl($name);
[$items, $next] = Timeline::query('user', $this->me, ['user' => $name, 'before' => $this->before()]);
$this->render('microblog/profile', $u->displayname ?: $u->username, [
'profile' => [
'url' => $url,
'name' => $u->displayname ?: $u->username,
'color' => namecolor($u),
'handle' => "@{$name}@".Fedi::host(),
'avatar' => avatar_url($u),
'bio' => ($u->bio ?? '') !== '' ? Html::render($u->bio) : '',
'local' => true,
'profilePage' => "/profile/{$name}",
'locked' => (bool)Actor::settings($name)['locked'],
'followers' => count(Actor::followers($name)),
'following' => count(array_filter(Actor::following($name), fn($f) => $f['state'] === 'accepted')),
],
'relation' => $this->relation($url),
'items' => $this->present($items),
'next' => $next !== null ? "/microblog/user/{$name}?before={$next}" : null,
]);
}
/** リモートのアクター(/microblog/remote?actor=URL)。送信ボックスから最近の投稿を取得する */
public function remote(array $params): void {
$url = (string)($_GET['actor'] ?? '');
$local = Fedi::localUsername($url);
if ($local !== null) $this->redirect("/microblog/user/{$local}");
if ($url === Fedi::blogActorUrl()) $this->blogActor();
if (!Remote::isSafeUrl($url) || Actor::isDomainBlocked($url)) $this->notFound();
// 他のサーバーへの問い合わせはログインしたユーザーだけ(誰でも取得させられると、踏み台にされる)
$doc = $this->me !== null ? Remote::actor($url, isset($_GET['refresh'])) : Remote::cachedActor($url);
if (!$doc) $this->notFound();
$items = [];
$notes = $this->me !== null ? Remote::outbox($doc) : [];
if ($notes && Actor::isFollowing($this->me, $url)) foreach ($notes as $obj) Timeline::add($obj);
foreach ($notes as $obj) {
$items[] = ['entry' => ['type' => 'note', 'actor' => $url, 'object' => $obj['id']], 'object' => $obj];
}
$this->render('microblog/profile', (string)($doc['name'] ?? $doc['preferredUsername'] ?? ''), [
'profile' => [
'url' => $url,
'name' => $rname = (string)(($doc['name'] ?? '') ?: ($doc['preferredUsername'] ?? '')),
'color' => htmlspecialchars($rname, ENT_QUOTES, 'UTF-8'),
'handle' => Remote::handle($doc),
'avatar' => Remote::imageUrl(self::safeUrl($doc['icon']['url'] ?? (is_string($doc['icon'] ?? null) ? $doc['icon'] : ''))) ?: ass_url('user/noicon.png'),
'bio' => Html::sanitize((string)($doc['summary'] ?? '')),
'local' => false,
'profilePage' => self::safeUrl(is_string($doc['url'] ?? null) ? $doc['url'] : ''),
'locked' => (bool)($doc['manuallyApprovesFollowers'] ?? false),
'followers' => null,
'following' => null,
],
'relation' => $this->relation($url),
'items' => $this->present($items),
'next' => null,
]);
}
/**
* このサイトのブログのアカウント(FEDIINFOのactor)のプロフィール
* 記事はブログで読むので投稿は表示せず、マイクロブログからはフォロー出来ない(Social::follow)
*/
private function blogActor(): never {
try {
$doc = Remote::actor(Fedi::blogActorUrl());
} catch (\Exception $e) {
$doc = null; // 公開鍵が読めない等
}
if (!$doc) $this->notFound();
$this->render('microblog/profile', (string)($doc['name'] ?? $doc['preferredUsername'] ?? ''), [
'profile' => [
'url' => $doc['id'],
'name' => $name = (string)(($doc['name'] ?? '') ?: ($doc['preferredUsername'] ?? '')),
'color' => htmlspecialchars($name, ENT_QUOTES, 'UTF-8'),
'handle' => Remote::handle($doc),
'avatar' => self::safeUrl(is_string($doc['icon']['url'] ?? null) ? $doc['icon']['url'] : '') ?: ass_url('user/noicon.png'),
'bio' => Html::sanitize((string)($doc['summary'] ?? '')),
'local' => true,
'profilePage' => '',
'locked' => false,
'followers' => null,
'following' => null,
],
'relation' => ['self' => false, 'can' => false],
'blogActor' => true,
'items' => [],
'next' => null,
]);
exit;
}
//////// 投稿のページ
/** 投稿とスレッド(/microblog/note?id=URL) */
public function note(array $params): void {
$id = (string)($_GET['id'] ?? '');
$obj = $this->visibleObject($id);
if (!$obj) $this->notFound();
// 返信先を辿る(5件まで)
$ancestors = [];
$parent = Fedi::id($obj['inReplyTo'] ?? null);
for ($i = 0; $i < 5 && $parent !== null; $i++) {
$p = $this->visibleObject($parent, $this->me !== null);
if (!$p) break;
array_unshift($ancestors, ['entry' => ['type' => 'note', 'actor' => Fedi::id($p['attributedTo']), 'object' => $p['id']], 'object' => $p]);
$parent = Fedi::id($p['inReplyTo'] ?? null);
}
$replies = [];
foreach (Timeline::replies($obj['id']) as $e) {
if (!Timeline::canSee($this->me, $e)) continue;
if ($this->me && Actor::isBlocked($this->me, $e['author'])) continue;
$r = Timeline::object($e['object']);
if ($r) $replies[] = ['entry' => $e, 'object' => $r];
}
$item = $this->present([['entry' => ['type' => 'note', 'actor' => Fedi::id($obj['attributedTo']), 'object' => $obj['id']], 'object' => $obj]])[0];
// 返信の初期値:相手と、メンションされた人
$mention = '';
if ($this->me) {
$handles = [];
$authorDoc = Remote::cachedActor($item['author']['url']);
if ($authorDoc && $item['author']['url'] !== Fedi::actorUrl($this->me)) $handles[] = Remote::handle($authorDoc);
foreach ($obj['tag'] ?? [] as $t) {
if (is_array($t) && ($t['type'] ?? '') === 'Mention' && ($t['href'] ?? '') !== Fedi::actorUrl($this->me) && is_string($t['name'] ?? null)) {
$n = str_contains(ltrim($t['name'], '@'), '@') ? $t['name'] : $t['name'].'@'.Fedi::domainOf((string)$t['href']);
$handles[] = '@'.ltrim($n, '@');
}
}
$handles = array_unique(array_map(fn($h) => preg_replace('/@'.preg_quote(Fedi::host(), '/').'$/', '', $h), $handles));
$mention = $handles ? implode(' ', $handles).' ' : '';
}
$this->render('microblog/note', Html::text((string)($obj['summary'] ?? '') ?: (string)($obj['content'] ?? ''), 30), [
'ancestors' => $this->present($ancestors),
'item' => $item,
'replies' => $this->present($replies),
'replyTo' => $obj['id'],
'replyText' => $mention,
'replyVis' => $item['visKey'] === 'direct' ? 'direct' : ($item['visKey'] === 'followers' ? 'followers' : 'public'),
]);
}
/** 自分の投稿の編集(GET /microblog/edit?id=) */
public function edit(array $params): void {
$this->requireMe();
$note = Notes::get((string)($_GET['id'] ?? $_POST['id'] ?? ''));
if (!$note || $note['author'] !== $this->me) $this->notFound();
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!$this->csrfOk()) {
$error = 'セッションの有効期限が切れました。もう一度送信して下さい。';
$note['source'] = (string)($_POST['content'] ?? $note['source']);
} else {
$res = Social::edit($this->me, $note['id'], (string)($_POST['content'] ?? ''), (string)($_POST['cw'] ?? ''));
if ($res->isSuccess) $this->redirect('/microblog/note?id='.rawurlencode(Notes::url($note)));
$error = $res->message;
$note['source'] = (string)($_POST['content'] ?? '');
$note['summary'] = (string)($_POST['cw'] ?? '');
}
}
$this->render('microblog/edit', '投稿の編集', ['note' => $note, 'error' => $error]);
}
//////// 投稿と操作
/** 投稿する(POST /microblog/post、multipart/form-data) */
public function post(array $params): void {
$this->requireMe();
$text = (string)($_POST['content'] ?? '');
$back = safe_local_path($_POST['back'] ?? '', '/microblog');
$error = '';
if (empty($_POST) && (int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 0) {
$error = '送信したファイルが大き過ぎます(サーバーの上限を超えました)。';
} else if (!$this->csrfOk()) {
$error = 'セッションの有効期限が切れました。もう一度送信して下さい。';
} else {
// 添付
$media = [];
$files = $_FILES['media'] ?? null;
if (is_array($files) && is_array($files['name'] ?? null)) {
foreach ($files['name'] as $i => $name) {
if (($files['error'][$i] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) continue;
if (count($media) >= Fedi::MAX_ATTACHMENTS) break;
$one = ['name' => $name, 'tmp_name' => $files['tmp_name'][$i], 'size' => $files['size'][$i], 'error' => $files['error'][$i]];
$res = Media::save($one, 'media/'.$this->me, video: true);
if (!$res->isSuccess) {
$error = $res->message;
break;
}
$media[] = $res->data;
}
}
if ($error === '') {
$res = Social::post($this->me, $text, [
'cw' => (string)($_POST['cw'] ?? ''),
'visibility' => (string)($_POST['visibility'] ?? 'public'),
'inReplyTo' => (string)($_POST['inReplyTo'] ?? ''),
'media' => $media,
'alts' => array_map('strval', (array)($_POST['alt'] ?? [])),
]);
if ($res->isSuccess) $this->redirect($back);
$error = $res->message;
}
foreach ($media ?? [] as $m) Media::remove($m['path']);
}
// 失敗:入力した内容を残して表示する
[$items, $next] = Timeline::query('home', $this->me);
$this->render('microblog/timeline', 'ホーム', [
'scope' => 'home',
'heading' => 'ホーム',
'items' => $this->present($items),
'next' => null,
'error' => $error,
'draft' => $text,
'draftCw' => (string)($_POST['cw'] ?? ''),
'replyTo' => (string)($_POST['inReplyTo'] ?? '') ?: null,
]);
}
/**
* いいね・ブースト・削除・フォロー・ブロック等(POST /microblog/action)
* do:操作、target:投稿又はアクターのURL、back:戻るページ
*/
public function action(array $params): void {
$this->requireMe();
$back = safe_local_path($_POST['back'] ?? '', '/microblog');
if (!$this->csrfOk()) $this->message('セッションの有効期限が切れました。前のページに戻って、もう一度お試し下さい。', $back);
$do = (string)($_POST['do'] ?? '');
$target = trim((string)($_POST['target'] ?? ''));
$me = $this->me;
$res = match ($do) {
'like' => Social::like($me, $target),
'unlike' => Social::unlike($me, $target),
'boost' => Social::boost($me, $target),
'unboost' => Social::unboost($me, $target),
'delete' => ($ids = Fedi::localNoteId($target)) ? Social::delete($me, $ids[1]) : \Result::Error('投稿が見つかりません。'),
'follow' => Social::follow($me, $target),
'unfollow' => Social::unfollow($me, $target),
'accept' => Social::answerRequest($me, $target, true),
'reject' => Social::answerRequest($me, $target, false),
'removefollower' => Social::removeFollower($me, $target),
'block' => Social::block($me, $target),
'unblock' => Social::unblock($me, $target),
'blockdomain' => Social::blockDomain($me, $target, true),
'unblockdomain' => Social::blockDomain($me, $target, false),
'report' => Social::report($me, $target, array_values(array_filter([(string)($_POST['object'] ?? '')])),
(string)($_POST['comment'] ?? ''), isset($_POST['forward'])),
default => \Result::Error('不明な操作です。'),
};
// 削除した投稿のページには戻れない
if ($do === 'delete' && str_starts_with($back, '/microblog/note')) $back = '/microblog';
if (!$res->isSuccess) $this->message((string)$res->message, $back);
$this->redirect($back);
}
//////// 検索
/**
* 検索(/microblog/search?q=)
* 「@user@host」・URL:アカウントか投稿を探し、見つかればそのページへ
* 「#タグ」:タグのページへ
* それ以外:ローカルと受け取った投稿の本文を検索する
*/
public function search(array $params): void {
$q = trim((string)($_GET['q'] ?? ''));
$items = [];
$error = '';
if ($q !== '') {
if (preg_match('/^#([\p{L}\p{N}_]+)$/u', $q, $m)) $this->redirect('/microblog/tag/'.rawurlencode(mb_strtolower($m[1])));
$isLocalHandle = (bool)preg_match('/^@[A-Za-z0-9]+$/', $q);
if ($isLocalHandle || preg_match('/^@?[A-Za-z0-9_.-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/', $q)) {
// 他のサーバーへの問い合わせはログインしたユーザーだけ
$url = $this->me !== null || $isLocalHandle ? Remote::resolve($q) : null;
if ($url !== null) $this->redirect($this->actorPage($url));
$error = $this->me === null ? '他のサーバーのアカウントを探すにはログインして下さい。' : 'アカウントが見つかりません。';
} else if (preg_match('#^https://#', $q)) {
if ($this->me === null) {
$error = '他のサーバーを検索するにはログインして下さい。';
} else if (($doc = Remote::actor($q)) !== null) {
$this->redirect($this->actorPage($doc['id']));
} else if (($obj = Remote::object($q)) !== null && in_array($obj['type'] ?? '', ['Note', 'Article', 'Question', 'Page'], true)) {
// 見つけた投稿は保存し、いいね・ブースト・返信が出来る様にする
if (!Fedi::isLocal($obj['id'])) {
Remote::store($obj);
Timeline::add($obj);
Remote::actor((string)Fedi::id($obj['attributedTo'] ?? null));
}
$this->redirect('/microblog/note?id='.rawurlencode($obj['id']));
} else {
$error = '見つかりません。';
}
} else {
$items = Timeline::search($q, $this->me);
if (empty($items)) $error = '見つかりません。';
}
}
$this->render('microblog/search', '検索', ['q' => $q, 'items' => $this->present($items), 'error' => $error]);
}
//////// 通知・ブロック・管理
public function notifications(array $params): void {
$this->requireMe();
$list = [];
foreach (Actor::notifications($this->me) as $n) {
$a = $this->who($n['actor']);
$obj = $n['object'] ? Timeline::object($n['object']) : null;
$list[] = [
'type' => $n['type'],
'label' => ['follow' => 'があなたをフォローしました', 'follow_request' => 'がフォローをリクエストしました',
'mention' => 'があなたをメンションしました', 'reply' => 'が返信しました',
'like' => 'がいいねしました', 'boost' => 'がブーストしました'][$n['type']] ?? $n['type'],
'who' => $a,
'object' => $n['object'],
'page' => $n['object'] ? '/microblog/note?id='.rawurlencode($n['object']) : null,
'excerpt' => $obj ? Html::text((string)($obj['content'] ?? ''), 80) : '',
'at' => date('Y-m-d H:i', $n['at']),
'read' => $n['read'],
];
}
$requests = [];
foreach (Actor::requests($this->me) as $actor => $r) $requests[] = ['who' => $this->who($actor), 'actor' => $actor];
Actor::markRead($this->me);
$this->render('microblog/notifications', '通知', ['list' => $list, 'requests' => $requests]);
}
public function blocks(array $params): void {
$this->requireMe();
$b = Actor::blocks($this->me);
$this->render('microblog/blocks', 'ブロック', [
'actors' => array_map(fn($a) => ['actor' => $a, 'who' => $this->who($a)], $b['actors']),
'domains' => $b['domains'],
]);
}
public function follows(array $params): void {
$this->requireMe();
$following = [];
foreach (array_reverse(Actor::following($this->me), true) as $a => $f) {
$following[] = ['actor' => $a, 'who' => $this->who($a), 'pending' => ($f['state'] ?? '') !== 'accepted'];
}
$this->render('microblog/follows', 'フォロー', [
'scope' => 'follows',
'following' => $following,
'followers' => array_map(fn($a) => ['actor' => $a, 'who' => $this->who($a)], array_reverse(array_keys(Actor::followers($this->me)))),
]);
}
/** 管理(サイト全体のドメインのブロック、通報)。管理者だけ */
public function admin(array $params): void {
if (!$this->user || !($this->user->role & Roles::ADMIN)) $this->notFound();
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!$this->csrfOk()) {
$error = 'セッションの有効期限が切れました。もう一度お試し下さい。';
} else {
$do = (string)($_POST['do'] ?? '');
$res = match ($do) {
'blockinstance' => Social::blockInstance((string)($_POST['domain'] ?? ''), true),
'unblockinstance' => Social::blockInstance((string)($_POST['domain'] ?? ''), false),
'resolve' => (function() { Social::resolveReport((string)($_POST['id'] ?? '')); return \Result::Success(); })(),
default => \Result::Error('不明な操作です。'),
};
if ($res->isSuccess) $this->redirect('/microblog/admin');
$error = (string)$res->message;
}
}
$reports = [];
foreach (Social::reports() as $r) {
$reports[] = $r + ['fromWho' => $this->who($r['from']), 'actorWho' => $this->who($r['actor']), 'at' => date('Y-m-d H:i', $r['at']),
'objectPages' => array_map(fn($o) => '/microblog/note?id='.rawurlencode($o), $r['objects'])];
}
$this->render('microblog/admin', 'Fediverseの管理', [
'domains' => Actor::blockedDomains(),
'reports' => $reports,
'queue' => Delivery::pending(),
'error' => $error,
]);
}
//////// 表示用
/**
* タイムラインの項目をテンプレート用の配列にする
*
* @param array $items ['entry' => 行, 'object' => Note]
* @return array
*/
private function present(array $items): array {
$out = [];
$likes = $this->me ? Fedi::read(Fedi::userPath($this->me, 'likes.json')) : [];
$boosts = $this->me ? Fedi::read(Fedi::userPath($this->me, 'boosts.json')) : [];
foreach ($items as ['entry' => $e, 'object' => $o]) {
$id = (string)$o['id'];
$authorUrl = (string)Fedi::id($o['attributedTo'] ?? null);
$to = Fedi::ids($o['to'] ?? []);
$cc = Fedi::ids($o['cc'] ?? []);
$vis = Fedi::visibility($to, $cc, Fedi::isLocal($authorUrl) ? $authorUrl.'/followers' : null);
$local = Fedi::localNoteId($id);
$note = $local ? Notes::get($local[1]) : null;
$attachments = [];
foreach ((array)($o['attachment'] ?? []) as $a) {
if (!is_array($a)) continue;
$url = self::safeUrl(is_string($a['url'] ?? null) ? $a['url'] : (string)($a['url'][0]['href'] ?? ''));
if ($url === '') continue;
$mt = (string)($a['mediaType'] ?? '');
$kind = str_starts_with($mt, 'video/') ? 'video' : (str_starts_with($mt, 'audio/') ? 'audio'
: (str_starts_with($mt, 'image/') || ($a['type'] ?? '') === 'Image' ? 'image' : 'link'));
$attachments[] = ['url' => $url, 'src' => $kind === 'image' ? Remote::imageUrl($url) : $url, 'alt' => (string)($a['name'] ?? ''), 'kind' => $kind];
}
$out[] = [
'id' => $id,
'page' => '/microblog/note?id='.rawurlencode($id),
'original' => self::safeUrl(is_string($o['url'] ?? null) ? $o['url'] : $id),
'author' => $this->who($authorUrl),
'booster' => ($e['type'] ?? '') === 'boost' ? $this->who($e['actor']) : null,
'content' => $this->localMentionLinks(Html::sanitize((string)($o['content'] ?? '')), $o),
'summary' => (string)($o['summary'] ?? ''),
'sensitive' => (bool)($o['sensitive'] ?? false) || ($o['summary'] ?? '') !== '',
'attachments' => $attachments,
'published' => date('Y-m-d H:i', strtotime((string)($o['published'] ?? '')) ?: time()),
'edited' => !empty($o['updated']),
'visKey' => $vis,
'vis' => Social::VISIBILITIES[$vis],
'reply' => ($r = Fedi::id($o['inReplyTo'] ?? null)) ? '/microblog/note?id='.rawurlencode($r) : null,
'likes' => $note ? count($note['likes']) : null,
'boosts' => $note ? count($note['boosts']) : null,
'replies' => $note ? count($note['replies']) : null,
'liked' => isset($likes[$id]),
'boosted' => isset($boosts[$id]),
'canBoost' => in_array($vis, ['public', 'unlisted'], true),
'mine' => $this->me !== null && $authorUrl === Fedi::actorUrl($this->me),
'editUrl' => $note ? '/microblog/edit?id='.$note['id'] : null,
];
}
return $out;
}
/**
* リモートの画像(/microblog/media?u=URL&s=署名)
* CSPのimg-srcで他のサーバーの画像は表示できないので、このサイトから出す
*/
public function media(array $params): void {
$url = (string)($_GET['u'] ?? '');
$img = $url !== '' && hash_equals(Remote::imageSig($url), (string)($_GET['s'] ?? '')) ? Remote::image($url) : null;
if ($img === null) {
header('HTTP/1.1 404 Not Found');
exit;
}
header('Content-Type: '.$img['type']);
header('Content-Length: '.filesize($img['path']));
header('Cache-Control: public, max-age=86400');
header("Content-Security-Policy: default-src 'none'");
readfile($img['path']);
exit;
}
/**
* アクターの表示用の情報(キャッシュだけ使う。取得しない)
* color:namecolor()のHTML(リモートのアクターはエスケープした名前)
*/
private function who(string $url): array {
$local = Fedi::localUsername($url);
if ($local !== null) {
$u = Fedi::localUser($local);
return ['url' => $url, 'name' => $u ? ($u->displayname ?: $u->username) : $local,
'color' => $u ? namecolor($u) : htmlspecialchars($local, ENT_QUOTES, 'UTF-8'), 'handle' => "@{$local}",
'avatar' => $u ? avatar_url($u) : ass_url('user/noicon.png'), 'page' => "/microblog/user/{$local}"];
}
$doc = Remote::cachedActor($url);
$handle = $doc ? Remote::handle($doc) : '@'.basename((string)parse_url($url, PHP_URL_PATH)).'@'.Fedi::domainOf($url);
$icon = $doc ? ($doc['icon']['url'] ?? (is_string($doc['icon'] ?? null) ? $doc['icon'] : '')) : '';
return [
'url' => $url,
'name' => $name = $doc ? (string)(($doc['name'] ?? '') ?: ($doc['preferredUsername'] ?? $handle)) : $handle,
'color' => htmlspecialchars($name, ENT_QUOTES, 'UTF-8'),
'handle' => $handle,
'avatar' => Remote::imageUrl(self::safeUrl(is_string($icon) ? $icon : '')) ?: ass_url('user/noicon.png'),
'page' => '/microblog/remote?actor='.rawurlencode($url),
];
}
/**
* 本文のメンションのリンクを、相手のサーバーではなくこのサイトのプロフィールのページ(/microblog/remote等)にする
* 投稿のtag(Mention)でアクターが分かるリンクだけ。ログインしていなければ他のサーバーに問い合わせないので、
* キャッシュしているアクターだけ(それ以外は元のリンクのまま)
*
* @param string $html 安全にした本文
* @param array $o 投稿(Note等)
* @return string
*/
private function localMentionLinks(string $html, array $o): string {
$actors = [];
foreach ((array)($o['tag'] ?? []) as $t) {
if (!is_array($t) || ($t['type'] ?? '') !== 'Mention' || !is_string($t['href'] ?? null)) continue;
$actors[$t['href']] = $t['href'];
// Mastodon・Misskey等はリンクにプロフィールのURL(https://host/@user)を使うので、サーバーとユーザー名でも探す
$name = strtolower(explode('@', ltrim((string)($t['name'] ?? ''), '@'))[0]);
if ($name !== '') $actors[Fedi::domainOf($t['href']).'/'.$name] ??= $t['href'];
}
if (empty($actors)) return $html;
return preg_replace_callback('#me === null && !Fedi::isLocal($actor) && Remote::cachedActor($actor) === null) return $m[0];
return 'me === null) return ['self' => false, 'can' => false];
$f = Actor::following($this->me)[$url] ?? null;
return [
'self' => $url === Fedi::actorUrl($this->me),
'can' => true,
'following' => ($f['state'] ?? '') === 'accepted',
'pending' => ($f['state'] ?? '') === 'pending',
'followsYou' => Actor::isFollowedBy($this->me, $url),
'blocked' => in_array($url, Actor::blocks($this->me)['actors'], true),
'domain' => Fedi::domainOf($url),
'remote' => !Fedi::isLocal($url),
];
}
/**
* 見る事が出来るオブジェクト(ローカル又は保存しているもの。$fetchなら取得もする)
*/
private function visibleObject(string $id, bool $fetch = false): ?array {
if ($id === '') return null;
$obj = Timeline::object($id);
if (!$obj && $fetch && !Fedi::isLocal($id) && Remote::isSafeUrl($id)) {
$obj = Remote::object($id);
if ($obj && in_array(Fedi::visibility(Fedi::ids($obj['to'] ?? []), Fedi::ids($obj['cc'] ?? [])), ['public', 'unlisted'], true)) {
Remote::store($obj);
Timeline::add($obj);
} else {
$obj = null;
}
}
if (!$obj) return null;
$author = (string)Fedi::id($obj['attributedTo'] ?? null);
$e = ['vis' => Fedi::visibility(Fedi::ids($obj['to'] ?? []), Fedi::ids($obj['cc'] ?? []), Fedi::isLocal($author) ? $author.'/followers' : null),
'author' => $author, 'aud' => array_merge(Fedi::ids($obj['to'] ?? []), Fedi::ids($obj['cc'] ?? []))];
return Timeline::canSee($this->me, $e) ? $obj : null;
}
/**
* リモートのアクターの最近の投稿(送信ボックスの最初のページ、公開のNoteだけ)
*/
private function actorPage(string $url): string {
$local = Fedi::localUsername($url);
return $local !== null ? "/microblog/user/{$local}" : '/microblog/remote?actor='.rawurlencode($url);
}
private static function safeUrl(string $url): string {
return preg_match('#^https?://[^\s"<>]+$#', $url) ? $url : '';
}
private function before(): ?float {
return isset($_GET['before']) && is_numeric($_GET['before']) ? (float)$_GET['before'] : null;
}
private function csrfOk(): bool {
return is_string($_POST['csrf_token'] ?? null) && verify_csrf_token($_POST['csrf_token']);
}
private function requireMe(): void {
if ($this->me !== null) return;
if ($this->user === null) $this->redirect('/login');
$this->message('Fediverseの機能を使う権限がありません。', '/microblog/local');
}
private function redirect(string $to): never {
header('Location: '.$to);
exit;
}
private function notFound(): never {
header('Location: /404');
exit;
}
private function message(string $msg, string $back): never {
$this->render('microblog/message', 'マイクロブログ', ['msg' => $msg, 'back' => $back]);
exit;
}
private function render(string $view, string $title, array $vars): void {
$tmpl = new Template('/');
$tmpl->assign('pagetit', $title);
$tmpl->assign('curPage', 'microblog');
$tmpl->assign('menu', $this->getMenu());
$tmpl->assign('support', $this->getSupport());
$tmpl->assign('sns', $this->getSns());
$tmpl->assign('description', SITEINFO['description']);
$tmpl->assign('user', $this->user);
$tmpl->assign('me', $this->me);
$tmpl->assign('unread', $this->me ? Actor::unreadCount($this->me) : 0);
$tmpl->assign('isAdmin', $this->user && ($this->user->role & Roles::ADMIN));
$tmpl->assign('here', safe_local_path($_SERVER['REQUEST_URI'] ?? '', '/microblog'));
$tmpl->assign('visibilities', Social::VISIBILITIES);
$tmpl->assign('maxLength', Fedi::MAX_LENGTH);
$tmpl->assign('maxMedia', Fedi::MAX_ATTACHMENTS);
// クッキーはテンプレートの出力の前に設定する
$tmpl->assign('csrf', make_csrf_token());
foreach (['error' => '', 'draft' => '', 'draftCw' => '', 'replyTo' => null, 'replyText' => '', 'replyVis' => 'public', 'scope' => ''] as $k => $v) {
$tmpl->assign($k, $vars[$k] ?? $v);
}
foreach ($vars as $k => $v) $tmpl->assign($k, $v);
$tmpl->addCss('microblog');
$tmpl->render($view);
}
}