public static function set_user_preferences($preferences) {
        global $USER;

        $params = self::validate_parameters(self::set_user_preferences_parameters(), array('preferences' => $preferences));
        $warnings = array();
        $saved = array();

        $context = context_system::instance();
        self::validate_context($context);

        $userscache = array();
        foreach ($params['preferences'] as $pref) {
            // Check to which user set the preference.
            if (!empty($userscache[$pref['userid']])) {
                $user = $userscache[$pref['userid']];
            } else {
                try {
                    $user = core_user::get_user($pref['userid'], '*', MUST_EXIST);
                    core_user::require_active_user($user);
                    $userscache[$pref['userid']] = $user;
                } catch (Exception $e) {
                    $warnings[] = array(
                        'item' => 'user',
                        'itemid' => $pref['userid'],
                        'warningcode' => 'invaliduser',
                        'message' => $e->getMessage()
                    );
                    continue;
                }
            }

            try {
                if (core_user::can_edit_preference($pref['name'], $user)) {
                    $value = core_user::clean_preference($pref['value'], $pref['name']);
                    set_user_preference($pref['name'], $value, $user->id);
                    $saved[] = array(
                        'name' => $pref['name'],
                        'userid' => $user->id,
                    );
                } else {
                    $warnings[] = array(
                        'item' => 'user',
                        'itemid' => $user->id,
                        'warningcode' => 'nopermission',
                        'message' => 'You are not allowed to change the preference '.s($pref['name']).' for user '.$user->id
                    );
                }
            } catch (Exception $e) {
                $warnings[] = array(
                    'item' => 'user',
                    'itemid' => $user->id,
                    'warningcode' => 'errorsavingpreference',
                    'message' => $e->getMessage()
                );
            }
        }

        $result = array();
        $result['saved'] = $saved;
        $result['warnings'] = $warnings;
        return $result;
    }