Copied from \Gems_User_StaffUserDefinition but left out the password link

@param type $login_name
@param type $organization
@return \Zend_Db_Select
760686
protected function getUserSelect($login_name, $organization)
    {
        /**
         * Read the needed parameters from the different tables, lots of renames
         * for compatibility accross implementations.
         */
        $select = new \Zend_Db_Select($this->db);
        $select->from('gems__user_logins', array(
                    'user_login_id'       => 'gul_id_user',
                    'user_two_factor_key' => 'gul_two_factor_key',
                    'user_enable_2factor' => 'gul_enable_2factor'
                    ))
                ->join('gems__staff', 'gul_login = gsf_login AND gul_id_organization = gsf_id_organization', array(
                    'user_id'             => 'gsf_id_user',
                    'user_login'          => 'gsf_login',
                    'user_email'          => 'gsf_email',
                    'user_first_name'     => 'gsf_first_name',
                    'user_surname_prefix' => 'gsf_surname_prefix',
                    'user_last_name'      => 'gsf_last_name',
                    'user_gender'         => 'gsf_gender',
                    'user_group'          => 'gsf_id_primary_group',
                    'user_locale'         => 'gsf_iso_lang',
                    'user_logout'         => 'gsf_logout_on_survey',
                    'user_base_org_id'    => 'gsf_id_organization',
                    ))
               ->join('gems__groups', 'gsf_id_primary_group = ggp_id_group', array(
                   'user_role'=>'ggp_role',
                   'user_allowed_ip_ranges' => 'ggp_allowed_ip_ranges',
                   ))
               //->joinLeft('gems__user_passwords', 'gul_id_user = gup_id_user', array(
               //    'user_password_reset' => 'gup_reset_required',
               //    ))
               ->where('ggp_group_active = 1')
               ->where('gsf_active = 1')
               ->where('gul_can_login = 1')
               ->where('gul_login = ?')
               ->where('gul_id_organization = ?')
               ->limit(1);

        return $select;
    }
