Skip to content

Instantly share code, notes, and snippets.

@GonDragon
Created November 1, 2023 14:38
Show Gist options
  • Save GonDragon/a0d96be4fcc763c1b168b4a0ae458abc to your computer and use it in GitHub Desktop.
Save GonDragon/a0d96be4fcc763c1b168b4a0ae458abc to your computer and use it in GitHub Desktop.
A short PHP script for moodle. Mark all the messages from the current user as readed.
<?php
require_once('config.php');
require_login();
global $USER, $DB;
$userid = $USER->id;
// Check if the user is logged in
if (empty($userid)) {
// Redirect to the home page if the user isn't logged in
redirect(new moodle_url('/'));
}
try {
// Retrieve all conversation IDs for the user
$conversations = $DB->get_fieldset_select(
'message_conversation_members',
'conversationid',
'userid = ?',
array($userid)
);
// Retrieve all message IDs for the user's conversations, excluding their own messages
list($in_sql, $params) = $DB->get_in_or_equal($conversations);
$messages = $DB->get_records_select(
'messages',
"conversationid $in_sql AND useridfrom <> ?",
array_merge($params, array($userid)),
'',
'id'
);
// Check for unread messages
$unread_messages = [];
foreach ($messages as $message) {
if (!$DB->record_exists('message_user_actions', array('userid' => $userid, 'messageid' => $message->id, 'action' => 1))) {
$unread_messages[] = $message->id;
}
}
// Mark messages as read
$time = time();
foreach ($unread_messages as $messageid) {
$record = new stdClass();
$record->userid = $userid;
$record->messageid = $messageid;
$record->action = 1; // Action for read
$record->timecreated = $time;
$DB->insert_record('message_user_actions', $record);
}
// Redirect to the messages page or add a success message if needed
echo "All unread messages have been marked as read.";
} catch (dml_exception $e) {
// Handle any exceptions (e.g., database errors)
echo "An error occurred: " . $e->getMessage();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment