Export all user preferences for the plugin.

@param   int $userid The userid of the user whose data is to be exported.
183287
public static function export_user_preferences(int $userid) {
        $userhomepagepreference = get_user_preferences('user_home_page_preference', null, $userid);

        if (null !== $userhomepagepreference) {
            writer::export_user_preference(
                'core_my',
                'user_home_page_preference',
                $userhomepagepreference,
                get_string('privacy:metadata:core_my:preference:user_home_page_preference', 'core_my')
            );
        }
    }
171021
public function loadRoleAssignmentsForUser($userId)
    {
        $user = $this->userService->loadUser($userId);

        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);

        return new Values\RoleAssignmentList($roleAssignments, $user->id);
    }
669933
protected static function export_password_resets(int $userid, \context $context) {
        global $DB;
        $records = $DB->get_records('user_password_resets', ['userid' => $userid]);
        if (!empty($records)) {
            $passwordresets = (object) array_map(function($record) {
                return [
                    'timerequested' => transform::datetime($record->timerequested),
                    'timererequested' => transform::datetime($record->timererequested)
                ];
            }, $records);
            writer::with_context($context)->export_data([get_string('privacy:passwordresetpath', 'user')], $passwordresets);
        }
    }
992621
public final function set_user_config($config, $userid=0) {
        global $DB;

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

        foreach ($config as $key => $value) {
            if ($key != 'visible' && !in_array($key, $this->get_allowed_user_config())) {
                $a = (object)array('property' => $key, 'class' => get_class($this));
                throw new portfolio_export_exception($this->get('exporter'), 'invaliduserproperty', 'portfolio', null, $a);
            }
            if (!$existing = $DB->get_record('portfolio_instance_user', array('instance'=> $this->id, 'userid' => $userid, 'name' => $key))) {
                $DB->insert_record('portfolio_instance_user', (object)array(
                    'instance' => $this->id,
                    'name' => $key,
                    'value' => $value,
                    'userid' => $userid,
                ));
            } else if ($existing->value != $value) {
                $DB->set_field('portfolio_instance_user', 'value', $value, array('name' => $key, 'instance' => $this->id, 'userid' => $userid));
            }
            $this->userconfig[$userid]->{$key} = $value;
        }

    }
501283
public static function convertUserIdToVisitorIdBin($userId)
    {
        require_once PIWIK_INCLUDE_PATH . '/libs/PiwikTracker/PiwikTracker.php';
        $userIdHashed = \PiwikTracker::getUserIdHashed($userId);

        return self::convertVisitorIdToBin($userIdHashed);
    }
407845
public static function export_user_preferences(int $userid) {
        $preference = get_user_preferences('quiz_overview_slotmarks', null);
        if (null !== $preference) {
            if (empty($preference)) {
                $description = get_string('privacy:preference:slotmarks:no', 'quiz_overview');
            } else {
                $description = get_string('privacy:preference:slotmarks:yes', 'quiz_overview');
            }

            writer::export_user_preference(
                'quiz_overview',
                'slotmarks',
                transform::yesno($preference),
                $description
            );
        }
    }
1014980
public function deleteUserLoginTokenFields($userID) {
        $user = $this->getFind($userID);

        $user->login_token            = '';
        $user->login_token_created_at = '';

        return $user->save();
    }
