TEMPLATE;
}
/**
* Format a the context url and context url name of a message for display
*
* @param object $message the message object
* @return string the formatted string
*/
function message_format_contexturl($message) {
$s = null;
if (!empty($message->contexturl)) {
$displaytext = null;
if (!empty($message->contexturlname)) {
$displaytext= $message->contexturlname;
} else {
$displaytext= $message->contexturl;
}
$s .= html_writer::start_tag('div',array('class' => 'messagecontext'));
$s .= get_string('view').': '.html_writer::tag('a', $displaytext, array('href' => $message->contexturl));
$s .= html_writer::end_tag('div');
}
return $s;
}
/**
* Send a message from one user to another. Will be delivered according to the message recipients messaging preferences
*
* @param object $userfrom the message sender
* @param object $userto the message recipient
* @param string $message the message
* @param int $format message format such as FORMAT_PLAIN or FORMAT_HTML
* @return int|false the ID of the new message or false
*/
function message_post_message($userfrom, $userto, $message, $format) {
global $PAGE;
$eventdata = new \core\message\message();
$eventdata->courseid = 1;
$eventdata->component = 'moodle';
$eventdata->name = 'instantmessage';
$eventdata->userfrom = $userfrom;
$eventdata->userto = $userto;
//using string manager directly so that strings in the message will be in the message recipients language rather than the senders
$eventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message', fullname($userfrom), $userto->lang);
if ($format == FORMAT_HTML) {
$eventdata->fullmessagehtml = $message;
//some message processors may revert to sending plain text even if html is supplied
//so we keep both plain and html versions if we're intending to send html
$eventdata->fullmessage = html_to_text($eventdata->fullmessagehtml);
} else {
$eventdata->fullmessage = $message;
$eventdata->fullmessagehtml = '';
}
$eventdata->fullmessageformat = $format;
$eventdata->smallmessage = $message;//store the message unfiltered. Clean up on output.
$eventdata->timecreated = time();
$eventdata->notification = 0;
// User image.
$userpicture = new user_picture($userfrom);
$userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
$eventdata->customdata = [
'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
'actionbuttons' => [
'send' => get_string_manager()->get_string('send', 'message', null, $eventdata->userto->lang),
],
'placeholders' => [
'send' => get_string_manager()->get_string('writeamessage', 'message', null, $eventdata->userto->lang),
],
];
return message_send($eventdata);
}
/**
* Get all message processors, validate corresponding plugin existance and
* system configuration
*
* @param bool $ready only return ready-to-use processors
* @param bool $reset Reset list of message processors (used in unit tests)
* @param bool $resetonly Just reset, then exit
* @return mixed $processors array of objects containing information on message processors
*/
function get_message_processors($ready = false, $reset = false, $resetonly = false) {
global $DB, $CFG;
static $processors;
if ($reset) {
$processors = array();
if ($resetonly) {
return $processors;
}
}
if (empty($processors)) {
// Get all processors, ensure the name column is the first so it will be the array key
$processors = $DB->get_records('message_processors', null, 'name DESC', 'name, id, enabled');
foreach ($processors as &$processor){
$processor = \core_message\api::get_processed_processor_object($processor);
}
}
if ($ready) {
// Filter out enabled and system_configured processors
$readyprocessors = $processors;
foreach ($readyprocessors as $readyprocessor) {
if (!($readyprocessor->enabled && $readyprocessor->configured)) {
unset($readyprocessors[$readyprocessor->name]);
}
}
return $readyprocessors;
}
return $processors;
}
/**
* Get all message providers, validate their plugin existance and
* system configuration
*
* @return mixed $processors array of objects containing information on message processors
*/
function get_message_providers() {
global $CFG, $DB;
$pluginman = core_plugin_manager::instance();
$providers = $DB->get_records('message_providers', null, 'name');
// Remove all the providers whose plugins are disabled or don't exist
foreach ($providers as $providerid => $provider) {
$plugin = $pluginman->get_plugin_info($provider->component);
if ($plugin) {
if ($plugin->get_status() === core_plugin_manager::PLUGIN_STATUS_MISSING) {
unset($providers[$providerid]); // Plugins does not exist
continue;
}
if ($plugin->is_enabled() === false) {
unset($providers[$providerid]); // Plugin disabled
continue;
}
}
}
return $providers;
}
/**
* Get an instance of the message_output class for one of the output plugins.
* @param string $type the message output type. E.g. 'email' or 'jabber'.
* @return message_output message_output the requested class.
*/
function get_message_processor($type) {
global $CFG;
// Note, we cannot use the get_message_processors function here, becaues this
// code is called during install after installing each messaging plugin, and
// get_message_processors caches the list of installed plugins.
$processorfile = $CFG->dirroot . "/message/output/{$type}/message_output_{$type}.php";
if (!is_readable($processorfile)) {
throw new coding_exception('Unknown message processor type ' . $type);
}
include_once($processorfile);
$processclass = 'message_output_' . $type;
if (!class_exists($processclass)) {
throw new coding_exception('Message processor ' . $type .
' does not define the right class');
}
return new $processclass();
}
/**
* Get messaging outputs default (site) preferences
*
* @return object $processors object containing information on message processors
*/
function get_message_output_default_preferences() {
return get_config('message');
}
/**
* Translate message default settings from binary value to the array of string
* representing the settings to be stored. Also validate the provided value and
* use default if it is malformed.
*
* @param int $plugindefault Default setting suggested by plugin
* @param string $processorname The name of processor
* @return array $settings array of strings in the order: $permitted, $loggedin, $loggedoff.
*/
function translate_message_default_setting($plugindefault, $processorname) {
// Preset translation arrays
$permittedvalues = array(
0x04 => 'disallowed',
0x08 => 'permitted',
0x0c => 'forced',
);
$loggedinstatusvalues = array(
0x00 => null, // use null if loggedin/loggedoff is not defined
0x01 => 'loggedin',
0x02 => 'loggedoff',
);
// define the default setting
$processor = get_message_processor($processorname);
$default = $processor->get_default_messaging_settings();
// Validate the value. It should not exceed the maximum size
if (!is_int($plugindefault) || ($plugindefault > 0x0f)) {
debugging(get_string('errortranslatingdefault', 'message'));
$plugindefault = $default;
}
// Use plugin default setting of 'permitted' is 0
if (!($plugindefault & MESSAGE_PERMITTED_MASK)) {
$plugindefault = $default;
}
$permitted = $permittedvalues[$plugindefault & MESSAGE_PERMITTED_MASK];
$loggedin = $loggedoff = null;
if (($plugindefault & MESSAGE_PERMITTED_MASK) == MESSAGE_PERMITTED) {
$loggedin = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDIN];
$loggedoff = $loggedinstatusvalues[$plugindefault & MESSAGE_DEFAULT_LOGGEDOFF];
}
return array($permitted, $loggedin, $loggedoff);
}
/**
* Get messages sent or/and received by the specified users.
* Please note that this function return deleted messages too. Besides, only individual conversation messages
* are returned to maintain backwards compatibility.
*
* @param int $useridto the user id who received the message
* @param int $useridfrom the user id who sent the message. -10 or -20 for no-reply or support user
* @param int $notifications 1 for retrieving notifications, 0 for messages, -1 for both
* @param bool $read true for retrieving read messages, false for unread
* @param string $sort the column name to order by including optionally direction
* @param int $limitfrom limit from
* @param int $limitnum limit num
* @return external_description
* @since 2.8
*/
function message_get_messages($useridto, $useridfrom = 0, $notifications = -1, $read = true,
$sort = 'mr.timecreated DESC', $limitfrom = 0, $limitnum = 0) {
global $DB;
// If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
if (empty($useridto)) {
$userfields = get_all_user_name_fields(true, 'u', '', 'userto');
$messageuseridtosql = 'u.id as useridto';
} else {
$userfields = get_all_user_name_fields(true, 'u', '', 'userfrom');
$messageuseridtosql = "$useridto as useridto";
}
// Create the SQL we will be using.
$messagesql = "SELECT mr.*, $userfields, 0 as notification, '' as contexturl, '' as contexturlname,
mua.timecreated as timeusertodeleted, mua2.timecreated as timeread,
mua3.timecreated as timeuserfromdeleted, $messageuseridtosql
FROM {messages} mr
INNER JOIN {message_conversations} mc
ON mc.id = mr.conversationid
INNER JOIN {message_conversation_members} mcm
ON mcm.conversationid = mc.id ";
$notificationsql = "SELECT mr.*, $userfields, 1 as notification
FROM {notifications} mr ";
$messagejoinsql = "LEFT JOIN {message_user_actions} mua
ON (mua.messageid = mr.id AND mua.userid = mcm.userid AND mua.action = ?)
LEFT JOIN {message_user_actions} mua2
ON (mua2.messageid = mr.id AND mua2.userid = mcm.userid AND mua2.action = ?)
LEFT JOIN {message_user_actions} mua3
ON (mua3.messageid = mr.id AND mua3.userid = mr.useridfrom AND mua3.action = ?)";
$messagejoinparams = [\core_message\api::MESSAGE_ACTION_DELETED, \core_message\api::MESSAGE_ACTION_READ,
\core_message\api::MESSAGE_ACTION_DELETED];
$notificationsparams = [];
// If the 'useridto' value is empty then we are going to retrieve messages sent by the useridfrom to any user.
if (empty($useridto)) {
// Create the messaging query and params.
$messagesql .= "INNER JOIN {user} u
ON u.id = mcm.userid
$messagejoinsql
WHERE mr.useridfrom = ?
AND mr.useridfrom != mcm.userid
AND u.deleted = 0
AND mc.type = ? ";
$messageparams = array_merge($messagejoinparams, [$useridfrom, \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL]);
// Create the notifications query and params.
$notificationsql .= "INNER JOIN {user} u
ON u.id = mr.useridto
WHERE mr.useridfrom = ?
AND u.deleted = 0 ";
$notificationsparams[] = $useridfrom;
} else {
// Create the messaging query and params.
// Left join because useridfrom may be -10 or -20 (no-reply and support users).
$messagesql .= "LEFT JOIN {user} u
ON u.id = mr.useridfrom
$messagejoinsql
WHERE mcm.userid = ?
AND mr.useridfrom != mcm.userid
AND u.deleted = 0
AND mc.type = ? ";
$messageparams = array_merge($messagejoinparams, [$useridto, \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL]);
// If we're dealing with messages only and both useridto and useridfrom are set,
// try to get a conversation between the users. Break early if we can't find one.
if (!empty($useridfrom) && $notifications == 0) {
$messagesql .= " AND mr.useridfrom = ? ";
$messageparams[] = $useridfrom;
// There should be an individual conversation between the users. If not, we can return early.
$conversationid = \core_message\api::get_conversation_between_users([$useridto, $useridfrom]);
if (empty($conversationid)) {
return [];
}
$messagesql .= " AND mc.id = ? ";
$messageparams[] = $conversationid;
}
// Create the notifications query and params.
// Left join because useridfrom may be -10 or -20 (no-reply and support users).
$notificationsql .= "LEFT JOIN {user} u
ON (u.id = mr.useridfrom AND u.deleted = 0)
WHERE mr.useridto = ? ";
$notificationsparams[] = $useridto;
if (!empty($useridfrom)) {
$notificationsql .= " AND mr.useridfrom = ? ";
$notificationsparams[] = $useridfrom;
}
}
if ($read) {
$notificationsql .= "AND mr.timeread IS NOT NULL ";
} else {
$notificationsql .= "AND mr.timeread IS NULL ";
}
$messagesql .= "ORDER BY $sort";
$notificationsql .= "ORDER BY $sort";
// Handle messages if needed.
if ($notifications === -1 || $notifications === 0) {
$messages = $DB->get_records_sql($messagesql, $messageparams, $limitfrom, $limitnum);
// Get rid of the messages that have either been read or not read depending on the value of $read.
$messages = array_filter($messages, function ($message) use ($read) {
if ($read) {
return !is_null($message->timeread);
}
return is_null($message->timeread);
});
}
// All.
if ($notifications === -1) {
return array_merge($messages, $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum));
} else if ($notifications === 1) { // Just notifications.
return $DB->get_records_sql($notificationsql, $notificationsparams, $limitfrom, $limitnum);
}
// Just messages.
return $messages;
}
/**
* Handles displaying processor settings in a fragment.
*
* @param array $args
* @return bool|string
* @throws moodle_exception
*/
function message_output_fragment_processor_settings($args = []) {
global $PAGE;
if (!isset($args['type'])) {
throw new moodle_exception('Must provide a processor type');
}
if (!isset($args['userid'])) {
throw new moodle_exception('Must provide a userid');
}
$type = $args['type'];
$userid = $args['userid'];
$user = core_user::get_user($userid, '*', MUST_EXIST);
$processor = get_message_processor($type);
$providers = message_get_providers_for_user($userid);
$processorwrapper = new stdClass();
$processorwrapper->object = $processor;
$preferences = \core_message\api::get_all_message_preferences([$processorwrapper], $providers, $user);
$processoroutput = new \core_message\output\preferences\processor($processor, $preferences, $user, $type);
$renderer = $PAGE->get_renderer('core', 'message');
return $renderer->render_from_template('core_message/preferences_processor', $processoroutput->export_for_template($renderer));
}
/**
* Checks if current user is allowed to edit messaging preferences of another user
*
* @param stdClass $user user whose preferences we are updating
* @return bool
*/
function core_message_can_edit_message_profile($user) {
global $USER;
if ($user->id == $USER->id) {
return has_capability('moodle/user:editownmessageprofile', context_system::instance());
} else {
$personalcontext = context_user::instance($user->id);
if (!has_capability('moodle/user:editmessageprofile', $personalcontext)) {
return false;
}
if (isguestuser($user)) {
return false;
}
// No editing of admins by non-admins.
if (is_siteadmin($user) and !is_siteadmin($USER)) {
return false;
}
return true;
}
}
/**
* Implements callback user_preferences, whitelists preferences that users are allowed to update directly
*
* Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
*
* @return array
*/
function core_message_user_preferences() {
$preferences = [];
$preferences['message_blocknoncontacts'] = array(
'type' => PARAM_INT,
'null' => NULL_NOT_ALLOWED,
'default' => 0,
'choices' => array(
\core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
\core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
\core_message\api::MESSAGE_PRIVACY_SITE
),
'cleancallback' => function ($value) {
global $CFG;
// When site-wide messaging between users is disabled, MESSAGE_PRIVACY_SITE should be converted.
if (empty($CFG->messagingallusers) && $value === \core_message\api::MESSAGE_PRIVACY_SITE) {
return \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER;
}
return $value;
}
);
$preferences['message_entertosend'] = array(
'type' => PARAM_BOOL,
'null' => NULL_NOT_ALLOWED,
'default' => false
);
$preferences['/^message_provider_([\w\d_]*)_logged(in|off)$/'] = array('isregex' => true, 'type' => PARAM_NOTAGS,
'null' => NULL_NOT_ALLOWED, 'default' => 'none',
'permissioncallback' => function ($user, $preferencename) {
global $CFG;
require_once($CFG->libdir.'/messagelib.php');
if (core_message_can_edit_message_profile($user) &&
preg_match('/^message_provider_([\w\d_]*)_logged(in|off)$/', $preferencename, $matches)) {
$providers = message_get_providers_for_user($user->id);
foreach ($providers as $provider) {
if ($matches[1] === $provider->component . '_' . $provider->name) {
return true;
}
}
}
return false;
},
'cleancallback' => function ($value, $preferencename) {
if ($value === 'none' || empty($value)) {
return 'none';
}
$parts = explode('/,/', $value);
$processors = array_keys(get_message_processors());
array_filter($parts, function($v) use ($processors) {return in_array($v, $processors);});
return $parts ? join(',', $parts) : 'none';
});
return $preferences;
}
/**
* Render the message drawer to be included in the top of the body of each page.
*
* @return string HTML
*/
function core_message_standard_after_main_region_html() {
return \core_message\helper::render_messaging_widget(true, null, null);
}