public static function update_user_preferences($userid = 0, $emailstop = null, $preferences = array()) {
        global $USER, $CFG;

        require_once($CFG->dirroot . '/user/lib.php');
        require_once($CFG->dirroot . '/user/editlib.php');
        require_once($CFG->dirroot . '/message/lib.php');

        if (empty($userid)) {
            $userid = $USER->id;
        }

        $systemcontext = context_system::instance();
        self::validate_context($systemcontext);
        $params = array(
            'userid' => $userid,
            'emailstop' => $emailstop,
            'preferences' => $preferences
        );
        $params = self::validate_parameters(self::update_user_preferences_parameters(), $params);
        $preferences = $params['preferences'];

        // Preferences.
        if (!empty($preferences)) {
            $userpref = ['id' => $userid];
            foreach ($preferences as $preference) {
                $userpref['preference_' . $preference['type']] = $preference['value'];
            }
            useredit_update_user_preference($userpref);
        }

        // Check if they want to update the email.
        if ($emailstop !== null) {
            $otheruser = ($userid == $USER->id) ? $USER : core_user::get_user($userid, '*', MUST_EXIST);
            core_user::require_active_user($otheruser);
            if (core_message_can_edit_message_profile($otheruser) && $otheruser->emailstop != $emailstop) {
                $user = new stdClass();
                $user->id = $userid;
                $user->emailstop = $emailstop;
                user_update_user($user);

                // Update the $USER if we should.
                if ($userid == $USER->id) {
                    $USER->emailstop = $emailstop;
                }
            }
        }

        return null;
    }