Tells if this command blocks while waiting for a response, to avoid
being affected by connection timeouts.

@return bool If true, this command blocks
172467
public function isBlocking()
    {
        $arguments = $this->getArguments();
        $options = end($arguments);
        if (is_array($options) && !empty($options['nohang'])) {
            return false;
        }
        return true;
    }
1348159
public function isLocked()
    {
        $result = false;
        if(!$this->isNew())
        {
            if(isset($this->locked_on) && isset($this->locked_by))
            {
                $locked  = strtotime($this->locked_on);
                $current = strtotime(gmdate('Y-m-d H:i:s'));

                //Check if the lock has gone stale
                if($current - $locked < $this->_lifetime)
                {
                    $userid = $this->getObject('user')->getId();
                    if($this->locked_by != 0 && $this->locked_by != $userid) {
                        $result= true;
                    }
                }
            }
        }

        return $result;
    }
872966
public function checkIfReady()
    {
        if (!$this->attrs->paramsDone || !$this->attrs->inputDone) {
            return false;
        }
        if (isset($this->appInstance->passphrase)) {
            if (!isset($this->attrs->server['PASSPHRASE'])
                || ($this->appInstance->passphrase !== $this->attrs->server['PASSPHRASE'])
            ) {
                $this->finish();
            }

            return false;
        }

        if ($this->attrs->input->isFrozen()) {
            return false;
        }

        if ($this->sleepTime === 0) {
            $this->wakeup();
        }

        return true;
    }
2209
protected function allSlavesReady()
    {
        if ($this->status === self::STATE_STARTING || $this->status === self::STATE_EMERGENCY) {
            $readySlaves = $this->slaves->getByStatus(Slave::READY);
            $busySlaves = $this->slaves->getByStatus(Slave::BUSY);
            return count($readySlaves) + count($busySlaves) === $this->slaveCount;
        }

        return false;
    }
1284605
public function is_connection_ready() {
        if (!@$this->connection->set("ping", 'ping', 1)) {
            // Test the connection to the server.
            return false;
        }

        if ($this->isshared) {
            // There is a bug in libmemcached which means that it is not possible to purge the cache in a shared cache
            // configuration.
            // This issue currently affects:
            // - memcached 1.4.23+ with php-memcached <= 2.2.0
            // The following combinations are not affected:
            // - memcached <= 1.4.22 with any version of php-memcached
            // - any version of memcached with php-memcached >= 3.0.1


            // This check is cheapest as it does not involve connecting to the server at all.
            $safecombination = false;
            $extension = new ReflectionExtension('memcached');
            if ((version_compare($extension->getVersion(), '3.0.1') >= 0)) {
                // This is php-memcached version >= 3.0.1 which is a safe combination.
                $safecombination = true;
            }

            if (!$safecombination) {
                $allsafe = true;
                foreach ($this->connection->getVersion() as $version) {
                    $allsafe = $allsafe && (version_compare($version, '1.4.22') <= 0);
                }
                // All memcached servers connected are version <= 1.4.22 which is a safe combination.
                $safecombination = $allsafe;
            }

            if (!$safecombination) {
                // This is memcached 1.4.23+ and php-memcached < 3.0.1.
                // The issue may have been resolved in a subsequent update to any of the three libraries.
                // The only way to safely determine if the combination is safe is to call getAllKeys.
                // A safe combination will return an array, whilst an affected combination will return false.
                // This is the most expensive check.
                if (!is_array($this->connection->getAllKeys())) {
                    return false;
                }
            }
        }

        return true;
    }
328012
protected function checkTimeout()
    {
        $info = stream_get_meta_data($this->socket);
        if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
            $reason = $this->deadline
                ? "after {$this->timeout} second(s)"
                : 'due to default_socket_timeout php.ini setting';

            throw new Net_Notifier_Socket_TimeoutException(
                "Request timed out {$reason}"
            );
        }
    }
