Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.56% covered (warning)
75.56%
34 / 45
50.00% covered (danger)
50.00%
4 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
subscriptions
75.56% covered (warning)
75.56%
34 / 45
50.00% covered (danger)
50.00%
4 / 8
29.07
0.00% covered (danger)
0.00%
0 / 1
 add
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
8
 for_user
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 remove
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 remove_endpoint
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 forget
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 sent
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 acknowledge
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 is_stale
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2// This file is part of Moodle - https://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
16
17namespace message_webpush\local;
18
19use stdClass;
20
21/**
22 * The browsers in which users turned on notifications.
23 *
24 * @package    message_webpush
25 * @copyright  2026 DevLMS
26 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28class subscriptions {
29    /** @var string Table name. */
30    public const TABLE = 'message_webpush_subs';
31
32    /** @var int Browsers kept per person; the oldest go first. Each send waits on every one of them. */
33    public const MAX_PER_USER = 10;
34
35    /**
36     * Save a browser for a user. One browser has one row: turning it on again, even as someone else (a shared
37     * computer), moves the row to the new person with a new confirmation token.
38     *
39     * @param int $userid
40     * @param string $endpoint from PushSubscription.endpoint
41     * @param string $p256dh from getKey('p256dh'), base64url
42     * @param string $auth from getKey('auth'), base64url
43     * @param string $label browser and system, shown in the user's list
44     * @return stdClass the row
45     * @throws \invalid_parameter_exception when the address or keys are not a real push subscription
46     */
47    public static function add(int $userid, string $endpoint, string $p256dh, string $auth, string $label): stdClass {
48        global $DB;
49        $public = crypto::b64u_decode($p256dh);
50        if (
51            !hosts::allowed($endpoint) || strlen($public) !== 65 || $public[0] !== "\x04" ||
52                strlen(crypto::b64u_decode($auth)) !== 16 || strlen($endpoint) > 2048
53        ) {
54            throw new \invalid_parameter_exception('Not a push subscription from a known push service');
55        }
56        $now = time();
57        $row = (object)[
58            'userid' => $userid,
59            'endpoint' => $endpoint,
60            'endpointhash' => hash('sha256', $endpoint),
61            'p256dh' => crypto::b64u_encode($public),
62            'auth' => $auth,
63            'acktoken' => random_string(32),
64            'label' => \core_text::substr(trim(clean_param($label, PARAM_NOTAGS)), 0, 100),
65            'timecreated' => $now,
66            'timeacked' => 0,
67            'pendingsince' => 0,
68        ];
69        if ($existing = $DB->get_record(self::TABLE, ['endpointhash' => $row->endpointhash])) {
70            $row->id = (int)$existing->id;
71            $DB->update_record(self::TABLE, $row);
72        } else {
73            $row->id = (int)$DB->insert_record(self::TABLE, $row);
74        }
75
76        $all = $DB->get_records(self::TABLE, ['userid' => $userid], 'timecreated DESC, id DESC', 'id');
77        foreach (array_slice(array_keys($all), self::MAX_PER_USER) as $old) {
78            $DB->delete_records(self::TABLE, ['id' => $old]);
79        }
80        return $row;
81    }
82
83    /**
84     * A user's browsers, newest first.
85     *
86     * @param int $userid
87     * @return stdClass[]
88     */
89    public static function for_user(int $userid): array {
90        global $DB;
91        return array_values($DB->get_records(self::TABLE, ['userid' => $userid], 'timecreated DESC, id DESC'));
92    }
93
94    /**
95     * Remove one of a user's own browsers.
96     *
97     * @param int $userid
98     * @param int $id
99     * @return bool whether a row was removed
100     */
101    public static function remove(int $userid, int $id): bool {
102        global $DB;
103        if (!$DB->record_exists(self::TABLE, ['id' => $id, 'userid' => $userid])) {
104            return false;
105        }
106        $DB->delete_records(self::TABLE, ['id' => $id, 'userid' => $userid]);
107        return true;
108    }
109
110    /**
111     * Remove a user's browser by its address (the browser turned push off).
112     *
113     * @param int $userid
114     * @param string $endpoint
115     * @return bool
116     */
117    public static function remove_endpoint(int $userid, string $endpoint): bool {
118        global $DB;
119        $conditions = ['endpointhash' => hash('sha256', $endpoint), 'userid' => $userid];
120        if (!$DB->record_exists(self::TABLE, $conditions)) {
121            return false;
122        }
123        $DB->delete_records(self::TABLE, $conditions);
124        return true;
125    }
126
127    /**
128     * Forget a browser the push service says is gone.
129     *
130     * @param stdClass $sub
131     */
132    public static function forget(stdClass $sub): void {
133        global $DB;
134        $DB->delete_records(self::TABLE, ['id' => $sub->id]);
135    }
136
137    /**
138     * Note a push the service accepted; the clock for "never confirms" starts at the first unconfirmed one.
139     *
140     * @param stdClass $sub
141     */
142    public static function sent(stdClass $sub): void {
143        global $DB;
144        if (empty($sub->pendingsince)) {
145            $sub->pendingsince = time();
146            $DB->set_field(self::TABLE, 'pendingsince', $sub->pendingsince, ['id' => $sub->id]);
147        }
148    }
149
150    /**
151     * The browser showed a notification and said so.
152     *
153     * @param string $token the subscription's acktoken
154     * @return bool whether the token belongs to a browser
155     */
156    public static function acknowledge(string $token): bool {
157        global $DB;
158        if (strlen($token) !== 32 || !($sub = $DB->get_record(self::TABLE, ['acktoken' => $token]))) {
159            return false;
160        }
161        $DB->update_record(self::TABLE, (object)['id' => $sub->id, 'timeacked' => time(), 'pendingsince' => 0]);
162        return true;
163    }
164
165    /**
166     * Whether a browser has gone quiet: pushes accepted, none confirmed for the configured number of days.
167     *
168     * @param stdClass $sub
169     * @param int|null $now
170     * @return bool
171     */
172    public static function is_stale(stdClass $sub, ?int $now = null): bool {
173        $days = max(1, (int)(get_config('message_webpush', 'staledays') ?: 3));
174        return !empty($sub->pendingsince) && ($now ?? time()) - $sub->pendingsince > $days * DAYSECS;
175    }
176}