@param string $userId
@param array $data
@param bool $getOrCreate

@return array
492561
public function add($userId, array $data=null, $getOrCreate=null)
    {
        $endpoint = 'user/';
        $payload = [
            'id' => $userId,
        ];
        if( $data !== null ){
            $payload['data'] = $data;
        }
        if($getOrCreate){
            $endpoint .= '?get_or_create=true';
        }
        $response = $this->doRequest('POST', $endpoint, $payload);
        $body = $response->getBody()->getContents();
        return json_decode($body, true);
    }
304311
protected function create(array $data)
    {
        $user = UserModel::create($data);
        return User::find($user->id);
    }
258164
public function create($data)
    {
        $uae = new AddUser($data);
        $uae = \Events::dispatch('on_before_user_add', $uae);
        if (!$uae->proceed()) {
            return false;
        }

        $config = $this->application->make('config');
        $hasher = new PasswordHash($config->get('concrete.user.password.hash_cost_log2'), $config->get('concrete.user.password.hash_portable'));

        if (isset($data['uIsValidated']) && $data['uIsValidated'] == 1) {
            $uIsValidated = 1;
        } elseif (isset($data['uIsValidated']) && $data['uIsValidated'] == 0) {
            $uIsValidated = 0;
        } else {
            $uIsValidated = -1;
        }

        if (isset($data['uIsFullRecord']) && $data['uIsFullRecord'] == 0) {
            $uIsFullRecord = 0;
        } else {
            $uIsFullRecord = 1;
        }

        $password_to_insert = isset($data['uPassword']) ? $data['uPassword'] : null;
        $hash = $hasher->HashPassword($password_to_insert);

        $uDefaultLanguage = null;
        if (isset($data['uDefaultLanguage']) && $data['uDefaultLanguage'] != '') {
            $uDefaultLanguage = $data['uDefaultLanguage'];
        }

        $entity = new UserEntity();
        $entity->setUserName($data['uName']);
        $entity->setUserEmail($data['uEmail']);
        $entity->setUserPassword($hash);
        $entity->setUserIsValidated($uIsValidated);
        $entity->setUserIsFullRecord($uIsFullRecord);
        $entity->setUserDefaultLanguage($uDefaultLanguage);
        $entity->setUserIsActive(true);

        $this->entityManager->persist($entity);
        $this->entityManager->flush();

        $newUID = $entity->getUserID();
        $ui = $this->userInfoRepository->getByID($newUID);

        if (is_object($ui)) {
            $uo = $ui->getUserObject();
            $groupControllers = \Group::getAutomatedOnRegisterGroupControllers($uo);
            foreach ($groupControllers as $ga) {
                if ($ga->check($uo)) {
                    $uo->enterGroup($ga->getGroupObject());
                }
            }

            // run any internal event we have for user add
            $ue = new UserInfoWithPassword($ui);
            $ue->setUserPassword($password_to_insert);
            \Events::dispatch('on_user_add', $ue);

            // Now we notify any relevant users.
            $type = $this->application->make('manager/notification/types')->driver('user_signup');
            /* @var UserSignupType $type */
            $u = new User();
            $createdBy = null;
            if (is_object($u)) {
                $creator = $u->getUserInfoObject();
                if (is_object($creator)) {
                    $createdBy = $creator->getEntityObject();
                }
            }
            $signup = new UserSignup($ui->getEntityObject(), $createdBy);
            $notifier = $type->getNotifier();
            $subscription = $type->getSubscription($signup);
            $notified = $notifier->getUsersToNotify($subscription, $signup);
            $notification = $type->createNotification($signup);
            $notifier->notify($notified, $notification);
        }

        return $ui;
    }
