Reimplemented to store in the context the current user at start of workflow

@param null $defaultLanguageCode
@param null $adminLogin
@param array $workflowParameters
@return array
176424
protected function migrationContextFromParameters($defaultLanguageCode = null, $adminLogin = null, $workflowParameters = null)
    {
        $properties = parent::migrationContextFromParameters($defaultLanguageCode, $adminLogin);

        if (!is_array($workflowParameters)) {
            /// @todo log warning
            $workflowParameters = array();
        }

        $workflowParameters = array_merge(
            array(
                'original_user' => $this->repository->getCurrentUser()->login,
                'start_time' => time()
            ),
            $workflowParameters
        );

        $properties['workflow'] = $workflowParameters;

        return $properties;
    }
1327880
final protected function getFormAdminType(FormMapper $formMapper, AdminInterface $admin, $formField, $field, $fieldOptions = [], $adminOptions = [])
    {
        $adminOptions = array_merge([
            'edit' => 'list',
            'translation_domain' => 'SonataClassificationBundle',
        ], $adminOptions);

        $fieldDescription = $admin->getModelManager()->getNewFieldDescriptionInstance($admin->getClass(), $field, $adminOptions);
        $fieldDescription->setAssociationAdmin($admin);
        $fieldDescription->setAdmin($formMapper->getAdmin());
        $fieldDescription->setAssociationMapping([
            'fieldName' => $field,
            'type' => ClassMetadataInfo::MANY_TO_ONE,
        ]);

        $fieldOptions = array_merge([
            'sonata_field_description' => $fieldDescription,
            'class' => $admin->getClass(),
            'model_manager' => $admin->getModelManager(),
            'required' => false,
        ], $fieldOptions);

        return $formMapper->create($formField, ModelTypeList::class, $fieldOptions);
    }
1177107
protected function authNtlmMessageType3( $challenge, $user, $password, $workstation, $domain )
    {
        $domain = chunk_split( $domain, 1, "\x00" );
        $user = chunk_split( $user, 1, "\x00" );
        $workstation = chunk_split( $workstation, 1, "\x00" );
        $lm = '';
        $ntlm = $this->authNtlmResponse( $challenge, $password );
        $session = '';

        $domainOffset = 64;
        $userOffset = $domainOffset + strlen( $domain );
        $workstationOffset = $userOffset + strlen( $user );
        $lmOffset = $workstationOffset + strlen( $workstation );
        $ntlmOffset = $lmOffset + strlen( $lm );
        $sessionOffset = $ntlmOffset + strlen( $ntlm );

        $parts = array(
                        "NTLMSSP\x00",
                        "\x03\x00\x00\x00",
                        $this->authNtlmSecurityBuffer( $lm, $lmOffset ),
                        $this->authNtlmSecurityBuffer( $ntlm, $ntlmOffset ),
                        $this->authNtlmSecurityBuffer( $domain, $domainOffset ),
                        $this->authNtlmSecurityBuffer( $user, $userOffset ),
                        $this->authNtlmSecurityBuffer( $workstation, $workstationOffset ),
                        $this->authNtlmSecurityBuffer( $session, $sessionOffset ),
                        "\x01\x02\x00\x00",
                        $domain,
                        $user,
                        $workstation,
                        $lm,
                        $ntlm
                      );

        return implode( '', $parts );
    }
