Create a new session and copy variables from the old one

@throws \RuntimeException
@return  boolean $result true on success

@since   2.0
422231
public function fork()
    {
        if ($this->state !== static::STATE_ACTIVE) {
            throw new \RuntimeException('Session is not active.');
        }

        // Keep session config
        $cookie = $this->bridge->getCookieParams();

        // Kill session
        $this->bridge->destroy();

        // Re-register the session store after a session has been destroyed, to avoid PHP bug
        $this->registerHandler();

        // Restore config
        $this->bridge->setCookieParams(
            $cookie['lifetime'],
            $cookie['path'],
            $cookie['domain'],
            $cookie['secure'],
            true
        );

        // Restart session with new id
        $this->bridge->restart(true);

        return true;
    }
315975
public function execute()
    {
        $storage = $this->em->unwrap();

        if (! $storage instanceof RangeQueryStorage) {
            throw new \RuntimeException(
                'The storage backend ' . $storage->getName() . ' does not support range queries.'
            );
        }

        $uow   = $this->em->getUnitOfWork();
        $class = $this->em->getClassMetadata($this->className);

        $rowHydration = function ($row) use ($uow, $class) {
            $key = [];
            foreach ($class->identifier as $id) {
                $key[$id] = $row[$id];
            }

            return $uow->createEntity($class, $key, $row);
        };
        return $storage->executeRangeQuery($this, $class->storageName, $class->identifier, $rowHydration);
    }
1286645
public function create()
    {
        if ($this->getIsNewRecord() == false) {
            throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
        }

        $transaction = $this->getDb()->beginTransaction();

        try {
            $this->password = ($this->password == null && $this->module->enableGeneratingPassword) ? Password::generate(8) : $this->password;

            $this->trigger(self::BEFORE_CREATE);

            if (!$this->save()) {
                $transaction->rollBack();
                return false;
            }

            $this->confirm();

            $this->mailer->sendWelcomeMessage($this, null, true);
            $this->trigger(self::AFTER_CREATE);

            $transaction->commit();

            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            \Yii::warning($e->getMessage());
            throw $e;
        }
    }
529049
public function loadConfig()
    {
        $result = $this->configStorage->lock();
        if ($result === false) {
            throw new \RuntimeException('Failed to lock the configStorage');
        }
        try {
            $result = $this->configStorage->load();
        } catch (\RuntimeException $e) {
            $this->configStorage->clear();
            throw $e;
        } finally {
            $this->configStorage->unlock();
        }

        $this->config = $result;
        return true;
    }
550698
protected function _execute()
    {
        $this->triggerBeforeFind();
        if ($this->_results) {
            $decorator = $this->_decoratorClass();

            return new $decorator($this->_results);
        }

        $statement = $this->getEagerLoader()->loadExternal($this, $this->execute());

        return new ResultSet($this, $statement);
    }
