Export all user preferences for the plugin.

@param   int $userid The userid of the user whose data is to be exported.
336691
public static function export_user_preferences(int $userid) {
        $accesstoken = get_user_preferences('repository_flickr_access_token', null, $userid);
        if ($accesstoken !== null) {
            writer::export_user_preference(
                'repository_flickr',
                'repository_flickr_access_token',
                $accesstoken,
                get_string('privacy:metadata:repository_flickr:preference:repository_flickr_access_token', 'repository_flickr')
            );
        }
        $accesstokensecret = get_user_preferences('repository_flickr_access_token_secret', null, $userid);
        if ($accesstokensecret !== null) {
            writer::export_user_preference(
                'repository_flickr',
                'repository_flickr_access_token_secret',
                '',
                get_string('privacy:metadata:repository_flickr:preference:repository_flickr_access_token_secret', 'repository_flickr')
            );
        }
    }
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;
                }, [])
            ]
        );
    }
445468
protected static function export_user_data_in_module_contexts($userid, array $contexts) {
        global $DB;

        $contexts = array_filter($contexts, function($context) {
            return $context->contextlevel == CONTEXT_MODULE;
        });
        if (empty($contexts)) {
            return;
        }

        $path = [get_string('competencies', 'core_competency')];
        $cmids = array_map(function($context) {
            return $context->instanceid;
        }, $contexts);

        // Fetch all the modules with associations we created or modified.
        $compfields = competency::get_sql_fields('c', 'c_');
        $cmcfields = course_module_competency::get_sql_fields('cmc', 'cmc_');
        $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
        list($insql, $inparams) = $DB->get_in_or_equal($cmids, SQL_PARAMS_NAMED);
        $sql = "
            SELECT $compfields, $cmcfields, $ctxfields
              FROM {" . course_module_competency::TABLE . "} cmc
              JOIN {" . competency::TABLE . "} c
                ON c.id = cmc.competencyid
              JOIN {" . competency_framework::TABLE . "} f
                ON f.id = c.competencyframeworkid
              JOIN {context} ctx
                ON ctx.id = f.contextid
             WHERE cmc.usermodified = :userid
               AND cmc.cmid $insql
          ORDER BY cmc.cmid";
        $params = array_merge($inparams, ['userid' => $userid]);

        // Export the data.
        $recordset = $DB->get_recordset_sql($sql, $params);
        static::recordset_loop_and_export($recordset, 'cmc_cmid', [], function($carry, $record) {
            context_helper::preload_from_record($record);
            $competency = new competency(null, competency::extract_record($record, 'c_'));
            $cmc = new course_module_competency(null, course_module_competency::extract_record($record, 'cmc_'));
            $carry[] = array_merge(static::transform_competency_brief($competency), [
                'timecreated' => transform::datetime($cmc->get('timecreated')),
                'timemodified' => transform::datetime($cmc->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno(true)
            ]);
            return $carry;

        }, function($cmid, $data) use ($path) {
            $context = context_module::instance($cmid);
            writer::with_context($context)->export_data($path, (object) ['associations' => $data]);
        });
    }
1211780
protected static function export_user_data_blocked_users(int $userid) {
        global $DB;

        $context = \context_user::instance($userid);

        if ($blockedusers = $DB->get_records('message_users_blocked', ['userid' => $userid], 'id ASC')) {
            $blockedusersdata = [];
            foreach ($blockedusers as $blockeduser) {
                $blockedusersdata[] = (object) [
                    'blockeduser' => transform::user($blockeduser->blockeduserid)
                ];
            }
            writer::with_context($context)->export_data([get_string('blockedusers', 'core_message')], (object) $blockedusersdata);
        }
    }
339265
protected static function delete_user_data($userid) {
        global $DB;

        // Delete the stuff.
        $DB->delete_records('badge_manual_award', ['recipientid' => $userid]);
        $DB->delete_records('badge_criteria_met', ['userid' => $userid]);
        $DB->delete_records('badge_issued', ['userid' => $userid]);

        // Delete the backpacks and related stuff.
        $backpackids = $DB->get_fieldset_select('badge_backpack', 'id', 'userid = :userid', ['userid' => $userid]);
        if (!empty($backpackids)) {
            list($insql, $inparams) = $DB->get_in_or_equal($backpackids, SQL_PARAMS_NAMED);
            $DB->delete_records_select('badge_external', "backpackid $insql", $inparams);
            $DB->delete_records_select('badge_backpack', "id $insql", $inparams);
        }
    }
584455
public function getReviewsByUserId($userId)
    {
        $queryBuilder = $this->queryBuilderFactory->create();
        $queryBuilder
            ->select('r.*')
            ->from('oxreviews', 'r')
            ->where('r.oxuserid = :userId')
            ->orderBy('r.oxcreate', 'DESC')
            ->setParameter('userId', $userId);

        return $this->mapReviews($queryBuilder->execute()->fetchAll());
    }
597978
public function exportUserTypeEntity($fieldId) {
        $item = $this->getUserTypeEntityById($fieldId);
        return $this->prepareExportUserTypeEntity($item, true);
    }
1046456
public static function export_user_preferences(int $userid) {
        $lastpasswordupdatetime = get_user_preferences('auth_manual_passwordupdatetime', null, $userid);
        if ($lastpasswordupdatetime !== null) {
            $time = transform::datetime($lastpasswordupdatetime);
            writer::export_user_preference('auth_manual',
                'auth_manual_passwordupdatetime',
                $time,
                get_string('privacy:metadata:preference:passwordupdatetime', 'auth_manual')
            );
        }
    }
1249621
public function getUserPreferenceByUserIdAndName(int $userId, string $name): UserPreference
    {
        $userPreference = $this->getCacheValue(
            $userId,
            'ez-user-preference-',
            function ($userId) use ($name) {
                try {
                    return $this->persistenceHandler->userPreferenceHandler()->getUserPreferenceByUserIdAndName(
                        $userId,
                        $name
                    );
                } catch (APINotFoundException $e) {
                    return self::NOT_FOUND;
                }
            },
            static function () use ($userId) {
                return ['user-preference-' . $userId];
            },
            static function () use ($userId, $name) {
                return ['ez-user-preference-' . $userId . '-' . $name];
            },
            '-' . $name
        );

        if ($userPreference === self::NOT_FOUND) {
            throw new NotFoundException('User Preference', $userId . ',' . $name);
        }

        return $userPreference;
    }
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();
   }