30646
public function call($userData = array(), $verifyData = TRUE)
    {
	    if ($verifyData)
	    {
		    foreach (self::$_KEYS as $k)
		    {
			    if ((!array_key_exists($k, $this->_API)) || (empty($this->_API[$k])))
			    {
				    throw new \Exception($k . ' must be set.');
			    }
		    }
	    }

	    $defaults = array(
		    'CHARSET'       => 'UTF-8',
		    'METHOD'        => 'GET',
		    'URL'           => '/',
			'HEADERS'       => array(),
	        'DATA'          => array(),
	        'FAILONERROR'   => TRUE,
	        'RETURNARRAY'   => FALSE,
	        'ALLDATA'       => FALSE
	    );

	    if ($verifyData)
	    {
		    $request = $this->setupUserData(array_merge($defaults, $userData));
	    }
	    else
	    {
		    $request = array_merge($defaults, $userData);
	    }


	    // Send & accept JSON data
	    $defaultHeaders = array();
	    $defaultHeaders[] = 'Content-Type: application/json; charset=' . $request['CHARSET'];
	    $defaultHeaders[] = 'Accept: application/json';
	    if (array_key_exists('ACCESS_TOKEN', $this->_API))
	    {
		    $defaultHeaders[] = 'X-Shopify-Access-Token: ' . $this->_API['ACCESS_TOKEN'];
	    }

        $headers = array_merge($defaultHeaders, $request['HEADERS']);


	    if ($verifyData)
	    {
		    $url = 'https://' . $this->_API['API_KEY'] . ':' . $this->_API['ACCESS_TOKEN'] . '@' . $this->_API['SHOP_DOMAIN'] . $request['URL'];
	    }
	    else
	    {
		    $url = $request['URL'];
	    }

	    // cURL setup
        $ch = curl_init();
        $options = array(
            CURLOPT_RETURNTRANSFER  => TRUE,
            CURLOPT_URL             => $url,
            CURLOPT_HTTPHEADER      => $headers,
            CURLOPT_CUSTOMREQUEST   => strtoupper($request['METHOD']),
            CURLOPT_ENCODING        => '',
            CURLOPT_USERAGENT       => 'RocketCode Shopify API Wrapper',
            CURLOPT_FAILONERROR     => $request['FAILONERROR'],
            CURLOPT_VERBOSE         => $request['ALLDATA'],
            CURLOPT_HEADER          => 1
        );

	    // Checks if DATA is being sent
	    if (!empty($request['DATA']))
	    {
		    if (is_array($request['DATA']))
		    {
			    $options[CURLOPT_POSTFIELDS] = json_encode($request['DATA']);
		    }
		    else
		    {
			    // Detect if already a JSON object
			    json_decode($request['DATA']);
			    if (json_last_error() == JSON_ERROR_NONE)
			    {
				    $options[CURLOPT_POSTFIELDS] = $request['DATA'];
			    }
			    else
			    {
				    throw new \Exception('DATA malformed.');
			    }
		    }
	    }

        curl_setopt_array($ch, $options);

        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);


        // Data returned
        $result = json_decode(substr($response, $headerSize), $request['RETURNARRAY']);

        // Headers
        $info = array_filter(array_map('trim', explode("\n", substr($response, 0, $headerSize))));

        foreach($info as $k => $header)
        {
	        if (strpos($header, 'HTTP/') > -1)
	        {
                $_INFO['HTTP_CODE'] = $header;
                continue;
            }

            list($key, $val) = explode(':', $header);
            $_INFO[trim($key)] = trim($val);
        }


        // cURL Errors
        $_ERROR = array('NUMBER' => curl_errno($ch), 'MESSAGE' => curl_error($ch));

        curl_close($ch);

	    if ($_ERROR['NUMBER'])
	    {
		    throw new \Exception('ERROR #' . $_ERROR['NUMBER'] . ': ' . $_ERROR['MESSAGE']);
	    }


	    // Send back in format that user requested
	    if ($request['ALLDATA'])
	    {
		    if ($request['RETURNARRAY'])
		    {
			    $result['_ERROR'] = $_ERROR;
			    $result['_INFO'] = $_INFO;
		    }
		    else
		    {
			    $result->_ERROR = $_ERROR;
			    $result->_INFO = $_INFO;
		    }
		    return $result;
	    }
	    else
	    {
		    return $result;
	    }


    }
