aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Model/Note.php
blob: c39b7c3d71952932672490b91f4744bb5690d95a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<?php
namespace Digitigrade\Model;

use Digitigrade\Db;
use Digitigrade\FormattingProvider\CommonMark;
use Digitigrade\FormattingProvider\SanitisedHtml;
use Digitigrade\LinkPreview;
use Digitigrade\Model\HomeTimelineItem;
use Digitigrade\Notification\Notifyable;
use Digitigrade\Page;
use Digitigrade\Timeline\TimelineIncludeable;
use Digitigrade\Timeline\TimelineItem;

class Note extends PushableModel implements TimelineIncludeable, Notifyable {
    public const EXTENSION_LINK_PREVIEWS = 'https://pawpub.entities.org.uk/extension/link-previews';
    public const EXTENSION_PAGES = 'https://pawpub.entities.org.uk/extension/pages';

    public ?int $id;
    public string $uri;
    public \DateTimeImmutable $created;
    public ?\DateTimeImmutable $modified;
    public Actor $author;
    public ?string $summary;
    public string $plainContent;
    /** @var array associative array mapping strings to strings - mimetypes to content */
    public array $formattedContent = [];
    public string $language;
    /**
     * @var Actor[]
     */
    public array $mentions = [];
    public ?Note $inReplyTo;
    public ?Note $threadApex;
    public NotePrivacy $privacy;
    /**
     * @var NoteAttachment[]
     */
    public array $attachments = [];
    public array $extensions = [];

    /**
     * Creates and saves a new note with the specified fields pre-set
     * @param Actor $author who wrote the note
     * @param string $plainContent text of the note, without any markup
     * @param string $language ISO 639-3 3-letter language code
     * @param ?string $summary summary line or content warning
     * @param NotePrivacyScope $scope who is allowed to view this note
     * @param bool $indexable whether this note should be findable e.g. in search results
     * @return self
     */
    public static function create(
        Actor $author,
        string $plainContent,
        string $language,
        ?string $summary = null,
        NotePrivacyScope $scope = NotePrivacyScope::PUBLIC ,
        bool $indexable = true
    ): self {
        $note = new self();
        // can't set the note uri properly until it's been saved and we have an id
        $note->uri = "UNKNOWN";
        $note->created = new \DateTimeImmutable();
        $note->author = $author;
        $note->summary = $summary;
        $note->plainContent = $plainContent;
        $note->language = $language;
        $note->privacy = new NotePrivacy();
        $note->privacy->scope = $scope;
        $note->privacy->indexable = $indexable;

        $note->save();
        $note->uri = path_to_uri("/note/$note->id");
        $note->save();

        return $note;
    }

    protected function getUpdateWhereClause(\PDO $db): ?string {
        if (self::findWhere('uri = ?', [$this->uri]) != null)
            return 'uri = ' . $db->quote($this->uri);
        if (self::findWhere('id = ?', [$this->id]) != null)
            return "id = $this->id";
        return null;
    }

    protected function hydrate() {
        $this->privacy = NotePrivacy::findWhere('note_id = ?', [$this->id]);
        $this->formattedContent = $this->findFormattedContents();
        $this->mentions = $this->findMentions();
        $this->attachments = NoteAttachment::findAllWhere('note_id = ?', [$this->id]);
        $this->extensions = $this->findExtensions();

        // put attachments back in the right order
        usort($this->attachments, fn($a, $b) => $a->index <=> $b->index);
    }

    protected function dehydrate() {
        $this->saveMentions();
        $this->saveAttachments();
        $this->saveExtensions();
        $this->saveFormattedContents();
    }

    protected function validate(): bool {
        // author has to be from the same instance as the note itself
        return hostname_from_uri($this->author->uri) == hostname_from_uri($this->uri);
    }