152941
protected function forceLogoutForUserById($userId) {
		$this->deleteRememberDirectiveForUserById($userId);
		$this->db->exec(
			'UPDATE ' . $this->makeTableName('users') . ' SET force_logout = force_logout + 1 WHERE id = ?',
			[ $userId ]
		);
	}
342550
public static function export_user_preferences(int $userid) {
        $preference = get_user_preferences('block_myoverview_user_sort_preference', null, $userid);
        if (isset($preference)) {
            writer::export_user_preference('block_myoverview',
                'block_myoverview_user_sort_preference', get_string($preference, 'block_myoverview'),
                get_string('privacy:metadata:overviewsortpreference', 'block_myoverview'));
        }

        $preference = get_user_preferences('block_myoverview_user_view_preference', null, $userid);
        if (isset($preference)) {
            writer::export_user_preference('block_myoverview',
                'block_myoverview_user_view_preference',
                get_string($preference, 'block_myoverview'),
                get_string('privacy:metadata:overviewviewpreference', 'block_myoverview'));
        }

        $preference = get_user_preferences('block_myoverview_user_grouping_preference', null, $userid);
        if (isset($preference)) {
            writer::export_user_preference('block_myoverview',
                'block_myoverview_user_grouping_preference',
                get_string($preference, 'block_myoverview'),
                get_string('privacy:metadata:overviewgroupingpreference', 'block_myoverview'));
        }

        $preferences = get_user_preferences(null, null, $userid);
        foreach ($preferences as $name => $value) {
            if ((substr($name, 0, 30) == 'block_myoverview_hidden_course')) {
                writer::export_user_preference(
                    'block_myoverview',
                    $name,
                    $value,
                    get_string('privacy:request:preference:set', 'block_myoverview', (object) [
                        'name' => $name,
                        'value' => $value,
                    ])
                );
            }
        }

        $preference = get_user_preferences('block_myoverview_user_paging_preference', null, $userid);
        if (isset($preference)) {
            \core_privacy\local\request\writer::export_user_preference('block_myoverview',
                'block_myoverview_user_paging_preference',
                $preference,
                get_string('privacy:metadata:overviewpagingpreference', 'block_myoverview'));
        }
    }
390858
protected static function export_recentitems(int $userid, \context $context) {
        global $DB;
        $sql = "SELECT ra.id, c.fullname, ra.timeaccess, m.name, ra.cmid
                  FROM {block_recentlyaccesseditems} ra
                  JOIN {course} c ON c.id = ra.courseid
                  JOIN {course_modules} cm on cm.id = ra.cmid
                  JOIN {modules} m ON m.id = cm.module
                 WHERE ra.userid = :userid";

        $params = ['userid' => $userid];
        $records = $DB->get_records_sql($sql, $params);
        if (!empty($records)) {
            $recentitems = (object) array_map(function($record) use($context) {
                return [
                        'course_name' => format_string($record->fullname, true, ['context' => $context]),
                        'module_name' => format_string($record->name),
                        'timeaccess' => transform::datetime($record->timeaccess)
                ];
            }, $records);
            writer::with_context($context)->export_data([get_string('privacy:recentlyaccesseditemspath',
                    'block_recentlyaccesseditems')], $recentitems);
        }
    }
390539
public function activeForUser($userId)
    {
        return $this->forUser($userId)->reject(function ($client) {
            return $client->revoked;
        })->values();
    }
171021
public function loadRoleAssignmentsForUser($userId)
    {
        $user = $this->userService->loadUser($userId);

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

        return new Values\RoleAssignmentList($roleAssignments, $user->id);
    }
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;
        }

    }
212113
public function delete($userid)
	{
		$event = new Event('onPlatformUserDelete');
		$event->addArgument('userid', $userid);
		$event->addArgument('activePlugin', $this->activePlugin);

		Factory::getDispatcher()->triggerEvent($event);

		$debug = $event->getArgument('debug', null);
		if ($debug) {
			$this->debug[] = $debug;
		}

		$error = $event->getArgument('error', null);
		if ($error) {
			$this->error[] = $error;
		}
	}