Login user

@param   string
@param   string
@return  bool
165799
public function login($username_or_email = '', $password = '')
	{
		if ( ! ($this->user = $this->validate_user($username_or_email, $password)))
		{
			$this->user = \Config::get('simpleauth.guest_login', true) ? static::$guest_login : false;
			\Session::delete('username');
			\Session::delete('login_hash');
			return false;
		}

		// register so Auth::logout() can find us
		Auth::_register_verified($this);

		\Session::set('username', $this->user['username']);
		\Session::set('login_hash', $this->create_login_hash());
		\Session::instance()->rotate();
		return true;
	}
58946
public function login($username = '', $password = '', $remember = false)
    {
        $db = $this->getDb();
        $table = $this->getTables();
        list($userColumnName, $passColumnName) = $table['login'];
        $getTables = $table['select'];

        $getTables[] = $table['authentication']['column'];

        $db->where([
            [$userColumnName, $username],
            [$passColumnName, $password]
        ]);

        if ($db->exists()) {
            $login = $db->first();

            // we will find user ip address
            // and add it to login information
            $ip = Security::ip();


            $login['ip'] = $ip;
            $login = new LoginObject($login);

            $this->getSession()->set(static::USER_SESSION, $login);
            if ($remember) {
                $this->getCookie()->set(static::USER_SESSION, serialize($login));
            }

            $add = $db->insert([
                'ip' => $ip,
                'username' => $username
            ]);

            if ($add->isSuccess()) {
                return $login;
            }
        }

        return false;


    }
529111
public static function is_login(){
        $user = self::sessionGet('user');
        if (empty($user)) {
            return false;
        } else {
            return  self::sessionGet('user_sign') == self::data_auth_sign($user) ? $user : false;
        }
    }
114478
public static function login()
    {
        if (Cookie::existe(static::resource('cookie'))) {
            $token = Cookie::get(static::resource('cookie'));

            $result = Query::from(config('auth.table'))
                ->where('rememberToken', '=', $token)
                ->get();

            if (count($result) > 0) {
                static::$user = static::orm($result[0]);

                static::save_session();

                return static::$user;
            }

            return false;
        }

        return false;
    }
1346939
public function loginUser($user = null, $properties = array())
    {
        if($this->_login_user && $user)
        {
            //Get the user data
            if(!is_array($user))
            {
                if($user instanceof UserInterface) {
                    $user = $user->toArray();
                } else {
                    $user = $this->getObject('user.provider')->getUser($user)->toArray();
                }
            }

            //Set the user properties
            $properties = array_merge($properties, (array) $user);

            $this->getObject('user')->setProperties($properties);
            $this->getObject('user')->setAuthentic();

            return true;
        }

        return false;
    }
1276317
public function getUserByLogin(string $login)
    {
        $retval = null;

        if (strlen($login) > 0) {
            $nb_user = CNabuUser::findByLogin($this, $login);
            if ($nb_user instanceof CNabuUser && $nb_user->validateCustomer($this)) {
                $nb_user->setCustomer($this);
                $retval = $nb_user;
            }
        }

        return $retval;
    }
768055
public function login()
    {
        $success = false;
        if ($this->output && $this->input && $this->input->isInteractive()) {
            $method = $this->config()->getWithDefault('application.login_method', 'browser');
            if ($method === 'browser') {
                /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
                $questionHelper = $this->getService('question_helper');
                $urlService = $this->getService('url');
                if ($urlService->canOpenUrls()
                    && $questionHelper->confirm("Authentication is required.\nLog in via a browser?")) {
                    $this->stdErr->writeln('');
                    $exitCode = $this->runOtherCommand('auth:browser-login');
                    $this->stdErr->writeln('');
                    $success = $exitCode === 0;
                }
            } elseif ($method === 'password') {
                $exitCode = $this->runOtherCommand('auth:password-login');
                $this->stdErr->writeln('');
                $success = $exitCode === 0;
            }
        }
        if (!$success) {
            throw new LoginRequiredException();
        }
    }