    private function findFormattedContents(): array {
        $pdo = Db::getInstance()->getPdo();
        $stmt = $pdo->prepare('SELECT mimetype, body FROM note_formatted_content WHERE note_id = ?');
        $stmt->execute([$this->id]);
        $rows = $stmt->fetchAll();
        return array_combine(
            array_map(fn($row) => $row['mimetype'], $rows),
            array_map(fn($row) => $row['body'], $rows)
        );
    }

    private function findMentions(): array {
        $pdo = Db::getInstance()->getPdo();
        $stmt = $pdo->prepare('SELECT actor_id FROM note_mention WHERE note_id = ?');
        $stmt->execute([$this->id]);
        $actors = array_map(function ($actorId) {
            return Actor::find($actorId);
        }, $stmt->fetchAll(\PDO::FETCH_COLUMN, 0));
        return $actors;
    }

    private function findExtensions(): array {
        $pdo = Db::getInstance()->getPdo();
        $stmt = $pdo->prepare('SELECT uri, data FROM note_extension WHERE note_id = ?');
        $stmt->execute([$this->id]);
        $items = [];
        while ($row = $stmt->fetch()) {
            $items[$row['uri']] = json_decode($row['data']);
        }
        return $items;
    }

    private function saveFormattedContents() {
        $pdo = Db::getInstance()->getPdo();
        foreach ($this->formattedContent as $mimetype => $body) {
            $stmt = $pdo->prepare(
                'INSERT INTO note_formatted_content(note_id, mimetype, body) VALUES (?, ?, ?)' .
                'ON CONFLICT (note_id, mimetype) DO UPDATE SET body = EXCLUDED.body'
            );
            $stmt->execute([$this->id, $mimetype, $body]);
        }
    }

    private function saveMentions() {
        $pdo = Db::getInstance()->getPdo();
        foreach ($this->mentions as $mention) {
            $stmt = $pdo->prepare('INSERT INTO note_mention(note_id, actor_id) VALUES (?, ?) ON CONFLICT DO NOTHING');
            $stmt->execute([$this->id, $mention->id]);
        }
    }

    private function saveAttachments() {
        $index = 0;
        foreach ($this->attachments as $att) {
            $att->index = $index++;
            $att->setOwnerId($this->id);
            $att->save();
        }
    }

    private function saveExtensions() {
        $pdo = Db::getInstance()->getPdo();
        foreach ($this->extensions as $uri => $obj) {
            $stmt = $pdo->prepare(
                'INSERT INTO note_extension(note_id, uri, data) VALUES (?, ?, ?) ' .
                'ON CONFLICT (note_id, uri) DO UPDATE SET data = EXCLUDED.data'
            );
            $stmt->execute([$this->id, $uri, json_encode($obj)]);
        }
    }

    public static function findAllWithAuthor(Actor $author, ?int $limit = null, int $offset = 0, bool $includeDeleted = false): array {
        $where = 'author = ?';
        if (!$includeDeleted) {
            $where .= ' AND deleted = false';
        }
        return self::findAllWhere($where, [$author->id], $limit, $offset, 'created DESC');
    }

    public static function countWithAuthor(Actor $author): int {
        return self::countWhere('author = ? AND deleted = false', [$author->id]);
    }

    public static function findAllInThread(Note $threadApex, ?int $limit = null, int $offset = 0): array {
        if (isset($limit))
            $limit--; // to account for adding the note afterwards
        $notes = self::findAllWhere('thread_apex = ? AND deleted = false', [$threadApex->id], $limit, $offset, 'created ASC');
        array_splice($notes, 0, 0, [$threadApex]); // since the apex itself has threadApex = null
        return $notes;
    }

    public static function findAllWithExtension(string $extensionUri, ?int $limit = null, int $offset = 0): array {
        $pdo = Db::getInstance()->getPdo();
        $query = 'SELECT note_id FROM note_extension LEFT JOIN note ON note.id = note_id '
            . 'WHERE note_extension.uri = ? ORDER BY note.created DESC';
        if ($limit != null) {
            $query .= " LIMIT $limit OFFSET $offset";
        }
        $stmt = $pdo->prepare($query);
        $stmt->execute([$extensionUri]);
        $notes = [];
        while ($id = $stmt->fetchColumn(0)) {
            $notes[] = self::find($id);
        }
        return $notes;
    }