940743
public static function export_user_role_to_cohort(int $userid) {
        global $DB;

        $rolesnames = self::get_roles_name();
        $sql = "SELECT ra.id, ra.contextid, ra.roleid, ra.userid, ra.timemodified, ra.modifierid, r.id as roleid
                  FROM {role_assignments} ra
                  JOIN {context} ctx
                    ON ctx.id = ra.contextid
                   AND ctx.contextlevel = :contextlevel
                   AND ra.component = 'tool_cohortroles'
                  JOIN {role} r
                    ON r.id = ra.roleid
                 WHERE ctx.instanceid = :instanceid
                    OR ra.userid = :userid";
        $params = ['userid' => $userid, 'instanceid' => $userid, 'contextlevel' => CONTEXT_USER];
        $assignments = $DB->get_recordset_sql($sql, $params);
        foreach ($assignments as $assignment) {
            $alldata[$assignment->contextid][$rolesnames[$assignment->roleid]][] = (object)[
                'timemodified' => transform::datetime($assignment->timemodified),
                'userid' => transform::user($assignment->userid),
                'modifierid' => transform::user($assignment->modifierid)
            ];
        }
        $assignments->close();
        if (!empty($alldata)) {
            array_walk($alldata, function($roledata, $contextid) {
                $context = \context::instance_by_id($contextid);
                array_walk($roledata, function($data, $rolename) use ($context) {
                    writer::with_context($context)->export_related_data(
                            [get_string('privacy:metadata:role_cohortroles', 'core_role'), $rolename], 'cohortroles',
                            (object)$data);
                });
            });
        }
    }
677197
protected static function delete_user_data(int $userid) {
        global $DB;

        // Delete individual conversations information for this user.
        self::delete_user_data_conversations($userid, [], '', '');

        // Delete contacts, requests, users blocked and notifications.
        $DB->delete_records_select('message_contacts', 'userid = ? OR contactid = ?', [$userid, $userid]);
        $DB->delete_records_select('message_contact_requests', 'userid = ? OR requesteduserid = ?', [$userid, $userid]);
        $DB->delete_records_select('message_users_blocked', 'userid = ? OR blockeduserid = ?', [$userid, $userid]);
        $DB->delete_records_select('notifications', 'useridfrom = ? OR useridto = ?', [$userid, $userid]);
    }
1226836
public static function export_user_preferences(int $userid) {
        $preferences = get_user_preferences();
        foreach ($preferences as $name => $value) {
            $prefname = null;
            $prefdescription = null;
            $transformedvalue = null;
            switch ($name) {
                case 'grade_report_showcalculations':
                case 'grade_report_showeyecons':
                case 'grade_report_showaverages':
                case 'grade_report_showlocks':
                case 'grade_report_showuserimage':
                case 'grade_report_showactivityicons':
                case 'grade_report_showranges':
                case 'grade_report_showanalysisicon':
                case 'grade_report_shownumberofgrades':
                case 'grade_report_quickgrading':
                case 'grade_report_showonlyactiveenrol':
                case 'grade_report_showquickfeedback':
                case 'grade_report_enableajax':
                    $prefname = $name;
                    $transformedvalue = transform::yesno($value);
                    break;
                case 'grade_report_meanselection':
                    $prefname = $name;
                    switch ($value) {
                        case GRADE_REPORT_MEAN_ALL:
                            $transformedvalue = get_string('meanall', 'grades');
                            break;
                        case GRADE_REPORT_MEAN_GRADED:
                            $transformedvalue = get_string('meangraded', 'grades');
                            break;
                    }
                    break;
                case 'grade_report_rangesdecimalpoints':
                case 'grade_report_averagesdecimalpoints':
                case 'grade_report_studentsperpage':
                    $prefname = $name;
                    $transformedvalue = $value;
                    break;
                case 'grade_report_rangesdisplaytype':
                case 'grade_report_averagesdisplaytype':
                    $prefname = $name;
                    switch ($value) {
                        case GRADE_REPORT_PREFERENCE_INHERIT:
                            $transformedvalue = get_string('inherit', 'grades');
                            break;
                        case GRADE_DISPLAY_TYPE_REAL:
                            $transformedvalue = get_string('real', 'grades');
                            break;
                        case GRADE_DISPLAY_TYPE_PERCENTAGE:
                            $transformedvalue = get_string('percentage', 'grades');
                            break;
                        case GRADE_DISPLAY_TYPE_LETTER:
                            $transformedvalue = get_string('letter', 'grades');
                            break;
                    }
                    break;
                case 'grade_report_aggregationposition':
                    $prefname = $name;
                    switch ($value) {
                        case GRADE_REPORT_AGGREGATION_POSITION_FIRST:
                            $transformedvalue = get_string('positionfirst', 'grades');
                            break;
                        case GRADE_REPORT_AGGREGATION_POSITION_LAST:
                            $transformedvalue = get_string('positionlast', 'grades');
                            break;
                    }
                    break;
                default:
                    if (strpos($name, 'grade_report_grader_collapsed_categories') === 0) {
                        $prefname = 'grade_report_grader_collapsed_categories';
                        $courseid = substr($name, strlen('grade_report_grader_collapsed_categories'));
                        $transformedvalue = $value;
                        $course = get_course($courseid);
                        $prefdescription = get_string(
                            'privacy:request:preference:'.$prefname,
                            'gradereport_grader',
                            (object) [
                                'name' => $course->fullname,
                            ]
                        );
                    }
            }

            if ($prefname !== null) {
                if ($prefdescription == null) {
                    $prefdescription = get_string('privacy:metadata:preference:'.$prefname, 'gradereport_grader');
                }
                writer::export_user_preference(
                    'gradereport_grader',
                    $prefname,
                    $transformedvalue,
                    $prefdescription
                );
            }
        }
    }
