Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.93% covered (warning)
87.93%
51 / 58
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
router
87.93% covered (warning)
87.93%
51 / 58
0.00% covered (danger)
0.00%
0 / 4
20.70
0.00% covered (danger)
0.00%
0 / 1
 deliver
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
11
 send_test
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
3
 send
25.00% covered (danger)
25.00%
1 / 4
0.00% covered (danger)
0.00%
0 / 1
3.69
 already_receives
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
4.18
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_notifyhub\local;
18
19use message_notifyhub\event\notification_delivered;
20use message_notifyhub\event\notification_undelivered;
21
22/**
23 * Sends one notification to one user through the first channel that works.
24 *
25 * Core calls every output a user has switched on and ignores what they answer, so it cannot fall back. The hub
26 * is itself an output: it tries the channels in the admin's order and stops at the first that confirms delivery.
27 * It skips channels the user has not set up and channels that already get this notification for this user, so
28 * nobody gets the same notification twice.
29 *
30 * @package    message_notifyhub
31 * @copyright  2026 DevLMS
32 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 */
34final class router {
35    /** @var \message_output[]|null For tests: channel name => output, instead of the site's outputs. */
36    public static ?array $outputs = null;
37
38    /**
39     * Deliver a notification.
40     *
41     * @param \stdClass $message As core hands it to an output.
42     * @return bool True when a channel delivered it or the user already gets it elsewhere; false otherwise.
43     */
44    public static function deliver(\stdClass $message): bool {
45        $user = is_object($message->userto) ? $message->userto : \core_user::get_user($message->userto);
46        if (!$user || !empty($user->deleted)) {
47            return false;
48        }
49        $component = (string) ($message->component ?? '');
50        $name = (string) ($message->name ?? '');
51        $outputs = channels::outputs();
52        // Every channel counts here, in any order and even if it is out of the hub: if core already sends this
53        // notification to this user somewhere, the hub adds nothing.
54        foreach ($outputs as $channel => $output) {
55            if ($output->is_user_configured($user) && self::already_receives($channel, $output, $user, $component, $name)) {
56                return true;
57            }
58        }
59        $tried = [];
60        foreach (channels::active() as $channel) {
61            $output = $outputs[$channel] ?? null;
62            if (!$output || !$output->is_user_configured($user)) {
63                continue;
64            }
65            $tried[] = $channel;
66            if (self::send($output, $message)) {
67                log::add($user->id, $component, $name, $channel, log::SENT);
68                notification_delivered::for_user($user->id, $component, $name, $channel)->trigger();
69                return true;
70            }
71            log::add($user->id, $component, $name, $channel, log::FAILED);
72        }
73        log::add($user->id, $component, $name, '', log::UNDELIVERED);
74        notification_undelivered::for_user($user->id, $component, $name, $tried)->trigger();
75        return false;
76    }
77
78    /**
79     * Send a test notification to the current user through one channel.
80     *
81     * @param string $channel
82     * @return bool
83     */
84    public static function send_test(string $channel): bool {
85        global $USER;
86        $output = channels::outputs()[$channel] ?? null;
87        if (!$output) {
88            return false;
89        }
90        $site = format_string(get_site()->fullname, true, ['context' => \context_system::instance()]);
91        $text = get_string('test:body', 'message_notifyhub', $site);
92        $message = (object) [
93            'userto' => $USER,
94            'userfrom' => \core_user::get_noreply_user(),
95            'component' => 'message_notifyhub',
96            'name' => 'test',
97            'subject' => get_string('test:subject', 'message_notifyhub'),
98            'fullmessage' => $text,
99            'fullmessageformat' => FORMAT_PLAIN,
100            'fullmessagehtml' => '<p>' . s($text) . '</p>',
101            'smallmessage' => $text,
102            'notification' => 1,
103            'contexturl' => (new \moodle_url('/message/output/notifyhub/index.php'))->out(false),
104            'contexturlname' => get_string('pluginname', 'message_notifyhub'),
105        ];
106        $ok = self::send($output, $message);
107        log::add($USER->id, 'message_notifyhub', 'test', $channel, $ok ? log::SENT : log::FAILED);
108        return $ok;
109    }
110
111    /**
112     * Call one output, treating an exception as a failure.
113     *
114     * @param \message_output $output
115     * @param \stdClass $message
116     * @return bool
117     */
118    private static function send(\message_output $output, \stdClass $message): bool {
119        try {
120            return (bool) $output->send_message(clone $message);
121        } catch (\Throwable $e) {
122            debugging('Notification hub: ' . $e->getMessage(), DEBUG_DEVELOPER);
123            return false;
124        }
125    }
126
127    /**
128     * Whether core already sends this notification to this user on a channel, using the same rules as
129     * message_send() in lib/messagelib.php: a locked setting wins; otherwise the user's preference, or the site
130     * default, unless the user has emailstop set.
131     *
132     * @param string $channel
133     * @param \message_output $output
134     * @param \stdClass $user
135     * @param string $component
136     * @param string $name
137     * @return bool
138     */
139    public static function already_receives(
140        string $channel,
141        \message_output $output,
142        \stdClass $user,
143        string $component,
144        string $name
145    ): bool {
146        $base = $component . '_' . $name;
147        $enabled = 'message_provider_' . $base . '_enabled';
148        $defaults = get_message_output_default_preferences();
149        if (!empty($defaults->{$channel . '_provider_' . $base . '_locked'})) {
150            return in_array($channel, explode(',', (string) ($defaults->{$enabled} ?? '')), true);
151        }
152        if (!empty($user->emailstop)) {
153            return false;
154        }
155        $list = get_user_preferences($enabled, null, $user) ?: (string) ($defaults->{$enabled} ?? '');
156        return in_array($channel, explode(',', $list), true);
157    }
158}