Handles the event of updating user's information

@return JsonModel
763154
public function updateUserInfoAction()
    {
        $response = [];
        $this->getEventManager()->trigger('meliscore_tooluser_save_info_start', $this, $response);

        $success = false;
        $errors = [];
        $datas = [];
        $userInfo = [];
        // translator
        $translator = $this->getServiceLocator()->get('translator');

        // declare the Tool service that we will be using to completely create our tool.
        $melisTool = $this->getServiceLocator()->get('MelisCoreTool');

        // tell the Tool what configuration in the app.tool.php that will be used.
        $melisTool->setMelisToolKey('meliscore', $this::TOOL_KEY);
        /** @var \Zend\Form\Form $userUpdateForm */
        $userUpdateForm = $melisTool->getForm('meliscore_tool_user_form_edit');

        if ($this->getRequest()->isPost()) {
            $postValues = $melisTool->sanitizePost($this->getRequest()->getPost()->toArray());
            $userUpdateForm->setData($postValues);

            // get the user id for sql wildcard
            $userId = empty($postValues['usr_id']) ? null : $postValues['usr_id'];
            $password = empty($postValues['usr_password']) ? '' : $postValues['usr_password'];
            $confirmPass = empty($postValues['usr_confirm_password']) ? '' : $postValues['usr_confirm_password'];
            $roleId = empty($postValues['usr_role_id']) ? 0 : (int)$postValues['usr_role_id'];

            if ($userUpdateForm->isValid()) {
                $userTable = $this->getServiceLocator()->get('MelisCoreTableUser');
                $imgService = $this->getServiceLocator()->get('MelisCoreImage');
                $melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth');
                $newXmlRights = ''; // xml rights temp holder
                // pass values that should not be changed
                foreach ($userTable->getEntryById($userId) as $user) {
                    $userInfo = [
                        'usr_login' => $user->usr_login,
                        'usr_password' => $user->usr_password,
                        'usr_lang_id' => $user->usr_lang_id,
                        'usr_rights' => $user->usr_rights,
                        'usr_creation_date' => $user->usr_creation_date,
                        'usr_last_login_date' => $user->usr_last_login_date,
                        'usr_image' => $user->usr_image,
                        'usr_role_id' => $user->usr_role_id
                    ];
                }
                $data = $userUpdateForm->getData();

                $imageContent = null;

                // create tmp folder if not exists
                $dirName = $_SERVER['DOCUMENT_ROOT'] . '/media/';
                if (!file_exists($dirName) && is_writable($dirName)) {
                    mkdir($dirName, 0777, true);
                }

                if (file_exists($dirName)) {
                    // process image, convert image content into mysql BLOB || image validation needed (file size & file type)
                    $imageFile = $this->params()->fromFiles('usr_image');

                    /** Ensuring file is an image */
                    if($imageFile['tmp_name'] !== ""){
                        $sourceImg = @imagecreatefromstring(@file_get_contents($imageFile['tmp_name']));
                        if ($sourceImg === false) {
                            $success = false;

                            $errors['usr_image'] = [
                                'invalidImage' => $translator->translate('tr_meliscore_tool_user_usr_image_error_invalid'),
                                'label' => $translator->translate('tr_meliscore_tool_user_col_profile'),
                            ];
                        } else {
                            if (!empty($imageFile['tmp_name'])) {
                                $imgService->createThumbnail($dirName, $imageFile['name'], $imageFile['tmp_name']);
                            }
                            $imageContent = !empty($imageFile['tmp_name']) ? file_get_contents($dirName . 'tmb_' . $imageFile['name']) : $userInfo['usr_image'];


                            // delete tmp image
                            if (!empty($imageFile['tmp_name'])) {
                                unlink($dirName . 'tmb_' . $imageFile['name']);
                            }
                        }
                    } else {
                        // it means you did not select an image
                        // if you did not select an image then we will get the current usr_image
                        if (! empty($userInfo)) {
                            $imageContent = $userInfo['usr_image'];
                        }
                    }
                }
                $data['usr_image'] = $imageContent;

                $newPass = '';
                // check if the user exists
                if ($userInfo) {
                    if (!empty($password) || !empty($confirmPass)) {
                        if (strlen($password) >= 8) {
                            if (strlen($confirmPass) >= 8) {
                                $passValidator = new MelisPasswordValidator();
                                if ($passValidator->isValid($password)) {
                                    // password and confirm password matching
                                    if ($password == $confirmPass) {
                                        $melisEmailBO = $this->getServiceLocator()->get('MelisCoreBOEmailService');

                                        // Fetching user language Id
                                        $userTable = $this->getServiceLocator()->get('MelisCoreTableUser');
                                        $userDataResult = $userTable->getEntryById($userId);
                                        $userDatas = $userDataResult->current();

                                        // Tags to be replace at email content with the corresponding value
                                        $tags = [
                                            'NAME' => $userDatas->usr_firstname . ' ' . $userDatas->usr_lastname,
                                            'PASSWORD' => $password,
                                        ];

                                        $email_to = $userDatas->usr_email;
                                        $name_to = $userDatas->usr_login;
                                        $langId = $userDatas->usr_lang_id;

                                        $melisEmailBO->sendBoEmailByCode('PASSWORDMODIFICATION', $tags, $email_to, $name_to, $langId);

                                        $newPass = $melisCoreAuth->encryptPassword($password);
                                        if (empty($errors)) {
                                            $success = true;
                                        }
                                    } else {
                                        $success = false;
                                        $errors['usr_password'] = [
                                            'invalidPassword' => $translator->translate('tr_meliscore_tool_user_usr_password_not_match'),
                                            'label' => 'Password',
                                        ];
                                        $errors['usr_confirm_password'] = [
                                            'invalidPassword' => $translator->translate('tr_meliscore_tool_user_usr_password_not_match'),
                                            'label' => 'Password',
                                        ];
                                    } // password and confirm password matching
                                } else {
                                    $errors['usr_password'] = [
                                        'invalidPassword' => $translator->translate('tr_meliscore_tool_user_usr_password_regex_not_match'),
                                        'label' => 'Password',
                                    ];
                                } // password regex validator
                            } else {
                                $errors['usr_confirm_password'] = [
                                    'invalidPassword' => $translator->translate('tr_meliscore_tool_user_usr_confirm_password_error_low'),
                                    'label' => 'Password',
                                ];
                            }// end confirm password length
                        } else {
                            $errors['usr_password'] = [
                                'invalidPassword' => $translator->translate('tr_meliscore_tool_user_usr_password_error_low'),
                                'label' => 'Password',
                            ];
                        }// end password length
                    } else {
                        // update without touching the password
                        $success = true;
                    } // password and confirm password not empty

                    if ($success && empty($errors)) {
                        $savedPassword = !empty($newPass) ? $newPass : $userInfo['usr_password'];
                        // remove confirm pass when updating
                        unset($data['usr_confirm_password']);

                        $data['usr_login'] = $userInfo['usr_login'];
                        $data['usr_password'] = $savedPassword;
                        // $data['usr_lang_id'] = $userInfo['usr_lang_id'];
                        $data['usr_admin'] = ($data['usr_admin']) ? 1 : 0;
                        $data['usr_rights'] = $userInfo['usr_rights'];
                        $data['usr_creation_date'] = $userInfo['usr_creation_date'];
                        $data['usr_last_login_date'] = $userInfo['usr_last_login_date'];
                        $data['usr_role_id'] = $userInfo['usr_role_id'];

                        if ($roleId == 0 || $roleId == 1) {
                            $data['usr_role_id'] = 1;
                            $container = new Container('meliscore');
                            if (!empty($container['action-tool-user-setrights-tmp'])) {
                                $newXmlRights = '<?xml version="1.0" encoding="UTF-8"?><document type="MelisUserRights" author="MelisTechnology" version="2.0">';
                                foreach ($container['action-tool-user-setrights-tmp'] as $xmlrights)
                                    $newXmlRights .= $xmlrights;

                                $newXmlRights .= '</document>';

                                $data['usr_rights'] = $newXmlRights;
                            }
                        } else {
                            $data['usr_role_id'] = $roleId;
                            $rolesTable = $this->getServiceLocator()->get('MelisUserRole');
                            $roleData = $rolesTable->getEntryById($roleId);
                            $roleData = $roleData->current();
                            $newXmlRights = $roleData->urole_rights;
                            $data['usr_rights'] = $roleData->urole_rights;
                        }

                        $userTable->save($data, $userId);
                        // check if you are updating your own info
                        $userSession = $melisCoreAuth->getStorage()->read();
                        if ($data['usr_login'] == $userSession->usr_login) {
                            // update session data
                            $userSession->usr_status = $data['usr_status'];
                            $userSession->usr_email = $data['usr_email'];
                            $userSession->usr_firstname = $data['usr_firstname'];
                            $userSession->usr_lastname = $data['usr_lastname'];
                            $userSession->usr_lang_id = $data['usr_lang_id'];
                            $userSession->usr_role_id = $data['usr_role_id'];
                            $userSession->usr_rights = $newXmlRights;
                            $userSession->usr_image = $data['usr_image'];
                            $userSession->usr_password = $savedPassword;

                            $datas = [
                                'isMyInfo' => 1,
                                'loadProfile' => 'data:image/jpeg;base64,' . base64_encode($userSession->usr_image),
                            ];
                        }
                        // free up memory
                        unset($data);
                    }
                }
            } else {
                $success = false;
                $formErrors = $userUpdateForm->getMessages();
                foreach ($formErrors as $fieldName => $fieldErrors) {
                    $errors[$fieldName] = $fieldErrors;
                    $errors[$fieldName]['label'] = $userUpdateForm->get($fieldName)->getLabel();
                }
            }
        }
        if (!empty($errors)) {
            $success = false;
        }

        $response = [
            'success' => $success,
            'errors' => [$errors],
            'datas' => $datas
        ];
        $this->getEventManager()->trigger('meliscore_tooluser_save_info_end', $this, $response);

        return new JsonModel($response);
    }