788874
public static function export_user_preferences(int $userid) {

        $yesno = function($v) {
            return transform::yesno($v);
        };
        $datetime = function($v) {
            return $v ? transform::datetime($v) : null;
        };

        $prefs = [
            ['auth_forcepasswordchange', 'forcepasswordchange', $yesno],
            ['create_password', 'createpassword', $yesno],
            ['login_failed_count', 'loginfailedcount', null],
            ['login_failed_count_since_success', 'loginfailedcountsincesuccess', null],
            ['login_failed_last', 'loginfailedlast', $datetime],
            ['login_lockout', 'loginlockout', $datetime],
            ['login_lockout_ignored', 'loginlockoutignored', $yesno],
            ['login_lockout_secret', 'loginlockoutsecret', null],
        ];

        foreach ($prefs as $prefdata) {
            list($prefname, $langkey, $transformer) = $prefdata;
            $value = get_user_preferences($prefname, null, $userid);
            if ($value === null) {
                continue;
            }
            writer::export_user_preference('core_auth', $prefname, $transformer ? $transformer($value) : $value,
                get_string("privacy:metadata:userpref:{$langkey}", 'core_auth'));
        }
    }
914184
protected static function export_user_data_frameworks_in_context($userid, context $context) {
        global $DB;

        $ffields = competency_framework::get_sql_fields('f', 'f_');
        $cfields = competency::get_sql_fields('c', 'c_');
        $c2fields = competency::get_sql_fields('c2', 'c2_');
        $rcfields = related_competency::get_sql_fields('rc', 'rc_');

        $frameworks = [];
        $initframework = function($record) use (&$frameworks, $userid) {
            $framework = new competency_framework(null, competency_framework::extract_record($record, 'f_'));
            $frameworks[$framework->get('id')] = array_merge(static::transform_framework_brief($framework), [
                'timemodified' => transform::datetime($framework->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno($framework->get('usermodified') == $userid),
                'competencies' => []
            ]);
        };
        $initcompetency = function($record, $prefix) use (&$frameworks, $userid) {
            $competency = new competency(null, competency::extract_record($record, $prefix));
            $frameworks[$competency->get('competencyframeworkid')]['competencies'][$competency->get('id')] = array_merge(
                static::transform_competency_brief($competency),
                [
                    'timemodified' => transform::datetime($competency->get('timemodified')),
                    'created_or_modified_by_you' => transform::yesno($competency->get('usermodified') == $userid),
                    'related_competencies' => []
                ]
            );
        };

        // Start by looking for related competencies.
        $sql = "
            SELECT $ffields, $cfields, $c2fields, $rcfields
              FROM {" . related_competency::TABLE . "} rc
              JOIN {" . competency::TABLE . "} c
                ON c.id = rc.competencyid
              JOIN {" . competency::TABLE . "} c2
                ON c2.id = rc.relatedcompetencyid
              JOIN {" . competency_framework::TABLE . "} f
                ON f.id = c.competencyframeworkid
             WHERE rc.usermodified = :userid
               AND f.contextid = :contextid
          ORDER BY rc.id, c.id";
        $params = ['userid' => $userid, 'contextid' => $context->id];

        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $frameworkid = $record->f_id;
            $comp1id = $record->c_id;
            $comp2id = $record->c2_id;

            if (!isset($frameworks[$frameworkid])) {
                $initframework($record);
            }

            foreach (['c_', 'c2_'] as $key) {
                $competencyid = $record->{$key . 'id'};
                if (!isset($frameworks[$frameworkid]['competencies'][$competencyid])) {
                    $initcompetency($record, $key);
                }
            }

            $relcomp = new related_competency(null, related_competency::extract_record($record, 'rc_'));
            foreach (['c_' => 'c2_', 'c2_' => 'c_'] as $key => $relatedkey) {
                $competencyid = $record->{$key . 'id'};
                $competency = new competency(null, competency::extract_record($record, $relatedkey));
                $frameworks[$frameworkid]['competencies'][$competencyid]['related_competencies'][] = [
                    'name' => $competency->get('shortname'),
                    'idnumber' => $competency->get('idnumber'),
                    'timemodified' => transform::datetime($relcomp->get('timemodified')),
                    'created_or_modified_by_you' => transform::yesno($relcomp->get('usermodified') == $userid),
                ];
            }
        }
        $recordset->close();

        // Now look for competencies, but skip the ones we've already seen.
        $competencyids = array_reduce($frameworks, function($carry, $framework) {
            return array_merge($carry, array_keys($framework['competencies']));
        }, []);
        $insql = ' IS NOT NULL';
        $inparams = [];
        if (!empty($competencyids)) {
            list($insql, $inparams) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED, 'param', false);
        }
        $sql = "
            SELECT $ffields, $cfields
              FROM {" . competency::TABLE . "} c
              JOIN {" . competency_framework::TABLE . "} f
                ON f.id = c.competencyframeworkid
             WHERE c.usermodified = :userid
               AND f.contextid = :contextid
               AND c.id $insql
          ORDER BY c.id";
        $params = array_merge($inparams, ['userid' => $userid, 'contextid' => $context->id]);
        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            $frameworkid = $record->f_id;
            if (!isset($frameworks[$frameworkid])) {
                $initframework($record);
            }
            $initcompetency($record, 'c_');
        }
        $recordset->close();

        // Now look for frameworks, but skip the ones we've already seen.
        $frameworkids = array_keys($frameworks);
        $insql = ' IS NOT NULL';
        $inparams = [];
        if (!empty($frameworkids)) {
            list($insql, $inparams) = $DB->get_in_or_equal($frameworkids, SQL_PARAMS_NAMED, 'param', false);
        }
        $sql = "
            SELECT $ffields
              FROM {" . competency_framework::TABLE . "} f
             WHERE f.usermodified = :userid
               AND f.contextid = :contextid
               AND f.id $insql
          ORDER BY f.id";
        $params = array_merge($inparams, ['userid' => $userid, 'contextid' => $context->id]);
        $recordset = $DB->get_recordset_sql($sql, $params);
        foreach ($recordset as $record) {
            context_helper::preload_from_record($record);
            $initframework($record);
        }
        $recordset->close();

        // Export all the things!
        writer::with_context($context)->export_related_data(
            [get_string('competencies', 'core_competency')],
            'frameworks',
            (object) [
                // Drop the temporary IDs.
                'frameworks' => array_reduce($frameworks, function($carry, $item) {
                    $item['competencies'] = array_values($item['competencies']);
                    $carry[] = $item;
                    return $carry;
                }, [])
            ]
        );
    }