    public static function countWithExtension(string $extensionUri): int {
        $pdo = Db::getInstance()->getPdo();
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM note_extension WHERE uri = ?');
        $stmt->execute([$extensionUri]);
        return $stmt->fetchColumn(0);
    }

    public function getInteractions(): array {
        return Interaction::findAllWithTarget($this);
    }

    public function countInteractionsOfKind(InteractionKind $kind): int {
        return Interaction::countWhere('target = ? AND kind = ? AND deleted = false', [$this->id, $kind->value]);
    }

    public function getInteractionsWithAuthor(Actor $author): array {
        return Interaction::findAllWhere('author = ? AND target = ? AND deleted = false', [$author->id, $this->id]);
    }

    public function countReplies(): int {
        return self::countWhere('in_reply_to = ? AND deleted = false', [$this->id]);
    }

    /**
     * @return Actor[] actors who this note can be seen by, are mentioned, etc
     */
    public function getRelevantActors(): array {
        return array_unique(array_merge(match ($this->privacy->scope) {
            NotePrivacyScope::NONE => [],
            NotePrivacyScope::MUTUALS => $this->author->findMutualFollows(),
            default => $this->author->findFollowers()
        }, $this->mentions, $this->privacy->alsoVisibleTo, [$this->author]));
    }

    public function getRelevantServers(): array {
        $recipientActors = $this->getRelevantActors();
        // reply-to and thread apex author should be covered by mentions but in case they're not:
        if (isset($this->inReplyTo))
            $recipientActors[] = $this->inReplyTo->author;
        if (isset($this->threadApex))
            $recipientActors[] = $this->threadApex->author;

        $recipientActors = array_unique($recipientActors);
        $instances = array_map(fn(Actor $a) => $a->isLocal ? null : $a->findHomeInstance(), $recipientActors);
        return array_unique(array_filter($instances, fn(?Instance $i) => $i != null));
    }

    public function isViewableBy(?UserAccount $viewer): bool {
        if ($this->privacy->scope == NotePrivacyScope::PUBLIC ) {
            return true;
        }
        if ($viewer == null) {
            return false;
        }
        return in_array($viewer->actor, $this->getRelevantActors());
    }

    /**
     * Gets this note's formatted content in the given mimetype or null if there isn't one
     * @param string $mimetype content type to return
     * @return ?string the marked up content
     */
    public function getFormattedContent(string $mimetype): ?string {
        return $this->formattedContent[$mimetype] ?? null;
    }

    /**
     * Gets the best available formatted content (or plain if there aren't any)
     * and converts it to sanitised HTML
     * @return string HTML that is hopefully safe to include directly
     */
    public function getBestContentAsHtml(): string {
        if (isset($this->formattedContent['text/html'])) {
            return SanitisedHtml::getInstance()->renderToHtml($this->formattedContent['text/html']);
        } elseif (isset($this->formattedContent['text/markdown'])) {
            return CommonMark::getInstance()->renderToHtml($this->formattedContent['text/markdown']);
        }
        return htmlspecialchars($this->plainContent);
    }

    public function getLocalUiHref(bool $asPage = false): string {
        return '/@/' . $this->author->getFullHandle() . ($asPage ? '/page/' : '/note/') . $this->id;
    }

    /**
     * Gets a list of LinkPreviews applicable to this note
     * @return LinkPreview[]
     */
    public function getLinkPreviews(): array {
        if (($this->extensions[self::EXTENSION_LINK_PREVIEWS] ?? []) == []) {
            return [];
        }
        $mapper = new \JsonMapper();
        $results = [];
        foreach ($this->extensions[self::EXTENSION_LINK_PREVIEWS] as $preview) {
            $results[] = $mapper->map($preview, LinkPreview::class);
        }
        return $results;
    }

