diff --git a/lib/classes/event/message_sent.php b/lib/classes/event/message_sent.php index 2ddb1b20d0e..91a759e8860 100644 --- a/lib/classes/event/message_sent.php +++ b/lib/classes/event/message_sent.php @@ -65,8 +65,13 @@ class message_sent extends base { * @return string */ public function get_description() { - return 'The user with the id \'' . $this->userid . '\' sent a message to the user with the id \'' . - $this->relateduserid . '\'.'; + // Check that we are sending from a valid user. + if ($this->userid > 0) { + return 'The user with the id \'' . $this->userid . '\' sent a message to the user with the id \'' . + $this->relateduserid . '\'.'; + } else { + return 'A message was sent by the system to the user with the id \'' . $this->relateduserid . '\'.'; + } } /** @@ -75,8 +80,14 @@ class message_sent extends base { * @return array */ protected function get_legacy_logdata() { - return array(SITEID, 'message', 'write', 'index.php?user=' . $this->userid . '&id=' . $this->relateduserid . - '&history=1#m' . $this->other['messageid'], $this->userid); + // The add_to_log function was only ever called when we sent a message from one user to another. We do not want + // to return the legacy log data if we are sending a system message, so check that the userid is valid. + if ($this->userid > 0) { + return array(SITEID, 'message', 'write', 'index.php?user=' . $this->userid . '&id=' . $this->relateduserid . + '&history=1#m' . $this->other['messageid'], $this->userid); + } + + return null; } /** diff --git a/lib/messagelib.php b/lib/messagelib.php index 0b4346f55e4..9d99f25f6b3 100644 --- a/lib/messagelib.php +++ b/lib/messagelib.php @@ -247,10 +247,21 @@ function message_send($eventdata) { } } + // We may be sending a message from the 'noreply' address, which means we are not actually sending a + // message from a valid user. In this case, we will set the userid to 0 and the context to system. + // Check if the userid is valid. + if ($eventdata->userfrom->id > 0) { + $userfromid = $eventdata->userfrom->id; + $context = context_user::instance($eventdata->userfrom->id); + } else { + $userfromid = 0; + $context = context_system::instance(); + } + // Trigger event for sending a message. $event = \core\event\message_sent::create(array( - 'userid' => $eventdata->userfrom->id, - 'context' => context_user::instance($eventdata->userfrom->id), + 'userid' => $userfromid, + 'context' => $context, 'relateduserid' => $eventdata->userto->id, 'other' => array( 'messageid' => $messageid // Can't use this as the objectid as it can either be the id in the 'message_read'