743159
public function check() {
        if ($this->_checkCsrf() == true) {
            switch ($this->request->logged) {
                case '*' :
                    return true;
                    break;

                case 'true' :
                    if ($this->_checkLogged()) {
                        if ($this->_checkRole()) {
                            return true;
                        }
                        else {
                            $t = new Template($this->_configFirewall['forbidden']['template'], 'gcsfirewall', 0);
                            foreach ($this->_configFirewall['forbidden']['variable'] as $val) {
                                if ($val['type'] == 'var') {
                                    $t->assign([$val['name'] => $val['value']]);
                                }
                                else {
                                    $t->assign([$val['name'] => $this->useLang($val['value'])]);
                                }
                            }
                            echo $t->show();

                            $this->addError('The access to the page ' . $this->request->src . '/' . $this->request->controller . '/' . $this->request->action . ' is forbidden', __FILE__, __LINE__, ERROR_FATAL);

                            return false;
                        }
                    }
                    else {
                        $this->addError('The access to the page ' . $this->request->src . '/' . $this->request->controller . '/' . $this->request->action . ' is forbidden because the user must be logged', __FILE__, __LINE__, ERROR_FATAL);
                        $url = Url::get($this->_configFirewall['login']['name'], $this->_configFirewall['login']['vars']);

                        if ($url != "") {
                            $this->response->header('Location: ' . $url);

                            return false;
                        }
                        else {
                            $this->addError('The firewall failed to redirect the user to the url ' . $url, __FILE__, __LINE__, ERROR_FATAL);

                            return false;
                        }
                    }
                    break;

                case 'false' :
                    if ($this->_checkLogged() == false) {
                        return true;
                    }
                    else {
                        $this->addError('The access to the page ' . $this->request->src . '/' . $this->request->controller . '/' . $this->request->action . ' is forbidden because the user mustn\'t be logged', __FILE__, __LINE__, ERROR_FATAL);
                        $url = Url::get($this->_configFirewall['default']['name'], $this->_configFirewall['default']['vars']);

                        if ($url != "") {
                            $this->response->header('Location:' . $url);
                        }
                        else {
                            $this->addError('The firewall failed to redirect the user to the url ' . $url, __FILE__, __LINE__, ERROR_FATAL);

                            return false;
                        }

                        return false;
                    }
                    break;
            }
        }
        else {
            $t = new Template($this->_configFirewall['csrf']['template'], 'gcsfirewall', 0);
            foreach ($this->_configFirewall['csrf']['variable'] as $val) {
                if ($val['type'] == 'var') {
                    $t->assign([$val['name'] => $val['value']]);
                }
                else {
                    $t->assign([$val['name'] => $this->useLang($val['value'])]);
                }
            }

            echo $t->show();
            $this->addError('The access to the page ' . $this->request->src . '/' . $this->request->controller . '/' . $this->request->action . ' is forbidden : CSRF error', __FILE__, __LINE__, ERROR_FATAL);

            return false;
        }

        return true;
    }
1355154
public function isTimedOut()
    {
        if (is_resource($this->socket)) {
            $info = stream_get_meta_data($this->socket);
        }

        return $this->socket === null || $this->socket === false || $info['timed_out'] || feof($this->socket);
    }
800419
public function rateLimitReached()
    {
        if ($this->isIpWhitelisted()) {
            return false; // we cannot block whitelisted IPs
        }

        if ($this->isIpBlacklisted()) {
            return true;
        }

        $rateLimit = $this->config->get('BlockThreshold', 0);
        if ($rateLimit < 1) {
            return false; // rate limit not used
        }

        // get the last record that's on the end of the rate limit window
        $rc = LoginRateControlEntity::find(['ip' => $this->ip], ['-timestamp'], 1, $rateLimit);
        if (!$rc) {
            return false;
        }

        $blockTtl = $this->config->get('BlockTimelimit', 1) * 60; // defined in minutes, cast to seconds
        if ((time() - $blockTtl) > 60) {
            return false;
        }

        return true;
    }
