store user method.

Method is called after user data is stored in the database

@param 	array		holds the new user data
@param 	bool		true if a new user is stored
@param	bool		true if user was succesfully stored in the database
@param	string		message
512120
public function onAfterAddPerson(AnEvent $event)
    {
        $person = $event->person;
        $actor_ids = explode(',', $this->_params->actor_ids);

        foreach ($actor_ids as $actor_id) {
            $actor_id = (int) $actor_id;
            if ($actor_id) {
                $actor = AnService::get('repos:actors.actor')->find(array('id' => $actor_id));
                if ($actor && $actor->isFollowable()) {
                    $actor->addFollower($person);
                    $actor->save();
                }
            }
        }
    }
203298
public function main()
    {
        $this->loadModel('CakeManager.Users');

        $email = $this->in('Enter the e-mailaddress');

        $password = $this->in('Enter the password');

        $data = [
            'email' => $email,
            'password' => $password,
        ];

        $new = $this->Users->newEntity($data);

        $new->set('role_id', 1);
        $new->set('active', 1);

        if ($this->Users->save($new)) {
            $this->out('The user "' . $email . '" has been created.');
            return true;
        }

        $this->out('Someting went wrong. The user could not be saved. We will debug the validation errors...');

        if ($new->errors()) {
            $errors = $new->errors();
            foreach ($errors as $key => $error) {
                foreach ($error as $message) {
                    $this->out($key . ': ' . ($message));
                }
            }
        }

        return false;
    }
220094
protected function & storeUserData(&$user = null)
    {
        // If no user is passed - create it
        if (!isset($user)) {
            $user = new $this->dbTable(false);
        }

        // Store social data for user
        $user[$this->dbIdField]         = $this->user->socialID;
        $user[$this->dbNameField]       = strlen($this->user->name) ? $this->user->name : $user[$this->dbNameField];
        $user[$this->dbSurnameField]    = strlen($this->user->surname) ? $this->user->surname : $user[$this->dbSurnameField] ;
        $user[$this->dbGenderField]     = strlen($this->user->gender) ? $this->user->gender : $user[$this->dbGenderField] ;
        $user[$this->dbBirthdayField]   = max($user[$this->dbBirthdayField],$this->user->birthday);
        $user[$this->dbPhotoField]      = strlen($this->user->photo) ? $this->user->photo : $user[$this->dbPhotoField];

        // If no email is passed - set hashed socialID as email
        if (!strlen($this->user->email)) {
            if (!strlen($user->email)) {
                $user[$this->dbEmailField] = md5($this->user->socialID);
            }
        } else {
            $user[$this->dbEmailField] = $this->user->email;
        }

        $user->save();

        return $user;
    }
1324214
public function store(array $data)
    {
        DB::transaction(function() use($data) {
            $model = $this->storeNotificationInstance($data);
            foreach ($data['title'] as $langId => $content) {
                $model->contents()->save($model->contents()->getModel()->newInstance([
                            'notification_id' => $model->id,
                            'lang_id'         => $langId,
                            'title'           => $content,
                            'content'         => $data['content'][$langId],
                            'subject'         => $data['subject'][$langId]
                ]));
            }
        });
    }
862535
public boolean registerUser(String username, String email,
            String password) {
        if (((username == null) && (email == null)) || (password == null)) {
            return false;
        }
        Object[] methodArgs = new Object[1];
        Map<String,Object> options = new HashMap<>();
        methodArgs[0] = options;
        if (username != null) {
            options.put("username", username);
        }
        if (email != null) {
            options.put("email", email);
        }
        options.put("password", password);
        getDDP().call("createUser", methodArgs, new DDPListener() {
            @Override
            public void onResult(Map<String, Object> jsonFields) {
                handleLoginResult(jsonFields);
            }
        });
        return true;
    }
1305811
public function info($message, array $context = array())
    {
        if (self::isSetLogger()) {
            return self::$logger->info($message, $context);
        }

        return false;
    }
1071028
function insert($save_data, $check = false)
    {
        if (!is_array($save_data)) {
            return false;
        }

        $insert_id = $existing = false;

        if ($check) {
            foreach ($save_data as $col => $values) {
                if (strpos($col, 'email') === 0) {
                    foreach ((array)$values as $email) {
                        if ($existing = $this->search('email', $email, false, false))
                            break 2;
                    }
                }
            }
        }

        $save_data     = $this->convert_save_data($save_data);
        $a_insert_cols = $a_insert_values = array();

        foreach ($save_data as $col => $value) {
            $a_insert_cols[]   = $this->db->quote_identifier($col);
            $a_insert_values[] = $this->db->quote($value);
        }

        if (!$existing->count && !empty($a_insert_cols)) {
            $this->db->query(
                "INSERT INTO " . $this->db->table_name($this->db_name, true).
                " (`user_id`, `changed`, `del`, ".join(', ', $a_insert_cols).")".
                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
            );

            $insert_id = $this->db->insert_id($this->db_name);
        }

        $this->cache = null;

        return $insert_id;
    }
