aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Model/ActorWebfinger.php
blob: 3ac61ad9bc48bacc5310e328f2ef585e7a69cd68 (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
<?php
namespace Digitigrade\Model;

use Digitigrade\Model;

class ActorWebfinger extends Model {
    public const REL_URI = "https://pawpub.entities.org.uk/rel/actor";

    public string $acct;
    public Actor $actor;

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

    public static function findByAcct(string $acct, bool $autoSave = true, bool $forceRefetch = false): ?self {
        if (!$forceRefetch) {
            $entry = self::findWhere('acct = ?', [$acct]);
            if ($entry != null)
                return $entry;
        }

        // fetch from remote
        $domain = explode('@', $acct, 2)[1];
        $data = @file_get_contents("https://$domain/.well-known/webfinger?resource=$acct",
            context: stream_context_create([
                'http' => ['header' => 'Accept: application/jrd+json, application/json']
            ])
        );
        if ($data === false)
            return null;
        $data = json_decode($data);
        if ($data === null)
            return null;
        // find the right link
        if (!isset($data->links))
            return null;
        $matching = array_filter($data->links, function (\stdClass $linkObj) {
            return $linkObj->rel == self::REL_URI;
        });
        if (count($matching) == 0)
            return null;
        $actor = Actor::findByUri($matching[0]->href, $autoSave, $forceRefetch);

        // save and return
        $entry = new self();
        $entry->acct = $acct;
        $entry->actor = $actor;

        if ($autoSave)
            $entry->save();

        return $entry;
    }
}