762952
function login($username)
    {
        $args = func_get_args();
        if (!call_user_func_array(array(&$this, '_login'), $args)) {
            return false;
        }

        $this->window_size_server_to_client[self::CHANNEL] = $this->window_size;

        $packet = pack(
            'CNa*N3',
            NET_SSH2_MSG_CHANNEL_OPEN,
            strlen('session'),
            'session',
            self::CHANNEL,
            $this->window_size,
            0x4000
        );

        if (!$this->_send_binary_packet($packet)) {
            return false;
        }

        $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_OPEN;

        $response = $this->_get_channel_packet(self::CHANNEL, true);
        if ($response === false) {
            return false;
        }

        $packet = pack(
            'CNNa*CNa*',
            NET_SSH2_MSG_CHANNEL_REQUEST,
            $this->server_channels[self::CHANNEL],
            strlen('subsystem'),
            'subsystem',
            1,
            strlen('sftp'),
            'sftp'
        );
        if (!$this->_send_binary_packet($packet)) {
            return false;
        }

        $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;

        $response = $this->_get_channel_packet(self::CHANNEL, true);
        if ($response === false) {
            // from PuTTY's psftp.exe
            $command = "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n" .
                       "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n" .
                       "exec sftp-server";
            // we don't do $this->exec($command, false) because exec() operates on a different channel and plus the SSH_MSG_CHANNEL_OPEN that exec() does
            // is redundant
            $packet = pack(
                'CNNa*CNa*',
                NET_SSH2_MSG_CHANNEL_REQUEST,
                $this->server_channels[self::CHANNEL],
                strlen('exec'),
                'exec',
                1,
                strlen($command),
                $command
            );
            if (!$this->_send_binary_packet($packet)) {
                return false;
            }

            $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST;

            $response = $this->_get_channel_packet(self::CHANNEL, true);
            if ($response === false) {
                return false;
            }
        }

        $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_DATA;

        if (!$this->_send_sftp_packet(NET_SFTP_INIT, "\0\0\0\3")) {
            return false;
        }

        $response = $this->_get_sftp_packet();
        if ($this->packet_type != NET_SFTP_VERSION) {
            user_error('Expected SSH_FXP_VERSION');
            return false;
        }

        if (strlen($response) < 4) {
            return false;
        }
        extract(unpack('Nversion', $this->_string_shift($response, 4)));
        $this->version = $version;
        while (!empty($response)) {
            if (strlen($response) < 4) {
                return false;
            }
            extract(unpack('Nlength', $this->_string_shift($response, 4)));
            $key = $this->_string_shift($response, $length);
            if (strlen($response) < 4) {
                return false;
            }
            extract(unpack('Nlength', $this->_string_shift($response, 4)));
            $value = $this->_string_shift($response, $length);
            $this->extensions[$key] = $value;
        }

        /*
         SFTPv4+ defines a 'newline' extension.  SFTPv3 seems to have unofficial support for it via 'newline@vandyke.com',
         however, I'm not sure what 'newline@vandyke.com' is supposed to do (the fact that it's unofficial means that it's
         not in the official SFTPv3 specs) and 'newline@vandyke.com' / 'newline' are likely not drop-in substitutes for
         one another due to the fact that 'newline' comes with a SSH_FXF_TEXT bitmask whereas it seems unlikely that
         'newline@vandyke.com' would.
        */
        /*
        if (isset($this->extensions['newline@vandyke.com'])) {
            $this->extensions['newline'] = $this->extensions['newline@vandyke.com'];
            unset($this->extensions['newline@vandyke.com']);
        }
        */

        $this->request_id = 1;

        /*
         A Note on SFTPv4/5/6 support:
         <http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.1> states the following:

         "If the client wishes to interoperate with servers that support noncontiguous version
          numbers it SHOULD send '3'"

         Given that the server only sends its version number after the client has already done so, the above
         seems to be suggesting that v3 should be the default version.  This makes sense given that v3 is the
         most popular.

         <http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-5.5> states the following;

         "If the server did not send the "versions" extension, or the version-from-list was not included, the
          server MAY send a status response describing the failure, but MUST then close the channel without
          processing any further requests."

         So what do you do if you have a client whose initial SSH_FXP_INIT packet says it implements v3 and
         a server whose initial SSH_FXP_VERSION reply says it implements v4 and only v4?  If it only implements
         v4, the "versions" extension is likely not going to have been sent so version re-negotiation as discussed
         in draft-ietf-secsh-filexfer-13 would be quite impossible.  As such, what \phpseclib\Net\SFTP would do is close the
         channel and reopen it with a new and updated SSH_FXP_INIT packet.
        */
        switch ($this->version) {
            case 2:
            case 3:
                break;
            default:
                return false;
        }

        $this->pwd = $this->_realpath('.');

        $this->_update_stat_cache($this->pwd, array());

        return true;
    }
934005
public function login(string $userID): bool
    {
        $data = Internal\Server::call('login', ['userID' => $userID], true);
        if (isset($data['result'])) {
            return $data['result'] === 'ok';
        }
        return false;
    }
1121611
public function loginUser($user = null, $data = array())
    {
        if($this->_login_user)
        {
            $session  = $this->getObject('user')->getSession();
            $response = $this->getObject('response');

            //Start the session
            $session->start();

            //Set the messsages into the response
            $messages = $session->getContainer('message')->all();
            $response->setMessages($messages);

            if($user) {
                $result = parent::loginUser($user, $data);
            } else {
                $result = $this->getObject('user')->isAuthentic();
            }

            return $result;
        }

        return false;
    }
