Setup ftp connection

@throws \RuntimeException
556082
private function login()
    {
        if (empty($this->host)) {
            throw new RuntimeException('no host to connect to');
        }

        $old  = error_reporting(0);
        $link = $this->isSecure
              ? ftp_ssl_connect($this->host, $this->port)
              : ftp_connect($this->host, $this->port);

        if (!$link) {
            error_reporting($old);
            throw new RuntimeException(sprintf('unable to connect to ftp server %s', $this->host));
        }

        $this->connection = $link;
        if (!ftp_login($this->connection, $this->user, $this->password)) {
            error_reporting($old);
            throw new RuntimeException(
                sprintf('authentication failed for %s@%s', $this->user, $this->host)
            );
        }
        // set passive mode if needed
        $this->pasv($this->passive);
        error_reporting($old);
    }
853411
public function _connect()
    {
        $siteINI = eZINI::instance( 'site.ini' );
        // DB Connection setup
        // This part is not actually required since _connect will only be called
        // once, but it is useful to run the unit tests. So be it.
        // @todo refactor this using eZINI::setVariable in unit tests
        if ( parent::$dbparams === null )
        {
            $fileINI = eZINI::instance( 'file.ini' );

            parent::$dbparams = array();
            parent::$dbparams['host']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBHost' );
            $dbPort = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPort' );
            parent::$dbparams['port']       = $dbPort !== '' ? $dbPort : null;
            parent::$dbparams['socket']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBSocket' );
            parent::$dbparams['dbname']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBName' );
            parent::$dbparams['user']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBUser' );
            parent::$dbparams['pass']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPassword' );

            parent::$dbparams['max_connect_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBConnectRetries' );
            parent::$dbparams['max_execute_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBExecuteRetries' );

            parent::$dbparams['sql_output'] = $siteINI->variable( "DatabaseSettings", "SQLOutput" ) == "enabled";

            parent::$dbparams['cache_generation_timeout'] = $siteINI->variable( "ContentSettings", "CacheGenerationTimeout" );
        }

        $serverString = parent::$dbparams['host'];
        if ( parent::$dbparams['socket'] )
            $serverString .= ':' . parent::$dbparams['socket'];
        elseif ( parent::$dbparams['port'] )
            $serverString .= ':' . parent::$dbparams['port'];

        $maxTries = parent::$dbparams['max_connect_tries'];
        $tries = 0;
        eZPerfLogger::accumulatorStart( 'mysql_cluster_connect', 'MySQL Cluster', 'Cluster database connection' );
        while ( $tries < $maxTries )
        {
            if ( $this->db = mysqli_connect( parent::$dbparams['host'], parent::$dbparams['user'], parent::$dbparams['pass'], parent::$dbparams['dbname'], parent::$dbparams['port'] ) )
                break;
            ++$tries;
        }
        eZPerfLogger::accumulatorStop( 'mysql_cluster_connect' );
        if ( !$this->db )
        {
            throw new eZClusterHandlerDBNoConnectionException(
                $serverString,
                self::$dbparams['user'],
                self::$dbparams['pass'],
                'Error ' . mysqli_connect_errno() . ': ' . mysqli_connect_error()
            );
        }

        /*if ( !mysql_select_db( parent::$dbparams['dbname'], $this->db ) )
           throw new eZClusterHandlerDBNoDatabaseException( parent::$dbparams['dbname'] );*/

        // DFS setup
        if ( $this->dfsbackend === null )
        {
            $this->dfsbackend = new eZDFSFileHandlerTracing47DFSBackend();
        }

        $charset = trim( $siteINI->variable( 'DatabaseSettings', 'Charset' ) );
        if ( $charset === '' )
        {
            $charset = eZTextCodec::internalCharset();
        }

        if ( $charset )
        {
            if ( !mysqli_set_charset( $this->db, eZMySQLCharset::mapTo( $charset ) ) )
            {
                $this->_fail( "Failed to set Database charset to $charset." );
            }
        }
    }
408360
private function setup()
    {
        $this->host = 'ws.audioscrobbler.com';
        $this->port = 80;
        $this->connected = 0;

        $this->socket = new Socket($this->host, $this->port);
        if (!$this->socket->error_number && !$this->socket->error_string) {
            $this->connected = 1;
            return true;
        } else {
            throw new ConnectionException($this->socket->error_string);
        }
    }
1002229
public function connect()
    {
        if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING &&
             $this->_status !== self::STATUS_CLOSED) {
            return;
        }
        $this->_status           = self::STATUS_CONNECTING;
        $this->_connectStartTime = microtime(true);
        // Open socket connection asynchronously.
        if ($this->_contextOption) {
            $context = stream_context_create($this->_contextOption);
            $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
                STREAM_CLIENT_ASYNC_CONNECT, $context);
        } else {
            $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
                STREAM_CLIENT_ASYNC_CONNECT);
        }
        // If failed attempt to emit onError callback.
        if (!$this->_socket) {
            $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr);
            if ($this->_status === self::STATUS_CLOSING) {
                $this->destroy();
            }
            if ($this->_status === self::STATUS_CLOSED) {
                $this->onConnect = null;
            }
            return;
        }
        // Add socket to global event loop waiting connection is successfully established or faild. 
        Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
        // For windows.
        if(DIRECTORY_SEPARATOR === '\\') {
            Worker::$globalEvent->add($this->_socket, EventInterface::EV_EXCEPT, array($this, 'checkConnection'));
        }
    }