14391
public function loginAction()
    {
        $authPlugin = $this->cmsAuthentication();

        $redirectKey = $this->options->getRedirectKey();
        $redirect = $this->options->getUseRedirectParameter()
            ? $this->params()->fromQuery($redirectKey, false)
            : false;

        $url = $this->url()->fromRoute(
            null,
            [],
            $redirect ? ['query' => [$redirectKey => $redirect]] : []
        );

        $prg = $this->prg($url, true);
        // Return early if prg plugin returned a response
        if ($prg instanceof Response) {
            return $prg;
        }

        $post = $prg;

        $form = $this->loginForm;
        $fm   = $this->flashMessenger();

        if ($this->forwardingController && $fm->hasCurrentErrorMessages()) {
            foreach($fm->getCurrentErrorMessages() as $messages) {
                $form->setMessages($messages);
            }
            $fm->clearCurrentMessages($fm::NAMESPACE_ERROR);
        } elseif ($fm->hasErrorMessages()) {
            foreach($fm->getErrorMessages() as $messages) {
                $form->setMessages($messages);
            }
        }

        $form->setAttribute('action', $this->url()->fromRoute());
        if ($redirect) {
            $form->get($redirectKey)->setValue($redirect);
        }

        if ($post && $form->setData($post)->isValid()) {

            // clear adapters
            $this->cmsAuthentication()->getAuthenticationAdapter()->resetAdapters();
            $this->cmsAuthentication()->getAuthenticationService()->clearIdentity();

            $routeMatch = $this->getEvent()->getRouteMatch();
            $this->getRequest()->setPost(new Parameters($post));
            $this->options->setLoginRoute($routeMatch->getMatchedRouteName());
            $this->forwardingController = $routeMatch->getParam('controller');

            return $this->forward()->dispatch(
                $this->forwardingController,
                ['action' => 'authenticate']
            );
        }

        $this->forwardingController = null;

        $registrationRoute    = $this->options->getRegistrationRoute();
        $resetCredentialRoute = $this->options->getResetCredentialRoute();

        return new ViewModel(compact('form', 'registrationRoute', 'resetCredentialRoute'));
    }
589287
public function recordUserSettings()
    {
        $response = new ResponseBuilder(Common::getRequestVar('format'));
        try {
            $this->checkTokenInUrl();

            $defaultReport = Common::getRequestVar('defaultReport');
            $defaultDate = Common::getRequestVar('defaultDate');
            $language = Common::getRequestVar('language');
            $timeFormat = Common::getRequestVar('timeformat');
            $userLogin = Piwik::getCurrentUserLogin();

            Piwik::checkUserHasSuperUserAccessOrIsTheUser($userLogin);

            $this->processPasswordChange($userLogin);

            LanguagesManager::setLanguageForSession($language);

            Request::processRequest('LanguagesManager.setLanguageForUser', [
                'login' => $userLogin,
                'languageCode' => $language,
            ]);
            Request::processRequest('LanguagesManager.set12HourClockForUser', [
                'login' => $userLogin,
                'use12HourClock' => $timeFormat,
            ]);

            APIUsersManager::getInstance()->setUserPreference($userLogin,
                APIUsersManager::PREFERENCE_DEFAULT_REPORT,
                $defaultReport);
            APIUsersManager::getInstance()->setUserPreference($userLogin,
                APIUsersManager::PREFERENCE_DEFAULT_REPORT_DATE,
                $defaultDate);
            $toReturn = $response->getResponse();
        } catch (Exception $e) {
            $toReturn = $response->getResponseException($e);
        }

        return $toReturn;
    }
133367
public function requireDefaultRecords()
    {
        parent::requireDefaultRecords();

        $ssLoginUserName = Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME');
        if(!$ssLoginUserName){
            return;
        }

        // Check for default admin user by matching email
        $member = Member::get()->find(
            Member::config()->get('unique_identifier_field'),
            $ssLoginUserName
        );

        // If no member is found at this stage.
        // Find member ID 1
        if(!$member){
            $member = DataObject::get_by_id(Member::class, 1);
        }

        $firstName = 'Default Admin';

        // // If there isn't one then make it
        if(!$member){
            $member = ExternalLoginMember::create();
            $member->FirstName = $firstName;
            $member->Email = $ssLoginUserName;
            $member->write();
            DB::alteration_message("Created admin '$member->Email'", 'created');
        } else {
            if ($member->ClassName != $this->ClassName || $member->Email != $ssLoginUserName) {
                $member->ClassName = $this->ClassName;
                $member->FirstName = $firstName;
                $member->Surname = null;
                $member->Email = $ssLoginUserName;
                $member->TempIDHash = null;
                $member->TempIDExpired = null;
                $member->Password = null;
                $member->write();
                DB::alteration_message("Modified admin '$member->Email'", 'modified');
            }
        }

        // Find or create ADMIN group
        Group::singleton()->requireDefaultRecords();
        $adminGroup = Permission::get_groups_by_permission('ADMIN')->First();

        // Ensure this user is in the admin group
        if(!$member->inGroup($adminGroup)) {
            // Add member to group instead of adding group to member
            // This bypasses the privilege escallation code in Member_GroupSet
            $adminGroup->DirectMembers()->add($member);
        }
    }