26808
@SuppressWarnings("unchecked")
	public JSONObject getStatusUpdate() {
		JSONObject statusUpdate = null;
		try {
			statusUpdate = (JSONObject) JSON_PARSER
					.parse((String) this.nextStatusUpdateNode
							.getProperty(Properties.StatusUpdate.CONTENT));
		} catch (final ParseException e) {
			e.printStackTrace();
		}

		// (create and) add user object
		if (this.userJSON == null) {
			final User user = new User(this.userNode);
			this.userJSON = user.toActorJSON();
		}
		statusUpdate.put("actor", this.userJSON);

		this.nextStatusUpdate();
		return statusUpdate;
	}
835605
public function editAction()
    {
        $this->view->disable();
        $id     = $this->request->getPost('hidden_id');    
        $user   = Users::findFirstById($id);
        $msg    = "";
        if (!$user) {
            $alert = "sukses";
            $msg .= "User was not found";
        }

        if ($this->request->isPost()) {

            $user->assign([
                'name' => $this->request->getPost('name', 'striptags'),
                'profilesId' => $this->request->getPost('profile', 'int'),
                'email' => $this->request->getPost('email', 'email'),
                'banned' => $this->request->getPost('banned'),
                'suspended' => $this->request->getPost('suspended'),
                'active' => $this->request->getPost('active')
            ]);
            
            if (!$user->save()) {
                $alert = "error";
                foreach($user->getMessages() as $message)
                {
                    $msg .= $message ." ";
                }
            } else {
                $alert = "sukses";
                $msg .= "User was updated successfully";
            }
        }

        $response = new \Phalcon\Http\Response();
        $response->setContentType('application/json', 'UTF-8');
        $response->setJsonContent(array('_id' => $this->request->getPost("name"),'alert' => $alert, 'msg' => $msg ));
        return $response->send();
    }