    /**
     * @return bool whether this note has an attached page
     */
    public function hasPage(): bool {
        return isset($this->extensions[self::EXTENSION_PAGES]);
    }

    public function getPage(): ?Page {
        if (!$this->hasPage())
            return null;
        $mapper = new \JsonMapper();
        $mapper->bStrictObjectTypeChecking = false; // so that CharacterRanges can be decoded
        return $mapper->map($this->extensions[self::EXTENSION_PAGES], Page::class);
    }

    public function setPage(Page $page) {
        $this->extensions[self::EXTENSION_PAGES] = json_decode(json_encode($page));
    }

    /**
     * Generates new LinkPreviews for this note (but does not save them automatically)
     * @return LinkPreview[] the new link previews
     */
    public function generateLinkPreviews(): array {
        $matches = [];
        preg_match_all(
            '`[a-z+]+://[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(([-a-zA-Z0-9@:(%_\+.~#?&/=]|\)[^\s])*)`',
            $this->getFormattedContent('text/markdown') ?? $this->plainContent,
            $matches
        );
        $urls = $matches[0] ?? [];
        $previews = array_filter(
            array_map(fn($url) => LinkPreview::generate($url), $urls),
            fn($p) => $p != null
        );
        $this->extensions[self::EXTENSION_LINK_PREVIEWS] = array_map(
            fn($p) => json_decode(json_encode($p)),
            $previews
        );
        return $previews;
    }

    public function renderAsHtml() {
        render_template('note/note', ['note' => $this]);
    }

    public function toJsonReference(): mixed {
        return $this->id;
    }

    public static function fromJsonReference(mixed $reference): ?self {
        return self::find($reference);
    }

    public function getNotificationTitle(): string {
        $action = isset($this->inReplyTo) ? 'interaction.reply' : 'mention';
        return sprintf(__("notifications.$action.title"), $this->author->displayName);
    }
    public function getNotificationTitleLink(): ?string {
        return $this->author->getLocalUiHref();
    }
    public function getNotificationBody(): ?string {
        return isset($this->summary) ? "[$this->summary]" : $this->plainContent;
    }
    public function getNotificationImageUrl(): ?string {
        return $this->author->avatar ?? '/static/default-avatar.png';
    }
    public function getNotificationImageLink(): ?string {
        return $this->author->getLocalUiHref();
    }

    public function processNotifications() {
        foreach ($this->mentions as $a) {
            if (!$a->isLocal) {
                continue;
            }
            $user = UserAccount::findByLinkedActor($a);
            Notification::fromNotifyable($this, $user)->send();
        }
    }

    public function processTimelineAdditions() {
        $item = new TimelineItem($this);
        foreach ($this->getRelevantActors() as $actor) {
            if (!$actor->isLocal)
                continue;
            $user = UserAccount::findByLinkedActor($actor);
            HomeTimelineItem::fromTimelineItem($item, $user)->save();
        }
    }

    public function jsonSerialize(): array {
        if ($this->deleted) {
            return [
                'type' => 'tombstone',
                'self' => path_to_uri("/note/$this->id"),
                'previousType' => 'note'
            ];
        }
        return [
            'type' => 'note',
            'self' => path_to_uri("/note/$this->id"),
            'created' => $this->created->format('c'),
            'modified' => $this->modified?->format('c'),
            'author' => $this->author->uri,
            'summary' => $this->summary,
            'plainContent' => $this->plainContent,
            'formattedContent' => $this->formattedContent,
            'language' => $this->language,
            'mentions' => array_map(function (Actor $actor) {
                return $actor->uri;
            }, $this->mentions),
            'inReplyTo' => $this->inReplyTo?->uri,
            'threadApex' => $this->threadApex?->uri,
            'privacy' => $this->privacy,
            'attachments' => array_map(function (NoteAttachment $attachment) {
                return [
                    'type' => $attachment->type,
                    'href' => $attachment->href,
                    'description' => $attachment->description
                ];
            }, $this->attachments),
            'extensions' => $this->extensions
        ];
    }
}