MDL-64167 core_message: fix for sending bulk messages from site admin
[moodle.git] / lib / classes / message / manager.php
CommitLineData
349f98ad
PS
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/**
18 * New messaging manager class.
19 *
20 * @package core_message
21 * @since Moodle 2.8
22 * @copyright 2014 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @author Petr Skoda <petr.skoda@totaralms.com>
25 */
26
27namespace core\message;
28
29defined('MOODLE_INTERNAL') || die();
30
31/**
32 * Class used for various messaging related stuff.
33 *
34 * Note: Do NOT use directly in your code, it is intended to be used from core code only.
35 *
36 * @access private
37 *
38 * @package core_message
39 * @since Moodle 2.8
40 * @copyright 2014 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 * @author Petr Skoda <petr.skoda@totaralms.com>
43 */
44class manager {
45 /** @var array buffer of pending messages */
46 protected static $buffer = array();
47
b30f4d6d
JD
48 /** @var array buffer of pending messages to conversations */
49 protected static $convmessagebuffer = array();
50
9581bc3c
JD
51 /**
52 * Used for calling processors, and generating event data when sending a message to a conversation.
53 *
54 * This is ONLY used for messages of type 'message' (notification=0), and is responsible for:
55 *
56 * 1. generation of per-user event data (to pass to processors)
57 * 2. generation of the processors for each recipient member of the conversation
58 * 3. calling said processors for each member, passing in the per-user (local) eventdata.
59 * 4. generation of an appropriate event for the message send, depending on the conversation type
60 * - messages to individual conversations generate a 'message_sent' event (as per legacy send_message())
61 * - messages to group conversations generate a 'group_message_sent' event.
62 *
63 * @param message $eventdata
64 * @param \stdClass $savemessage
65 * @return int
66 */
67 public static function send_message_to_conversation(message $eventdata, \stdClass $savemessage) : int {
68 global $DB, $CFG, $SITE;
69
70 if (empty($eventdata->convid)) {
71 throw new \moodle_exception("Message is not being sent to a conversation. Please check event data.");
72 }
73
74 // Fetch default (site) preferences.
75 $defaultpreferences = get_message_output_default_preferences();
76 $preferencebase = $eventdata->component.'_'.$eventdata->name;
77
78 // Because we're dealing with multiple recipients, we need to send a localised (per-user) version of the eventdata to each
79 // processor, because of things like the language-specific subject. We're going to modify this, for each recipient member.
80 // Any time we're modifying the event data here, we should be using the localised version.
81 // This localised version is based on the generic event data, but we should keep that object intact, so we clone it.
82 $localisedeventdata = clone $eventdata;
83
84 // Get user records for all members of the conversation.
ad5de40c
JD
85 // We must fetch distinct users, because it's possible for a user to message themselves via bulk user actions.
86 // In such cases, there will be 2 records referring to the same user.
9581bc3c 87 $sql = "SELECT u.*
ad5de40c
JD
88 FROM {user} u
89 WHERE u.id IN (
90 SELECT mcm.userid FROM {message_conversation_members} mcm
91 WHERE mcm.conversationid = :convid
92 )";
9581bc3c
JD
93 $members = $DB->get_records_sql($sql, ['convid' => $eventdata->convid]);
94 if (empty($members)) {
95 throw new \moodle_exception("Conversation has no members or does not exist.");
96 }
97
98 if (!is_object($localisedeventdata->userfrom)) {
99 $localisedeventdata->userfrom = $members[$localisedeventdata->userfrom];
100 }
101
102 // This should now hold only the other users (recipients).
103 unset($members[$localisedeventdata->userfrom->id]);
104 $otherusers = $members;
105
106 // Get conversation type and name. We'll use this to determine which message subject to generate, depending on type.
107 $conv = $DB->get_record('message_conversations', ['id' => $eventdata->convid], 'id, type, name');
108
109 // We treat individual conversations the same as any direct message with 'userfrom' and 'userto' specified.
110 // We know the other user, so set the 'userto' field so that the event code will get access to this field.
111 // If this was a legacy caller (eventdata->userto is set), then use that instead, as we want to use the fields specified
112 // in that object instead of using one fetched from the DB.
113 $legacymessage = false;
114 if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
115 if (isset($eventdata->userto)) {
116 $legacymessage = true;
117 } else {
118 $otheruser = reset($otherusers);
119 $eventdata->userto = $otheruser;
120 }
121 }
122
123 // Fetch enabled processors.
124 // If we are dealing with a message some processors may want to handle it regardless of user and site settings.
125 $processors = array_filter(get_message_processors(false), function($processor) {
126 if ($processor->object->force_process_messages()) {
127 return true;
128 }
129
130 return ($processor->enabled && $processor->configured);
131 });
132
133 // For each member of the conversation, other than the sender:
134 // 1. Set recipient specific event data (language specific, user prefs, etc)
135 // 2. Generate recipient specific processor list
136 // 3. Call send_message() to pass the message to processors and generate the relevant per-user events.
137 $eventprocmaps = []; // Init the event/processors buffer.
138 foreach ($otherusers as $recipient) {
139 // If this message was a legacy (1:1) message, then we use the userto.
140 if ($legacymessage) {
141 $recipient = $eventdata->userto;
142 }
143
144 $usertoisrealuser = (\core_user::is_real_user($recipient->id) != false);
145
146 // Using string manager directly so that strings in the message will be in the message recipients language rather than
147 // the sender's.
148 if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
149 $localisedeventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message',
150 fullname($localisedeventdata->userfrom), $recipient->lang);
151 } else if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP) {
152 $stringdata = (object) ['name' => fullname($localisedeventdata->userfrom), 'conversationname' => $conv->name];
153 $localisedeventdata->subject = get_string_manager()->get_string('unreadnewgroupconversationmessage', 'message',
154 $stringdata, $recipient->lang);
155 }
156
157 // Spoof the userto based on the current member id.
158 $localisedeventdata->userto = $recipient;
159
160 $s = new \stdClass();
161 $s->sitename = format_string($SITE->shortname, true, array('context' => \context_course::instance(SITEID)));
162 // When the new interface lands, the URL may be reintroduced, but for now it isn't supported, so just hit the index.
163 $s->url = $CFG->wwwroot.'/message/index.php';
164 $emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $recipient->lang);
165
166 $localisedeventdata->fullmessage = $eventdata->fullmessage;
167 $localisedeventdata->fullmessagehtml = $eventdata->fullmessagehtml;
168 if (!empty($localisedeventdata->fullmessage)) {
169 $localisedeventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n"
170 . $emailtagline;
171 }
172 if (!empty($localisedeventdata->fullmessagehtml)) {
173 $localisedeventdata->fullmessagehtml .=
174 "<br><br>---------------------------------------------------------------------<br>" . $emailtagline;
175 }
176
177 // If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
178 if (!$usertoisrealuser && !empty($recipient->emailstop)) {
179 debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
180 return false;
181 }
182
183 // Set the online state.
184 if (isset($CFG->block_online_users_timetosee)) {
185 $timetoshowusers = $CFG->block_online_users_timetosee * 60;
186 } else {
187 $timetoshowusers = 300;
188 }
189
190 // Work out if the user is logged in or not.
191 $userstate = 'loggedoff';
192 if (!empty($localisedeventdata->userto->lastaccess)
193 && (time() - $timetoshowusers) < $localisedeventdata->userto->lastaccess) {
194 $userstate = 'loggedin';
195 }
196
197 // Fill in the array of processors to be used based on default and user preferences.
267b4f03 198 // This applies only to individual conversations. Messages to group conversations ignore processors.
9581bc3c 199 $processorlist = [];
267b4f03
JD
200 if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
201 foreach ($processors as $processor) {
202 // Skip adding processors for internal user, if processor doesn't support sending message to internal user.
203 if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
204 continue;
205 }
9581bc3c 206
267b4f03
JD
207 // First find out permissions.
208 $defaultpreference = $processor->name . '_provider_' . $preferencebase . '_permitted';
209 if (isset($defaultpreferences->{$defaultpreference})) {
210 $permitted = $defaultpreferences->{$defaultpreference};
211 } else {
212 // MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
213 // exist in the message_provider table (thus there is no default settings for them).
214 $preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
9581bc3c 215 to message_send() are valid.";
267b4f03
JD
216 throw new coding_exception($preferrormsg);
217 }
9581bc3c 218
267b4f03
JD
219 // Find out if user has configured this output.
220 // Some processors cannot function without settings from the user.
221 $userisconfigured = $processor->object->is_user_configured($recipient);
9581bc3c 222
267b4f03
JD
223 // DEBUG: notify if we are forcing unconfigured output.
224 if ($permitted == 'forced' && !$userisconfigured) {
225 debugging('Attempt to force message delivery to user who has "' . $processor->name .
226 '" output unconfigured', DEBUG_NORMAL);
227 }
9581bc3c 228
267b4f03
JD
229 // Populate the list of processors we will be using.
230 if (!$eventdata->notification && $processor->object->force_process_messages()) {
231 $processorlist[] = $processor->name;
232 } else if ($permitted == 'forced' && $userisconfigured) {
233 // An admin is forcing users to use this message processor. Use this processor unconditionally.
234 $processorlist[] = $processor->name;
235 } else if ($permitted == 'permitted' && $userisconfigured && !$recipient->emailstop) {
236 // User has not disabled notifications.
237 // See if user set any notification preferences, otherwise use site default ones.
238 $userpreferencename = 'message_provider_' . $preferencebase . '_' . $userstate;
239 if ($userpreference = get_user_preferences($userpreferencename, null, $recipient)) {
240 if (in_array($processor->name, explode(',', $userpreference))) {
241 $processorlist[] = $processor->name;
242 }
243 } else if (isset($defaultpreferences->{$userpreferencename})) {
244 if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
245 $processorlist[] = $processor->name;
246 }
9581bc3c
JD
247 }
248 }
249 }
250 }
b30f4d6d
JD
251 // Batch up the localised event data and processor list for all users into a local buffer.
252 $eventprocmaps[] = [clone($localisedeventdata), $processorlist];
9581bc3c 253 }
b30f4d6d
JD
254 // Then pass it off as one item of work, to be processed by send_conversation_message_to_processors(), which will
255 // handle all transaction buffering logic.
256 self::send_conversation_message_to_processors($eventprocmaps, $eventdata, $savemessage);
9581bc3c
JD
257
258 return $savemessage->id;
259 }
260
b30f4d6d
JD
261 /**
262 * Takes a list of localised event data, and tries to send them to their respective member's message processors.
263 *
264 * Input format:
265 * [CONVID => [$localisedeventdata, $savemessage, $processorlist], ].
266 *
267 * @param array $eventprocmaps the array of localised event data and processors for each member of the conversation.
268 * @param message $eventdata the original conversation message eventdata
269 * @param \stdClass $savemessage the saved message record.
270 * @throws \coding_exception
271 */
272 protected static function send_conversation_message_to_processors(array $eventprocmaps, message $eventdata,
273 \stdClass $savemessage) {
274 global $DB;
275
276 // We cannot communicate with external systems in DB transactions,
277 // buffer the messages if necessary.
278 if ($DB->is_transaction_started()) {
279 // Buffer this group conversation message and it's record.
280 self::$convmessagebuffer[] = [$eventprocmaps, $eventdata, $savemessage];
281 return;
282 }
283
284 // Send each localised version of the event data to each member's respective processors.
285 foreach ($eventprocmaps as $eventprocmap) {
286 $eventdata = $eventprocmap[0];
287 $processorlist = $eventprocmap[1];
288 self::call_processors($eventdata, $processorlist);
289 }
290
291 // Trigger event for sending a message or notification - we need to do this before marking as read!
292 self::trigger_message_events($eventdata, $savemessage);
293 }
294
349f98ad
PS
295 /**
296 * Do the message sending.
297 *
298 * NOTE: to be used from message_send() only.
299 *
cc350fd9 300 * @param \core\message\message $eventdata fully prepared event data for processors
349f98ad
PS
301 * @param \stdClass $savemessage the message saved in 'message' table
302 * @param array $processorlist list of processors for target user
883ce421 303 * @return int $messageid the id from 'messages' (false is not returned)
349f98ad 304 */
cc4952e9 305 public static function send_message(message $eventdata, \stdClass $savemessage, array $processorlist) {
349f98ad 306 global $CFG;
c6f45ef8 307
349f98ad
PS
308 require_once($CFG->dirroot.'/message/lib.php'); // This is most probably already included from messagelib.php file.
309
310 if (empty($processorlist)) {
376a79c2 311 // Trigger event for sending a message or notification - we need to do this before marking as read!
947d3289 312 self::trigger_message_events($eventdata, $savemessage);
349f98ad 313
883ce421 314 if ($eventdata->notification or empty($CFG->messaging)) {
349f98ad
PS
315 // If they have deselected all processors and its a notification mark it read. The user doesn't want to be bothered.
316 // The same goes if the messaging is completely disabled.
883ce421 317 if ($eventdata->notification) {
548936a6
MN
318 $savemessage->timeread = null;
319 \core_message\api::mark_notification_as_read($savemessage);
883ce421 320 } else {
548936a6 321 \core_message\api::mark_message_as_read($eventdata->userto->id, $savemessage);
883ce421 322 }
349f98ad
PS
323 }
324
883ce421 325 return $savemessage->id;
349f98ad
PS
326 }
327
328 // Let the manager do the sending or buffering when db transaction in progress.
329 return self::send_message_to_processors($eventdata, $savemessage, $processorlist);
330 }
331
332 /**
333 * Send message to message processors.
334 *
c6f45ef8 335 * @param \stdClass|\core\message\message $eventdata
349f98ad
PS
336 * @param \stdClass $savemessage
337 * @param array $processorlist
338 * @return int $messageid
339 */
c6f45ef8
AA
340 protected static function send_message_to_processors($eventdata, \stdClass $savemessage, array
341 $processorlist) {
349f98ad
PS
342 global $CFG, $DB;
343
344 // We cannot communicate with external systems in DB transactions,
345 // buffer the messages if necessary.
349f98ad
PS
346 if ($DB->is_transaction_started()) {
347 // We need to clone all objects so that devs may not modify it from outside later.
348 $eventdata = clone($eventdata);
349 $eventdata->userto = clone($eventdata->userto);
350 $eventdata->userfrom = clone($eventdata->userfrom);
351
352 // Conserve some memory the same was as $USER setup does.
353 unset($eventdata->userto->description);
354 unset($eventdata->userfrom->description);
355
356 self::$buffer[] = array($eventdata, $savemessage, $processorlist);
357 return $savemessage->id;
358 }
359
947d3289
JD
360 // Send the message to processors.
361 self::call_processors($eventdata, $processorlist);
349f98ad 362
376a79c2 363 // Trigger event for sending a message or notification - we need to do this before marking as read!
947d3289 364 self::trigger_message_events($eventdata, $savemessage);
349f98ad 365
0d657cc9
MN
366 if (empty($CFG->messaging)) {
367 // If they have deselected all processors and its a notification mark it read. The user doesn't want to be bothered.
368 // The same goes if the messaging is completely disabled.
883ce421 369 if ($eventdata->notification) {
548936a6
MN
370 $savemessage->timeread = null;
371 \core_message\api::mark_notification_as_read($savemessage);
883ce421 372 } else {
548936a6 373 \core_message\api::mark_message_as_read($eventdata->userto->id, $savemessage);
883ce421 374 }
349f98ad
PS
375 }
376
883ce421 377 return $savemessage->id;
349f98ad
PS
378 }
379
380 /**
381 * Notification from DML layer.
382 *
383 * Note: to be used from DML layer only.
384 */
385 public static function database_transaction_commited() {
b30f4d6d 386 if (!self::$buffer && !self::$convmessagebuffer) {
349f98ad
PS
387 return;
388 }
389 self::process_buffer();
390 }
391
392 /**
393 * Notification from DML layer.
394 *
395 * Note: to be used from DML layer only.
396 */
397 public static function database_transaction_rolledback() {
398 self::$buffer = array();
9581bc3c 399 self::$convmessagebuffer = array();
349f98ad
PS
400 }
401
402 /**
403 * Sent out any buffered messages if necessary.
404 */
405 protected static function process_buffer() {
b30f4d6d 406 // Reset the buffers first in case we get exception from processor.
349f98ad
PS
407 $messages = self::$buffer;
408 self::$buffer = array();
b30f4d6d
JD
409 $convmessages = self::$convmessagebuffer;
410 self::$convmessagebuffer = array();
349f98ad
PS
411
412 foreach ($messages as $message) {
413 list($eventdata, $savemessage, $processorlist) = $message;
414 self::send_message_to_processors($eventdata, $savemessage, $processorlist);
415 }
b30f4d6d
JD
416
417 foreach ($convmessages as $convmessage) {
418 list($eventprocmap, $eventdata, $savemessage) = $convmessage;
419 self::send_conversation_message_to_processors($eventprocmap, $eventdata, $savemessage);
420 }
349f98ad 421 }
947d3289
JD
422
423 /**
424 * Trigger an appropriate message creation event, based on the supplied $eventdata and $savemessage.
425 *
426 * @param message $eventdata the eventdata for the message.
427 * @param \stdClass $savemessage the message record.
428 * @throws \coding_exception
429 */
430 protected static function trigger_message_events(message $eventdata, \stdClass $savemessage) {
9581bc3c 431 global $DB;
947d3289
JD
432 if ($eventdata->notification) {
433 \core\event\notification_sent::create_from_ids(
434 $eventdata->userfrom->id,
435 $eventdata->userto->id,
436 $savemessage->id,
437 $eventdata->courseid
438 )->trigger();
439 } else { // Must be a message.
9581bc3c
JD
440 // If the message is a group conversation, then trigger the 'group_message_sent' event.
441 if ($eventdata->convid) {
442 $conv = $DB->get_record('message_conversations', ['id' => $eventdata->convid], 'id, type');
443 if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP) {
444 \core\event\group_message_sent::create_from_ids(
445 $eventdata->userfrom->id,
446 $eventdata->convid,
447 $savemessage->id,
448 $eventdata->courseid
449 )->trigger();
450 return;
451 }
452 // Individual type conversations fall through to the default 'message_sent' event.
453 }
947d3289
JD
454 \core\event\message_sent::create_from_ids(
455 $eventdata->userfrom->id,
456 $eventdata->userto->id,
457 $savemessage->id,
458 $eventdata->courseid
459 )->trigger();
460 }
461 }
462
463 /**
464 * For each processor, call it's send_message() method.
465 *
466 * @param message $eventdata the message object.
467 * @param array $processorlist the list of processors for a single user.
468 */
469 protected static function call_processors(message $eventdata, array $processorlist) {
470 foreach ($processorlist as $procname) {
471 // Let new messaging class add custom content based on the processor.
472 $proceventdata = ($eventdata instanceof message) ? $eventdata->get_eventobject_for_processor($procname) : $eventdata;
473 $stdproc = new \stdClass();
474 $stdproc->name = $procname;
475 $processor = \core_message\api::get_processed_processor_object($stdproc);
476 if (!$processor->object->send_message($proceventdata)) {
477 debugging('Error calling message processor ' . $procname);
478 }
479 }
480 }
349f98ad 481}