public static function search_get_user_details(\stdClass $user) : 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) ?? []; // 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);
                    if (!is_null($userdetails)) {
                        return $userdetails;
                    }
                }
            }
        }
        return [];
    }