1191417
protected function pingTimedout()
    {
        $timedout = false;

        $this->database = $this->database->filter(function ($item) use (
            &$timedout
        ) {
            if (! $item['ponged_at']) {
                if (
                    Carbon::now()->diffInSeconds(
                        $this->parseDate($item['pinged_at'])
                    ) > $this->target->timeout
                ) {
                    $timedout = true;

                    return false;
                }

                return true;
            }

            return false;
        });

        return $timedout;
    }
240006
public function helo()
    {
        // don't try if it was already done
        if ($this->state['helo']) {
            return true;
        }

        try {
            $this->expect(
                $this->config['responseCodes']['SMTP_CONNECT_SUCCESS'],
                $this->config['commandTimeouts']['helo']
            );
            $this->ehlo();
            // session started
            $this->state['helo'] = true;

            //todo: are we going for a TLS connection?

            return true;
        } catch (Exception\ExceptionUnexpectedResponse $e) {
            // connected, but received an unexpected response, so disconnect
            $this->disconnect(false);

            return false;
        }
    }
943930
protected function waitPid()
    {
        start:
        $pid = \pcntl_waitpid(-1, $status, WNOHANG);
        if ($pid > 0) {
            foreach ($this->collections as $col) {
                foreach ($col->threads as $k => $t) {
                    if ($t->pid === $pid) {
                        $t->setTerminated();
                        unset($col->threads[$k]);
                        goto start;
                    }
                }
            }
        }

        return false;
    }
268996
private boolean processCommands(int timeout, boolean throttle)
    {
        Command cmd;
        if (timeout != 0) {
            //  If we are asked to wait, simply ask mailbox to wait.
            cmd = mailbox.recv(timeout);
        }
        else {
            //  If we are asked not to wait, check whether we haven't processed
            //  commands recently, so that we can throttle the new commands.

            //  Get the CPU's tick counter. If 0, the counter is not available.
            long tsc = 0; // Clock.rdtsc();

            //  Optimized version of command processing - it doesn't have to check
            //  for incoming commands each time. It does so only if certain time
            //  elapsed since last command processing. Command delay varies
            //  depending on CPU speed: It's ~1ms on 3GHz CPU, ~2ms on 1.5GHz CPU
            //  etc. The optimization makes sense only on platforms where getting
            //  a timestamp is a very cheap operation (tens of nanoseconds).
            if (tsc != 0 && throttle) {
                //  Check whether TSC haven't jumped backwards (in case of migration
                //  between CPU cores) and whether certain time have elapsed since
                //  last command processing. If it didn't do nothing.
                if (tsc >= lastTsc && tsc - lastTsc <= Config.MAX_COMMAND_DELAY.getValue()) {
                    return true;
                }
                lastTsc = tsc;
            }

            //  Check whether there are any commands pending for this thread.
            cmd = mailbox.recv(0);
        }

        //  Process all the commands available at the moment.
        while (cmd != null) {
            cmd.process();
            cmd = mailbox.recv(0);
        }

        if (errno.get() == ZError.EINTR) {
            return false;
        }

        assert (errno.get() == ZError.EAGAIN) : errno;

        if (ctxTerminated) {
            errno.set(ZError.ETERM); // Do not raise exception at the blocked operation
            return false;
        }

        return true;
    }
878405
protected function proceedingAllowed(): bool
    {
        if ($this->input->getOption('no-interaction')) {
            return true;
        }

        return $this->getHelper('question')->ask($this->input, $this->output, new ConfirmationQuestion('<question>Are you sure you wish to flush the whole database? (y/n)</question>', false));
    }