1072932
public function updateUserSettingsAction(Request $request)
    {
        /** @var array $settings */
        $settings = $request->get('settings');

        $user = $this->getUser();

        $userSettings = $user->getSettings();

        foreach ($settings as $settingKey => $value) {
            $userSettings[$settingKey] = $value;
        }

        $user->setSettings($userSettings);

        $em = $this->get('doctrine')->getManager();

        $em->persist($user);
        $em->flush();

        return new JsonResponse();
    }
591401
public function actionSessionUpdate()
    {
        $identity = Yii::$app->adminuser->identity;
        $user = clone Yii::$app->adminuser->identity;
        $user->attributes = Yii::$app->request->bodyParams;
        $verify = ['title', 'firstname', 'lastname', 'id'];
        
        // check if email has changed, if yes send secure token and temp store new value in user settings table.
        if ($user->validate(['email']) && $user->email !== $identity->email && $this->module->emailVerification) {
            $token = $user->getAndStoreEmailVerificationToken();
            
            $mail = Yii::$app->mail->compose(Module::t('account_changeemail_subject'), Module::t('account_changeemail_body', ['url' => Url::base(true), 'token' => $token]))
            ->address($identity->email, $identity->firstname . ' '. $identity->lastname)
            ->send();
            
            if ($mail) {
                $identity->setting->set(User::USER_SETTING_NEWUSEREMAIL, $user->email);
            } else {
                $user->addError('email', Module::t('account_changeemail_tokensenterror', ['email' => $identity->email]));
                $identity->resetEmailVerification();
            }
        }
        
        if (!$this->module->emailVerification) {
            $verify[] = 'email';
        }
        
        if (!$user->hasErrors() && $user->update(true, $verify) !== false) {
            return $user;
        }
        
        return $this->sendModelError($user);
    }