681050
public function get($language = null, $default = null)
    {
        if ($language === null) {
            $language = 'default';
        }

        $data = parent::get($language, null);

        if ($data === null) {
            $data = $this->get('default', $default);
        }

        return $data;
    }
736553
public function login($username, $password, \Espo\Entities\AuthToken $authToken = null, $params = [], $request)
    {
        if (!$password) return;

        $isPortal = !empty($params['isPortal']);

        if ($authToken) {
            return $this->loginByToken($username, $authToken);
        }

        if ($isPortal) {
            $useLdapAuthForPortalUser = $this->getUtils()->getOption('portalUserLdapAuth');
            if (!$useLdapAuthForPortalUser) {
                return parent::login($username, $password, $authToken, $params, $request);
            }
        }

        $ldapClient = $this->getLdapClient();

        /* Login LDAP system user (ldapUsername, ldapPassword) */
        try {
            $ldapClient->bind();
        } catch (\Exception $e) {
            $options = $this->getUtils()->getLdapClientOptions();
            $GLOBALS['log']->error('LDAP: Could not connect to LDAP server ['.$options['host'].'], details: ' . $e->getMessage());

            $adminUser = $this->adminLogin($username, $password);
            if (!isset($adminUser)) {
                return null;
            }

            $GLOBALS['log']->info('LDAP: Administrator ['.$username.'] was logged in by Espo method.');
        }

        if (!isset($adminUser)) {
            try {
                $userDn = $this->findLdapUserDnByUsername($username);
            } catch (\Exception $e) {
                $GLOBALS['log']->error('Error while finding DN for ['.$username.'], details: ' . $e->getMessage() . '.');
            }

            if (!isset($userDn)) {
                $GLOBALS['log']->error('LDAP: Authentication failed for user ['.$username.'], details: user is not found.');

                $adminUser = $this->adminLogin($username, $password);
                if (!isset($adminUser)) {
                    return null;
                }

                $GLOBALS['log']->info('LDAP: Administrator ['.$username.'] was logged in by Espo method.');
            }

            $GLOBALS['log']->debug('User ['.$username.'] is found with this DN ['.$userDn.'].');

            try {
                $ldapClient->bind($userDn, $password);
            } catch (\Exception $e) {
                $GLOBALS['log']->error('LDAP: Authentication failed for user ['.$username.'], details: ' . $e->getMessage());
                return null;
            }
        }

        $user = $this->getEntityManager()->getRepository('User')->findOne([
            'whereClause' => [
                'userName' => $username,
                'type!=' => ['api', 'system']
            ]
        ]);

        if (!isset($user) && $this->getUtils()->getOption('createEspoUser')) {
            $userData = $ldapClient->getEntry($userDn);
            $user = $this->createUser($userData, $isPortal);
        }

        return $user;
    }
1356403
public String getLanguageOrDefault(RouteContext routeContext) {
        final String cookieName = generateLanguageCookie(defaultLanguage).getName();

        // Step 1: Look for a Response cookie.
        // The Response always has priority over the Request because it may have
        // been set earlier in the HandlerChain.
        Cookie cookie = routeContext.getResponse().getCookie(cookieName);
        if (cookie != null && !StringUtils.isNullOrEmpty(cookie.getValue())) {
            return getLanguageOrDefault(cookie.getValue());
        }

        // Step 2: Look for a Request cookie.
        cookie = routeContext.getRequest().getCookie(cookieName);
        if (cookie != null && !StringUtils.isNullOrEmpty(cookie.getValue())) {
            return getLanguageOrDefault(cookie.getValue());
        }

        // Step 3: Look for a lang parameter in the response locals
        if (routeContext.getResponse().getLocals().containsKey(PippoConstants.REQUEST_PARAMETER_LANG)) {
            String language = routeContext.getLocal(PippoConstants.REQUEST_PARAMETER_LANG);
            language = getLanguageOrDefault(language);
            return language;
        }

        // Step 4: Look for a language in the Accept-Language header.
        String acceptLanguage = routeContext.getHeader(HttpConstants.Header.ACCEPT_LANGUAGE);
        return getLanguageOrDefault(acceptLanguage);
    }