805422
public function pollMessage()
    {
        if (!$this->isConnected()) {
            throw new ConnectionException('Connection Closed!');
        }

        $r = [$this->socket];
        $w = [];
        $e = [];
        $s = socket_select($r, $w, $e, Constants::TIMEOUT_SEC, Constants::TIMEOUT_USEC);

        if ($s) {

            // Something to read
            if ($stanza = $this->readStanza()) {
                $this->processInboundData($stanza);

                return true;
            }
        }
        if (time() - $this->timeout > 60) {
            if ($this->pingCounter >= 3)
            {
              $this->sendOfflineStatus();
              $this->disconnect();
              $this->iqCounter = 1;
              $this->connect();
              $this->loginWithPassword($this->password);
              $this->pingCounter = 1;
            }
            else {
              $this->sendPing();
              $this->pingCounter++;
            }
        }

        return false;
    }
1250553
protected function _passive()
	{
		$match = array();
		$parts = array();
		$errno = null;
		$err = null;

		// Make sure we have a connection to the server
		if (!is_resource($this->conn))
		{
			Log::add(__METHOD__ . ': Not connected to the control port.', Log::WARNING, 'jerror');

			return false;
		}

		// Request a passive connection - this means, we'll talk to you, you don't talk to us.
		@ fwrite($this->conn, "PASV\r\n");

		// Wait for a response from the server, but timeout after the set time limit
		$endTime = time() + $this->timeout;
		$this->response = '';

		do
		{
			$this->response .= fgets($this->conn, 4096);
		}

		while (!preg_match("/^([0-9]{3})(-(.*" . CRLF . ")+\\1)? [^" . CRLF . "]+" . CRLF . "$/", $this->response, $parts) && time() < $endTime);

		// Catch a timeout or bad response
		if (!isset($parts[1]))
		{
			Log::add(
				sprintf(
					'%1$s: Timeout or unrecognised response while waiting for a response from the server. Server response: %2$s',
					__METHOD__, $this->response
				),
				Log::WARNING, 'jerror');

			return false;
		}

		// Separate the code from the message
		$this->_responseCode = $parts[1];
		$this->_responseMsg = $parts[0];

		// If it's not 227, we weren't given an IP and port, which means it failed.
		if ($this->_responseCode != '227')
		{
			Log::add(
				sprintf('%1$s: Unable to obtain IP and port for data transfer. Server response: %2$s', __METHOD__, $this->_responseMsg),
				Log::WARNING, 'jerror'
			);

			return false;
		}

		// Snatch the IP and port information, or die horribly trying...
		if (preg_match('~\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))\)~', $this->_responseMsg, $match) == 0)
		{
			Log::add(sprintf('%1$s: IP and port for data transfer not valid. Server response: %2$s', __METHOD__, $this->_responseMsg), Log::WARNING, 'jerror');

			return false;
		}

		// This is pretty simple - store it for later use ;).
		$this->pasv = array('ip' => $match[1] . '.' . $match[2] . '.' . $match[3] . '.' . $match[4], 'port' => $match[5] * 256 + $match[6]);

		// Connect, assuming we've got a connection.
		$this->dataconn = @fsockopen($this->pasv['ip'], $this->pasv['port'], $errno, $err, $this->timeout);

		if (!$this->dataconn)
		{
			Log::add(
				sprintf(
					'%1$s: Could not connect to host %2$s on port %3$s. Socket error number: %4$s and error message: %5$s',
					__METHOD__,
					$this->pasv['ip'],
					$this->pasv['port'],
					$errno,
					$err
				),
				Log::WARNING,
				'jerror'
			);

			return false;
		}

		// Set the timeout for this connection
		socket_set_timeout($this->conn, $this->timeout, 0);

		return true;
	}
852437
public function checkConnection() {
        try {
            $st = $this->_conn->query("SELECT 1");
        } catch(\PDOException $pe) {
            if ((strcasecmp($pe->getCode(), 'HY000') !== 0) && !stristr($pe->getMessage(), 'server has gone away'))
                throw $pe;

            if (function_exists('xdebug_start_trace'))
                xdebug_start_trace();

            $this->_resetConnection();
            $this->_connect();
        }

        return true;
    }