Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
<?php
2
// This file is part of Moodle - http://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 <http://www.gnu.org/licenses/>.
16
 
17
namespace core_sms;
18
 
19
use Generator;
20
use stdClass;
21
 
22
/**
23
 * SMS manager.
24
 *
25
 * @package    core_sms
26
 * @copyright  2024 Andrew Lyons <andrew@nicols.co.uk>
27
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28
 */
29
class manager {
30
    /**
31
     * Create a new SMS manager.
32
     *
33
     * @param \moodle_database $db
34
     */
35
    public function __construct(
36
        /** @var \moodle_database The database instance */
37
        protected readonly \moodle_database $db,
38
    ) {
39
    }
40
 
41
    /**
42
     * Send an SMS to the given recipient.
43
     *
44
     * @param string $recipientnumber The phone number to send the SMS to
45
     * @param string $content The SMS Content
46
     * @param string $component The owning component
47
     * @param string $messagetype The message type within the component
48
     * @param null|int $recipientuserid The user id of the recipient if one exists
49
     * @param bool $issensitive Whether this SMS contains sensitive information
50
     * @param bool $async Whether this SMS should be sent asynchronously. Note: sensitive messages cannot be sent async
51
     * @param ?int $gatewayid the gateway instance id to send the sms in a specific gateway config
52
     * @return message
53
     * @throws \coding_exception If a sensitive message is sent asynchronously
54
     */
55
    public function send(
56
        string $recipientnumber,
57
        string $content,
58
        string $component,
59
        string $messagetype,
60
        ?int $recipientuserid,
61
        bool $issensitive = false,
62
        bool $async = true,
63
        ?int $gatewayid = null,
64
    ): message {
65
        $message = new message(
66
            recipientnumber: $recipientnumber,
67
            content: $content,
68
            component: $component,
69
            messagetype: $messagetype,
70
            recipientuserid: $recipientuserid,
71
            issensitive: $issensitive,
72
        );
73
 
74
        if ($issensitive && $async) {
75
            throw new \coding_exception('Sensitive messages cannot be sent asynchronously');
76
        }
77
 
78
        return $this->send_message(
79
            message: $message,
80
            async: $async,
81
            gatewayid: $gatewayid,
82
        );
83
    }
84
 
85
    /**
86
     * Send a message using the message object.
87
     *
88
     * @param message $message The message object
89
     * @param bool $async Whether this SMS should be sent asynchronously. Note: sensitive messages cannot be sent async
90
     * @param ?int $gatewayid the gateway instance id to send the sms in a specific gateway config
91
     * @return message the message object after trying to send the message
92
     */
93
    public function send_message(
94
        message $message,
95
        bool $async = true,
96
        ?int $gatewayid = null,
97
    ): message {
98
        if ($async) {
99
            $message = $message->with(status: message_status::GATEWAY_QUEUED);
100
            $message = $this->save_message($message);
101
            \core_sms\task\send_sms_task::queue($message);
102
            return $message;
103
        }
104
 
105
        if ($gateway = $this->get_gateway_for_message($message, $gatewayid)) {
106
            $modifiedmessage = $message->with(
107
                gatewayid: $gateway->id,
108
                content: $gateway->truncate_message($message->content),
109
            );
110
            $message = $gateway->send($modifiedmessage);
111
        } else {
112
            $message = $message->with(status: message_status::GATEWAY_NOT_AVAILABLE);
113
        }
114
 
115
        return $this->save_message($message);
116
    }
117
 
118
    /**
119
     * Get the gateways that can send the given message.
120
     *
121
     * @param message $message
122
     * @return gateway[]
123
     */
124
    public function get_possible_gateways_for_message(
125
        message $message,
126
    ): array {
127
        $gateways = [];
128
        foreach ($this->get_enabled_gateway_instances() as $gateway) {
129
            if ($gateway->get_send_priority($message)) {
130
                $gateways[] = $gateway;
131
            }
132
        }
133
 
134
        return $gateways;
135
    }
136
 
137
    /**
138
     * Get the gateway that can send the given message.
139
     *
140
     * @param message $message The message instance
141
     * @param ?int $gatewayid the gateway instance id to send the sms in a specific gateway config
142
     * @return null|gateway
143
     */
144
    public function get_gateway_for_message(
145
        message $message,
146
        ?int $gatewayid = null,
147
    ): ?gateway {
148
        if ($gatewayid) {
149
            // Check if the gateway id is valid.
150
            $gateway = $this->get_gateway_instances(['id' => $gatewayid]);
151
            $gateway = $gateway ? reset($gateway) : null;
152
            return $gateway;
153
        }
154
 
155
        $gateways = $this->get_possible_gateways_for_message($message);
156
        if (!count($gateways)) {
157
            return null;
158
        }
159
 
160
        // Sort the gateways by their send priority for this message.
161
        usort($gateways, fn($a, $b) => $a->get_send_priority($message) <=> $b->get_send_priority($message));
162
 
163
        return array_pop($gateways);
164
    }
165
 
166
    /**
167
     * Get a list of all gateway instances.
168
     *
169
     * @param null|array $filter The database filter to apply
170
     * @return array
171
     */
172
    public function get_gateway_instances(?array $filter = null): array {
173
        return array_filter(
174
            array_map(
175
                function ($record): ?gateway {
176
                    if (!class_exists($record->gateway)) {
177
                        debugging(
178
                            "Unable to find a gateway class for {$record->gateway}",
179
                            DEBUG_DEVELOPER,
180
                        );
181
                        return null;
182
                    }
183
 
184
                    return new $record->gateway(
185
                        id: $record->id,
186
                        name: $record->name,
187
                        enabled: $record->enabled,
188
                        config: $record->config,
189
                    );
190
                },
191
                $this->get_gateway_records($filter),
192
            )
193
        );
194
    }
195
 
196
    /**
197
     * Get the gateway records according to the filter.
198
     *
199
     * @param array|null $filter The filterable elements to get the records from
200
     * @return array
201
     */
202
    public function get_gateway_records(?array $filter = null): array {
203
        return $this->db->get_records(
204
            table: 'sms_gateways',
205
            conditions: $filter,
206
        );
207
    }
208
 
209
    /**
210
     * Get a list of all enabled gateway instances.
211
     *
212
     * @return array
213
     */
214
    public function get_enabled_gateway_instances(): array {
215
        return $this->get_gateway_instances(['enabled' => 1]);
216
    }
217
 
218
    /**
219
     * Save the message to the database.
220
     *
221
     * @param message $message
222
     * @return message
223
     */
224
    public function save_message(
225
        message $message,
226
    ): message {
227
        if ($message->issensitive) {
228
            // Sensitive messages should not store content.
229
            $message = $message->with(content: null);
230
        }
231
        if ($message->id) {
232
            $this->db->update_record('sms_messages', $message->to_record());
233
            return $message;
234
        }
235
        $id = $this->db->insert_record('sms_messages', $message->to_record());
236
 
237
        return $message->with(id: $id);
238
    }
239
 
240
    /**
241
     * Enable a gateway.
242
     *
243
     * @param gateway $gateway
244
     * @return gateway
245
     */
246
    public function enable_gateway(gateway $gateway): gateway {
247
        if (!$gateway->enabled) {
248
            $gateway = $gateway->with(enabled: true);
249
            $this->db->update_record('sms_gateways', $gateway->to_record());
250
        }
251
 
252
        return $gateway;
253
    }
254
 
255
    /**
256
     * Disable a gateway.
257
     *
258
     * @param gateway $gateway
259
     * @return gateway
260
     */
261
    public function disable_gateway(gateway $gateway): gateway {
262
        if ($gateway->enabled) {
263
            try {
264
                $hook = new \core_sms\hook\before_gateway_disabled(
265
                    gateway: $gateway,
266
                );
267
                $hookmanager = \core\di::get(\core\hook\manager::class)->dispatch($hook);
268
                if (!$hookmanager->isPropagationStopped()) {
269
                    $gateway = $gateway->with(enabled: false);
270
                    $this->db->update_record('sms_gateways', $gateway->to_record());
271
                }
272
            } catch (\dml_exception $e) {
273
            }
274
        }
275
 
276
        return $gateway;
277
    }
278
 
279
    /**
280
     * Delete the gateway instance.
281
     *
282
     * @param gateway $gateway The gateway instance
283
     * @return bool
284
     */
285
    public function delete_gateway(gateway $gateway): bool {
286
        try {
287
            // Dispatch the hook before deleting the record.
288
            $hook = new \core_sms\hook\before_gateway_deleted(
289
                gateway: $gateway,
290
            );
291
            $hookmanager = \core\di::get(\core\hook\manager::class)->dispatch($hook);
292
            if ($hookmanager->isPropagationStopped()) {
293
                $deleted = false;
294
            } else {
295
                $deleted = $this->db->delete_records('sms_gateways', ['id' => $gateway->id]);
296
            }
297
        } catch (\dml_exception $exception) {
298
            $deleted = false;
299
        }
300
        return $deleted;
301
    }
302
 
303
    /**
304
     * Create a new gateway instance.
305
     *
306
     * @param string $classname Classname of the gateway
307
     * @param string $name The name of the gateway config
308
     * @param bool $enabled If the gateway is enabled or not
309
     * @param stdClass|null $config The config json
310
     * @return gateway
311
     */
312
    public function create_gateway_instance(
313
        string $classname,
314
        string $name,
315
        bool $enabled = false,
316
        ?stdClass $config = null,
317
    ): gateway {
318
        if (!class_exists($classname) || !is_a($classname, gateway::class, true)) {
319
            throw new \coding_exception("Gateway class not valid: {$classname}");
320
        }
321
        $gateway = new $classname(
322
            enabled: $enabled,
323
            name: $name,
324
            config: $config ? json_encode($config) : '',
325
        );
326
 
327
        $id = $this->db->insert_record('sms_gateways', $gateway->to_record());
328
 
329
        return $gateway->with(id: $id);
330
    }
331
 
332
    /**
333
     * Update gateway instance.
334
     *
335
     * @param gateway $gateway The gateway instance
336
     * @param stdClass|null $config the configuration of the gateway instance to be updated
337
     * @return gateway
338
     */
339
    public function update_gateway_instance(
340
        gateway $gateway,
341
        ?stdClass $config = null,
342
    ): gateway {
343
        $gateway = $gateway->with(config: $config, name: $gateway->name);
344
        $this->db->update_record('sms_gateways', $gateway->to_record());
345
        return $gateway;
346
    }
347
 
348
    /**
349
     * Get all messages.
350
     *
351
     * @param string $sort
352
     * @param null|array $filter
353
     * @param int $pagesize
354
     * @param int $page
355
     * @return Generator
356
     */
357
    public function get_messages(
358
        string $sort = 'timecreated ASC',
359
        ?array $filter = null,
360
        int $pagesize = 0,
361
        int $page = 0,
362
    ): Generator {
363
        $rows = $this->db->get_records(
364
            table: 'sms_messages',
365
            conditions: $filter,
366
            limitfrom: $pagesize * $page,
367
            limitnum: $pagesize,
368
            sort: $sort,
369
        );
370
 
371
        foreach ($rows as $record) {
372
            yield new message(
373
                id: $record->id,
374
                recipientnumber: $record->recipientnumber,
375
                content: $record->content,
376
                component: $record->component,
377
                messagetype: $record->messagetype,
378
                recipientuserid: $record->recipientuserid,
379
                issensitive: $record->issensitive,
380
                status: message_status::from($record->status),
381
                gatewayid: $record->gatewayid,
382
                timecreated: $record->timecreated,
383
            );
384
        }
385
    }
386
 
387
    /**
388
     * Get a message
389
     *
390
     * @param array $filter
391
     * @return message
392
     */
393
    public function get_message(
394
        array $filter,
395
    ): message {
396
        $record = $this->db->get_record(
397
            table: 'sms_messages',
398
            conditions: $filter,
399
        );
400
 
401
        return new message(
402
            id: $record->id,
403
            recipientnumber: $record->recipientnumber,
404
            content: $record->content,
405
            component: $record->component,
406
            messagetype: $record->messagetype,
407
            recipientuserid: $record->recipientuserid,
408
            issensitive: $record->issensitive,
409
            status: message_status::from($record->status),
410
            gatewayid: $record->gatewayid,
411
            timecreated: $record->timecreated,
412
        );
413
    }
414
 
415
    /**
416
     * This function internationalises a number to E.164 standard.
417
     * https://46elks.com/kb/e164
418
     *
419
     * @param string $phonenumber the phone number to format.
420
     * @param ?string $countrycode The country code of the phone number.
421
     * @return string the formatted phone number.
422
     */
423
    public static function format_number(
424
        string $phonenumber,
425
        ?string $countrycode = null,
426
    ): string {
427
        // Remove all whitespace, dashes, and brackets in one step.
428
        $phonenumber = preg_replace('/[ ()-]/', '', $phonenumber);
429
 
430
        // Check if the number is already in international format or if it starts with a 0.
431
        if (!str_starts_with($phonenumber, '+')) {
432
            // Strip leading 0.
433
            if (str_starts_with($phonenumber, '0')) {
434
                $phonenumber = substr($phonenumber, 1);
435
            }
436
 
437
            // Prepend country code if not already in international format.
438
            $phonenumber = !empty($countrycode) ? '+' . $countrycode . $phonenumber : $phonenumber;
439
        }
440
 
441
        return $phonenumber;
442
    }
443
}