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