first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,103 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_message\external;
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/message/lib.php');
use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_value;
use context_system;
use core_user;
use moodle_exception;
/**
* External service to get number of unread notifications
*
* @package core_message
* @category external
* @copyright 2021 Dani Palou <dani@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 4.0
*/
class get_unread_notification_count extends external_api {
/**
* Returns description of method parameters
*
* @return external_function_parameters
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters([
'useridto' => new external_value(PARAM_INT, 'user id who received the notification, 0 for any user', VALUE_REQUIRED),
]);
}
/**
* Get number of unread notifications.
*
* @param int $useridto the user id who received the notification, 0 for any user
* @return int number of unread notifications
* @throws \moodle_exception
*/
public static function execute(int $useridto): int {
global $USER, $DB;
$params = self::validate_parameters(
self::execute_parameters(),
['useridto' => $useridto],
);
$context = context_system::instance();
self::validate_context($context);
$useridto = $params['useridto'];
if (!empty($useridto)) {
if (core_user::is_real_user($useridto)) {
$userto = core_user::get_user($useridto, '*', MUST_EXIST);
} else {
throw new moodle_exception('invaliduser');
}
}
// Check if the current user is the sender/receiver or just a privileged user.
if ($useridto != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
throw new moodle_exception('accessdenied', 'admin');
}
return $DB->count_records_sql(
"SELECT COUNT(n.id)
FROM {notifications} n
LEFT JOIN {user} u ON (u.id = n.useridfrom AND u.deleted = 0)
WHERE n.useridto = ?
AND n.timeread IS NULL",
[$useridto],
);
}
/**
* Describe the return structure of the external service.
*
* @return external_value
*/
public static function execute_returns(): external_value {
return new external_value(PARAM_INT, 'The count of unread notifications.');
}
}
+724
View File
@@ -0,0 +1,724 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains helper class for the message area.
*
* @package core_message
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message;
use DOMDocument;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/message/lib.php');
/**
* Helper class for the message area.
*
* @copyright 2016 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class helper {
/**
* @deprecated since 3.6
*/
public static function get_messages() {
throw new \coding_exception('\core_message\helper::get_messages has been removed.');
}
/**
* Helper function to retrieve conversation messages.
*
* @param int $userid The current user.
* @param int $convid The conversation identifier.
* @param int $timedeleted The time the message was deleted
* @param int $limitfrom Return a subset of records, starting at this point (optional).
* @param int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
* @param string $sort The column name to order by including optionally direction.
* @param int $timefrom The time from the message being sent.
* @param int $timeto The time up until the message being sent.
* @return array of messages
*/
public static function get_conversation_messages(int $userid, int $convid, int $timedeleted = 0, int $limitfrom = 0,
int $limitnum = 0, string $sort = 'timecreated ASC', int $timefrom = 0,
int $timeto = 0): array {
global $DB;
$sql = "SELECT m.id, m.useridfrom, m.subject, m.fullmessage, m.fullmessagehtml,
m.fullmessageformat, m.fullmessagetrust, m.smallmessage, m.timecreated,
mc.contextid, muaread.timecreated AS timeread
FROM {message_conversations} mc
INNER JOIN {messages} m
ON m.conversationid = mc.id
LEFT JOIN {message_user_actions} muaread
ON (muaread.messageid = m.id
AND muaread.userid = :userid1
AND muaread.action = :readaction)";
$params = ['userid1' => $userid, 'readaction' => api::MESSAGE_ACTION_READ, 'convid' => $convid];
if (empty($timedeleted)) {
$sql .= " LEFT JOIN {message_user_actions} mua
ON (mua.messageid = m.id
AND mua.userid = :userid2
AND mua.action = :deleteaction
AND mua.timecreated is NOT NULL)";
} else {
$sql .= " INNER JOIN {message_user_actions} mua
ON (mua.messageid = m.id
AND mua.userid = :userid2
AND mua.action = :deleteaction
AND mua.timecreated = :timedeleted)";
$params['timedeleted'] = $timedeleted;
}
$params['userid2'] = $userid;
$params['deleteaction'] = api::MESSAGE_ACTION_DELETED;
$sql .= " WHERE mc.id = :convid";
if (!empty($timefrom)) {
$sql .= " AND m.timecreated >= :timefrom";
$params['timefrom'] = $timefrom;
}
if (!empty($timeto)) {
$sql .= " AND m.timecreated <= :timeto";
$params['timeto'] = $timeto;
}
if (empty($timedeleted)) {
$sql .= " AND mua.id is NULL";
}
$sql .= " ORDER BY m.$sort";
$messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
return $messages;
}
/**
* Helper function to return a conversation messages with the involved members (only the ones
* who have sent any of these messages).
*
* @param int $userid The current userid.
* @param int $convid The conversation id.
* @param array $messages The formated array messages.
* @return array A conversation array with the messages and the involved members.
*/
public static function format_conversation_messages(int $userid, int $convid, array $messages): array {
global $USER;
// Create the conversation array.
$conversation = array(
'id' => $convid,
);
// Store the messages.
$arrmessages = array();
foreach ($messages as $message) {
// Store the message information.
$msg = new \stdClass();
$msg->id = $message->id;
$msg->useridfrom = $message->useridfrom;
$msg->text = message_format_message_text($message);
$msg->timecreated = $message->timecreated;
$arrmessages[] = $msg;
}
// Add the messages to the conversation.
$conversation['messages'] = $arrmessages;
// Get the users who have sent any of the $messages.
$memberids = array_unique(array_map(function($message) {
return $message->useridfrom;
}, $messages));
if (!empty($memberids)) {
// Get members information.
$conversation['members'] = self::get_member_info($userid, $memberids);
} else {
$conversation['members'] = array();
}
return $conversation;
}
/**
* @deprecated since 3.6
*/
public static function create_messages() {
throw new \coding_exception('\core_message\helper::create_messages has been removed.');
}
/**
* Helper function for creating a contact object.
*
* @param \stdClass $contact
* @param string $prefix
* @return \stdClass
*/
public static function create_contact($contact, $prefix = '') {
global $PAGE;
// Create the data we are going to pass to the renderable.
$userfields = \user_picture::unalias($contact, array('lastaccess'), $prefix . 'id', $prefix);
$data = new \stdClass();
$data->userid = $userfields->id;
$data->useridfrom = null;
$data->fullname = fullname($userfields);
// Get the user picture data.
$userpicture = new \user_picture($userfields);
$userpicture->size = 1; // Size f1.
$data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
$userpicture->size = 0; // Size f2.
$data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
// Store the message if we have it.
$data->ismessaging = false;
$data->lastmessage = null;
$data->lastmessagedate = null;
$data->messageid = null;
if (isset($contact->smallmessage)) {
$data->ismessaging = true;
// Strip the HTML tags from the message for displaying in the contact area.
$data->lastmessage = clean_param($contact->smallmessage, PARAM_NOTAGS);
$data->lastmessagedate = $contact->timecreated;
$data->useridfrom = $contact->useridfrom;
if (isset($contact->messageid)) {
$data->messageid = $contact->messageid;
}
}
$data->isonline = null;
$user = \core_user::get_user($data->userid);
if (self::show_online_status($user)) {
$data->isonline = self::is_online($userfields->lastaccess);
}
$data->isblocked = isset($contact->blocked) ? (bool) $contact->blocked : false;
$data->isread = isset($contact->isread) ? (bool) $contact->isread : false;
$data->unreadcount = isset($contact->unreadcount) ? $contact->unreadcount : null;
$data->conversationid = $contact->conversationid ?? null;
return $data;
}
/**
* Helper function for checking if we should show the user's online status.
*
* @param \stdClass $user
* @return boolean
*/
public static function show_online_status($user) {
global $CFG;
require_once($CFG->dirroot . '/user/lib.php');
if ($lastaccess = user_get_user_details($user, null, array('lastaccess'))) {
if (isset($lastaccess['lastaccess'])) {
return true;
}
}
return false;
}
/**
* Helper function for checking the time meets the 'online' condition.
*
* @param int $lastaccess
* @return boolean
*/
public static function is_online($lastaccess) {
global $CFG;
// Variable to check if we consider this user online or not.
$timetoshowusers = 300; // Seconds default.
if (isset($CFG->block_online_users_timetosee)) {
$timetoshowusers = $CFG->block_online_users_timetosee * 60;
}
$time = time() - $timetoshowusers;
return $lastaccess >= $time;
}
/**
* Get providers preferences.
*
* @param array $providers
* @param int $userid
* @return \stdClass
*/
public static function get_providers_preferences($providers, $userid) {
$preferences = new \stdClass();
// Get providers preferences.
foreach ($providers as $provider) {
$linepref = get_user_preferences('message_provider_' . $provider->component . '_' . $provider->name
. '_enabled', '', $userid);
if ($linepref == '') {
continue;
}
$lineprefarray = explode(',', $linepref);
$preferences->{$provider->component.'_'.$provider->name.'_enabled'} = [];
foreach ($lineprefarray as $pref) {
$preferences->{$provider->component.'_'.$provider->name.'_enabled'}[$pref] = 1;
}
}
return $preferences;
}
/**
* Requires the JS libraries for the toggle contact button.
*
* @return void
*/
public static function togglecontact_requirejs() {
global $PAGE;
static $done = false;
if ($done) {
return;
}
$PAGE->requires->js_call_amd('core_message/toggle_contact_button', 'enhance', array('#toggle-contact-button'));
$done = true;
}
/**
* Returns the attributes to place on a contact button.
*
* @param object $user User object.
* @param bool $iscontact
* @param bool $displaytextlabel Instructs whether to display a text label.
* @param bool $isrequested Whether the contact request is sent or not.
* @return array
*/
public static function togglecontact_link_params(
$user,
$iscontact = false,
bool $displaytextlabel = true,
bool $isrequested = false,
) {
global $USER;
$params = array(
'data-currentuserid' => $USER->id,
'data-userid' => $user->id,
'data-is-contact' => $iscontact,
'data-is-requested' => $isrequested,
'data-display-text-label' => $displaytextlabel,
'id' => 'toggle-contact-button',
'role' => 'button',
'class' => 'ajax-contact-button',
);
return $params;
}
/**
* Requires the JS libraries for the message user button.
*
* @return void
*/
public static function messageuser_requirejs() {
global $PAGE;
static $done = false;
if ($done) {
return;
}
$PAGE->requires->js_call_amd('core_message/message_user_button', 'send', array('#message-user-button'));
$done = true;
}
/**
* Returns the attributes to place on the message user button.
*
* @param int $useridto
* @return array
*/
public static function messageuser_link_params(int $useridto): array {
global $USER;
return [
'id' => 'message-user-button',
'role' => 'button',
'data-conversationid' => api::get_conversation_between_users([$USER->id, $useridto]),
'data-userid' => $useridto,
];
}
/**
* Returns the conversation hash between users for easy look-ups in the DB.
*
* @param array $userids
* @return string
*/
public static function get_conversation_hash(array $userids) {
sort($userids);
return sha1(implode('-', $userids));
}
/**
* Returns the cache key for the time created value of the last message of this conversation.
*
* @param int $convid The conversation identifier.
* @return string The key.
*/
public static function get_last_message_time_created_cache_key(int $convid) {
return $convid;
}
/**
* Checks if legacy messages exist for a given user.
*
* @param int $userid
* @return bool
*/
public static function legacy_messages_exist($userid) {
global $DB;
$sql = "SELECT id
FROM {message} m
WHERE useridfrom = ?
OR useridto = ?";
$messageexists = $DB->record_exists_sql($sql, [$userid, $userid]);
$sql = "SELECT id
FROM {message_read} m
WHERE useridfrom = ?
OR useridto = ?";
$messagereadexists = $DB->record_exists_sql($sql, [$userid, $userid]);
return $messageexists || $messagereadexists;
}
/**
* Returns conversation member info for the supplied users, relative to the supplied referenceuserid.
*
* This is the basic structure used when returning members, and includes information about the relationship between each member
* and the referenceuser, such as a whether the referenceuser has marked the member as a contact, or has blocked them.
*
* @param int $referenceuserid the id of the user which check contact and blocked status.
* @param array $userids
* @param bool $includecontactrequests Do we want to include contact requests with this data?
* @param bool $includeprivacyinfo Do we want to include whether the user can message another, and if the user
* requires a contact.
* @return array the array of objects containing member info, indexed by userid.
* @throws \coding_exception
* @throws \dml_exception
*/
public static function get_member_info(int $referenceuserid, array $userids, bool $includecontactrequests = false,
bool $includeprivacyinfo = false): array {
global $DB, $PAGE;
// Prevent exception being thrown when array is empty.
if (empty($userids)) {
return [];
}
list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
$userfieldsapi = \core_user\fields::for_userpic()->including('lastaccess');
$userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
$userssql = "SELECT $userfields, u.deleted, mc.id AS contactid, mub.id AS blockedid
FROM {user} u
LEFT JOIN {message_contacts} mc
ON ((mc.userid = ? AND mc.contactid = u.id) OR (mc.userid = u.id AND mc.contactid = ?))
LEFT JOIN {message_users_blocked} mub
ON (mub.userid = ? AND mub.blockeduserid = u.id)
WHERE u.id $useridsql";
$usersparams = array_merge([$referenceuserid, $referenceuserid, $referenceuserid], $usersparams);
$otherusers = $DB->get_records_sql($userssql, $usersparams);
$members = [];
foreach ($otherusers as $member) {
// Set basic data.
$data = new \stdClass();
$data->id = $member->id;
$data->fullname = fullname($member);
// Create the URL for their profile.
$profileurl = new \moodle_url('/user/profile.php', ['id' => $member->id]);
$data->profileurl = $profileurl->out(false);
// Set the user picture data.
$userpicture = new \user_picture($member);
$userpicture->size = 1; // Size f1.
$data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
$userpicture->size = 0; // Size f2.
$data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
// Set online status indicators.
$data->isonline = false;
$data->showonlinestatus = false;
if (!$member->deleted) {
$data->isonline = self::show_online_status($member) ? self::is_online($member->lastaccess) : null;
$data->showonlinestatus = is_null($data->isonline) ? false : true;
}
// Set contact and blocked status indicators.
$data->iscontact = ($member->contactid) ? true : false;
// We don't want that a user has been blocked if they can message the user anyways.
$canmessageifblocked = api::can_send_message($referenceuserid, $member->id, true);
$data->isblocked = ($member->blockedid && !$canmessageifblocked) ? true : false;
$data->isdeleted = ($member->deleted) ? true : false;
$data->requirescontact = null;
$data->canmessage = null;
$data->canmessageevenifblocked = null;
if ($includeprivacyinfo) {
$privacysetting = api::get_user_privacy_messaging_preference($member->id);
$data->requirescontact = $privacysetting == api::MESSAGE_PRIVACY_ONLYCONTACTS;
// Here we check that if the sender wanted to block the recipient, the
// recipient would still be able to message them regardless.
$data->canmessageevenifblocked = !$data->isdeleted && $canmessageifblocked;
$data->canmessage = !$data->isdeleted && api::can_send_message($member->id, $referenceuserid);
}
// Populate the contact requests, even if we don't need them.
$data->contactrequests = [];
$members[$data->id] = $data;
}
// Check if we want to include contact requests as well.
if (!empty($members) && $includecontactrequests) {
list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
$wheresql = "(userid $useridsql AND requesteduserid = ?) OR (userid = ? AND requesteduserid $useridsql)";
$params = array_merge($usersparams, [$referenceuserid, $referenceuserid], $usersparams);
if ($contactrequests = $DB->get_records_select('message_contact_requests', $wheresql, $params,
'timecreated ASC, id ASC')) {
foreach ($contactrequests as $contactrequest) {
if (isset($members[$contactrequest->userid])) {
$members[$contactrequest->userid]->contactrequests[] = $contactrequest;
}
if (isset($members[$contactrequest->requesteduserid])) {
$members[$contactrequest->requesteduserid]->contactrequests[] = $contactrequest;
}
}
}
}
// Remove any userids not in $members. This can happen in the case of a user who has been deleted
// from the Moodle database table (which can happen in earlier versions of Moodle).
$userids = array_filter($userids, function($userid) use ($members) {
return isset($members[$userid]);
});
// Return member information in the same order as the userids originally provided.
$members = array_replace(array_flip($userids), $members);
return $members;
}
/**
* @deprecated since 3.6
*/
public static function get_conversations_legacy_formatter() {
throw new \coding_exception('\core_message\helper::get_conversations_legacy_formatter has been removed.');
}
/**
* Renders the messaging widget.
*
* @param bool $isdrawer Are we are rendering the drawer or is this on a full page?
* @param int|null $sendtouser The ID of the user we want to send a message to
* @param int|null $conversationid The ID of the conversation we want to load
* @param string|null $view The first view to load in the message widget
* @return string The HTML.
*/
public static function render_messaging_widget(
bool $isdrawer,
int $sendtouser = null,
int $conversationid = null,
string $view = null
) {
global $USER, $CFG, $PAGE;
// Early bail out conditions.
if (empty($CFG->messaging) || !isloggedin() || isguestuser() || \core_user::awaiting_action()) {
return '';
}
$renderer = $PAGE->get_renderer('core');
$requestcount = \core_message\api::get_received_contact_requests_count($USER->id);
$contactscount = \core_message\api::count_contacts($USER->id);
$choices = [];
$choices[] = [
'value' => \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
'text' => get_string('contactableprivacy_onlycontacts', 'message')
];
$choices[] = [
'value' => \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
'text' => get_string('contactableprivacy_coursemember', 'message')
];
if (!empty($CFG->messagingallusers)) {
// Add the MESSAGE_PRIVACY_SITE option when site-wide messaging between users is enabled.
$choices[] = [
'value' => \core_message\api::MESSAGE_PRIVACY_SITE,
'text' => get_string('contactableprivacy_site', 'message')
];
}
// Enter to send.
$entertosend = get_user_preferences('message_entertosend', $CFG->messagingdefaultpressenter, $USER);
$notification = '';
if (!get_user_preferences('core_message_migrate_data', false)) {
$notification = get_string('messagingdatahasnotbeenmigrated', 'message');
}
if ($isdrawer) {
$template = 'core_message/message_drawer';
$messageurl = new \moodle_url('/message/index.php');
} else {
$template = 'core_message/message_index';
$messageurl = null;
}
$templatecontext = [
'contactrequestcount' => $requestcount,
'loggedinuser' => [
'id' => $USER->id,
'midnight' => usergetmidnight(time())
],
// The starting timeout value for message polling.
'messagepollmin' => $CFG->messagingminpoll ?? MESSAGE_DEFAULT_MIN_POLL_IN_SECONDS,
// The maximum value that message polling timeout can reach.
'messagepollmax' => $CFG->messagingmaxpoll ?? MESSAGE_DEFAULT_MAX_POLL_IN_SECONDS,
// The timeout to reset back to after the max polling time has been reached.
'messagepollaftermax' => $CFG->messagingtimeoutpoll ?? MESSAGE_DEFAULT_TIMEOUT_POLL_IN_SECONDS,
'contacts' => [
'sectioncontacts' => [
'placeholders' => array_fill(0, $contactscount > 50 ? 50 : $contactscount, true)
],
'sectionrequests' => [
'placeholders' => array_fill(0, $requestcount > 50 ? 50 : $requestcount, true)
],
],
'settings' => [
'privacy' => $choices,
'entertosend' => $entertosend
],
'overview' => [
'messageurl' => $messageurl,
'notification' => $notification
],
'isdrawer' => $isdrawer,
'showemojipicker' => !empty($CFG->allowemojipicker),
'messagemaxlength' => api::MESSAGE_MAX_LENGTH,
'caneditownmessageprofile' => has_capability('moodle/user:editownmessageprofile', \context_system::instance())
];
if ($sendtouser || $conversationid) {
$route = [
'path' => 'view-conversation',
'params' => $conversationid ? [$conversationid] : [null, 'create', $sendtouser]
];
} else if ($view === 'contactrequests') {
$route = [
'path' => 'view-contacts',
'params' => ['requests']
];
} else {
$route = null;
}
$templatecontext['route'] = json_encode($route);
return $renderer->render_from_template($template, $templatecontext);
}
/**
* Returns user details for a user, if they are visible to the current user in the message search.
*
* This method checks the visibility of a user specifically for the purpose of inclusion in the message search results.
* Visibility depends on the site-wide messaging setting 'messagingallusers':
* If enabled, visibility depends only on the core notion of visibility; a visible site or course profile.
* If disabled, visibility requires that the user be sharing a course with the searching user, and have a visible profile there.
* The current user is always returned.
*
* You can use the $userfields parameter to reduce the amount of a user record that is required by the method.
* The minimum user fields are:
* * id
* * deleted
* * all potential fullname fields
*
* @param \stdClass $user
* @param array $userfields An array of userfields to be returned, the values must be a
* subset of user_get_default_fields (optional)
* @return array the array of userdetails, if visible, or an empty array otherwise.
*/
public static function search_get_user_details(\stdClass $user, array $userfields = []): array {
global $CFG, $USER;
require_once($CFG->dirroot . '/user/lib.php');
if ($CFG->messagingallusers || $user->id == $USER->id) {
return \user_get_user_details_courses($user, $userfields) ?? []; // This checks visibility of site and course profiles.
} else {
// Messaging specific: user must share a course with the searching user AND have a visible profile there.
$sharedcourses = enrol_get_shared_courses($USER, $user);
foreach ($sharedcourses as $course) {
if (user_can_view_profile($user, $course)) {
$userdetails = user_get_user_details($user, $course, $userfields);
if (!is_null($userdetails)) {
return $userdetails;
}
}
}
}
return [];
}
/**
* Prevent unclosed HTML elements in a message.
*
* @param string $message The html message.
* @param bool $removebody True if we want to remove tag body.
* @return string The html properly structured.
*/
public static function prevent_unclosed_html_tags(
string $message,
bool $removebody = false
): string {
$html = '';
if (!empty($message)) {
$doc = new DOMDocument();
$olderror = libxml_use_internal_errors(true);
$doc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $message);
libxml_clear_errors();
libxml_use_internal_errors($olderror);
$html = $doc->getElementsByTagName('body')->item(0)->C14N(false, true);
if ($removebody) {
// Remove <body> element added in C14N function.
$html = preg_replace('~<(/?(?:body))[^>]*>\s*~i', '', $html);
}
}
return $html;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace core_message;
/**
* Class hook_callbacks
*
* @package core_message
* @copyright 2024 Andrew Lyons <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class hook_callbacks {
/**
* Add messaging widgets after the main region content.
*
* @param \core\hook\output\after_standard_main_region_html_generation $hook
*/
public static function add_messaging_widget(
\core\hook\output\after_standard_main_region_html_generation $hook,
): void {
$hook->add_html(\core_message\helper::render_messaging_widget(
isdrawer: true,
));
}
}
@@ -0,0 +1,51 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains message_notification_list class for displaying on message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\output\preferences;
defined('MOODLE_INTERNAL') || die();
/**
* Class to create context for the list of notifications on the message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class message_notification_list extends notification_list {
/**
* Create the list component output object.
*
* @param string $component
* @param array $readyprocessors
* @param array $providers
* @param \stdClass $preferences
* @param \stdClass $user
* @return message_notification_list_component
*/
protected function create_list_component($component, $readyprocessors, $providers, $preferences, $user) {
return new message_notification_list_component($component, $readyprocessors, $providers, $preferences, $user);
}
}
@@ -0,0 +1,52 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains notification_list_component class for displaying on message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\output\preferences;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/message/lib.php');
use renderable;
use templatable;
/**
* Class to create context for a notification component on the message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class message_notification_list_component extends notification_list_component {
/**
* Determine if the preference should be displayed.
*
* @param string $preferencekey
* @return bool
*/
protected function should_show_preference_key($preferencekey) {
return $preferencekey === 'message_provider_moodle_instantmessage';
}
}
@@ -0,0 +1,167 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains notification_list class for displaying on message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\output\preferences;
defined('MOODLE_INTERNAL') || die();
use renderable;
use templatable;
use context_user;
/**
* Class to create context for the list of notifications on the message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class notification_list implements templatable, renderable {
/**
* @var array A list of message processors.
*/
protected $processors;
/**
* @var array A list of message providers.
*/
protected $providers;
/**
* @var array A list of message preferences.
*/
protected $preferences;
/**
* @var \stdClass A user.
*/
protected $user;
/**
* Constructor.
*
* @param array $processors
* @param array $providers
* @param \stdClass $preferences
* @param \stdClass $user
*/
public function __construct($processors, $providers, $preferences, $user) {
$this->processors = $processors;
$this->providers = $providers;
$this->preferences = $preferences;
$this->user = $user;
}
/**
* Create the list component output object.
*
* @param string $component
* @param array $readyprocessors
* @param array $providers
* @param \stdClass $preferences
* @param \stdClass $user
* @return notification_list_component
*/
protected function create_list_component($component, $readyprocessors, $providers, $preferences, $user) {
return new notification_list_component($component, $readyprocessors, $providers, $preferences, $user);
}
public function export_for_template(\renderer_base $output) {
$processors = $this->processors;
$providers = $this->providers;
$preferences = $this->preferences;
$user = $this->user;
$usercontext = context_user::instance($user->id);
$activitycomponents = [];
$othercomponents = [];
// Order the components so that the activities appear first, followed
// by the system and then anything else.
foreach ($providers as $provider) {
if ($provider->component != 'moodle') {
if (substr($provider->component, 0, 4) == 'mod_') {
// Activities.
$activitycomponents[] = $provider->component;
} else {
// Other stuff.
$othercomponents[] = $provider->component;
}
}
}
$activitycomponents = array_unique($activitycomponents);
asort($activitycomponents);
$othercomponents = array_unique($othercomponents);
asort($othercomponents);
$components = array_merge($activitycomponents, ['moodle'], $othercomponents);
asort($providers);
$context = [
'userid' => $user->id,
'disableall' => $user->emailstop,
'processors' => [],
];
$readyprocessors = [];
// Make the unconfigured processors appear last in the array.
uasort($processors, function($a, $b) {
$aconf = $a->object->is_user_configured();
$bconf = $b->object->is_user_configured();
if ($aconf == $bconf) {
return 0;
}
return ($aconf < $bconf) ? 1 : -1;
});
foreach ($processors as $processor) {
if (!$processor->enabled || !$processor->configured) {
// If the processor isn't enabled and configured at the site
// level then we should ignore it.
continue;
}
$context['processors'][] = [
'displayname' => get_string('pluginname', 'message_'.$processor->name),
'name' => $processor->name,
'hassettings' => !empty($processor->object->config_form($preferences)),
'contextid' => $usercontext->id,
'userconfigured' => $processor->object->is_user_configured(),
];
$readyprocessors[] = $processor;
}
foreach ($components as $component) {
$notificationcomponent = $this->create_list_component($component, $readyprocessors,
$providers, $preferences, $user);
$context['components'][] = $notificationcomponent->export_for_template($output);
}
return $context;
}
}
@@ -0,0 +1,168 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains notification_list_component class for displaying on message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\output\preferences;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/message/lib.php');
use renderable;
use templatable;
/**
* Class to create context for a notification component on the message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class notification_list_component implements templatable, renderable {
/**
* @var array A list of message processors.
*/
protected $processors;
/**
* @var array A list of message providers.
*/
protected $providers;
/**
* @var array A list of message preferences.
*/
protected $preferences;
/**
* @var string The component name.
*/
protected $component;
/**
* @var \stdClass A user.
*/
protected $user;
/**
* Constructor.
*
* @param string $component
* @param array $processors
* @param array $providers
* @param \stdClass $preferences
* @param \stdClass $user
*/
public function __construct($component, $processors, $providers, $preferences, $user) {
$this->processors = $processors;
$this->providers = $providers;
$this->preferences = $preferences;
$this->component = $component;
$this->user = $user;
}
/**
* Get the base key prefix for the given provider.
*
* @param \stdClass $provider The message provider
* @return string
*/
private function get_preference_base($provider) {
return $provider->component.'_'.$provider->name;
}
/**
* Get the display name for the given provider.
*
* @param \stdClass $provider The message provider
* @return string
*/
private function get_provider_display_name($provider) {
return get_string('messageprovider:'.$provider->name, $provider->component);
}
/**
* Determine if the preference should be displayed.
*
* @param string $preferencekey
* @return bool
*/
protected function should_show_preference_key($preferencekey) {
return $preferencekey !== 'message_provider_moodle_instantmessage';
}
public function export_for_template(\renderer_base $output) {
$processors = $this->processors;
$providers = $this->providers;
$preferences = $this->preferences;
$component = $this->component;
$defaultpreferences = get_message_output_default_preferences();
if ($component != 'moodle') {
$componentname = get_string('pluginname', $component);
} else {
$componentname = get_string('coresystem');
}
$context = [
'displayname' => $componentname,
'colspan' => count($processors) + 1,
'notifications' => [],
];
foreach ($providers as $provider) {
$preferencebase = $this->get_preference_base($provider);
$preferencekey = 'message_provider_'.$preferencebase;
// Hack to stop this one specific preference from showing up in the
// notification list because it belongs to the message preferences page.
if (!$this->should_show_preference_key($preferencekey)) {
continue;
}
// If provider component is not same or provider disabled then don't show.
if (($provider->component != $component) ||
(!empty($defaultpreferences->{$preferencebase.'_disable'}))) {
continue;
}
$notificationcontext = [
'displayname' => $this->get_provider_display_name($provider),
'preferencekey' => $preferencekey,
'processors' => [],
];
foreach ($processors as $processor) {
$notificationprocessor = new notification_list_processor($processor, $provider, $preferences);
$notificationcontext['processors'][] = $notificationprocessor->export_for_template($output);
}
$context['notifications'][] = $notificationcontext;
}
$context['hasnotifications'] = (count($context['notifications']) > 0);
return $context;
}
}
@@ -0,0 +1,170 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains notification_list_processor class for displaying on message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\output\preferences;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/message/lib.php');
use renderable;
use templatable;
/**
* Class to create context for a notification component on the message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class notification_list_processor implements templatable, renderable {
/**
* @var \stdClass A notification processor.
*/
protected $processor;
/**
* @var \stdClass A notification provider.
*/
protected $provider;
/**
* @var \stdClass A list of message preferences.
*/
protected $preferences;
/**
* Constructor.
*
* @param \stdClass $processor
* @param \stdClass $provider
* @param \stdClass $preferences
*/
public function __construct($processor, $provider, $preferences) {
$this->processor = $processor;
$this->provider = $provider;
$this->preferences = $preferences;
}
/**
* Get the base key prefix for the given provider.
*
* @return string
*/
private function get_preference_base() {
return $this->provider->component . '_' . $this->provider->name;
}
/**
* Check if the given preference is enabled or not.
*
* @param string $name preference name
* @param string $locked Wether the preference is locked by admin.
* @return bool
*/
private function is_preference_enabled($name, $locked) {
$processor = $this->processor;
$preferences = $this->preferences;
$defaultpreferences = get_message_output_default_preferences();
$checked = false;
// See if user has touched this preference.
if (!$locked && isset($preferences->{$name})) {
// User has some preferences for this state in the database.
$checked = isset($preferences->{$name}[$processor->name]);
} else {
// User has not set this preference yet, using site default preferences set by admin.
$defaultpreference = 'message_provider_'.$name;
if (isset($defaultpreferences->{$defaultpreference})) {
$checked = (int)in_array($processor->name, explode(',', $defaultpreferences->{$defaultpreference}));
}
}
return $checked;
}
/**
* Export this data so it can be used as the context for a mustache template.
* @todo Remove loggedin and loggedoff from context on MDL-73284.
*
* @param renderer_base $output
* @return stdClass
*/
public function export_for_template(\renderer_base $output) {
$processor = $this->processor;
$preferencebase = $this->get_preference_base();
$defaultpreferences = get_message_output_default_preferences();
$defaultpreference = $processor->name.'_provider_'.$preferencebase.'_locked';
$providername = get_string('messageprovider:'.$this->provider->name, $this->provider->component);
$processorname = get_string('pluginname', 'message_'.$processor->name);
$labelparams = [
'provider' => $providername,
'processor' => $processorname,
];
$context = [
'displayname' => $processorname,
'name' => $processor->name,
'locked' => false,
'userconfigured' => $processor->object->is_user_configured(),
// Backward compatibility, deprecated attribute.
'loggedin' => [
'name' => 'loggedin',
'displayname' => 'loggedin',
'checked' => false,
],
// Backward compatibility, deprecated attribute.
'loggedoff' => [
'name' => 'loggedoff',
'displayname' => 'loggedoff',
'checked' => false,
],
'enabled' => false,
'enabledlabel' => get_string('sendingviaenabled', 'message', $labelparams),
];
// Determine the default setting.
if (isset($defaultpreferences->{$defaultpreference})) {
$context['locked'] = $defaultpreferences->{$defaultpreference};
}
$context['enabled'] = $this->is_preference_enabled($preferencebase.'_enabled', $context['locked']);
$context['loggedoff']['checked'] = $context['enabled']; // Backward compatibility, deprecated attribute.
$context['loggedin']['checked'] = $context['enabled']; // Backward compatibility, deprecated attribute.
// If settings are disallowed or forced, just display the corresponding message, if not use user settings.
if ($context['locked']) {
if ($context['enabled']) {
$context['lockedmessage'] = get_string('forcedmessage', 'message');
$context['lockedlabel'] = get_string('providerprocesorislocked', 'message', $labelparams);
} else {
$context['lockedmessage'] = get_string('disallowed', 'message');
$context['lockedlabel'] = get_string('providerprocesorisdisallowed', 'message', $labelparams);
}
}
return $context;
}
}
@@ -0,0 +1,84 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains processor class for displaying on message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\output\preferences;
defined('MOODLE_INTERNAL') || die();
use renderable;
use templatable;
/**
* Class to create context for one of the message processors settings on the message preferences page.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class processor implements templatable, renderable {
/**
* @var \stdClass The message processor.
*/
protected $processor;
/**
* @var \stdClass list of message preferences.
*/
protected $preferences;
/**
* @var \stdClass A user.
*/
protected $user;
/**
* @var string The processor type.
*/
protected $type;
/**
* Constructor.
*
* @param \stdClass $processor
* @param \stdClass $preferences
* @param \stdClass $user
* @param string $type
*/
public function __construct($processor, $preferences, $user, $type) {
$this->processor = $processor;
$this->preferences = $preferences;
$this->user = $user;
$this->type = $type;
}
public function export_for_template(\renderer_base $output) {
return [
'userid' => $this->user->id,
'displayname' => get_string('pluginname', 'message_'.$this->type),
'name' => $this->type,
'formhtml' => $this->processor->config_form($this->preferences),
];
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains class used to prepare a message processor for display.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\output;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/message/lib.php');
use renderable;
use templatable;
/**
* Class to prepare a message processor for display.
*
* @package core_message
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class processor implements templatable, renderable {
/**
* @var \stdClass The message processor
*/
protected $processor;
/**
* @var \stdClass The user
*/
protected $user;
/**
* Constructor.
*
* @param \stdClass $processor
* @param \stdClass $user
*/
public function __construct($processor, $user) {
$this->processor = $processor;
$this->user = $user;
}
public function export_for_template(\renderer_base $output) {
$processor = $this->processor;
$user = $this->user;
$context = [
'systemconfigured' => $processor->is_system_configured(),
'userconfigured' => $processor->is_user_configured($user),
];
return $context;
}
}
File diff suppressed because it is too large Load Diff
+219
View File
@@ -0,0 +1,219 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Search area base class for messages.
*
* @package core_message
* @copyright 2016 Devang Gaur
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\search;
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/message/lib.php');
/**
* Search area base class for messages.
*
* @package core_message
* @copyright 2016 Devang Gaur
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class base_message extends \core_search\base {
/**
* The context levels the search area is working on.
* @var array
*/
protected static $levels = [CONTEXT_USER];
/**
* Returns the document associated with this message record.
*
* @param stdClass $record
* @param array $options
* @return \core_search\document
*/
public function get_document($record, $options = array()) {
// Check if user still exists, before proceeding.
$user = \core_user::get_user($options['user1id'], 'deleted');
if ($user->deleted == 1) {
return false;
}
// Get user context.
try {
$usercontext = \context_user::instance($options['user1id']);
} catch (\moodle_exception $ex) {
// Notify it as we run here as admin, we should see everything.
debugging('Error retrieving ' . $this->areaid . ' ' . $record->id . ' document, not all required data is available: ' .
$ex->getMessage(), DEBUG_DEVELOPER);
return false;
}
// Prepare associative array with data from DB.
$doc = \core_search\document_factory::instance($record->id, $this->componentname, $this->areaname);
$doc->set('title', content_to_text($record->subject, false));
$doc->set('itemid', $record->id);
$doc->set('content', content_to_text($record->smallmessage, false));
$doc->set('contextid', $usercontext->id);
$doc->set('courseid', SITEID);
$doc->set('owneruserid', $options['user1id']);
$doc->set('userid', $options['user2id']);
$doc->set('modified', $record->timecreated);
// Check if this document should be considered new.
if (isset($options['lastindexedtime']) && $options['lastindexedtime'] < $record->timecreated) {
// If the document was created after the last index time, it must be new.
$doc->set_is_new(true);
}
return $doc;
}
/**
* Link to the message.
*
* @param \core_search\document $doc
* @return \moodle_url
*/
public function get_doc_url(\core_search\document $doc) {
$users = $this->get_current_other_users($doc);
$position = 'm'.$doc->get('itemid');
return new \moodle_url('/message/index.php', array('history' => MESSAGE_HISTORY_ALL,
'user1' => $users['currentuserid'], 'user2' => $users['otheruserid']), $position);
}
/**
* Link to the conversation.
*
* @param \core_search\document $doc
* @return \moodle_url
*/
public function get_context_url(\core_search\document $doc) {
$users = $this->get_current_other_users($doc);
return new \moodle_url('/message/index.php', array('user1' => $users['currentuserid'], 'user2' => $users['otheruserid']));
}
/**
* Sorting the current(user1) and other(user2) user in the conversation.
*
* @param \core_search\document $doc
* @return array()
*/
protected function get_current_other_users($doc) {
global $USER;
$users = array();
if (($USER->id == $doc->get('owneruserid')) || (get_class($this) === 'message_sent')) {
$users['currentuserid'] = $doc->get('owneruserid');
$users['otheruserid'] = $doc->get('userid');
} else {
$users['currentuserid'] = $doc->get('userid');
$users['otheruserid'] = $doc->get('owneruserid');
}
return $users;
}
/**
* Helper function to implement get_document_recordset for subclasses.
*
* @param int $modifiedfrom Modified from date
* @param \context|null $context Context or null
* @param string $userfield Name of user field (from or to) being considered
* @return \moodle_recordset|null Recordset or null if no results possible
* @throws \coding_exception If context invalid
*/
protected function get_document_recordset_helper($modifiedfrom, ?\context $context,
$userfield) {
global $DB;
if ($userfield == 'useridto') {
$userfield = 'mcm.userid';
} else {
$userfield = 'm.useridfrom';
}
// Set up basic query.
$where = $userfield . ' != :noreplyuser AND ' . $userfield .
' != :supportuser AND m.timecreated >= :modifiedfrom';
$params = [
'noreplyuser' => \core_user::NOREPLY_USER,
'supportuser' => \core_user::SUPPORT_USER,
'modifiedfrom' => $modifiedfrom
];
// Check context to see whether to add other restrictions.
if ($context === null) {
$context = \context_system::instance();
}
switch ($context->contextlevel) {
case CONTEXT_COURSECAT:
case CONTEXT_COURSE:
case CONTEXT_MODULE:
case CONTEXT_BLOCK:
// There are no messages in any of these contexts so nothing can be found.
return null;
case CONTEXT_USER:
// Add extra restriction to specific user context.
$where .= ' AND ' . $userfield . ' = :userid';
$params['userid'] = $context->instanceid;
break;
case CONTEXT_SYSTEM:
break;
default:
throw new \coding_exception('Unexpected contextlevel: ' . $context->contextlevel);
}
$sql = "SELECT m.*, mcm.userid as useridto
FROM {messages} m
INNER JOIN {message_conversations} mc
ON m.conversationid = mc.id
INNER JOIN {message_conversation_members} mcm
ON mcm.conversationid = mc.id
WHERE mcm.userid != m.useridfrom
AND $where
ORDER BY m.timecreated ASC";
return $DB->get_recordset_sql($sql, $params);
}
/**
* Returns an icon instance for the document.
*
* @param \core_search\document $doc
*
* @return \core_search\document_icon
*/
public function get_doc_icon(\core_search\document $doc): \core_search\document_icon {
return new \core_search\document_icon('t/message');
}
/**
* Returns a list of category names associated with the area.
*
* @return array
*/
public function get_category_names() {
return [\core_search\manager::SEARCH_AREA_CATEGORY_USERS];
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Search area for received messages.
*
* @package core_message
* @copyright 2016 Devang Gaur
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\search;
defined('MOODLE_INTERNAL') || die();
/**
* Search area for received messages.
*
* @package core_message
* @copyright 2016 Devang Gaur
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class message_received extends base_message {
/**
* Returns a recordset with the messages for indexing.
*
* @param int $modifiedfrom
* @param \context|null $context Optional context to restrict scope of returned results
* @return moodle_recordset|null Recordset (or null if no results)
*/
public function get_document_recordset($modifiedfrom = 0, \context $context = null) {
return $this->get_document_recordset_helper($modifiedfrom, $context, 'useridto');
}
/**
* Returns the document associated with this message record.
*
* @param stdClass $record
* @param array $options
* @return \core_search\document
*/
public function get_document($record, $options = array()) {
return parent::get_document($record, array('user1id' => $record->useridto, 'user2id' => $record->useridfrom));
}
/**
* Whether the user can access the document or not.
*
* @param int $id The message instance id.
* @return int
*/
public function check_access($id) {
global $CFG, $DB, $USER;
if (!$CFG->messaging) {
return \core_search\manager::ACCESS_DENIED;
}
$sql = "SELECT m.*, mcm.userid as useridto
FROM {messages} m
INNER JOIN {message_conversations} mc
ON m.conversationid = mc.id
INNER JOIN {message_conversation_members} mcm
ON mcm.conversationid = mc.id
WHERE mcm.userid != m.useridfrom
AND m.id = :id";
$message = $DB->get_record_sql($sql, array('id' => $id));
if (!$message) {
return \core_search\manager::ACCESS_DELETED;
}
$userfrom = \core_user::get_user($message->useridfrom, 'id, deleted');
$userto = \core_user::get_user($message->useridto, 'id, deleted');
if (!$userfrom || !$userto || $userfrom->deleted || $userto->deleted) {
return \core_search\manager::ACCESS_DELETED;
}
if ($USER->id != $userto->id) {
return \core_search\manager::ACCESS_DENIED;
}
$usertodeleted = $DB->record_exists('message_user_actions', ['messageid' => $id, 'userid' => $message->useridto,
'action' => \core_message\api::MESSAGE_ACTION_DELETED]);
if ($usertodeleted) {
return \core_search\manager::ACCESS_DELETED;
}
return \core_search\manager::ACCESS_GRANTED;
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Search area for sent messages.
*
* @package core_message
* @copyright 2016 Devang Gaur
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\search;
defined('MOODLE_INTERNAL') || die();
/**
* Search area for sent messages.
*
* @package core_message
* @copyright 2016 Devang Gaur
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class message_sent extends base_message {
/**
* Returns a recordset with the messages for indexing.
*
* @param int $modifiedfrom
* @param \context|null $context Optional context to restrict scope of returned results
* @return moodle_recordset|null Recordset (or null if no results)
*/
public function get_document_recordset($modifiedfrom = 0, \context $context = null) {
return $this->get_document_recordset_helper($modifiedfrom, $context, 'useridfrom');
}
/**
* Returns the document associated with this message record.
*
* @param stdClass $record
* @param array $options
* @return \core_search\document
*/
public function get_document($record, $options = array()) {
return parent::get_document($record, array('user1id' => $record->useridfrom, 'user2id' => $record->useridto));
}
/**
* Whether the user can access the document or not.
*
* @param int $id The message instance id.
* @return int
*/
public function check_access($id) {
global $CFG, $DB, $USER;
if (!$CFG->messaging) {
return \core_search\manager::ACCESS_DENIED;
}
$sql = "SELECT m.*, mcm.userid as useridto
FROM {messages} m
INNER JOIN {message_conversations} mc
ON m.conversationid = mc.id
INNER JOIN {message_conversation_members} mcm
ON mcm.conversationid = mc.id
WHERE mcm.userid != m.useridfrom
AND m.id = :id";
$message = $DB->get_record_sql($sql, array('id' => $id));
if (!$message) {
return \core_search\manager::ACCESS_DELETED;
}
$userfrom = \core_user::get_user($message->useridfrom, 'id, deleted');
$userto = \core_user::get_user($message->useridto, 'id, deleted');
if (!$userfrom || !$userto || $userfrom->deleted || $userto->deleted) {
return \core_search\manager::ACCESS_DELETED;
}
if ($USER->id != $userfrom->id) {
return \core_search\manager::ACCESS_DENIED;
}
$userfromdeleted = $DB->record_exists('message_user_actions', ['messageid' => $id, 'userid' => $message->useridfrom,
'action' => \core_message\api::MESSAGE_ACTION_DELETED]);
if ($userfromdeleted) {
return \core_search\manager::ACCESS_DELETED;
}
return \core_search\manager::ACCESS_GRANTED;
}
}
@@ -0,0 +1,290 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Adhoc task handling migrating data to the new messaging table schema.
*
* @package core_message
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\task;
defined('MOODLE_INTERNAL') || die();
/**
* Class handling migrating data to the new messaging table schema.
*
* @package core_message
* @copyright 2018 Mark Nelson <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class migrate_message_data extends \core\task\adhoc_task {
/**
* Run the migration task.
*/
public function execute() {
global $DB;
$userid = $this->get_custom_data()->userid;
// Get the user's preference.
$hasbeenmigrated = get_user_preferences('core_message_migrate_data', false, $userid);
if (!$hasbeenmigrated) {
// To determine if we should update the preference.
$updatepreference = true;
// Get all the users the current user has received a message from.
$sql = "SELECT DISTINCT(useridfrom)
FROM {message} m
WHERE useridto = ?
UNION
SELECT DISTINCT(useridfrom)
FROM {message_read} m
WHERE useridto = ?";
$users = $DB->get_records_sql($sql, [$userid, $userid]);
// Get all the users the current user has messaged.
$sql = "SELECT DISTINCT(useridto)
FROM {message} m
WHERE useridfrom = ?
UNION
SELECT DISTINCT(useridto)
FROM {message_read} m
WHERE useridfrom = ?";
$users = $users + $DB->get_records_sql($sql, [$userid, $userid]);
if (!empty($users)) {
// Loop through each user and migrate the data.
foreach ($users as $otheruserid => $user) {
$ids = [$userid, $otheruserid];
sort($ids);
$key = implode('_', $ids);
// Set the lock data.
$timeout = 5; // In seconds.
$locktype = 'core_message_migrate_data';
// Get an instance of the currently configured lock factory.
$lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
// See if we can grab this lock.
if ($lock = $lockfactory->get_lock($key, $timeout)) {
try {
$transaction = $DB->start_delegated_transaction();
$this->migrate_data($userid, $otheruserid);
$transaction->allow_commit();
} catch (\Throwable $e) {
throw $e;
} finally {
$lock->release();
}
} else {
// Couldn't get a lock, move on to next user but make sure we don't update user preference so
// we still try again.
$updatepreference = false;
continue;
}
}
}
if ($updatepreference) {
set_user_preference('core_message_migrate_data', true, $userid);
} else {
// Throwing an exception in the task will mean that it isn't removed from the queue and is tried again.
throw new \moodle_exception('Task failed.');
}
}
}
/**
* Helper function to deal with migrating the data.
*
* @param int $userid The current user id.
* @param int $otheruserid The user id of the other user in the conversation.
* @throws \dml_exception
*/
private function migrate_data($userid, $otheruserid) {
global $DB;
if ($userid == $otheruserid) {
// Since 3.7, pending self-conversations should be migrated during the upgrading process so shouldn't be any
// self-conversations on the legacy tables. However, this extra-check has been added just in case.
$conversation = \core_message\api::get_self_conversation($userid);
if (empty($conversation)) {
$conversation = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_SELF,
[$userid]
);
}
$conversationid = $conversation->id;
} else if (!$conversationid = \core_message\api::get_conversation_between_users([$userid, $otheruserid])) {
$conversation = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
[
$userid,
$otheruserid
]
);
$conversationid = $conversation->id;
}
// First, get the rows from the 'message' table.
$select = "(useridfrom = ? AND useridto = ?) OR (useridfrom = ? AND useridto = ?)";
$params = [$userid, $otheruserid, $otheruserid, $userid];
$messages = $DB->get_recordset_select('message', $select, $params, 'id ASC');
foreach ($messages as $message) {
if ($message->notification) {
$this->migrate_notification($message, false);
} else {
$this->migrate_message($conversationid, $message);
}
}
$messages->close();
// Ok, all done, delete the records from the 'message' table.
$DB->delete_records_select('message', $select, $params);
// Now, get the rows from the 'message_read' table.
$messages = $DB->get_recordset_select('message_read', $select, $params, 'id ASC');
foreach ($messages as $message) {
if ($message->notification) {
$this->migrate_notification($message, true);
} else {
$this->migrate_message($conversationid, $message);
}
}
$messages->close();
// Ok, all done, delete the records from the 'message_read' table.
$DB->delete_records_select('message_read', $select, $params);
}
/**
* Helper function to deal with migrating an individual notification.
*
* @param \stdClass $notification
* @param bool $isread Was the notification read?
* @throws \dml_exception
*/
private function migrate_notification($notification, $isread) {
global $DB;
$tabledata = new \stdClass();
$tabledata->useridfrom = $notification->useridfrom;
$tabledata->useridto = $notification->useridto;
$tabledata->subject = $notification->subject;
$tabledata->fullmessage = $notification->fullmessage;
$tabledata->fullmessageformat = $notification->fullmessageformat ?? FORMAT_MOODLE;
$tabledata->fullmessagehtml = $notification->fullmessagehtml;
$tabledata->smallmessage = $notification->smallmessage;
$tabledata->component = $notification->component;
$tabledata->eventtype = $notification->eventtype;
$tabledata->contexturl = $notification->contexturl;
$tabledata->contexturlname = $notification->contexturlname;
$tabledata->timeread = $notification->timeread ?? null;
$tabledata->timecreated = $notification->timecreated;
$newid = $DB->insert_record('notifications', $tabledata);
// Check if there is a record to move to the new 'message_popup_notifications' table.
if ($mp = $DB->get_record('message_popup', ['messageid' => $notification->id, 'isread' => (int) $isread])) {
$mpn = new \stdClass();
$mpn->notificationid = $newid;
$DB->insert_record('message_popup_notifications', $mpn);
$DB->delete_records('message_popup', ['id' => $mp->id]);
}
}
/**
* Helper function to deal with migrating an individual message.
*
* @param int $conversationid The conversation between the two users.
* @param \stdClass $message The message from either the 'message' or 'message_read' table
* @throws \dml_exception
*/
private function migrate_message($conversationid, $message) {
global $DB;
// Create the object we will be inserting into the database.
$tabledata = new \stdClass();
$tabledata->useridfrom = $message->useridfrom;
$tabledata->conversationid = $conversationid;
$tabledata->subject = $message->subject;
$tabledata->fullmessage = $message->fullmessage;
$tabledata->fullmessageformat = $message->fullmessageformat ?? FORMAT_MOODLE;
$tabledata->fullmessagehtml = $message->fullmessagehtml;
$tabledata->smallmessage = $message->smallmessage;
$tabledata->timecreated = $message->timecreated;
$messageid = $DB->insert_record('messages', $tabledata);
// Check if we need to mark this message as deleted for the user from.
if ($message->timeuserfromdeleted) {
$mua = new \stdClass();
$mua->userid = $message->useridfrom;
$mua->messageid = $messageid;
$mua->action = \core_message\api::MESSAGE_ACTION_DELETED;
$mua->timecreated = $message->timeuserfromdeleted;
$DB->insert_record('message_user_actions', $mua);
}
// Check if we need to mark this message as deleted for the user to.
if ($message->timeusertodeleted and ($message->useridfrom != $message->useridto)) {
$mua = new \stdClass();
$mua->userid = $message->useridto;
$mua->messageid = $messageid;
$mua->action = \core_message\api::MESSAGE_ACTION_DELETED;
$mua->timecreated = $message->timeusertodeleted;
$DB->insert_record('message_user_actions', $mua);
}
// Check if we need to mark this message as read for the user to (it is always read by the user from).
// Note - we do an isset() check here because this column only exists in the 'message_read' table.
if (isset($message->timeread)) {
$mua = new \stdClass();
$mua->userid = $message->useridto;
$mua->messageid = $messageid;
$mua->action = \core_message\api::MESSAGE_ACTION_READ;
$mua->timecreated = $message->timeread;
$DB->insert_record('message_user_actions', $mua);
}
}
/**
* Queues the task.
*
* @param int $userid
*/
public static function queue_task($userid) {
// Let's set up the adhoc task.
$task = new \core_message\task\migrate_message_data();
$task->set_custom_data(
[
'userid' => $userid
]
);
// Queue it.
\core\task\manager::queue_adhoc_task($task, true);
}
}
+201
View File
@@ -0,0 +1,201 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains a helper class providing util methods for testing.
*
* @package core_message
* @copyright 2018 Jake Dallimore <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message\tests;
use stdClass;
/**
* The helper class providing util methods for testing.
*
* @copyright 2018 Jake Dallimore <markn@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class helper {
/**
* Send a fake message.
*
* {@link message_send()} does not support transaction, this function will simulate a message
* sent from a user to another. We should stop using it once {@link message_send()} will support
* transactions. This is not clean at all, this is just used to add rows to the table.
*
* @param \stdClass $userfrom user object of the one sending the message.
* @param \stdClass $userto user object of the one receiving the message.
* @param string $message message to send.
* @param int $notification if the message is a notification.
* @param int $time the time the message was sent
* @return int the id of the message
*/
public static function send_fake_message(
stdClass $userfrom,
stdClass $userto,
string $message = 'Hello world!',
int $notification = 0,
int $time = 0,
): int {
global $DB;
if (empty($time)) {
$time = time();
}
if ($notification) {
$record = new \stdClass();
$record->useridfrom = $userfrom->id;
$record->useridto = $userto->id;
$record->subject = 'No subject';
$record->fullmessage = $message;
$record->smallmessage = $message;
$record->timecreated = $time;
return $DB->insert_record('notifications', $record);
}
if ($userfrom->id == $userto->id) {
// It's a self conversation.
$conversation = \core_message\api::get_self_conversation($userfrom->id);
if (empty($conversation)) {
$conversation = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_SELF,
[$userfrom->id],
);
}
$conversationid = $conversation->id;
} else if (!$conversationid = \core_message\api::get_conversation_between_users([$userfrom->id, $userto->id])) {
// It's an individual conversation between two different users.
$conversation = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
[
$userfrom->id,
$userto->id,
]
);
$conversationid = $conversation->id;
}
// Ok, send the message.
$record = (object) [
'useridfrom' => $userfrom->id,
'conversationid' => $conversationid,
'subject' => 'No subject',
'fullmessage' => $message,
'smallmessage' => $message,
'timecreated' => $time,
];
return $DB->insert_record('messages', $record);
}
/**
* Sends a message to a conversation.
*
* @param \stdClass $userfrom user object of the one sending the message.
* @param int $convid id of the conversation in which we'll send the message.
* @param string $message message to send.
* @param int $time the time the message was sent.
* @return int the id of the message which was sent.
* @throws \dml_exception if the conversation doesn't exist.
*/
public static function send_fake_message_to_conversation(\stdClass $userfrom, int $convid, string $message = 'Hello world!',
int $time = null): int {
global $DB;
$conversationrec = $DB->get_record('message_conversations', ['id' => $convid], 'id', MUST_EXIST);
$conversationid = $conversationrec->id;
$time = $time ?? time();
$record = new \stdClass();
$record->useridfrom = $userfrom->id;
$record->conversationid = $conversationid;
$record->subject = 'No subject';
$record->fullmessage = $message;
$record->smallmessage = $message;
$record->timecreated = $time;
return $DB->insert_record('messages', $record);
}
/**
* Send a fake unread notification.
*
* message_send() does not support transaction, this function will simulate a message
* sent from a user to another. We should stop using it once message_send() will support
* transactions. This is not clean at all, this is just used to add rows to the table.
*
* @param stdClass $userfrom user object of the one sending the message.
* @param stdClass $userto user object of the one receiving the message.
* @param string $message message to send.
* @param int $timecreated time the message was created.
* @return int the id of the message
*/
public static function send_fake_unread_notification(\stdClass $userfrom, \stdClass $userto, string $message = 'Hello world!',
int $timecreated = 0): int {
global $DB;
$record = new \stdClass();
$record->useridfrom = $userfrom->id;
$record->useridto = $userto->id;
$record->notification = 1;
$record->subject = 'No subject';
$record->fullmessage = $message;
$record->smallmessage = $message;
$record->timecreated = $timecreated ? $timecreated : time();
$record->customdata = json_encode(['datakey' => 'data']);
return $DB->insert_record('notifications', $record);
}
/**
* Send a fake read notification.
*
* message_send() does not support transaction, this function will simulate a message
* sent from a user to another. We should stop using it once message_send() will support
* transactions. This is not clean at all, this is just used to add rows to the table.
*
* @param stdClass $userfrom user object of the one sending the message.
* @param stdClass $userto user object of the one receiving the message.
* @param string $message message to send.
* @param int $timecreated time the message was created.
* @param int $timeread the the message was read
* @return int the id of the message
*/
public static function send_fake_read_notification(\stdClass $userfrom, \stdClass $userto, string $message = 'Hello world!',
int $timecreated = 0, int $timeread = 0): int {
global $DB;
$record = new \stdClass();
$record->useridfrom = $userfrom->id;
$record->useridto = $userto->id;
$record->notification = 1;
$record->subject = 'No subject';
$record->fullmessage = $message;
$record->smallmessage = $message;
$record->timecreated = $timecreated ? $timecreated : time();
$record->timeread = $timeread ? $timeread : time();
$record->id = $DB->insert_record('notifications', $record);
// Mark it as read.
\core_message\api::mark_notification_as_read($record);
return $record->id;
}
}
@@ -0,0 +1,88 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Cache data source for the time of the last message between users.
*
* @package core_message
* @category cache
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_message;
defined('MOODLE_INTERNAL') || die();
/**
* Cache data source for the time of the last message in a conversation.
*
* @package core_message
* @category cache
* @copyright 2016 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class time_last_message_between_users implements \cache_data_source {
/** @var time_last_message_between_users the singleton instance of this class. */
protected static $instance = null;
/**
* Returns an instance of the data source class that the cache can use for loading data using the other methods
* specified by the cache_data_source interface.
*
* @param \cache_definition $definition
* @return object
*/
public static function get_instance_for_cache(\cache_definition $definition) {
if (is_null(self::$instance)) {
self::$instance = new time_last_message_between_users();
}
return self::$instance;
}
/**
* Loads the data for the key provided ready formatted for caching.
*
* @param string|int $key The key to load.
* @return mixed What ever data should be returned, or false if it can't be loaded.
*/
public function load_for_cache($key) {
$message = api::get_most_recent_conversation_message($key);
if ($message) {
return $message->timecreated;
} else {
return null;
}
}
/**
* Loads several keys for the cache.
*
* @param array $keys An array of keys each of which will be string|int.
* @return array An array of matching data items.
*/
public function load_many_for_cache(array $keys) {
$results = [];
foreach ($keys as $key) {
$results[] = $this->load_for_cache($key);
}
return $results;
}
}