390539
public function activeForUser($userId)
    {
        return $this->forUser($userId)->reject(function ($client) {
            return $client->revoked;
        })->values();
    }
948750
public function clearUserCachedPerms($userId)
    {
        $cache = $this->getCache();
        
        $ids = $cache->getIds();
        foreach ($ids as $id) {
            // get the item, see if it has the user ID
            if ($id == self::SOURCES_MAP || strpos($id, 'source_') !== false || strpos($id, self::ITEM_PREFIX) === false) {
                continue;
            }

            $userPerms = $cache->load($id);
            if (is_array($userPerms)) {
                $changed = false;
                foreach ($userPerms as $type => $grantedUserIds) {
                    $newIds = array();
                    foreach ($grantedUserIds as $grantedUserId => $grant) {
                        if ($userId != $grantedUserId) {
                            $newIds[$grantedUserId] = $grant;
                        }
                    }
                    if (count($newIds) != count($userPerms[$type])) {
                        $userPerms[$type] = $newIds;
                        $changed = true;
                    }
                }
                if ($changed) {
                    $cache->save($userPerms, $id);
                }
            }
        }
    }
597978
public function exportUserTypeEntity($fieldId) {
        $item = $this->getUserTypeEntityById($fieldId);
        return $this->prepareExportUserTypeEntity($item, true);
    }