816343
public function run()
	{
		// First lets login to the phpMyAdmin Server, if not already.
		if ($this->loggedIn == null)
		{
			$result = $this->taskPhpMyAdminLogin()
				->phpMyAdminUrl($this->phpMyAdminUrl)
				->phpMyAdminUser($this->phpMyAdminUser)
				->phpMyAdminPass($this->phpMyAdminPass)
				->remoteDbHost($this->remoteDbHost)
			->run();

			if (!$result->wasSuccessful())
			{
				throw new RuntimeException('Failed to Login!');
			}

			$this->loggedIn = $result->getTask();
		}

		// Create our dump filename
		$dump_name = tempnam(sys_get_temp_dir(), 'dump');

		// Create our dump locally
		$cmd = 'mysqldump '.
			'-h'.$this->localDbHost.
			' -u'.$this->localDbUser.
			' '.(empty($this->localDbPass) ? '' : '-p'.$this->localDbPass).
			' '.$this->localDbName.' > '.$dump_name
		;

		$this->printTaskInfo('Dumping db on local server - <info>'.$cmd.'</info>');
		if (!$this->taskExec($cmd)->run()->wasSuccessful())
		{
			throw new RuntimeException
			(
				'Failed to create dump locally.'.
				'HINT: Is the `mysqldump` binary in your "PATH"?'
			);
		}

		// Compress the dump
		$this->printTaskInfo('Compressing dump on local server');
		if ($fp_out = gzopen($dump_name.'.gz', 'wb9'))
		{
			if ($fp_in = fopen($dump_name, 'rb'))
			{
				while (!feof($fp_in))
				{
					gzwrite($fp_out, fread($fp_in, 1024 * 512));
				}

				fclose($fp_in);
			}
			else
			{
				throw new RuntimeException
				(
					'Failed to open source dump file for reading.'
				);
			}

			gzclose($fp_out);
		}
		else
		{
			throw new RuntimeException
			(
				'Failed to open destination compressed dump file for writing.'
			);
		}

		// Get a list of tables from phpMyAdmin
		$result = $this->taskPhpMyAdminListTables($this->loggedIn)
			->remoteDbName($this->remoteDbName)
		->run();

		if (!$result->wasSuccessful())
		{
			throw new RuntimeException('Failed to get list of tabels!');
		}

		$tables = $result->getTask()->getTables();

		// Check to see if we have any tables
		if (count($tables) > 0)
		{
			// Create the sql query to drop all those tables
			$sql = 'SET foreign_key_checks = 0; DROP TABLE ';
			foreach ($tables as $table) $sql .= $table.', ';
			$sql = substr($sql, 0, -2).'; SET foreign_key_checks = 1;';

			// Droping the tables
			$this->printTaskInfo('Droping tables from phpmyadmin.');
			$result = $this->taskExecuteSqlViaPhpMyAdmin($sql, $this->loggedIn)
				->remoteDbName($this->remoteDbName)
			->run();

			// Check to make sure it worked
			if (!$result->wasSuccessful())
			{
				throw new RuntimeException('Failed to drop tables via phpmyadmin.');
			}
		}

		// Upload the dump
		$this->printTaskInfo('Uploading sql dump.');
		$response = $this->loggedIn->getClient()->post('import.php',
		[
			'multipart' =>
			[
				[
					'name' => 'db',
					'contents' => $this->remoteDbName
				],
				[
					'name' => 'server',
					'contents' => $this->loggedIn->getServerId()
				],
				[
					'name' => 'token',
					'contents' => $this->loggedIn->getToken()
				],
				[
					'name' => 'import_type',
					'contents' => 'database'
				],
				[
					'name' => 'file_location',
					'contents' => 'on'
				],
				[
					'name' => 'import_file',
					'contents' => fopen($dump_name.'.gz', 'r')
				],
				[
					'name' => 'charset_of_file',
					'contents' => 'utf-8'
				],
				[
					'name' => 'allow_interrupt',
					'contents' => 'yes'
				],
				[
					'name' => 'skip_queries',
					'contents' => '0'
				],
				[
					'name' => 'format',
					'contents' => 'sql'
				],
				[
					'name' => 'sql_compatibility',
					'contents' => 'NONE'
				],
				[
					'name' => 'sql_no_auto_value_on_zero',
					'contents' => 'something'
				]
			]
		])->getBody();

		// Check that it worked
		if (!s::create($response)->contains('Import has been successfully finished'))
		{
			throw new RuntimeException('Failed to import dump via phpmyadmin. OH NO - we just dropped all the tables!!!');
		}

		// Remove the dump from the local server
		$this->printTaskInfo('Removing dump from local server. - <info>'.$dump_name.'</info>');
		unlink($dump_name); unlink($dump_name.'.gz');

		// If we get to here assume everything worked
		return Result::success($this);
	}
1001310
public function getRow($result = NULL, $useExceptions = _DbConfig::USE_EXCEPTIONS) {
        if ($result === NULL) {
            $result = $this->lastResult;
        }
        if ($this->count() <= 0) {
            return FALSE;
        }
        $this->lastRow = $this->lastResult->fetch_assoc();
        return $this->lastRow;
    }
574391
public function execute()
    {
        if (!is_resource($this->handle)) {
            throw new RuntimeException('Curl handle has been closed, just open it before execute...');
        }

        curl_setopt_array($this->handle, array_filter($this->options));
        $return = curl_exec($this->handle);

        if ($return === false) {
            throw ExceptionFactory::build(
                curl_errno($this->handle),
                curl_error($this->handle)
            );
        }

        return $return;
    }
90599
public function recover()
    {
        if (! class_exists($this->class)) {
            return new RuntimeException($this->message);
        }

        try {
            $reflection = new ReflectionClass($this->class);

            $e = $reflection->newInstanceWithoutConstructor();

            if (! $e instanceof Throwable) {
                throw new RuntimeException("Class [{$this->class}] is not an exception.");
            }

            foreach ($reflection->getProperties() as $property) {
                $name = $property->getName();

                if (isset($this->properties[$name])) {
                    $value = $this->properties[$name];

                    $property->setAccessible(true);

                    $property->setValue($e, $value instanceof Serialization ? $value->recover() : $value);
                }
            }

            return $e;
        } catch (Throwable $ex) {
            return new RuntimeException($this->message);
        }
    }