499949
public static function findProviderDataByUserId($userId, $provider)
    {
        $weChat = static::findOne(['user_id' => $userId, 'provider' => $provider]);
        if ($weChat) {
            return $weChat->getDecodedData();
        }
        return null;
    }
713613
public function createToken(array $tokenData, $userId)
    {
        $current = new \MUtil_Db_Expr_CurrentTimestamp();

        $tokenData['gto_changed']    = $current;
        $tokenData['gto_changed_by'] = $userId;
        $tokenData['gto_created']    = $current;
        $tokenData['gto_created_by'] = $userId;

        // Wait till the last nanosecond with creating the token id
        $tokenData['gto_id_token']   = $this->createTokenId();

        $this->db->insert('gems__tokens', $tokenData);

        if (\Gems_Tracker::$verbose) {
            \MUtil_Echo::r($tokenData, 'Created token: ' . $tokenData['gto_id_token']);
        }

        return $tokenData['gto_id_token'];
    }
1142129
public function update($userId, array $data=null)
    {
        $payload = [];
        if( $data !== null ){
            $payload['data'] = $data;
        }
        $response = $this->doRequest('PUT', 'user/' . $userId . '/', $payload);
        $body = $response->getBody()->getContents();
        return json_decode($body, true);
    }
101043
private function setupUserData($userData = array())
	{
		$returnable = array();

		foreach($userData as $key => $value)
		{
			switch($key)
			{
				case 'URL':
					// Remove shop domain
					$url = str_replace($this->_API['SHOP_DOMAIN'], '', $value);

					// Verify it contains /admin/
					if (strpos($url, '/admin/') !== 0)
					{
						$url = str_replace('//', '/', '/admin/' . preg_replace('/\/?admin\/?/', '', $url));
					}
					$returnable[$key] = $url;
					break;

				default:
					$returnable[$key] = $value;

			}
		}

		return $returnable;
	}
1010870
public function createNewSite(
        string $createdByUserId,
        string $createdReason = Tracking::UNKNOWN_REASON,
        $siteId = null
    ) {
        if (empty($siteId)) {
            // new site
            /** @var \Rcm\Entity\Site $newSite */
            return new \Rcm\Entity\Site(
                $createdByUserId,
                $createdReason
            );
        }

        return $this->copySiteById(
            $siteId,
            $createdByUserId,
            $createdReason
        );
    }
1317466
private function prepareGetterParams($getter_params, $user, $resource)
    {
        if (empty($getter_params)) {
            return [];
        }
        $values = [];
        foreach ($getter_params as $getter_name=>$params) {
            foreach ($params as $param) {
                if ('@' !== $param[ 'param_name' ][ 0 ]) {
                    $values[$getter_name][] = $param[ 'param_value' ];
                } else {
                    $values[$getter_name][] = $this->attributeManager->retrieveAttribute($this->attributeManager->getAttribute($param[ 'param_value' ]), $user, $resource);
                }
            }
        }
        return $values;
    }
350097
private function _make(&$value, $index, $userdata)
    {
        list($entity, $attribute) = $userdata;

        $value = entity($entity)->findByAttribute($attribute, $value);
    }