36290
protected function sendPasswordLostEmail($login, $email) 
    {
        $datas = array();
        foreach($this->getPassRequestDataByLogin($login) as $data) {
            $datas['rh_login'] = $data->rh_login;
            $datas['rh_hash'] = $data->rh_hash;
        }
        
        $login = $datas['rh_login'];
        $hash  = $datas['rh_hash'];
        
        $configPath = 'meliscore/datas';
        $melisConfig = $this->getServiceLocator()->get('MelisCoreConfig');
        
        $cfg = $melisConfig->getItem('meliscore/datas/'.getenv('MELIS_PLATFORM'));
        
        if (empty($cfg))
            $cfg = $melisConfig->getItem('meliscore/datas/default');
        
        $isActive = false;
        if (!empty($cfg['emails']))
            if (!empty($cfg['emails']['active']))
                $isActive = true;
            
        $url = $cfg['host'].'/melis/reset-password/'.$hash;
        
        if($isActive){
            // Tags to be replace at email content with the corresponding value
            $tags = array(
                'USER_Login' => $login,
                'URL' => $url
            );
            
            $name_to = $login;
            $email_to = $email;
            
            // Fetching user language Id
            $userTable = $this->getServiceLocator()->get('MelisCoreTableUser');
            $userData = $userTable->getDataByLoginAndEmail($login, $email);
            $userData = $userData->current();
            $langId = $userData->usr_lang_id;
            
            $melisEmailBO = $this->getServiceLocator()->get('MelisCoreBOEmailService');
            $emailResult = $melisEmailBO->sendBoEmailByCode('LOSTPASSWORD',  $tags, $email_to, $name_to, $langId);
            
            if ($emailResult){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
1348643
protected function findUserByField(LoginForm &$loginForm, $field = 'username')
    {
        return [
            $field,
            function ($attribute) use (&$loginForm) {
                $user = Yii::createObject(ModelMapHelper::User());
                /** @var LazyCache $cache */
                $cache = Yii::$app->cache;
                $value = $loginForm->$attribute;
                $loginForm->user = $cache->lazy(function () use ($user, $value, $attribute) {
                    return $user::find()
                        ->where(
                            "$attribute=:param",
                            [
                                ':param' => $value,
                            ]
                        )->one();
                }, "User:by:$attribute:$value", 86400, new TagDependency(['tags'=>$user::commonTag()]));
            }
        ];
    }
896619
public static function getEntries($login = null, $minDate = null, $maxDate = null, $resources = null, $actions = null)
    {
        $search = self::create();

        if (null !== $minDate) {
            $search->filterByCreatedAt($minDate, Criteria::GREATER_EQUAL);
        }

        if (null !== $maxDate) {
            $maxDateObject = new \DateTime($maxDate);
            $maxDateObject->add(new \DateInterval('P1D'));
            $search->filterByCreatedAt(date('Y-m-d', $maxDateObject->getTimestamp()), Criteria::LESS_THAN);
        }

        if (null !== $resources) {
            $search->filterByResource($resources);
        }

        if (null !== $actions) {
            $search->filterByAction($actions);
        }

        if (null !== $login) {
            $search->filterByAdminLogin($login);
        }

        return $search->find();
    }
738102
public function loginAction()
    {
        $return = $this->getReturnUri();
        $auth   = $this->getServiceLocator()
                       ->get( 'Zend\Authentication\AuthenticationService' );

        if ( $auth->hasIdentity() )
        {
            return $this->redirect()
                        ->toUrl( $this->getValidReturnUri( $return ) );
        }

        /* @var $form \Zend\Form\Form */
        $request = $this->getRequest();
        $data    = $request->getPost();
        $form    = $this->getServiceLocator()
                        ->get( 'Form' )
                        ->create( 'Grid\User\Login', array(
                            'returnUri' => $return,
                        ) );

        $form->setData( $data );

        if ( $request->isPost() )
        {
            if ( $form->isValid() )
            {
                /* @var $sessm \Zend\Session\SessionManager */
                /* @var $logger \Zork\Log\LoggerManager */
                $data   = $form->getData();
                $sessm  = $this->getSessionManager();
                $logger = $this->getServiceLocator()
                               ->get( 'Zork\Log\LoggerManager' );
                $result = $this->getServiceLocator()
                               ->get( 'Grid\User\Authentication\Service' )
                               ->login( $data, $sessm, $auth );

                $messages = $result->getMessages();

                if ( $result->isValid() )
                {
                    $sessm->regenerateId( false );

                    $this->messenger()
                         ->add( 'user.form.login.success',
                                'user', Message::LEVEL_INFO );

                    if ( $logger->hasLogger( 'application' ) )
                    {
                        $logger->getLogger( 'application' )
                               ->notice( 'user-login', array(
                                   'successful' => true,
                               ) );
                    }
                }
                else
                {
                    foreach ( $messages as $index => $message )
                    {
                        if ( is_int( $index ) && is_string( $message ) )
                        {
                            $this->messenger()
                                 ->add( $message, false, Message::LEVEL_WARN );
                        }
                    }

                    $this->messenger()
                         ->add( $this->getErrorMessageKey( $result->getCode() ),
                                'user', Message::LEVEL_ERROR );

                    if ( $logger->hasLogger( 'application' ) )
                    {
                        $logger->getLogger( 'application' )
                               ->warn( 'user-login', array(
                                   'successful' => false,
                               ) );
                    }
                }

                if ( empty( $messages['returnUri'] ) )
                {
                    if ( empty( $data['returnUri'] ) )
                    {
                        $returnUri = $return;
                    }
                    else
                    {
                        $returnUri = $data['returnUri'];
                    }
                }
                else
                {
                    $returnUri = $messages['returnUri'];
                }

                return $this->redirect()
                            ->toUrl( $this->getValidReturnUri( $returnUri ) );
            }
        }

        $this->plugin( 'layout' )
             ->setMiddleLayout( 'layout/middle/center' );

        return array(
            'form'      => $form,
            'display'   => $this->getServiceLocator()
                                ->get( 'Config' )
                                     [ 'modules' ]
                                     [ 'Grid\User' ]
                                     [ 'display' ]
        );
    }
306940
public static function userLogin($data, $loginField='email') {
		if( empty($data[$loginField]) )  {
			static::throwException('invalidLoginID');
		}
		$name = $data[$loginField];
		if( empty($data['password']) )  {
			static::throwException('invalidPassword');
		}
		$password = hashString($data['password']);
		//self::checkForEntry() does not return password and id now.
		
		$user = static::get(array(
// 			'where' => 'name LIKE '.static::formatValue($name),
			'where'		=> static::formatValue($name).' IN ('.implode(',', static::listLoginFields()).')',
			'number'	=> 1,
			'output'	=> SQLAdapter::OBJECT
		));
		if( empty($user) )  {
			static::throwException("invalidLoginID");
		}
		if( isset($user->published) && !$user->published )  {
			static::throwException('forbiddenLogin');
		}
		if( $user->password != $password )  {
			static::throwException('wrongPassword');
		}
		$user->logout();
		$user->login();
		return $user;
	}
214052
public function byFileNameAndByOrganization($file_name, $organizationId, $databaseConnectionName = null)
  {
    if(empty($databaseConnectionName))
    {
      $databaseConnectionName = $this->databaseConnectionName;
    }

    return $this->File->setConnection($databaseConnectionName)
      ->where('name', '=', $file_name)
      ->where('organization_id', '=', $organizationId)
      ->get();
  }
76948
public function login($userName, $password, AccessControlEvent $event)
    {
        $authCookie = $this->requestStack->getCurrentRequest()->cookies->get($this->authTokenName);

        // Remove expired tokens
        $this->getRepositoryAuthtoken()->deleteExpiredTokens();

        if ($userName !== null && $password !== null) {
            return $this->loginCheckUser($userName, $password, $event);
        } elseif ($authCookie !== null) {
            return $this->loginCheckAuthtoken($authCookie, $event);
        }

        $this->systemLogger->error('Login function called with empty username/password combination, or no authentication token.', ['event' => 'security']);
        throw new AccessControlException('Invalid login parameters.');
    }
433747
public function getOrganizationRole($user, $organization)
    {
        return $this->dm->getRepository('WobbleCodeUserBundle:Role')->findOneBy(
            [
                'organization.$id' => new \MongoId($organization->getId()),
                'user.$id' => new \MongoId($user->getId())
            ]
        );
    }
54689
public static function createFromLogin($login, $type, $key = 0) {

		switch($type) {
			case 'reverse':
				return strrev($login);
			case 'shuffle':
				return self::shuffle($login);
			case 'xor':
				return self::eXor($login, $key);
			case 'rot13':
				return str_rot13($login);
			case 'rotx':
				return self::rotx($login, $key);
			case 'rotx++':
				return self::rotxpp($login, $key);
			case 'rotx--':
				return self::rotxmm($login, $key);
			case 'ascii_rotx':
				return self::asciiRotx($login, $key);
			case 'ascii_rotx++':
				return self::asciiRotxpp($login, $key);
			case 'ascii_rotx--':
				return self::asciiRotxmm($login, $key);
		}
	}
1352670
public function getSecurityHeader($login, $password)
    {
        $authHeader = sprintf(
            $this->getSecurityHeaderTemplate(),
            htmlspecialchars($login),
            htmlspecialchars($password)
        );

        return new \SoapHeader(
            'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd',
            'Security',
            new \SoapVar($authHeader, XSD_ANYXML)
        );
    }
247089
public function hasPermission($login, $permission)
    {
        $groupName = $this->getLoginGroupName($login);

        // if login has no groups, no permission
        if ($groupName === null) {
            return false;
        }
        // master admin has all permissions
        if ($groupName == 'master_admin') {
            return true;
        }

        $permissions = $this->getGroupPermissions($groupName);

        return in_array($permission, $permissions);
    }
1036779
public function getUser(Login $login)
    {
        $user = new User();
        $user->setParams($this->params);
        $user->populate($login->getUsername(), $login->getPassword(), []);

        return $user;
    }
776167
public function login(string $login, string $password)
    {
        $user = $this->auth_repository->login($login, $password);

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

        if ($this->container->has('user')) {
            unset($this->container['user']);
        }
        $this->container['user'] = $user;

        return $this->auth_storage->setUser($user);
    }
833568
public static function Auth ($user_name = null, $password = null, $name = self::DEFAULT_CONNECTION_NAME) {
		if (static::IsAuthenticated($name)) {
			return static::$_loginUserName[$name];
		}

		//==============================================
		//設定確認
		//==============================================
		$options = static::GetAuthCookieOptions($name);
		foreach (['server_key', 'server_salt', 'client_key', 'client_salt'] as $key) {
			if (empty($options[$key])) {
				throw CoreException::RaiseSystemError('クッキー認証の%sが設定されていません。CookieAuth::Connect([\'%s\' => 任意のパスキー])として設定を行ってください。', [$key, $key]);
			}
		}
		if (empty($options['stretcher'])) {
			throw CoreException::RaiseSystemError('クッキー認証のstretcherが設定されていません。CookieAuth::Connect([\'stretcher\' => [一つ目のstretch, 二つ目のstretch, 三つ目のstretch]])として設定を行ってください。');
		}
		if (empty($options['password_callback'])) {
			throw CoreException::RaiseSystemError('クッキー認証のpassword_callbackが設定されていません。CookieAuth::Connect([\'password_callback\' => call back function]])として設定を行ってください。');
		}

		//==============================================
		//ガベージコレクタ
		//==============================================
		static::AuthCookieSessionGarbageCollection($options['divisor'], $options['probability'], $options, $name);

		//==============================================
		//認証クッキー取得
		//==============================================
		$auth_cookie	= static::GetAuthCookieValue($name);

		//ユーザー名とパスワードがある場合は強制再認証
		if ($auth_cookie !== null && $user_name !== null && $password !== null) {
			list($cookie_name, $cookie_value) = $auth_cookie;
			$auth_cookie = null;
			static::AuthDelete($cookie_name, $name);
		}

		//==============================================
		//認証
		//==============================================
		$password_callback	 = $options['password_callback'];

		//未認証の疑い
		if ($auth_cookie === null) {
			//認証クッキーがなく、user_nameの指定がない場合は未認証とする。
			if ($user_name === null) {
				static::$_loginUserName[$name] = null;
				return static::STATUS_UNAUTHORIZED;
			}

			//認証待ち
			//実在するユーザーかどうか確認する
			$on_storage_password = $password_callback($user_name);
			if ($on_storage_password === null) {
				//認証失敗
				static::$_loginUserName[$name] = null;
				return static::STATUS_FAILURE;
			}

			//正しいパスワードかどうか
			$auth_impact_callback	 = $options['auth_impact_callback'];
			if (!$auth_impact_callback($on_storage_password, $user_name, $password)) {
				//認証失敗
				static::$_loginUserName[$name] = null;
				return static::STATUS_FAILURE;
			}
			$password = $on_storage_password;

			//認証展開
			$cookie_name = static::CreateCookieName($name);
			if ($cookie_name === null) {
				throw CoreException::RaiseSystemError('クッキー認証ファイルの配置ができませんでした。');
			}
			static::UpdateAuthStatus($cookie_name, $user_name, $password, 1, $name);

			//認証成功
			static::$_loginUserName[$name] = $user_name;
			return ['user_name' => static::$_loginUserName[$name], 'cookie_auth' => false];
		}

		//==============================================
		//認証クッキーの正当性検証
		//==============================================
		//クッキー名と値の取得
		list($cookie_name, $cookie_value) = $auth_cookie;

		//認証データが残っているかどうか検証
		if (!is_file(static::CreateCookieSavePath($cookie_name, $name))) {
			static::AuthDelete($cookie_name, $name);
			throw CoreException::RaiseSystemError('存在しない認証クッキーを渡されました。cookie_name:%s, cookie_save_dir:%s', [$cookie_name, $options['cookie_save_dir']]);
		}

		//ユーザ名の取得
		$user_name = static::GetUserNameFromSessionData($cookie_name, $name);

		//パスワードを取得する
		$password = $password_callback($user_name);

		//実在するユーザーかどうか確認する
		if ($password === null || $password === false) {
			//認証失敗
			static::AuthDelete($cookie_name, $name);
			static::$_loginUserName[$name] = null;
			return static::STATUS_FAILURE;
		}

		//クッキー認証セッションデータの取得
		$server_data = static::GetAuthSessionData($cookie_name, $user_name, $password, $name);

		//クッキー値の展開
		$client_data = static::PurseAuthCookieData($cookie_value, $user_name, $password, $name);
		if ($client_data === false) {
			static::AuthDelete($cookie_name, $name);
			throw CoreException::RaiseSystemError('認証クッキーそのものが改ざんされています。');
		}

		//不動キーの突合検証
		if (!Hash::ValidRandomHash($client_data['shadow'], $options['client_key'], $options['server_salt'], $options['server_key'])) {
			static::AuthDelete($cookie_name, $name);
			throw CoreException::RaiseSystemError('認証クッキーの内容が改ざんされています。key:%s', [$client_data['shadow']]);
		}

		//認証値の突合確認
		foreach ($options['valid_alter_lv'] === static::VALID_ALTER_LV_LAZY ? [] : ['username', 'realm', 'uri', 'nc', 'nonce', 'cnonce', 'response'] as $key) {
			if ($server_data[$key] !== $client_data[$key]) {
				static::AuthDelete($cookie_name, $name);
				throw CoreException::RaiseSystemError('認証クッキーの内容が改ざんされています。key:%s', [$key]);
			}
		}

		//認証情報更新
		static::UpdateAuthStatus($cookie_name, $user_name, $password, $server_data['nc'] + 1, $name);

		//認証成功
		static::$_loginUserName[$name] = $user_name;
		return ['user_name' => static::$_loginUserName[$name], 'cookie_auth' => true];
	}
1045887
public function byParentByFolderNameAndByOrganization($parentId , $parent_name , $organizationId, $databaseConnectionName = null)
  {
    if(empty($databaseConnectionName))
    {
      $databaseConnectionName = $this->databaseConnectionName;
    }

    return $this->File->setConnection($databaseConnectionName)
      ->where('type', '=', 'C')
      ->where('parent_file_id', '=' , $parentId)
      ->where('name', '=', $parent_name)
      ->where('organization_id', '=', $organizationId)
      ->get();
  }
521744
static function loginUser( $login, $password, $authenticationMatch = false )
    {
        $http = eZHTTPTool::instance();
        $db = eZDB::instance();

        if ( $authenticationMatch === false )
            $authenticationMatch = eZUser::authenticationMatch();

        $loginEscaped = $db->escapeString( $login );
        $passwordEscaped = $db->escapeString( $password );

        $loginLdapEscaped = self::ldap_escape( $login );

        $loginArray = array();
        if ( $authenticationMatch & eZUser::AUTHENTICATE_LOGIN )
            $loginArray[] = "login='$loginEscaped'";
        if ( $authenticationMatch & eZUser::AUTHENTICATE_EMAIL )
            $loginArray[] = "email='$loginEscaped'";
        if ( count( $loginArray ) == 0 )
            $loginArray[] = "login='$loginEscaped'";
        $loginText = implode( ' OR ', $loginArray );

        $contentObjectStatus = eZContentObject::STATUS_PUBLISHED;

        $ini = eZINI::instance();
        $LDAPIni = eZINI::instance( 'ldap.ini' );
        $databaseName = $db->databaseName();
        // if mysql
        if ( $databaseName === 'mysql' )
        {
            $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login
                      FROM ezuser, ezcontentobject
                      WHERE ( $loginText ) AND
                            ezcontentobject.status='$contentObjectStatus' AND
                            ( ezcontentobject.id=contentobject_id OR ( password_hash_type=4 AND ( $loginText ) AND password_hash=PASSWORD('$passwordEscaped') ) )";
        }
        else
        {
            $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login
                      FROM ezuser, ezcontentobject
                      WHERE ( $loginText ) AND
                            ezcontentobject.status='$contentObjectStatus' AND
                            ezcontentobject.id=contentobject_id";
        }

        $users = $db->arrayQuery( $query );
        $exists = false;
        if ( count( $users ) >= 1 )
        {
            foreach ( $users as $userRow )
            {
                $userID = $userRow['contentobject_id'];
                $hashType = $userRow['password_hash_type'];
                $hash = $userRow['password_hash'];
                $exists = eZUser::authenticateHash( $userRow['login'], $password, eZUser::site(),
                                                    $hashType,
                                                    $hash );

                // If hash type is MySql
                if ( $hashType == eZUser::PASSWORD_HASH_MYSQL and $databaseName === 'mysql' )
                {
                    $queryMysqlUser = "SELECT contentobject_id, password_hash, password_hash_type, email, login
                                       FROM ezuser, ezcontentobject
                                       WHERE ezcontentobject.status='$contentObjectStatus' AND
                                             password_hash_type=4 AND ( $loginText ) AND password_hash=PASSWORD('$passwordEscaped') ";
                    $mysqlUsers = $db->arrayQuery( $queryMysqlUser );
                    if ( count( $mysqlUsers ) >= 1 )
                        $exists = true;
                }

                 // If current user has been disabled after a few failed login attempts.
                $canLogin = eZUser::isEnabledAfterFailedLogin( $userID );

                if ( $exists )
                {
                    eZDebugSetting::writeDebug( 'kernel-user', eZUser::createHash( $userRow['login'], $password, eZUser::site(),
                                                                                   $hashType ), "check hash" );
                    eZDebugSetting::writeDebug( 'kernel-user', $hash, "stored hash" );

                    // We should store userID for warning message.
                    $GLOBALS['eZFailedLoginAttemptUserID'] = $userID;

                    $userSetting = eZUserSetting::fetch( $userID );
                    $isEnabled = $userSetting->attribute( "is_enabled" );
                    if ( $hashType != eZUser::hashType() and
                         strtolower( $ini->variable( 'UserSettings', 'UpdateHash' ) ) == 'true' )
                    {
                        $hashType = eZUser::hashType();
                        $hash = eZUser::createHash( $login, $password, eZUser::site(),
                                                    $hashType );
                        $db->query( "UPDATE ezuser SET password_hash='$hash', password_hash_type='$hashType' WHERE contentobject_id='$userID'" );
                    }
                    break;
                }
            }
        }
        if ( $exists and $isEnabled and $canLogin )
        {
            eZDebugSetting::writeDebug( 'kernel-user', $userRow, 'user row' );
            $user = new eZUser( $userRow );
            eZDebugSetting::writeDebug( 'kernel-user', $user, 'user' );
            $userID = $user->attribute( 'contentobject_id' );

            eZUser::updateLastVisit( $userID );
            eZUser::setCurrentlyLoggedInUser( $user, $userID );

            // Reset number of failed login attempts
            eZUser::setFailedLoginAttempts( $userID, 0 );

            return $user;
        }
        else if ( $LDAPIni->variable( 'LDAPSettings', 'LDAPEnabled' ) === 'true' )
        {
            // read LDAP ini settings
            // and then try to bind to the ldap server

            $LDAPDebugTrace         = $LDAPIni->variable( 'LDAPSettings', 'LDAPDebugTrace' ) === 'enabled';
            $LDAPVersion            = $LDAPIni->variable( 'LDAPSettings', 'LDAPVersion' );
            $LDAPServer             = $LDAPIni->variable( 'LDAPSettings', 'LDAPServer' );
            $LDAPPort               = $LDAPIni->variable( 'LDAPSettings', 'LDAPPort' );
            $LDAPFollowReferrals    = (int) $LDAPIni->variable( 'LDAPSettings', 'LDAPFollowReferrals' );
            $LDAPBaseDN             = $LDAPIni->variable( 'LDAPSettings', 'LDAPBaseDn' );
            $LDAPBindUser           = $LDAPIni->variable( 'LDAPSettings', 'LDAPBindUser' );
            $LDAPBindPassword       = $LDAPIni->variable( 'LDAPSettings', 'LDAPBindPassword' );
            $LDAPSearchScope        = $LDAPIni->variable( 'LDAPSettings', 'LDAPSearchScope' );

            $LDAPLoginAttribute     = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPLoginAttribute' ) );
            $LDAPFirstNameAttribute = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPFirstNameAttribute' ) );
            $LDAPFirstNameIsCN      = $LDAPIni->variable( 'LDAPSettings', 'LDAPFirstNameIsCommonName' ) === 'true';
            $LDAPLastNameAttribute  = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPLastNameAttribute' ) );
            $LDAPEmailAttribute     = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPEmailAttribute' ) );

            $defaultUserPlacement   = $ini->variable( "UserSettings", "DefaultUserPlacement" );

            $LDAPUserGroupAttributeType = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPUserGroupAttributeType' ) );
            $LDAPUserGroupAttribute     = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPUserGroupAttribute' ) );

            if ( $LDAPIni->hasVariable( 'LDAPSettings', 'Utf8Encoding' ) )
            {
                $Utf8Encoding = $LDAPIni->variable( 'LDAPSettings', 'Utf8Encoding' );
                if ( $Utf8Encoding == "true" )
                    $isUtf8Encoding = true;
                else
                    $isUtf8Encoding = false;
            }
            else
            {
                $isUtf8Encoding = false;
            }

            if ( $LDAPIni->hasVariable( 'LDAPSettings', 'LDAPSearchFilters' ) )
            {
                $LDAPFilters = $LDAPIni->variable( 'LDAPSettings', 'LDAPSearchFilters' );
            }
            if ( $LDAPIni->hasVariable( 'LDAPSettings', 'LDAPUserGroupType' ) and  $LDAPIni->hasVariable( 'LDAPSettings', 'LDAPUserGroup' ) )
            {
                $LDAPUserGroupType = $LDAPIni->variable( 'LDAPSettings', 'LDAPUserGroupType' );
                $LDAPUserGroup = $LDAPIni->variable( 'LDAPSettings', 'LDAPUserGroup' );
            }

            $LDAPFilter = "( &";
            if ( count( $LDAPFilters ) > 0 )
            {
                foreach ( array_keys( $LDAPFilters ) as $key )
                {
                    $LDAPFilter .= "(" . $LDAPFilters[$key] . ")";
                }
            }
            $LDAPEqualSign = trim($LDAPIni->variable( 'LDAPSettings', "LDAPEqualSign" ) );
            $LDAPBaseDN    = str_replace( $LDAPEqualSign, "=", $LDAPBaseDN );
            $LDAPFilter    = str_replace( $LDAPEqualSign, "=", $LDAPFilter );
            $LDAPBindUser  = str_replace( $LDAPEqualSign, "=", $LDAPBindUser );

            if ( $LDAPDebugTrace )
            {
                $debugArray = array( 'stage' => '1/5: Connecting and Binding to LDAP server',
                                     'LDAPServer' => $LDAPServer,
                                     'LDAPPort' => $LDAPPort,
                                     'LDAPBindUser' => $LDAPBindUser,
                                     'LDAPVersion' => $LDAPVersion
                );
                // Set debug trace mode for ldap connections
                if ( function_exists( 'ldap_set_option' ) )
                    ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
                eZDebug::writeNotice( var_export( $debugArray, true ), __METHOD__ );
            }

            if ( function_exists( 'ldap_connect' ) )
                $ds = ldap_connect( $LDAPServer, $LDAPPort );
            else
                $ds = false;

            if ( $ds )
            {
                ldap_set_option( $ds, LDAP_OPT_PROTOCOL_VERSION, $LDAPVersion );
                ldap_set_option( $ds, LDAP_OPT_REFERRALS, $LDAPFollowReferrals );
                if ( $LDAPBindUser == '' )
                {
                    $r = ldap_bind( $ds );
                }
                else
                {
                    $r = ldap_bind( $ds, $LDAPBindUser, $LDAPBindPassword );
                }
                if ( !$r )
                {
                    // Increase number of failed login attempts.
                    eZDebug::writeError( 'Cannot bind to LDAP server, might be something wronge with connetion or bind user!', __METHOD__ );
                    if ( isset( $userID ) )
                        eZUser::setFailedLoginAttempts( $userID );

                    $user = false;
                    return $user;
                }

                $LDAPFilter .= "($LDAPLoginAttribute=$loginLdapEscaped)";
                $LDAPFilter .= ")";

                ldap_set_option( $ds, LDAP_OPT_SIZELIMIT, 0 );
                ldap_set_option( $ds, LDAP_OPT_TIMELIMIT, 0 );

                $retrieveAttributes = array( $LDAPLoginAttribute,
                                             $LDAPFirstNameAttribute,
                                             $LDAPLastNameAttribute,
                                             $LDAPEmailAttribute );
                if ( $LDAPUserGroupAttributeType )
                    $retrieveAttributes[] = $LDAPUserGroupAttribute;

                if ( $LDAPDebugTrace )
                {
                    $debugArray = array( 'stage' => '2/5: finding user',
                                         'LDAPFilter' => $LDAPFilter,
                                         'retrieveAttributes' => $retrieveAttributes,
                                         'LDAPSearchScope' => $LDAPSearchScope,
                                         'LDAPBaseDN' => $LDAPBaseDN
                    );
                    eZDebug::writeNotice( var_export( $debugArray, true ), __METHOD__ );
                }

                if ( $LDAPSearchScope == "one" )
                    $sr = ldap_list( $ds, $LDAPBaseDN, $LDAPFilter, $retrieveAttributes );
                else if ( $LDAPSearchScope == "base" )
                    $sr = ldap_read( $ds, $LDAPBaseDN, $LDAPFilter, $retrieveAttributes );
                else
                    $sr = ldap_search( $ds, $LDAPBaseDN, $LDAPFilter, $retrieveAttributes );

                $info = ldap_get_entries( $ds, $sr ) ;
                if ( $info['count'] > 1 )
                {
                    // More than one user with same uid, not allow login.
                    eZDebug::writeWarning( 'More then one user with same uid, not allowed to login!', __METHOD__ );
                    $user = false;
                    return $user;
                }
                else if ( $info['count'] < 1 )
                {
                    // Increase number of failed login attempts.
                    if ( isset( $userID ) )
                        eZUser::setFailedLoginAttempts( $userID );

                    // user DN was not found
                    eZDebug::writeWarning( 'User DN was not found!', __METHOD__ );
                    $user = false;
                    return $user;
                }
                else if ( $LDAPDebugTrace )
                {
                    $debugArray = array( 'stage' => '3/5: real authentication of user',
                                         'info' => $info
                    );
                    eZDebug::writeNotice( var_export( $debugArray, true ), __METHOD__ );
                }

                if( !$password )
                {
                    $password = crypt( microtime() );
                }

                // is it real authenticated LDAP user?
                if  ( !@ldap_bind( $ds, $info[0]['dn'], $password ) )
                {
                    // Increase number of failed login attempts.
                    if ( isset( $userID ) )
                        eZUser::setFailedLoginAttempts( $userID );

                    eZDebug::writeWarning( "User $userID failed to login!", __METHOD__ );
                    $user = false;
                    return $user;
                }

                $extraNodeAssignments = array();
                $userGroupClassID = $ini->variable( "UserSettings", "UserGroupClassID" );

                // default user group assigning
                if ( $LDAPUserGroupType != null )
                {
                    if ( $LDAPUserGroupType == "name" )
                    {
                        if ( is_array( $LDAPUserGroup ) )
                        {
                            foreach ( array_keys( $LDAPUserGroup ) as $key )
                            {
                                $groupName = $db->escapeString( $LDAPUserGroup[$key] );
                                $groupQuery = "SELECT ezcontentobject_tree.node_id
                                                 FROM ezcontentobject, ezcontentobject_tree
                                                WHERE ezcontentobject.name like '$groupName'
                                                  AND ezcontentobject.id=ezcontentobject_tree.contentobject_id
                                                  AND ezcontentobject.contentclass_id=$userGroupClassID";
                                $groupObject = $db->arrayQuery( $groupQuery );
                                if ( count( $groupObject ) > 0 and $key == 0 )
                                {
                                    $defaultUserPlacement = $groupObject[0]['node_id'];
                                }
                                else if ( count( $groupObject ) > 0 )
                                {
                                    $extraNodeAssignments[] = $groupObject[0]['node_id'];
                                }
                            }
                        }
                        else
                        {
                            $groupName = $db->escapeString( $LDAPUserGroup );
                            $groupQuery = "SELECT ezcontentobject_tree.node_id
                                             FROM ezcontentobject, ezcontentobject_tree
                                            WHERE ezcontentobject.name like '$groupName'
                                              AND ezcontentobject.id=ezcontentobject_tree.contentobject_id
                                              AND ezcontentobject.contentclass_id=$userGroupClassID";
                            $groupObject = $db->arrayQuery( $groupQuery );

                            if ( count( $groupObject ) > 0  )
                            {
                                $defaultUserPlacement = $groupObject[0]['node_id'];
                            }
                        }
                    }
                    else if ( $LDAPUserGroupType == "id" )
                    {
                        if ( is_array( $LDAPUserGroup ) )
                        {
                            foreach ( array_keys( $LDAPUserGroup ) as $key )
                            {
                                $groupID = $LDAPUserGroup[$key];
                                $groupQuery = "SELECT ezcontentobject_tree.node_id
                                                 FROM ezcontentobject, ezcontentobject_tree
                                                WHERE ezcontentobject.id='$groupID'
                                                  AND ezcontentobject.id=ezcontentobject_tree.contentobject_id
                                                  AND ezcontentobject.contentclass_id=$userGroupClassID";
                                $groupObject = $db->arrayQuery( $groupQuery );
                                if ( count( $groupObject ) > 0 and $key == 0 )
                                {
                                    $defaultUserPlacement = $groupObject[0]['node_id'];
                                }
                                else if ( count( $groupObject ) > 0 )
                                {
                                    $extraNodeAssignments[] = $groupObject[0]['node_id'];
                                }
                            }
                        }
                        else
                        {
                            $groupID = $LDAPUserGroup;
                            $groupQuery = "SELECT ezcontentobject_tree.node_id
                                             FROM ezcontentobject, ezcontentobject_tree
                                            WHERE ezcontentobject.id='$groupID'
                                              AND ezcontentobject.id=ezcontentobject_tree.contentobject_id
                                              AND ezcontentobject.contentclass_id=$userGroupClassID";
                            $groupObject = $db->arrayQuery( $groupQuery );

                            if ( count( $groupObject ) > 0  )
                            {
                                $defaultUserPlacement = $groupObject[0]['node_id'];
                            }
                        }
                    }
                }

                // read group mapping LDAP settings
                $LDAPGroupMappingType = $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupMappingType' );
                $LDAPUserGroupMap     = $LDAPIni->variable( 'LDAPSettings', 'LDAPUserGroupMap' );

                if ( !is_array( $LDAPUserGroupMap ) )
                    $LDAPUserGroupMap = array();

                // group mapping constants
                $ByMemberAttribute             = 'SimpleMapping'; // by group's member attributes (with mapping)
                $ByMemberAttributeHierarhicaly = 'GetGroupsTree'; // by group's member attributes hierarhically
                $ByGroupAttribute              = 'UseGroupAttribute'; // by user's group attribute (old style)
                $groupMappingTypes = array( $ByMemberAttribute,
                                            $ByMemberAttributeHierarhicaly,
                                            $ByGroupAttribute);

                $userData =& $info[ 0 ];

                // default mapping using old style
                if ( !in_array( $LDAPGroupMappingType, $groupMappingTypes ) )
                {
                    $LDAPGroupMappingType = $ByGroupAttribute;
                }

                if ( $LDAPDebugTrace )
                {
                    $debugArray = array( 'stage' => '4/5: group mapping init',
                                         'LDAPUserGroupType' => $LDAPUserGroupType,
                                         'LDAPGroupMappingType' => $LDAPGroupMappingType,
                                         'LDAPUserGroup' => $LDAPUserGroup,
                                         'defaultUserPlacement' => $defaultUserPlacement,
                                         'extraNodeAssignments' => $extraNodeAssignments
                    );
                    eZDebug::writeNotice( var_export( $debugArray, true ), __METHOD__ );
                }

                if ( $LDAPGroupMappingType == $ByMemberAttribute or
                     $LDAPGroupMappingType == $ByMemberAttributeHierarhicaly )
                {
                    $LDAPGroupBaseDN          = $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupBaseDN' );
                    $LDAPGroupBaseDN          = str_replace( $LDAPEqualSign, '=', $LDAPGroupBaseDN );
                    $LDAPGroupClass           = $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupClass' );

                    $LDAPGroupNameAttribute   = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupNameAttribute' ) );
                    $LDAPGroupMemberAttribute = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupMemberAttribute' ) );
                    $LDAPGroupDescriptionAttribute = strtolower( $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupDescriptionAttribute' ) );

                    $groupSearchingDepth = ( $LDAPGroupMappingType == '1' ) ? 1 : 1000;

                    // now, get all parents for currently ldap authenticated user
                    $requiredParams = array();
                    $requiredParams[ 'LDAPLoginAttribute' ]       = $LDAPLoginAttribute;
                    $requiredParams[ 'LDAPGroupBaseDN' ]          = $LDAPGroupBaseDN;
                    $requiredParams[ 'LDAPGroupClass' ]           = $LDAPGroupClass;
                    $requiredParams[ 'LDAPGroupNameAttribute' ]   = $LDAPGroupNameAttribute;
                    $requiredParams[ 'LDAPGroupMemberAttribute' ] = $LDAPGroupMemberAttribute;
                    $requiredParams[ 'LDAPGroupDescriptionAttribute' ] = $LDAPGroupDescriptionAttribute;
                    $requiredParams[ 'ds' ] =& $ds;
                    if ( $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupRootNodeId' ) !== '' )
                        $requiredParams[ 'TopUserGroupNodeID' ] = $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupRootNodeId' );
                    else
                        $requiredParams[ 'TopUserGroupNodeID' ] = 5;

                    $groupsTree = array();
                    $stack = array();
                    $newfilter = '(&(objectClass=' . $LDAPGroupClass . ')(' . $LDAPGroupMemberAttribute . '=' . $userData['dn'] . '))';

                    $groupsTree[ $userData['dn'] ] = array( 'data' => & $userData,
                                                                'parents' => array(),
                                                                'children' => array() );

                    eZLDAPUser::getUserGroupsTree( $requiredParams, $newfilter, $userData['dn'], $groupsTree, $stack, $groupSearchingDepth );
                    $userRecord =& $groupsTree[ $userData['dn'] ];

                    if ( $LDAPGroupMappingType == $ByMemberAttribute )
                    {
                        if ( count( $userRecord[ 'parents' ] ) > 0 )
                        {
                            $remappedGroupNames = array();
                            foreach ( array_keys( $userRecord[ 'parents' ] ) as $key )
                            {
                                $parentGroup =& $userRecord[ 'parents' ][ $key ];
                                if ( isset( $parentGroup[ 'data' ][ $LDAPGroupNameAttribute ] ) )
                                {
                                    $ldapGroupName = $parentGroup[ 'data' ][ $LDAPGroupNameAttribute ];
                                    if ( is_array( $ldapGroupName ) )
                                    {
                                        $ldapGroupName = ( $ldapGroupName[ 'count' ] > 0 ) ? $ldapGroupName[ 0 ] : '';
                                    }

                                    // remap group name and check that group exists
                                    if ( array_key_exists( $ldapGroupName, $LDAPUserGroupMap ) )
                                    {
                                        $remmapedGroupName = $db->escapeString( $LDAPUserGroupMap[ $ldapGroupName ] );
                                        $groupQuery = "SELECT ezcontentobject_tree.node_id
                                                         FROM ezcontentobject, ezcontentobject_tree
                                                        WHERE ezcontentobject.name like '$remmapedGroupName'
                                                          AND ezcontentobject.id=ezcontentobject_tree.contentobject_id
                                                          AND ezcontentobject.contentclass_id=$userGroupClassID";
                                        $groupRow = $db->arrayQuery( $groupQuery );

                                        if ( count( $groupRow ) > 0 )
                                        {
                                            $userRecord['new_parents'][] = $groupRow[ 0 ][ 'node_id' ];
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if ( $LDAPGroupMappingType == $ByMemberAttributeHierarhicaly )
                    {
                        $stack = array();
                        self::goAndPublishGroups( $requiredParams, $userData['dn'], $groupsTree, $stack, $groupSearchingDepth, true );
                    }
                    if ( isset( $userRecord['new_parents'] ) and
                         count( $userRecord['new_parents'] ) > 0 )
                    {
                        $defaultUserPlacement = $userRecord['new_parents'][0];
                        $extraNodeAssignments = array_merge( $extraNodeAssignments, $userRecord['new_parents'] );
                    }
                }
                else if ( $LDAPGroupMappingType == $ByGroupAttribute ) // old style mapping by group (employeetype) attribute
                {
                    if ( $LDAPUserGroupAttributeType )
                    {
                        // Should we create user groups that are specified in LDAP, but not found in eZ Publish?
                        $createMissingGroups = ( $LDAPIni->variable( 'LDAPSettings', 'LDAPCreateMissingGroups' ) === 'enabled' );
                        if ( $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupRootNodeId' ) !== '' )
                            $parentNodeID = $LDAPIni->variable( 'LDAPSettings', 'LDAPGroupRootNodeId' );
                        else
                            $parentNodeID = 5;

                        $groupAttributeCount = $info[0][$LDAPUserGroupAttribute]['count'];
                        if ( $LDAPUserGroupAttributeType == "name" )
                        {
                            for ( $i = 0; $i < $groupAttributeCount; $i++ )
                            {
                                if ( $isUtf8Encoding )
                                {
                                    $groupName = utf8_decode( $info[0][$LDAPUserGroupAttribute][$i] );
                                }
                                else
                                {
                                    $groupName = $info[0][$LDAPUserGroupAttribute][$i];
                                }

                                // Save group node id to either defaultUserPlacement or extraNodeAssignments
                                self::getNodeAssignmentsForGroupName( $groupName, ($i == 0), $defaultUserPlacement, $extraNodeAssignments,
                                                                      $createMissingGroups, $parentNodeID );
                            }
                        }
                        else if ( $LDAPUserGroupAttributeType == "id" )
                        {
                            for ( $i = 0; $i < $groupAttributeCount; $i++ )
                            {
                                if ( $isUtf8Encoding )
                                {
                                    $groupID = utf8_decode( $info[0][$LDAPUserGroupAttribute][$i] );
                                }
                                else
                                {
                                    $groupID = $info[0][$LDAPUserGroupAttribute][$i];
                                }
                                $groupName = "LDAP $groupID";

                                // Save group node id to either defaultUserPlacement or extraNodeAssignments
                                self::getNodeAssignmentsForGroupName( $groupName, ($i == 0), $defaultUserPlacement, $extraNodeAssignments,
                                                                      $createMissingGroups, $parentNodeID );
                            }
                        }
                        else if ( $LDAPUserGroupAttributeType == "dn" )
                        {
                            for ( $i = 0; $i < $groupAttributeCount; $i++ )
                            {
                                $groupDN = $info[0][$LDAPUserGroupAttribute][$i];
                                $groupName = self::getGroupNameByDN( $ds, $groupDN );

                                if ( $groupName )
                                {
                                    // Save group node id to either defaultUserPlacement or extraNodeAssignments
                                    self::getNodeAssignmentsForGroupName( $groupName, ($i == 0), $defaultUserPlacement, $extraNodeAssignments,
                                                                          $createMissingGroups, $parentNodeID );
                                }
                            }
                        }
                        else
                        {
                            eZDebug::writeError( "Bad LDAPUserGroupAttributeType '$LDAPUserGroupAttributeType'. It must be either 'name', 'id' or 'dn'.", __METHOD__ );
                            $user = false;
                            return $user;
                        }
                    }
                }

                // remove ' last_name' from first_name if cn is used for first name
                if ( $LDAPFirstNameIsCN && isset( $userData[ $LDAPFirstNameAttribute ] ) && isset( $userData[ $LDAPLastNameAttribute ] ) )
                {
                    $userData[ $LDAPFirstNameAttribute ][0] = str_replace( ' ' . $userData[ $LDAPLastNameAttribute ][0], '', $userData[ $LDAPFirstNameAttribute ][0] );
                }

                if ( isset( $userData[ $LDAPEmailAttribute ] ) )
                    $LDAPuserEmail = $userData[ $LDAPEmailAttribute ][0];
                else if( trim( $LDAPIni->variable( 'LDAPSettings', 'LDAPEmailEmptyAttributeSuffix' ) ) )
                    $LDAPuserEmail = $login . $LDAPIni->variable( 'LDAPSettings', 'LDAPEmailEmptyAttributeSuffix' );
                else
                    $LDAPuserEmail = false;


                $userAttributes = array( 'login'      => $login,
                                         'first_name' => isset( $userData[ $LDAPFirstNameAttribute ] ) ? $userData[ $LDAPFirstNameAttribute ][0] : false,
                                         'last_name'  => isset( $userData[ $LDAPLastNameAttribute ] ) ? $userData[ $LDAPLastNameAttribute ][0] : false,
                                         'email'      => $LDAPuserEmail );

                if ( $LDAPDebugTrace )
                {
                    $debugArray = array( 'stage' => '5/5: storing user',
                                         'userAttributes' => $userAttributes,
                                         'isUtf8Encoding' => $isUtf8Encoding,
                                         'defaultUserPlacement' => $defaultUserPlacement,
                                         'extraNodeAssignments' => $extraNodeAssignments
                    );
                    eZDebug::writeNotice( var_export( $debugArray, true ), __METHOD__ );
                }

                $oldUser = clone eZUser::currentUser();
                $existingUser = eZLDAPUser::publishUpdateUser( $extraNodeAssignments, $defaultUserPlacement, $userAttributes, $isUtf8Encoding );

                if ( is_object( $existingUser ) )
                {
                    eZUser::setCurrentlyLoggedInUser( $existingUser, $existingUser->attribute( 'contentobject_id' ) );
                }
                else
                {
                    eZUser::setCurrentlyLoggedInUser( $oldUser, $oldUser->attribute( 'contentobject_id' ) );
                }

                ldap_close( $ds );
                return $existingUser;
            }
            else
            {
                eZDebug::writeError( 'Cannot initialize connection for LDAP server', __METHOD__ );
                $user = false;
                return $user;
            }
        }
        else
        {
            // Increase number of failed login attempts.
            if ( isset( $userID ) )
                eZUser::setFailedLoginAttempts( $userID );

            eZDebug::writeWarning( 'User does not exist or LDAP is not enabled in php', __METHOD__ );
            $user = false;
            return $user;
        }
    }