265283
protected function doConnect()
    {
        $host = $this->getParam('host');
        $port = $this->getParam('port');
        $timeout = $this->getParam('timeout');

        return $this->retry(function () use ($host, $port, $timeout) {
            $res = @ftp_connect($host, $port, $timeout);

            if (false === $res) {
                throw new \RuntimeException("Couldn't connect to: $host:$port");
            }

            return $res;
        });
    }
613720
public function connect()
  {
    if($this->stream !== null) return;

    $host = strval($this->config["host"]);
    $port = strval($this->config["port"]);

    $address = "udp://" . (strstr($host, ":") !== FALSE ? "[" . $host . "]" : $host) . ":" . $port;
    $timeout = (int) $this->config["timeout"];

    $this->stream = @stream_socket_client($address, $errno, $errstr, $timeout);

    if($this->stream === FALSE)
    {
      throw new Exception(Str::factory($errstr)->toUtf8()->toString(), $errno);
    }

    @stream_set_timeout($this->stream, $timeout);
    @stream_set_blocking($this->stream, $this->config["blocking"] ? 1 : 0);
  }
963799
public function run()
    {
        if(version_compare(SWOOLE_VERSION, '4.1', '>='))
        {
            \Swoole\Runtime::enableCoroutine(true);
        }
        if(file_exists($this->socketFile))
        {
            unlink($this->socketFile);
        }
        go(function(){
            $this->socket = stream_socket_server('unix://' . $this->socketFile, $errno, $errstr);
            if(false === $this->socket)
            {
                throw new \RuntimeException(sprintf('Create unix socket server failed, errno: %s, errstr: %s', $errno, $errstr));
            }
            while(true)
            {
                $conn = stream_socket_accept($this->socket, 0);
                if(false === $conn)
                {
                    continue;
                }
                go(function() use($conn){
                    $this->parseConn($conn);
                });
            }
        });
    }
629382
protected function connectSftp()
    {
        if ( ! $this->connected) return false;

        $this->ftpConnection = ssh2_sftp($this->connection);

        return true;
    }
867946
public function connect()
	{
		if ($this->connection)
		{
			return;
		}

		// Build the connection configuration array.
		$config = array(
			'Database' => $this->options['database'],
			'uid' => $this->options['user'],
			'pwd' => $this->options['password'],
			'CharacterSet' => 'UTF-8',
			'ReturnDatesAsStrings' => true);

		// Make sure the SQLSRV extension for PHP is installed and enabled.
		if (!static::isSupported())
		{
			throw new \RuntimeException('PHP extension sqlsrv_connect is not available.');
		}

		// Attempt to connect to the server.
		if (!($this->connection = @ sqlsrv_connect($this->options['host'], $config)))
		{
			throw new \RuntimeException('Database sqlsrv_connect failed');
		}

		// Make sure that DB warnings are not returned as errors.
		sqlsrv_configure('WarningsReturnAsErrors', 0);

		// If auto-select is enabled select the given database.
		if ($this->options['select'] && !empty($this->options['database']))
		{
			$this->select($this->options['database']);
		}
	}
770946
private function _connect()
    {
        if (empty($this->_config))
            throw new \Exception('Empty connection settings provided'); 
        
        $port = $this->_config->getPort();
        $port = !empty($port) ? $port : 3306;
        $dsn = $this->_config->getType().':host='.$this->_config->getHost().';port='.$port.';dbname='.$this->_config->getName();
        // Create a PDO Instance for this user + database combination
        try {
            $this->_conn = new \PDO($dsn, $this->_config->getUser(), $this->_config->getPassword());
        } catch(\PDOException $pe) {
            throw new \RuntimeException("Cannot connect to DB '".$this->_config->getName().
                "' with user '".$this->_config->getUser()."'".PHP_EOL."Message: ".$pe->getMessage());
        }

        $this->_conn->setAttribute(\PDO::ATTR_PERSISTENT, false);
        $this->_conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->_conn->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'UTF8'");
        $this->_conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
        $this->_conn->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_TO_STRING);
        $this->_conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
    }