456206
public static function get_users_courses($userid, $returnusercount = true) {
        global $CFG, $USER, $DB;

        require_once($CFG->dirroot . '/course/lib.php');
        require_once($CFG->libdir . '/completionlib.php');

        // Do basic automatic PARAM checks on incoming data, using params description
        // If any problems are found then exceptions are thrown with helpful error messages
        $params = self::validate_parameters(self::get_users_courses_parameters(),
                ['userid' => $userid, 'returnusercount' => $returnusercount]);
        $userid = $params['userid'];
        $returnusercount = $params['returnusercount'];

        $courses = enrol_get_users_courses($userid, true, '*');
        $result = array();

        // Get user data including last access to courses.
        $user = get_complete_user_data('id', $userid);
        $sameuser = $USER->id == $userid;

        // Retrieve favourited courses (starred).
        $favouritecourseids = array();
        if ($sameuser) {
            $ufservice = \core_favourites\service_factory::get_service_for_user_context(\context_user::instance($userid));
            $favourites = $ufservice->find_favourites_by_type('core_course', 'courses');

            if ($favourites) {
                $favouritecourseids = array_flip(array_map(
                    function($favourite) {
                        return $favourite->itemid;
                    }, $favourites));
            }
        }

        foreach ($courses as $course) {
            $context = context_course::instance($course->id, IGNORE_MISSING);
            try {
                self::validate_context($context);
            } catch (Exception $e) {
                // current user can not access this course, sorry we can not disclose who is enrolled in this course!
                continue;
            }

            if (!$sameuser and !course_can_view_participants($context)) {
                // we need capability to view participants
                continue;
            }

            if ($returnusercount) {
                list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context);
                $enrolledsql = "SELECT COUNT('x') FROM ($enrolledsqlselect) enrolleduserids";
                $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams);
            }

            $displayname = external_format_string(get_course_display_name_for_list($course), $context->id);
            list($course->summary, $course->summaryformat) =
                external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', null);
            $course->fullname = external_format_string($course->fullname, $context->id);
            $course->shortname = external_format_string($course->shortname, $context->id);

            $progress = null;
            $completed = null;
            $completionhascriteria = false;
            $completionusertracked = false;

            // Return only private information if the user should be able to see it.
            if ($sameuser || completion_can_view_data($userid, $course)) {
                if ($course->enablecompletion) {
                    $completion = new completion_info($course);
                    $completed = $completion->is_course_complete($userid);
                    $completionhascriteria = $completion->has_criteria();
                    $completionusertracked = $completion->is_tracked_user($userid);
                    $progress = \core_completion\progress::get_course_progress_percentage($course, $userid);
                }
            }

            $lastaccess = null;
            // Check if last access is a hidden field.
            $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
            $canviewlastaccess = $sameuser || !isset($hiddenfields['lastaccess']);
            if (!$canviewlastaccess) {
                $canviewlastaccess = has_capability('moodle/course:viewhiddenuserfields', $context);
            }

            if ($canviewlastaccess && isset($user->lastcourseaccess[$course->id])) {
                $lastaccess = $user->lastcourseaccess[$course->id];
            }

            $hidden = false;
            if ($sameuser) {
                $hidden = boolval(get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0));
            }

            // Retrieve course overview used files.
            $courselist = new core_course_list_element($course);
            $overviewfiles = array();
            foreach ($courselist->get_course_overviewfiles() as $file) {
                $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
                                                                        $file->get_filearea(), null, $file->get_filepath(),
                                                                        $file->get_filename())->out(false);
                $overviewfiles[] = array(
                    'filename' => $file->get_filename(),
                    'fileurl' => $fileurl,
                    'filesize' => $file->get_filesize(),
                    'filepath' => $file->get_filepath(),
                    'mimetype' => $file->get_mimetype(),
                    'timemodified' => $file->get_timemodified(),
                );
            }

            $courseresult = [
                'id' => $course->id,
                'shortname' => $course->shortname,
                'fullname' => $course->fullname,
                'displayname' => $displayname,
                'idnumber' => $course->idnumber,
                'visible' => $course->visible,
                'summary' => $course->summary,
                'summaryformat' => $course->summaryformat,
                'format' => $course->format,
                'showgrades' => $course->showgrades,
                'lang' => clean_param($course->lang, PARAM_LANG),
                'enablecompletion' => $course->enablecompletion,
                'completionhascriteria' => $completionhascriteria,
                'completionusertracked' => $completionusertracked,
                'category' => $course->category,
                'progress' => $progress,
                'completed' => $completed,
                'startdate' => $course->startdate,
                'enddate' => $course->enddate,
                'marker' => $course->marker,
                'lastaccess' => $lastaccess,
                'isfavourite' => isset($favouritecourseids[$course->id]),
                'hidden' => $hidden,
                'overviewfiles' => $overviewfiles,
            ];
            if ($returnusercount) {
                $courseresult['enrolledusercount'] = $enrolledusercount;
            }
            $result[] = $courseresult;
        }

        return $result;
    }