767097
public function update()
    {
        if (!Input::has('settings')) {
            return $this->jsonErrorResponse('"settings" is required.');
        }

        $settings = Subbly::api('subbly.setting');

        $user = $settings->updateMany(Input::get('settings'));

        return $this->jsonResponse(array(
                'settings' => $settings->all(),
            ),
            array(
                'status' => array(
                    'code'    => 200,
                    'message' => 'Settings updated',
                ),
        ));
    }
729203
public function onGetJSONData()
    {
        $iElementID = Input::get('element_id');
        $obElementItem = $this->makeItem($iElementID);

        return $obElementItem->toJSON();
    }
930473
public function jsonResponse()
    {
        $user = Auth::getUser();

        //Change here whatever you need
        $ssoUser = new SSOUser();
        $ssoUser->id = $user->id;
        $ssoUser->name = $user->username;
        $ssoUser->email = $user->email;
        $ssoUser->roles = $user->roles;
        $ssoUser->profilepicture = "";

        $userInfo = $ssoUser->toArray();

        return VanillaSSO::WriteJsConnect($userInfo, $_GET, true);
    }
1324109
public function getChangeInfoForm()
    {

        if (! $this->changeInfoForm) {
            $this->setChangeInfoForm($this->getServiceLocator()->get('playgrounduser_change_info_form'));
        }

        return $this->changeInfoForm;
    }
204275
public function getCurrentUserId()
    {
        $contents = $this
            ->call('GET', self::USER_RESOURCE)
            ->getBody()
            ->getContents();

        $json = json_decode($contents, true);

        return $json['user_id'];
    }
986522
protected  function requestUserInfo() {
        $res = $this->sendRequest('GET', $this->getUrl('oauth', 'userinfo'), array(), array(
            'Authorization' => 'Bearer ' . $this->sessionStorage->read('access_token'),
        ));
        $result = $res->getBody();

        return json_decode($result, true);
    }
1085405
function update() {
		$db=$this->db;
		$now=microtime(TRUE);
		$data=&$db->read($this->file);
		if (isset($this->trigger['beforeupdate']) &&
			\Base::instance()->call($this->trigger['beforeupdate'],
				[$this,['_id'=>$this->id]])===FALSE)
			return $this->document;
		$data[$this->id]=$this->document;
		$db->write($this->file,$data);
		$db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
			$this->file.' [update] '.json_encode($this->document));
		if (isset($this->trigger['afterupdate']))
			\Base::instance()->call($this->trigger['afterupdate'],
				[$this,['_id'=>$this->id]]);
		return $this->document;
	}
1335332
public function checkForUpdates()
    {
        Piwik::checkUserHasSomeAdminAccess();
        $this->checkTokenInUrl();

        // perform check (but only once every 10s)
        UpdateCheck::check($force = false, UpdateCheck::UI_CLICK_CHECK_INTERVAL);

        $view = new View('@CoreHome/checkForUpdates');
        $this->setGeneralVariablesView($view);
        return $view->render();
    }
