/*!
@method      generateHeader
@public
@param       str     $login
@param       str     $key
@param       str     $sessid
@return      []
515991
public function generateHeader($login, $key, $sessid=null)
    {
        $token = $this->generateToken($login, $key, $sessid);
        $ndate = $this->formatDate($token->getDate());
        return array(
            $this->config['header']['auth'] .': ' . $token->getType() . ' ' . $ndate . $token->getValue() . $token->getNoise(),
            $this->config['header']['ident'].': ' . $token->getIdent()
        );
    }
591986
protected function prepareHeaders($server)
    {
        $output = [];

        if (!is_array($server)) {
            return $output;
        }

        foreach ($server as $key => $value) {
            if (is_string($key) && strlen($key) > 5 && strpos($key, 'HTTP_') !== false) {
                $output[substr($key, 5)] = $value;
            }
        }

        return $output;
    }
133496
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 );

        $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();
        $textFileIni = eZINI::instance( 'textfile.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 ( $textFileIni->variable( 'TextFileSettings', 'TextFileEnabled' ) == "true" )
        {
            $fileName =  $textFileIni->variable( 'TextFileSettings', 'FileName' );
            $filePath =  $textFileIni->variable( 'TextFileSettings', 'FilePath' );
            $defaultUserPlacement = $ini->variable( "UserSettings", "DefaultUserPlacement" );
            $separator = $textFileIni->variable( "TextFileSettings", "FileFieldSeparator" );
            $loginColumnNr = $textFileIni->variable( "TextFileSettings", "LoginAttribute" );
            $passwordColumnNr = $textFileIni->variable( "TextFileSettings", "PasswordAttribute" );
            $emailColumnNr = $textFileIni->variable( "TextFileSettings", "EmailAttribute" );
            $lastNameColumnNr = $textFileIni->variable( "TextFileSettings", "LastNameAttribute" );
            $firstNameColumnNr = $textFileIni->variable( "TextFileSettings", "FirstNameAttribute" );
            if ( $textFileIni->hasVariable( 'TextFileSettings', 'DefaultUserGroupType' ) )
            {
                $UserGroupType =  $textFileIni->variable( 'TextFileSettings', 'DefaultUserGroupType' );
                $UserGroup = $textFileIni->variable( 'TextFileSettings', 'DefaultUserGroup' );
            }

            if ( $UserGroupType != null )
            {
                if ( $UserGroupType == "name" )
                {
                    $groupName = $UserGroup;
                    $groupQuery = "SELECT ezcontentobject_tree.node_id
                                       FROM ezcontentobject, ezcontentobject_tree
                                       WHERE ezcontentobject.name='$groupName'
                                       AND ezcontentobject.id=ezcontentobject_tree.contentobject_id";
                    $groupObject = $db->arrayQuery( $groupQuery );

                    if ( count( $groupObject ) > 0  )
                    {
                        $defaultUserPlacement = $groupObject[0]['node_id'];
                    }
                }
                else if ( $UserGroupType == "id" )
                {
                    $groupID = $UserGroup;
                    $groupQuery = "SELECT ezcontentobject_tree.node_id
                                           FROM ezcontentobject, ezcontentobject_tree
                                           WHERE ezcontentobject.id='$groupID'
                                           AND ezcontentobject.id=ezcontentobject_tree.contentobject_id";
                    $groupObject = $db->arrayQuery( $groupQuery );

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

            if ( $filePath != "root" and $filePath != null  )
                $fileName = $filePath . "/" . $fileName;

            if ( file_exists( $fileName ) )
                $handle = fopen ( $fileName, "r");
            else
            {
                // Increase number of failed login attempts.
                if ( isset( $userID ) )
                    eZUser::setFailedLoginAttempts( $userID );

                return false;
            }

            while ( !feof( $handle ) )
            {
                $line = trim( fgets( $handle, 4096 ) );

                if ( $line === '' )
                    continue;

                if ( $separator == "tab" )
                    $userArray = explode( "\t", $line );
                else
                    $userArray = explode( $separator, $line );

                $uid = $userArray[$loginColumnNr-1];
                $email = $userArray[$emailColumnNr-1];
                $pass = $userArray[$passwordColumnNr-1];
                $firstName = $userArray[ $firstNameColumnNr-1];
                $lastName = $userArray[$lastNameColumnNr-1];
                if ( $login == $uid )
                {
                    if ( trim( $pass ) == $password )
                    {
                        $createNewUser = true;
                        $existUser = eZUser::fetchByName( $login );
                        if ( $existUser != null )
                        {
                            $createNewUser = false;
                        }
                        if ( $createNewUser )
                        {
                            $userClassID = $ini->variable( "UserSettings", "UserClassID" );
                            $userCreatorID = $ini->variable( "UserSettings", "UserCreatorID" );
                            $defaultSectionID = $ini->variable( "UserSettings", "DefaultSectionID" );

                            $remoteID = "TextFile_" . $login;

                            $db->begin();

                            // The content object may already exist if this process has failed once before, before the eZUser object was created.
                            // Therefore we try to fetch the eZContentObject before instantiating it.
                            $contentObject = eZContentObject::fetchByRemoteID( $remoteID );
                            if ( !is_object( $contentObject ) )
                            {
                                $class = eZContentClass::fetch( $userClassID );
                                $contentObject = $class->instantiate( $userCreatorID, $defaultSectionID );
                            }

                            $contentObject->setAttribute( 'remote_id', $remoteID );
                            $contentObject->store();

                            $contentObjectID = $contentObject->attribute( 'id' );
                            $userID = $contentObjectID;
                            $nodeAssignment = eZNodeAssignment::create( array( 'contentobject_id' => $contentObjectID,
                                                                               'contentobject_version' => 1,
                                                                               'parent_node' => $defaultUserPlacement,
                                                                               'is_main' => 1 ) );
                            $nodeAssignment->store();
                            $version = $contentObject->version( 1 );
                            $version->setAttribute( 'modified', time() );
                            $version->setAttribute( 'status', eZContentObjectVersion::STATUS_DRAFT );
                            $version->store();

                            $contentObjectID = $contentObject->attribute( 'id' );
                            $contentObjectAttributes = $version->contentObjectAttributes();

                            $contentObjectAttributes[0]->setAttribute( 'data_text', $firstName );
                            $contentObjectAttributes[0]->store();

                            $contentObjectAttributes[1]->setAttribute( 'data_text', $lastName );
                            $contentObjectAttributes[1]->store();

                            $user = eZUser::create( $userID );
                            $user->setAttribute( 'login', $login );
                            $user->setAttribute( 'email', $email );
                            $user->setAttribute( 'password_hash', "" );
                            $user->setAttribute( 'password_hash_type', self::PASSWORD_HASH_EMPTY );
                            $user->store();

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

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

                            $operationResult = eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $contentObjectID,
                                                                                                         'version' => 1 ) );

                            $db->commit();

                            return $user;
                        }
                        else
                        {
                            $db->begin();

                            // Update user information
                            $userID = $existUser->attribute( 'contentobject_id' );
                            $contentObject = eZContentObject::fetch( $userID );

                            $parentNodeID = $contentObject->attribute( 'main_parent_node_id' );
                            $currentVersion = $contentObject->attribute( 'current_version' );

                            $version = $contentObject->attribute( 'current' );
                            $contentObjectAttributes = $version->contentObjectAttributes();

                            $contentObjectAttributes[0]->setAttribute( 'data_text', $firstName );
                            $contentObjectAttributes[0]->store();

                            $contentObjectAttributes[1]->setAttribute( 'data_text', $lastName );
                            $contentObjectAttributes[1]->store();

                            $existUser = eZUser::fetch(  $userID );
                            $existUser->setAttribute('email', $email );
                            $existUser->setAttribute('password_hash', "" );
                            $existUser->setAttribute('password_hash_type', self::PASSWORD_HASH_EMPTY );
                            $existUser->store();

                            if ( $defaultUserPlacement != $parentNodeID )
                            {
                                $newVersion = $contentObject->createNewVersion();
                                $newVersion->assignToNode( $defaultUserPlacement, 1 );
                                $newVersion->removeAssignment( $parentNodeID );
                                $newVersionNr = $newVersion->attribute( 'version' );
                                $operationResult = eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $userID,
                                                                                                             'version' => $newVersionNr ) );
                            }

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

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

                            $db->commit();

                            return $existUser;
                        }
                    }
                    else
                    {
                        // Increase number of failed login attempts.
                        if ( isset( $userID ) )
                            eZUser::setFailedLoginAttempts( $userID );

                        return false;
                    }
                }
            }
            fclose( $handle );
        }
        // Increase number of failed login attempts.
        if ( isset( $userID ) )
            eZUser::setFailedLoginAttempts( $userID );

        return false;
    }
266019
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::_xor($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);
        }
    }
375257
public function getUserAuthenticationConfiguration($email, $password) 
    {
        return [
        'grant_type'    => 'password',
        'client_id'     => $this->getClientId(),
        'client_secret' => $this->getClientSecret(),
        'username'      => $email,
        'password'      => $password,
        'scope'         => $this->getScopes(),
        ];
    }
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)
        );
    }
259068
public function getCampaignsByLogin($login)
    {
        $resource = 'campaigns/by_login/' . $login . '.json';

        $response = $this->sendRequest('GET', $this->getServiceUrl($resource));

        $decodedResponseBody = $this->getDecodedBody($response->getBody());

        $getCampaignsResponse = new Models\GetCampaignsResponse($decodedResponseBody);
        return $getCampaignsResponse->getCampaigns();
    }
90356
static function start( $sessid = null ) {
		// switch to named session
		$oldname = session_name( PLUG_SESSION_NAME );
		// session could have been started already
		if( session_id() ){
			if( $oldname === PLUG_SESSION_NAME ){
				trigger_error( "Session '$oldname' already started", E_USER_NOTICE );
			}
			// or another system could have started a session under a different name
			else if( ! session_destroy() ){
				trigger_error( "Failed to destroy session '$oldname'", E_USER_WARNING );
				return false;
			}
			// force session id if passed
			if( $sessid ){
				session_id( $sessid );
			}
			if( ! session_start() ){
				trigger_error( "Failed to start session after destroying previous session '$oldname'", E_USER_WARNING );
				return false;
			}
		}
		// else ok to start session for the first time
		// when session starts __wakeup will be called if resuming
		else {
			// force session id if passed
			if( $sessid ){
				session_id( $sessid );
			}
			if( ! session_start() ){
				trigger_error( 'Failed to start session', E_USER_WARNING );
				return false;
			}
		}
		// create new instance of self if new session
		if( ! isset(self::$Session) ){
			new PLUGSession();
		}
		// manually check timeout now that session is intilaized
		// Session must expire now regardless of cookie lifetime.
		else if( PLUG_SESSION_TIMEOUT && self::$Session->t_idle >= (PLUG_SESSION_TIMEOUT * 60) ){
			$id = session_id();
			self::destroy();
			self::$Session->expired_id = $id;
		}
		// else session resumed
		else {
			self::header('resume-after-'.self::$Session->t_idle.'-seconds');
		}
		return true;
	}
1012127
private function getHeaders(PushMessage $message) : array
    {
        return [
            'Content-Type' => 'application/json',
            'Content-Length' => $message->getContentLength(),
            'Encryption' => 'keyid=p256dh;salt='.$message->getSalt(),
            'Crypto-Key' => 'keyid=p256dh;dh='.$message->getCryptoKey(),
            'Content-Encoding' => 'aesgcm',
            'TTL' => $message->getTTL(),
        ];
    }
776821
protected function generatePluginHeaders(string $name)
    {
        $description = $this->ask('Description:', '');
        $author = $this->ask('Author:', 'Themosis');
        $textdomain = $this->ask('Text domain:', trim($name, '\/-_'));
        $variable = strtoupper($this->ask('Domain variable:', 'PLUGIN_TD'));
        $prefix = $this->ask('Plugin prefix:', str_replace(['-', ' '], '_', $name));
        $namespace = $this->ask('PHP Namespace:', 'Tld\Domain\Plugin');

        return [
            'name' => ucwords(str_replace(['-', '_'], ' ', $name)),
            'description' => $description,
            'author' => $author,
            'text_domain' => $textdomain,
            'domain_var' => $variable,
            'plugin_prefix' => $prefix,
            'plugin_namespace' => $namespace,
            'plugin_id' => $name
        ];
    }
1039114
public function authenticate($login, $password)
    {
        $defaultHttpHeaders                       = $this->defaultHttpHeaders;
        $this->defaultHttpHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
        $this->setPostFields(http_build_query(['username' => $login, 'password' => $password]));
        $result                                   = $this->performRequest('authenticate',
            'POST', 'xml');
        $this->defaultHttpHeaders                 = $defaultHttpHeaders;
        if (!empty($result['message'])) {
            $this->addStatusMessage($result['message'],
                $result['success'] == 'true' ? 'success' : 'warning' );
        }
        return array_key_exists('success', $result) && $result['success'] == 'true';
    }
693924
protected function getHeadersFromServerArr(array $server) : array
    {
        $headers = [];
        $specialKeys = [
            'CONTENT_TYPE'   => 'Content-Type',
            'CONTENT_LENGTH' => 'Content-Length',
        ];
        foreach ($server as $key => $value) {
            if (substr($key, 0, 5) === 'HTTP_') {
                $header = str_replace(' ', '-',
                    ucwords(str_replace('_', ' ', strtolower(substr($key, 5))))
                );
                $headers[$header] = $value;
            } elseif (isset($specialKeys[$key])) {
                $headers[$specialKeys[$key]] = $value;
            }
        }
        
        if (!isset($headers['Authorization']) && isset($server['REDIRECT_HTTP_AUTHORIZATION'])) {
            $headers['Authorization'] = $server['REDIRECT_HTTP_AUTHORIZATION'];
        }
        
        if (isset($server['PHP_AUTH_USER'])) {
            $headers['PHP_AUTH_USER'] = $server['PHP_AUTH_USER'];
            $headers['PHP_AUTH_PW'] = $server['PHP_AUTH_PW'] ?? '';
        }
        
        return $headers;
    }
109031
private function orderedEntry(array $entry, array $headerKeys)
    {
        $result = [];

        foreach ($headerKeys as $key) {
            $result[$key] = $entry[$key];
        }

        return $result;
    }
897296
protected function buildGuzzleOptions($headers, $timeout)
    {
        $finalHeaders = [];

        foreach ($headers as $header) {
            list($name, $value) = explode(':', $header, 2);
            $finalHeaders[$name] = trim($value);
        }

        $options = ['headers' => $finalHeaders, 'timeout' => $timeout];
        if (!empty($this->username) && !empty($this->password)) {
            $options['auth'] = [$this->username, $this->password];
        }

        if ($this->extensionConfiguration->getIsSelfSignedCertificatesEnabled()) {
            $options['verify'] = false;
        }

        return $options;
    }
324024
public function generateHeaders()
    {
        // set our headers first.
        if ( $this->from !== null )
        {
            $this->setHeader( "From", ezcMailTools::composeEmailAddress( $this->from ) );
        }

        if ( $this->to !== null )
        {
            $this->setHeader( "To", ezcMailTools::composeEmailAddresses( $this->to ) );
        }
        if ( count( $this->cc ) )
        {
            $this->setHeader( "Cc", ezcMailTools::composeEmailAddresses( $this->cc ) );
        }
        if ( count( $this->bcc ) && $this->options->stripBccHeader === false )
        {
            $this->setHeader( "Bcc", ezcMailTools::composeEmailAddresses( $this->bcc ) );
        }

        $this->setHeader( 'Subject', $this->subject, $this->subjectCharset );

        $this->setHeader( 'MIME-Version', '1.0' );
        $this->setHeader( 'User-Agent', 'eZ Components' );
        $this->setHeader( 'Date', date( 'r' ) );
        $idhost = $this->from != null && $this->from->email != '' ? $this->from->email : 'localhost';
        if ( is_null( $this->messageId ) )
        {
            $this->setHeader( 'Message-Id', '<' . ezcMailTools::generateMessageId( $idhost ) . '>' );
        }
        else
        {
            $this->setHeader( 'Message-Id', $this->messageID );
        }

        // if we have a body part, include the headers of the body
        if ( is_subclass_of( $this->body, "ezcMailPart" ) )
        {
            return parent::generateHeaders() . $this->body->generateHeaders();
        }
        return parent::generateHeaders();
    }
1154066
protected static function _shuffle($login)
    {
        $tmp = array();

        for ($i = 0; $i < strlen($login); $i++) {
            $tmp[] = $login[$i];
        }

        shuffle($tmp);

        return implode($tmp, '');
    }
26401
protected function createTableHeader()
    {
        return [
            $this->trans('commands.database.log.common.messages.event-id'),
            $this->trans('commands.database.log.common.messages.type'),
            $this->trans('commands.database.log.common.messages.date'),
            $this->trans('commands.database.log.common.messages.message'),
            $this->trans('commands.database.log.common.messages.user'),
            $this->trans('commands.database.log.common.messages.severity'),
        ];
    }