247139
public function create($data)
    {
        /* ACCESS CHECK */
        if (!$this->isAllowed(ResourceName::RESOURCE_SITES, 'admin')) {
            $this->getResponse()->setStatusCode(Response::STATUS_CODE_401);

            return $this->getResponse();
        }
        /* */

        $inputFilter = new SiteInputFilter();
        $inputFilter->setData($data);

        if (!$inputFilter->isValid()) {
            return new ApiJsonModel(
                [],
                1,
                'Some values are missing or invalid.',
                $inputFilter->getMessages()
            );
        }

        $data = $inputFilter->getValues();

        $siteManager = $this->getSiteManager();
        $userId = $this->getCurrentUserId();

        $data = $siteManager->prepareSiteData($data);
        /** @var \Rcm\Repository\Domain $domainRepo */
        $domainRepo = $this->getEntityManager()->getRepository(
            \Rcm\Entity\Domain::class
        );

        $data['domain'] = $domainRepo->createDomain(
            $data['domainName'],
            $userId,
            'Create new domain in ' . get_class($this)
        );

        /** @var \Rcm\Entity\Site $newSite */
        $newSite = new Site(
            $userId,
            'Create new site in ' . get_class($this)
        );

        $newSite->populate($data);
        // make sure we don't have a siteId
        $newSite->setSiteId(null);

        $newSite = $siteManager->createSite($newSite);

        return new ApiJsonModel($newSite, 0, 'Success');
    }
346563
public function createNew(
        int $sourceId,
        string $collectionName,
        array $data
    ) : array {
        return $this->sendPost(
            sprintf('/profiles/%s/raw', $this->userName),
            [],
            [
                'source_id'  => $sourceId,
                'collection' => $collectionName,
                'data'       => $data
            ]
        );
    }
329763
protected function createSignup(array $data, $userId)
    {
        return Signup::create([
            'user_id' => $userId,
            'firstname' => $data['firstname'],
            'surname' => $data['surname'],
            'gender' => $data['gender'],
            'email' => $data['email'],
            'mobile_number' => $data['mobile_number'],
        ]);
    }
1096046
public static function create_contact_request(int $userid, int $requesteduserid) : \stdClass {
        global $DB, $PAGE;

        $request = new \stdClass();
        $request->userid = $userid;
        $request->requesteduserid = $requesteduserid;
        $request->timecreated = time();

        $request->id = $DB->insert_record('message_contact_requests', $request);

        // Send a notification.
        $userfrom = \core_user::get_user($userid);
        $userfromfullname = fullname($userfrom);
        $userto = \core_user::get_user($requesteduserid);
        $url = new \moodle_url('/message/pendingcontactrequests.php');

        $subject = get_string('messagecontactrequestsnotificationsubject', 'core_message', $userfromfullname);
        $fullmessage = get_string('messagecontactrequestsnotification', 'core_message', $userfromfullname);

        $message = new \core\message\message();
        $message->courseid = SITEID;
        $message->component = 'moodle';
        $message->name = 'messagecontactrequests';
        $message->notification = 1;
        $message->userfrom = $userfrom;
        $message->userto = $userto;
        $message->subject = $subject;
        $message->fullmessage = text_to_html($fullmessage);
        $message->fullmessageformat = FORMAT_HTML;
        $message->fullmessagehtml = $fullmessage;
        $message->smallmessage = '';
        $message->contexturl = $url->out(false);
        $userpicture = new \user_picture($userfrom);
        $userpicture->includetoken = $userto->id; // Generate an out-of-session token for the user receiving the message.
        $message->customdata = [
            'notificationiconurl' => $userpicture->get_url($PAGE)->out(false),
            'actionbuttons' => [
                'accept' => get_string_manager()->get_string('accept', 'moodle', null, $userto->lang),
                'reject' => get_string_manager()->get_string('reject', 'moodle', null, $userto->lang),
            ],
        ];

        message_send($message);

        return $request;
    }
727138
public function createToken(array $tokenData, $userId = null)
    {
        $userId = $this->_checkUserId($userId);
        return $this->getTokenLibrary()->createToken($tokenData, $userId);
    }