846344
public function refresh()
    {
        //Create the namespace if it doesn't exist
        $namespace = $this->getNamespace();

        if(!isset($_SESSION[$namespace])) {
            $_SESSION[$namespace] = array();
        }

        //Re-load the session containers
        foreach($this->_containers as $container)
        {
            $namespace = $this->getNamespace();
            $container->load($_SESSION[$namespace]);
        }

        return $this;
    }
1369050
public function postBatch()
    {
        $fp = fsockopen($this->hostname, $this->port, $errno, $errstr, 30);

        if (FALSE === $fp) {
            throw new \RuntimeException($errstr, $errno);
        }

        for ($i = 0, $c = count($this->buffer); $i < $c; $i++) {

            $message = $this->buffer[$i];

            $request = "POST /inputs/" . $this->input->getKey() . " HTTP/1.1\r\n";
            $request .= "Host: " . ClientInterface::LOGGLY_HOST . "\r\n";
            $request .= "User-Agent: " . ClientInterface::USER_AGENT . "\r\n";
            $request .= "Content-Type: " . $this->getContentType() . "\r\n";
            $request .= "Content-Length: " . strlen($message) . "\r\n";

            // Add Connection: Close header on the last request.
            $request .= $i === $c - 1 ? "Connection: Close\r\n\r\n" : "\r\n";

            $request .= $message;
            $request .= $i === $c - 1 ? "" : "\r\n";

            fwrite($fp, $request);
        }

        fclose($fp);

        return TRUE;
    }
1351402
protected function initialiseConfiguration()
    {
        $configuration = $this->registerConfiguration($this->environment);

        if ( ! is_array($configuration)) {
            throw new \RuntimeException(sprintf(
                'The configuration must be a valid array (%s given).',
                $this->varToString($configuration)
            ));
        }

        return $this->configuration = new Configuration($configuration);
    }
462684
public function start(array $options = null)
    {
        $sessionStatus = \session_status();

        if ($sessionStatus === PHP_SESSION_DISABLED) {
            throw new \RuntimeException('PHP sessions are disabled');
        }

        if ($sessionStatus === PHP_SESSION_ACTIVE) {
            throw new \RuntimeException('session has already been started');
        }

        if ($this->handler) {
            \session_set_save_handler($this->handler, true);
        }

        \session_set_cookie_params(
            $this->cookieParams['lifetime'],
            $this->cookieParams['path'],
            $this->cookieParams['domain'],
            $this->cookieParams['secure'],
            $this->cookieParams['httponly']
        );

        if ($options === null) {
            $options = [];
        }

        if (!isset($options['serialize_handler'])) {
            $serializeHandler = \ini_get('serialize_handler');
            if ($serializeHandler === 'php' || $serializeHandler === 'php_binary') {
                $options['serialize_handler'] = 'php_serialize';
            }
        }

        $result = \session_start($options);

        if ($result) {
            $this->moveFlash();
        }

        return $result;
    }
1130460
public function setResult($name = null, $result = null)
    {
        if (null === $result) {
            $result = $name;
            array_push($this->results, $result);

            return $this;
        }

        $this->results[(string) $name] = $result;

        return $this;
    }
918827
public function execute()
	{
		$this->connect();

		if (!is_resource($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			$sql .= ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset;
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
		$this->cursor = @pg_query($this->connection, $sql);

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					// Get the error number and message.
					$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' ';
					$this->errorMsg = pg_last_error($this->connection) . "\nSQL=$sql";

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				// Get the error number and message.
				$this->errorNum = (int) pg_result_error_field($this->cursor, PGSQL_DIAG_SQLSTATE) . ' ';
				$this->errorMsg = pg_last_error($this->connection) . "\nSQL=$sql";

				// Throw the normal query exception.
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg);
			}
		}

		return $this->cursor;
	}
406447
@Memoized
  Session session() {
    Session result = sessionFactory().create(this);
    provisioned = true;
    return result;
  }
1267374
protected function createResource()
    {
        $resource = $this->connect($this->configuration->asArguments());

        if (!is_resource($resource)) {
            throw new RuntimeException('The SSH connection failed.');
        }

        $this->resource = $resource;

        if (null !== $this->authentication) {
            $this->authenticate();
        }
    }