1047004
public function setForceDefaultLang(string $force_default_lang = "T") : CNabuDataObject
    {
        if ($force_default_lang === null) {
            throw new ENabuCoreException(
                    ENabuCoreException::ERROR_NULL_VALUE_NOT_ALLOWED_IN,
                    array("\$force_default_lang")
            );
        }
        $this->setValue('nb_site_user_force_default_lang', $force_default_lang);
        
        return $this;
    }
277799
protected function createAdminUser($admin, $output)
    {
        try {
            $this->reloadConfig();

            $userStore = Factory::getStore('User');
            $userService = new UserService($userStore);
            $userService->createUser($admin['name'], $admin['mail'], $admin['pass'], 1);

            $output->writeln('<info>'.Lang::get('user_created').'</info>');
        } catch (\Exception $ex) {
            $output->writeln('<error>'.Lang::get('failed_to_create').'</error>');
            $output->writeln('<error>' . $ex->getMessage() . '</error>');
        }
    }
1025070
public function doApplyStart(BaseCommand $command, Workflow $workflow)
    {
        $subject = $command->storage;
        if ($workflow->can($subject, 'start')) {
            $workflow->apply($subject, 'start');

            $command->message->text = 'Please Enter username & password.';

            return true;
        }

        return false;
    }
831937
public function getRequestEscapedParameter($name, $defaultValue = null)
    {
        $value = $this->getRequestParameter($name, $defaultValue);

        // TODO: remove this after special chars concept implementation
        $isAdmin = Registry::getConfig()->isAdmin() && Registry::getSession()->getVariable("blIsAdmin");
        if ($value !== null && !$isAdmin) {
            $this->checkParamSpecialChars($value);
        }

        return $value;
    }
256739
public function login($loginDuration = 0)
    {
        $loginStatus = Yii::$app->getUser()->login($this, $loginDuration);
        if ($loginStatus) {
            $this->trigger(User::EVENT_LOGIN);
        }
        return $loginStatus;
    }
203420
protected function _getLoginQuery($userName, $password, $shopId, $isAdmin)
    {
        $database = DatabaseProvider::getDb();
        $userNameCondition = $this->formQueryPartForUserName($userName, $database);
        $shopOrRightsCondition = $this->formQueryPartForAdminView($shopId, $isAdmin);
        $passwordCondition = $this->formQueryPartForSha512Password($password, $database, $userNameCondition, $shopOrRightsCondition);
        $userActiveCondition = $this->formQueryPartForActiveUser();


        $query = "SELECT `oxid`
                    FROM oxuser 
                    WHERE 1  
                    AND $userActiveCondition 
                    AND $passwordCondition 
                    AND $userNameCondition 
                    $shopOrRightsCondition
                    ";

        return $query;
    }
78100
public static function changePasswordByCodeWithUsername($username, $code, $newPassword, $login)
    {
        return static::changePasswordByCode(static::getEmailByUsername($username), $code, $newPassword, $login);
    }
446144
public function checkAdmin($user = NULL, $pass = NULL, $force = false)
    {
        Logger::log('Checking admin session');
        if ((!$this->authorized && !$this->checked) || $force) {
            $admins = $this->getAdmins();
            if (null !== $admins) {
                $request = Request::getInstance();
                //Sacamos las credenciales de la petición
                $user = $user ?: $request->getServer('PHP_AUTH_USER');
                $pass = $pass ?: $request->getServer('PHP_AUTH_PW');
                if (NULL === $user || (array_key_exists($user, $admins) && empty($admins[$user]))) {
                    list($user, $pass) = $this->getAdminFromCookie();
                }
                if (!empty($user) && !empty($admins[$user])) {
                    $auth = $admins[$user]['hash'];
                    $this->authorized = ($auth === sha1($user . $pass));
                    if ($this->authorized) {
                        $this->updateAdmin($user , $admins[$user]['profile']);
                        ResponseHelper::setCookieHeaders([
                            [
                                'name' => $this->getHash(),
                                'value' => base64_encode("$user:$pass"),
                                'http' => true,
                                'domain' => '',
                            ]
                        ]);
                        $this->setSessionKey(self::LOGGED_USER_TOKEN, base64_encode("{$user}:{$pass}"));
                    }
                } else {
                    $this->admin = null;
                    $this->setSessionKey(self::ADMIN_ID_TOKEN, null);
                }
                $this->checked = true;
            }
        }

        return $this->authorized || self::isTest();
    }