22405
public function connect()
    {
        if ($this->connection) {
            $this->disconnect();
        }

        $hasProtocol = strpos($this->_config['host'], '://') !== false;
        if ($hasProtocol) {
            list($this->_config['protocol'], $this->_config['host']) = explode('://', $this->_config['host']);
        }
        $scheme = null;
        if (!empty($this->_config['protocol'])) {
            $scheme = $this->_config['protocol'] . '://';
        }

        $this->_setSslContext($this->_config['host']);
        if (!empty($this->_config['context'])) {
            $context = stream_context_create($this->_config['context']);
        } else {
            $context = stream_context_create();
        }

        $connectAs = STREAM_CLIENT_CONNECT;
        if ($this->_config['persistent']) {
            $connectAs |= STREAM_CLIENT_PERSISTENT;
        }

        set_error_handler([$this, '_connectionErrorHandler']);
        $this->connection = stream_socket_client(
            $scheme . $this->_config['host'] . ':' . $this->_config['port'],
            $errNum,
            $errStr,
            $this->_config['timeout'],
            $connectAs,
            $context
        );
        restore_error_handler();

        if (!empty($errNum) || !empty($errStr)) {
            $this->setLastError($errNum, $errStr);
            throw new SocketException($errStr, $errNum);
        }

        if (!$this->connection && $this->_connectionErrors) {
            $message = implode("\n", $this->_connectionErrors);
            throw new SocketException($message, E_WARNING);
        }

        $this->connected = is_resource($this->connection);
        if ($this->connected) {
            stream_set_timeout($this->connection, $this->_config['timeout']);
        }

        return $this->connected;
    }
879153
protected function getFtpConnection()
    {
        if (is_null($this->ftpConnection)) {
            $host = $this->connection['host'];
            $user = $this->connection['user'];
            $pass = $this->connection['pass'];

            $this->ftpConnection = $this->connect($host, $user, $pass);

            // set timeout
            ftp_set_option($this->ftpConnection, FTP_TIMEOUT_SEC, $this->connection['timeout']);

            // set passive mode if it's defined
            if (null !== $pasv = $this->getPasv()) {
                ftp_pasv($this->ftpConnection, $pasv);
            }
        }

        return $this->ftpConnection;
    }
10898
protected function setupFile() {
		$this->_file->setNamespace($this->getNames()->namespace_entity);
	
		$this->_file->setUse('Zend\Db\RowGateway\RowGatewayInterface');
		$this->_file->setUse("{$this->getNames()->namespace_model}\\{$this->getNames()->modelName}");
	}
743986
public function connect()
    {
        $streamContext = stream_context_create(array(
            $this->getTransport() => $this->getContextOptions()
        ));

        $streamResource = stream_socket_client(
            $this->getAddress(),
            $errorCode,
            $errorMessage,
            $this->getSocketTimeout(),
            $this->getConnectionFlags(),
            $streamContext
        );

        if (!$streamResource) {
            throw new \RuntimeException(sprintf(
                'Unable to connect on socket. Error [%d]: %s',
                $errorCode,
                $errorMessage
            ));
        }

        stream_set_blocking($streamResource, $this->isBlockingMode());

        $this->setStreamResource($streamResource);

        return $this;
    }
941008
protected function setConnectionPassiveMode()
	{
		if (!ftp_pasv($this->getConnection(), $this->passive))
		{
			throw new RuntimeException(sprintf('Could not set passive mode for connection: %s::%s', $this->getHost(), $this->getPort()));
		}
	}
1358985
private function connect() {
        $connection = fsockopen('tcp://'.$this->options['host'],
                                         $this->options['port'],
                                         $errorCode,
                                         $errorMsg,
                                         $this->options['timeout']);
        // TODO: connect() might hang without producing an error if the connection fails
        if (!$connection) throw new RuntimeException('Could not open socket: '.$errorMsg.' (error '.$errorCode.')');

        $data = stream_get_meta_data($connection);
        if ($data['timed_out']) throw new InfrastructureException('Timeout on socket connection');

        socket_set_timeout($connection, $this->options['timeout']);
        $this->connection = $connection;

        // init connection
        $this->readResponse();                          // read greeting
        $this->writeData('EHLO '.$this->hostName);      // extended "Hello" first
        $response = $this->readResponse();

        $this->parseResponse($response);
        if ($this->responseStatus != 250) {
            $this->writeData('HELO '.$this->hostName);  // regular "Hello" if the extended one fails
            $response = $this->readResponse();

            $this->parseResponse($response);
            if ($this->responseStatus != 250)
                throw new RuntimeException('HELO command not accepted: '.$this->responseStatus.' '.$this->response);
        }
    }
519129
public function connect() {
        if (!function_exists('\mysql_connect')) throw new RuntimeException('Undefined function mysql_connect(), mysql extension is not available');

        $host = $this->host; if ($this->port) $host .= ':'.$this->port;
        $user = $this->username;
        $pass = $this->password;

        // connect
        try {                                                                      // flags: CLIENT_FOUND_ROWS = 2
            $php_errormsg = '';
            $this->hConnection = mysql_connect($host, $user, $pass, $newLink=true/*, $flags=2*/);
            !$this->hConnection && trigger_error($php_errormsg, E_USER_ERROR);
        }
        catch (\Exception $ex) {
            if (!$ex instanceof IRosasurferException)
                $ex = new DatabaseException($ex->getMessage(), $ex->getCode(), $ex);
            throw $ex->addMessage('Can not connect to MySQL server on "'.$host.'"');
        }

        $this->setConnectionOptions();
        $this->selectDatabase();
        return $this;
    }