808601
public function Preferences($UserReference = '', $Username = '', $UserID = '') {
      $this->AddJsFile('profile.js');
      $Session = Gdn::Session();
      $this->Permission('Garden.SignIn.Allow');
      
      // Get user data
      $this->GetUserInfo($UserReference, $Username, $UserID, TRUE);
      $UserPrefs = Gdn_Format::Unserialize($this->User->Preferences);
      if ($this->User->UserID != $Session->UserID)
         $this->Permission('Garden.Users.Edit');
      
      if (!is_array($UserPrefs))
         $UserPrefs = array();
      $MetaPrefs = UserModel::GetMeta($this->User->UserID, 'Preferences.%', 'Preferences.');

      // Define the preferences to be managed
      $this->Preferences = array(
         'Notifications' => array(
            'Email.WallComment' => T('Notify me when people write on my wall.'),
            'Email.ActivityComment' => T('Notify me when people reply to my wall comments.'),
            'Popup.WallComment' => T('Notify me when people write on my wall.'),
            'Popup.ActivityComment' => T('Notify me when people reply to my wall comments.')
         )
      );
      
      // Allow email notification of applicants (if they have permission & are using approval registration)
      if (CheckPermission('Garden.Users.Approve') && C('Garden.Registration.Method') == 'Approval')
         $this->Preferences['Notifications']['Email.Applicant'] = array(T('NotifyApplicant', 'Notify me when anyone applies for membership.'), 'Meta');
      
      $this->FireEvent('AfterPreferencesDefined');
      
      // Loop through the preferences looking for duplicates, and merge into a single row
      $this->PreferenceGroups = array();
      $this->PreferenceTypes = array();
      foreach ($this->Preferences as $PreferenceGroup => $Preferences) {
         $this->PreferenceGroups[$PreferenceGroup] = array();
         $this->PreferenceTypes[$PreferenceGroup] = array();
         foreach ($Preferences as $Name => $Description) {
            $Location = 'Prefs';
            if (is_array($Description))
               list($Description, $Location) = $Description;

            $NameParts = explode('.', $Name);
            $PrefType = GetValue('0', $NameParts);
            $SubName = GetValue('1', $NameParts);
            if ($SubName != FALSE) {
               // Save an array of all the different types for this group
               if (!in_array($PrefType, $this->PreferenceTypes[$PreferenceGroup]))
                  $this->PreferenceTypes[$PreferenceGroup][] = $PrefType;
               
               // Store all the different subnames for the group   
               if (!array_key_exists($SubName, $this->PreferenceGroups[$PreferenceGroup])) {
                  $this->PreferenceGroups[$PreferenceGroup][$SubName] = array($Name);
               } else {
                  $this->PreferenceGroups[$PreferenceGroup][$SubName][] = $Name;
               }
            } else {
               $this->PreferenceGroups[$PreferenceGroup][$Name] = array($Name);
            }
         }
      }

      // Loop the preferences, setting defaults from the configuration.
      $CurrentPrefs = array();
      foreach ($this->Preferences as $PrefGroup => $Prefs) {
         foreach ($Prefs as $Pref => $Desc) {
            $Location = 'Prefs';
            if (is_array($Desc))
               list($Desc, $Location) = $Desc;

            if ($Location == 'Meta')
               $CurrentPrefs[$Pref] = GetValue($Pref, $MetaPrefs, FALSE);
            else
               $CurrentPrefs[$Pref] = GetValue($Pref, $UserPrefs, C('Preferences.'.$Pref, '0'));
            
            unset($MetaPrefs[$Pref]);
         }
      }
      $CurrentPrefs = array_merge($CurrentPrefs, $MetaPrefs);
      $CurrentPrefs = array_map('intval', $CurrentPrefs);
      $this->SetData('Preferences', $CurrentPrefs);
      
      if (UserModel::NoEmail()) {
         $this->PreferenceGroups = self::_RemoveEmailPreferences($this->PreferenceGroups);
         $this->PreferenceTypes = self::_RemoveEmailPreferences($this->PreferenceTypes);
         $this->SetData('NoEmail', TRUE);
      }
      
      $this->SetData('PreferenceGroups', $this->PreferenceGroups);
      $this->SetData('PreferenceTypes', $this->PreferenceTypes);
      $this->SetData('PreferenceList', $this->Preferences);
      
      if ($this->Form->AuthenticatedPostBack()) {
         // Get, assign, and save the preferences.
         $NewMetaPrefs = array();
         foreach ($this->Preferences as $PrefGroup => $Prefs) {
            foreach ($Prefs as $Pref => $Desc) {
               $Location = 'Prefs';
               if (is_array($Desc))
                  list($Desc, $Location) = $Desc;

               $Value = $this->Form->GetValue($Pref, NULL);
               if (is_null($Value)) continue;

               if ($Location == 'Meta') {
                  $NewMetaPrefs[$Pref] = $Value ? $Value : NULL;
                  if ($Value)
                     $UserPrefs[$Pref] = $Value; // dup for notifications code.
               } else {
                  if (!$CurrentPrefs[$Pref] && !$Value)
                     unset($UserPrefs[$Pref]); // save some space
                  else
                     $UserPrefs[$Pref] = $Value;
               }
            }
         }
         
         $this->UserModel->SavePreference($this->User->UserID, $UserPrefs);
         UserModel::SetMeta($this->User->UserID, $NewMetaPrefs, 'Preferences.');
         
         $this->SetData('Preferences', array_merge($this->Data('Preferences', array()), $UserPrefs, $NewMetaPrefs));
         
         if (count($this->Form->Errors() == 0))
            $this->InformMessage(Sprite('Check', 'InformSprite').T('Your preferences have been saved.'), 'Dismissable AutoDismiss HasSprite');
      } else {
         $this->Form->SetData($CurrentPrefs);
      }
      
      $this->Title(T('Notification Preferences'));
      $this->_SetBreadcrumbs($this->Data('Title'), $this->CanonicalUrl());
      $this->Render();
   }
56162
public static function get_user_preferences($name = '', $userid = 0) {
        global $USER;

        $params = self::validate_parameters(self::get_user_preferences_parameters(),
                                            array(
                                                'name' => $name,
                                                'userid' => $userid
                                            ));
        $preferences = array();
        $warnings = array();

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

        if (empty($params['name'])) {
            $name = null;
        }
        if (empty($params['userid'])) {
            $user = null;
        } else {
            $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
            core_user::require_active_user($user);
            if ($user->id != $USER->id) {
                // Only admins can retrieve other users preferences.
                require_capability('moodle/site:config', $context);
            }
        }

        $userpreferences = get_user_preferences($name, null, $user);
        // Check if we received just one preference.
        if (!is_array($userpreferences)) {
            $userpreferences = array($name => $userpreferences);
        }

        foreach ($userpreferences as $name => $value) {
            $preferences[] = array(
                'name' => $name,
                'value' => $value,
            );
        }

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