568286
public function processUpdateAction()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, Dealer::getModuleCode(),
                AccessManager::VIEW)
        ) {
            return $response;
        }

        // Error (Default: false)
        $error_msg = false;

        // Create the Form from the request
        $changeForm = $this->getForm($this->getRequest());

        try {
            // Check the form against constraints violations
            $form = $this->validateForm($changeForm, "POST");

            // Get the form field values
            $data = $form->getData();

            $updatedObject = $this->getService()->updateFromArray($data);

            // Check if object exist
            if (!$updatedObject) {
                throw new \LogicException(
                    $this->getTranslator()->trans("No %obj was updated.", ['%obj' => 'Dealer'])
                );
            }
            // If we have to stay on the same page, do not redirect to the successUrl,
            // just redirect to the edit page again.
            if ($this->getRequest()->get('save_mode') == 'stay') {
                $id = $this->getRequest()->query->get("dealer_id");

                return new RedirectResponse(URL::getInstance()->absoluteUrl("/admin/module/Dealer/dealer/edit",
                    ["dealer_id" => $id, ]));
            }

            // Redirect to the success URL
            return $this->generateSuccessRedirect($changeForm);
        } catch (FormValidationException $ex) {
            // Form cannot be validated
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
            /*} catch (\Exception $ex) {
                // Any other error
                $error_msg = $ex->getMessage();*/
        }

        if (false !== $error_msg) {
            // At this point, the form has errors, and should be redisplayed.
            $this->setupFormErrorContext(
                $this->getTranslator()->trans("%obj modification", ['%obj' => 'Dealer']),
                $error_msg,
                $changeForm,
                $ex
            );

            $id = $this->getRequest()->query->get("dealer_id");

            return new RedirectResponse(URL::getInstance()->absoluteUrl("/admin/module/Dealer/dealer/edit",
                ["dealer_id" => $id, ]));
        }
    }
807686
final public function update() {
        global $DB, $USER;

        if ($this->raw_get('id') <= 0) {
            throw new coding_exception('id is required to update');
        } else if (!$this->is_valid()) {
            throw new invalid_persistent_exception($this->get_errors());
        }

        // Before update hook.
        $this->before_update();

        // We can safely set those values after the validation because we know what we're doing.
        $this->raw_set('timemodified', time());
        $this->raw_set('usermodified', $USER->id);

        $record = $this->to_record();
        unset($record->timecreated);
        $record = (array) $record;

        // Save the record.
        $result = $DB->update_record(static::TABLE, $record);

        // We ensure that this is flagged as validated.
        $this->validated = true;

        // After update hook.
        $this->after_update($result);

        return $result;
    }
1023469
private function update() {
        // pre-processing hook
        if ($this->beforeUpdate() !== true)
            return $this;

        $mapping = $this->dao()->getMapping();
        $changes = [];

        // collect modified properties and their values
        foreach ($mapping['properties'] as $property) {                 // TODO: Until the dirty check is implemented all
            $propertyName = $property['name'];                          //       properties are assumed dirty.
            $changes[$propertyName] = $this->$propertyName;
        }

        // perform update
        if ($this->doUpdate($changes)) {
            $this->_modified = false;

            // post-processing hook
            $this->afterUpdate();
        }
        return $this;
    }
1241176
public function actionUpdateStatus()
    {
        $this->requirePostRequest();
        $request = Craft::$app->getRequest();

        // Fetch list id from hidden input
        $listId = $request->getRequiredBodyParam('listId');
        $memberId = $request->getRequiredBodyParam('memberId');
        $memberStatus = $request->getRequiredBodyParam('status');

        // Set params
        $params = [
          'status' => $memberStatus,
        ];

        // Patch request to update member status
        $response = HttpService::request('PATCH', 'lists/'.$listId.'/members/'.$memberId, $params);

        if ($response['success'] and $response['statusCode'] === 200) {
          Craft::$app->getSession()->setNotice('Member status updated.');
          return $this->redirectToPostedUrl();
        } elseif ($response['success'] and $response['statusCode'] !== 200) {
          Craft::$app->session->setFlash('errorBody', $response['body']);
          Craft::$app->getSession()->setError($response['statusCode'].' '.$response['reason']);
        } else {
          Craft::$app->getSession()->setError($response['reason']);
        }

        return $this->redirectToPostedUrl();
    }