637256
public function result(string $message, bool $isOk)
    {
        if ($isOk) {
            $this->ok($message);
        } else {
            $this->fail($message);
        }
    }
1102963
public function updateAddress(array $data, $user)
    {
        $this->getEventManager()->trigger('updateInfo.pre', $this, array('user' => $user, 'data' => $data));

        $form  = $this->getServiceManager()->get('playgrounduser_address_form');
        $form->bind($user);
        $form->setData($data);

        $filter = $user->getInputFilter();
        $filter->remove('password');
        $filter->remove('passwordVerify');
        $filter->remove('dob');

        $form->setInputFilter($filter);

        if ($form->isValid()) {
            $user = $this->getUserMapper()->update($user);
            $this->getEventManager()->trigger('updateInfo.post', $this, array('user' => $user, 'data' => $data));

            if ($user) {
                return $user;
            }
        }

        return false;
    }
337540
public function store($check=true)
	{
		// Validate data?
		if ($check)
		{
			// Is data valid?
			if (!$this->check())
			{
				return false;
			}

			if ($this->_context)
			{
				$results = \Event::trigger('content.onContentBeforeSave', array(
					$this->_context,
					&$this,
					$this->exists()
				));
				foreach ($results as $result)
				{
					if ($result === false)
					{
						$this->setError(\App::get('language')->txt('Content failed validation.'));
						return false;
					}
				}
			}
		}

		// Attempt to store data
		if (!$this->_tbl->store())
		{
			$this->setError($this->_tbl->getError());
			return false;
		}

		return true;
	}
585400
public function afterInsert(array &$args) {
        $data = $args[1];
        $primaryKey = &$args[2];

        // Check if an email address was changed. If so, send a validation email
        if (array_key_exists('email', $data) && !empty($data['email'])) {
            $this->_onEmailChange($data['email']);
        }

        // Save the password that was stored in beforeInsert()
        if ($this->_password) {
            $authLocalModel = new Model_AuthLocal();
            $newAuthLocalData = array(
                'password' => $this->_password,
                'user_id'  => $primaryKey
            );
            // Save the AuthLocal record
            $authLocalModel->insert($newAuthLocalData);
        }
    }
1356414
public static function send_instant_messages($messages = array()) {
        global $CFG, $USER, $DB;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        // Ensure the current user is allowed to run this function
        $context = context_system::instance();
        self::validate_context($context);
        require_capability('moodle/site:sendmessage', $context);

        $params = self::validate_parameters(self::send_instant_messages_parameters(), array('messages' => $messages));

        //retrieve all tousers of the messages
        $receivers = array();
        foreach($params['messages'] as $message) {
            $receivers[] = $message['touserid'];
        }
        list($sqluserids, $sqlparams) = $DB->get_in_or_equal($receivers);
        $tousers = $DB->get_records_select("user", "id " . $sqluserids . " AND deleted = 0", $sqlparams);

        $resultmessages = array();
        $messageids = array();
        foreach ($params['messages'] as $message) {
            $resultmsg = array(); //the infos about the success of the operation

            // We are going to do some checking.
            // Code should match /messages/index.php checks.
            $success = true;

            // Check the user exists.
            if (empty($tousers[$message['touserid']])) {
                $success = false;
                $errormessage = get_string('touserdoesntexist', 'message', $message['touserid']);
            }

            // TODO MDL-31118 performance improvement - edit the function so we can pass an array instead userid
            // Check if the recipient can be messaged by the sender.
            if ($success && !\core_message\api::can_post_message($tousers[$message['touserid']], $USER)) {
                $success = false;
                $errormessage = get_string('usercantbemessaged', 'message', fullname(\core_user::get_user($message['touserid'])));
            }

            // Now we can send the message (at least try).
            if ($success) {
                // TODO MDL-31118 performance improvement - edit the function so we can pass an array instead one touser object.
                $success = message_post_message($USER, $tousers[$message['touserid']],
                        $message['text'], external_validate_format($message['textformat']));
            }

            // Build the resultmsg.
            if (isset($message['clientmsgid'])) {
                $resultmsg['clientmsgid'] = $message['clientmsgid'];
            }
            if ($success) {
                $resultmsg['msgid'] = $success;
                $resultmsg['timecreated'] = time();
                $messageids[] = $success;
            } else {
                // WARNINGS: for backward compatibility we return this errormessage.
                //          We should have thrown exceptions as these errors prevent results to be returned.
                // See http://docs.moodle.org/dev/Errors_handling_in_web_services#When_to_send_a_warning_on_the_server_side .
                $resultmsg['msgid'] = -1;
                $resultmsg['errormessage'] = $errormessage;
            }

            $resultmessages[] = $resultmsg;
        }

        if (!empty($messageids)) {
            $messagerecords = $DB->get_records_list(
                'messages',
                'id',
                $messageids,
                '',
                'id, conversationid, smallmessage, fullmessageformat, fullmessagetrust');
            $resultmessages = array_map(function($resultmessage) use ($messagerecords, $USER) {
                $id = $resultmessage['msgid'];
                $resultmessage['conversationid'] = isset($messagerecords[$id]) ? $messagerecords[$id]->conversationid : null;
                $resultmessage['useridfrom'] = $USER->id;
                $resultmessage['text'] = message_format_message_text((object) [
                    'smallmessage' => $messagerecords[$id]->smallmessage,
                    'fullmessageformat' => external_validate_format($messagerecords[$id]->fullmessageformat),
                    'fullmessagetrust' => $messagerecords[$id]->fullmessagetrust
                ]);
                return $resultmessage;
            }, $resultmessages);
        }

        return $resultmessages;
    }