294278
public function authenticate($username, $password)
	{
		$this->debug->groupCollapsed(__METHOD__);
		$return = false;
		$users = $this->search(array(
			'username'	=> $username,
			'email'		=> $username,
		));
		if ($users && $this->verifyPassword($password, $users[0]['password'])) {
			$this->debug->info('login success');
			$this->log('login', $users[0]['userid']);
			$return = $users[0]['userid'];
		} else {
			$this->debug->warn('login failed');
			$userid = $users
				? $users[0]['userid']
				: null;
			$this->log('loginFail', $userid);
		}
		$this->debug->groupEnd();
		return $return;
	}
1338689
public function login(string $username, string $password)
    {
        $this->userInfo = $this->makeRequest('POST', 'login', compact('username', 'password'));

        if (!isset($this->userInfo['error']) && isset($this->userInfo['data']['id'])) {
            return true;
        }

        return false;
    }
657540
public function login($force=false) {
		if( !$force && static::isLogged() ) {
			static::throwException('alreadyLoggedin');
		}
		/**
		 * @var AbstractUser $USER
		 * @deprecated
		 */
		global $USER;
		$_SESSION['USER'] = $USER = $this;
		$this->login = $force ? self::LOGGED_FORCED : self::IS_LOGGED;
		if( !$force ) {
			static::logEvent('login');
		}
		static::logEvent('activity');
	}
264110
public function checkPassword(string $password): bool
    {
        $password_hash = DB::table('user')
            ->where('user_id', '=', $this->id())
            ->value('password');

        if ($password_hash !== null && password_verify($password, $password_hash)) {
            if (password_needs_rehash($password_hash, PASSWORD_DEFAULT)) {
                $this->setPassword($password);
            }

            return true;
        }

        return false;
    }
982205
function user_login($username, $password) {
        global $CFG, $DB, $USER;
        if (!$user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
            return false;
        }
        if (!validate_internal_user_password($user, $password)) {
            return false;
        }
        if ($password === 'changeme') {
            // force the change - this is deprecated and it makes sense only for manual auth,
            // because most other plugins can not change password easily or
            // passwords are always specified by users
            set_user_preference('auth_forcepasswordchange', true, $user->id);
        }
        return true;
    }
483534
public static function login(string $email, string $password, int $autologin = 1, int $admin, string $userIp) : Users
    {
        //trim email
        $email = ltrim(trim($email));
        $password = ltrim(trim($password));

        //load config
        $config = new stdClass();
        $config->login_reset_time = getenv('AUTH_MAX_AUTOLOGIN_TIME');
        $config->max_login_attempts = getenv('AUTH_MAX_AUTOLOGIN_ATTEMPS');

        //if its a email lets by it by email, if not by displayname
        $user = self::getByEmail($email);

        //first we find the user
        if ($user) {
            // If the last login is more than x minutes ago, then reset the login tries/time
            if ($user->user_last_login_try && $config->login_reset_time && $user->user_last_login_try < (time() - ($config->login_reset_time * 60))) {
                $user->user_login_tries = 0; //turn back to 0 attems, succes
                $user->user_last_login_try = 0;
                $user->update();
            }

            // Check to see if user is allowed to login again... if his tries are exceeded
            if ($user->user_last_login_try && $config->login_reset_time && $config->max_login_attempts && $user->user_last_login_try >= (time() - ($config->login_reset_time * 60)) && $user->user_login_tries >= $config->max_login_attempts) {
                throw new Exception(sprintf(_('You have exhausted all login attempts.'), $config->max_login_attempts));
            }

            //will only work with php.5.5 new password api
            if (password_verify($password, trim($user->password)) && $user->user_active) {
                //rehas passw if needed
                $user->passwordNeedRehash($password);

                $autologin = (isset($autologin)) ? true : 0;

                $admin = (isset($admin)) ? 1 : 0;

                // Reset login tries
                $user->lastvisit = date('Y-m-d H:i:s');
                $user->user_login_tries = 0;
                $user->user_last_login_try = 0;
                $user->update();

                return $user;
            } // Only store a failed login attempt for an active user - inactive users can't login even with a correct password
            elseif ($user->user_active) {
                // Save login tries and last login
                if ($user->getId() != self::ANONYMOUS) {
                    $user->user_login_tries += 1;
                    $user->user_last_login_try = time();
                    $user->update();
                }

                throw new Exception(_('Invalid Username or Password.'));
            } elseif ($user->isBanned()) {
                throw new Exception(_('User has not been banned, please check your email for the activation link.'));
            } else {
                throw new Exception(_('User has not been activated, please check your email for the activation link.'));
            }
        } else {
            throw new Exception(_('Invalid Username or Password.'));
        }
    }
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;
        }
    }