1282067
private static function activated(array $data, $user)
    {
        $input = array_keys($data);

        $field = $input[0];
        $value = $data[$field];

        if ($user->$field != $value) {
            return false;
        }

        return true;
    }
187870
public function save(array $data = [], array $rules = [], array $messages = [])
    {
        // Validate, and if it fails abort save
        if ($this->validateBeforeSave && ! $this->validate($data, $rules, $messages)) return false;

        return $this->saveRecord($data, $rules, $messages);
    }
779980
public void sendTextMessage(String message) {
		MessageEnvelope envelope = new MessageEnvelope();
		ReceivedMessage body = new ReceivedMessage();

		body.setText(message);
		envelope.setMessage(body);
		envelope.setSender(new User(facebookMockId));

		System.out.println("Sending message: [" + message + "] as user : ["
				+ facebookMockId + "].");
		forward(envelope);
		System.out.println("Sent!");
	}
319819
private function keepMessage($level, $message) {
		if(static::LOG_LEVELS[$this->keepMessages] > static::LOG_LEVELS[$level]) {
			return;
		}

		if($level == '' || $level == 'LOG'){
			$keepMessage = $message;
		} else {
			$keepMessage = $level . " " . $message;
		}
		$this->logEntries[] = $keepMessage;
	}
344446
public function updateNewsletter(array $data)
    {
        $user = $this->getAuthService()->getIdentity();
        $optinChange = false;
        $optin2Change = false;
        $optinPartnerChange = false;

        // I trigger an optin event before updating user if it has changed .
        if (isset($data['optin']) && $user->getOptin() != $data['optin']) {
            $optinChange = true;
            $this->getEventManager()->trigger(__FUNCTION__.'.pre', $this, array('user' => $user, 'data' => $data));
            $user->setOptin($data['optin']);
        }

        // I trigger an optin2 event before updating user if it has changed .
        if (isset($data['optin2']) && $user->getOptin2() != $data['optin2']) {
            $optin2Change = true;
            $this->getEventManager()->trigger(__FUNCTION__.'.pre', $this, array('user' => $user, 'data' => $data));
            $user->setOptin2($data['optin2']);
        }

        // I trigger an optinPartner event before updating user if it has changed
        if (isset($data['optinPartner']) && $user->getOptinPartner() != $data['optinPartner']) {
            $optinPartnerChange = true;
            $this->getEventManager()->trigger(__FUNCTION__.'Partner.pre', $this, array('user' => $user, 'data' => $data));
            $user->setOptinPartner($data['optinPartner']);
        }

        $form  = $this->getServiceManager()->get('playgrounduser_newsletter_form');
        $form->bind($user);
        $form->setData($data);

        /*if (!$form->isValid()) {
            return false;
        }*/

        $user = $this->getUserMapper()->update($user);
        if ($optinChange) {
            $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $user, 'data' => $data));
        }

        if ($optin2Change) {
            $this->getEventManager()->trigger(__FUNCTION__.'.optin2.post', $this, array('user' => $user, 'data' => $data));
        }

        if ($optinPartnerChange) {
            $this->getEventManager()->trigger(__FUNCTION__.'Partner.post', $this, array('user' => $user, 'data' => $data));
        }

        return $user;
    }