Open a URL in the browser, or print it.

@param $url
@param \Symfony\Component\Console\Output\OutputInterface $stdErr
@param \Symfony\Component\Console\Output\OutputInterface $stdOut
167209
protected function openUrl($url, OutputInterface $stdErr, OutputInterface $stdOut)
    {
        $browser = $this->getDefaultBrowser();
        if ($browser) {
            $opened = shell_exec("$browser $url 2>&1; echo $?");
            if ($opened == 0) {
                $stdErr->writeln("<info>Opened</info>: $url");
                return;
            }
        } else {
            $stdErr->writeln("<error>Browser not found: $browser</error>");
        }
        $stdOut->writeln($url);
    }
1257311
public function executeCommand(&$output)
	{
		$descriptorspec = array(
			0 => array("pipe", "r"), // stdin is a pipe that the child will read from
			1 => array("pipe", "w"), // stdout is a pipe that the child will write to
			2 => array("pipe", "w") // stderr is a pipe that the child will write to
		);

		$process = proc_open($this->cmd . ' ' . $this->getParams() . ' ' . $this->getInputSource() . ' ' . $this->getPDFPath(), $descriptorspec, $pipes);

		$output = stream_get_contents($pipes[1]) . stream_get_contents($pipes[2]);

		fclose($pipes[0]);
		fclose($pipes[1]);
		fclose($pipes[2]);

		return proc_close($process);
	}
990035
def redirect_stderr(self, enabled=True, log_level=logging.ERROR):
        
        if enabled:
            if self.__stderr_wrapper:
                self.__stderr_wrapper.update_log_level(log_level=log_level)
            else:
                self.__stderr_wrapper = StdErrWrapper(logger=self, log_level=log_level)

            self.__stderr_stream = self.__stderr_wrapper
        else:
            self.__stderr_stream = _original_stderr

        # Assign the new stream to sys.stderr
        sys.stderr = self.__stderr_stream
421328
public function redirectUrl($url)
	{
		$processor = new ParamProcessor();
		$url = $processor->GetFullLink($url);
		$url = str_replace("&amp;", "&", $url);

		// IIS running CGI mode has a bug related to POST and header(LOCATION) to the SAME script.
		// In this environment the behavior expected causes a loop to the same page
		// To reproduce this behavior comment the this and try use any processpage state class
		$isBugVersion = stristr(PHP_OS, "win") && stristr($this->get("GATEWAY_INTERFACE"), "cgi") && stristr($this->get("SERVER_SOFTWARE"), "iis");

		ob_clean();
		if (!$isBugVersion)
		{
			header("Location: " . $url);
		}

		echo "<html>";
		echo "<head>";
		echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"1;URL=$url\">";
		echo "<style type='text/css'> ";
		echo "	#logo{";
		echo "		width:32px;";
		echo "		height:32px;";
		echo "		top: 50%;";
		echo "		left: 50%;";
		echo "		margin-top: -16px;";
		echo "		margin-left: -16px;";
		echo "		position:absolute;";
		echo "} </style>";
		echo "</head>";
		echo "<h1></h1>";
		echo "<div id='logo'><a href='$url'><img src='common/imgs/ajax-loader.gif' border='0' title='If this page does not refresh, Click here' alt='If this page does not refresh, Click here' /></a></div>";
		echo "</html>";
		exit;
	}
996752
public function outputOf(string $command, string $redirect = '2>&1')
    {
        $pd = $this->runCommand($command, $redirect);
        while (!feof($pd) && false !== ($line = fgets($pd, 4096))) {
            yield rtrim($line);
        }

        $returnCode = pclose($pd);
        if (0 != $returnCode) {
            throw new \RuntimeException(
                    'Executing command "' . $command . '"'
                    . ' failed: #' . $returnCode
            );
        }
    }
811560
static public function conditional_header($url, $permRedir=FALSE) {
		if(count(func_get_args())==3) {
			self::debug_print(func_get_args(),1);
			throw new InvalidArgumentException("the 'exitAfter' argument is no longer valid");
		}
		
		if(isset($_SESSION) && is_array($_SESSION)) {
			//do some things to help protect against recursive redirects.
			if(isset($_SESSION['__conditional_header__'])) {
				$number = $_SESSION['__conditional_header__']['number'];
				$lastTime = $_SESSION['__conditional_header__']['last_time'];
				$timeSinceLast = microtime(true) - $lastTime;
				if(($timeSinceLast) <= 0.005 && $number > 5) {
					unset($_SESSION['__conditional_header__']);
					throw new Exception(__METHOD__ .": too many redirects (". $number .") in a short time (". $timeSinceLast ."), last url: (". $url .")");
				}
				else {
					$_SESSION['__conditional_header__']['number']++;
					$_SESSION['__conditional_header__']['last_time'] = microtime(true);
				}
			}
			else {
				$_SESSION['__conditional_header__'] = array(
					'last_time'	=> microtime(true),
					'number'		=> 0
				);
			}
		}
		
		if(!strlen($url)) {
			throw new InvalidArgumentException(__METHOD__ .": failed to specify URL (". $url .")");
		}
		else {
			if(headers_sent()) {
				//headers sent.  Use the meta redirect.
				print "
				<HTML>
				<HEAD>
				<TITLE>Redirect Page</TITLE>
				<META HTTP-EQUIV='refresh' content='0; URL=$url'>
				</HEAD>
				<a href=\"$url\"></a>
				</HTML>
				";
			}
			else {
				if($permRedir) {
					//NOTE: can't do much for permanent redirects if headers have already been sent.
					header("HTTP/1.1 301 Moved Permanently");
				}
				header("location:$url");
			}
		}
	}
8038
public function run($URL,$host=''){
		if(ROUTER_DEBUG){
			BLog::addToLog('[Router]: Router started! URL='.$URL.'; host='.$host);
			}
		$this->init();
		//bimport('ip.ban');
		//$r=BIpBan::check();
		//if($r===false){
		//	header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
		//	return $this->errorpage('ipban');
		//	}
		$this->url=$URL;
		$this->host=$host;

		$r=$this->parseurl($URL,$host);

		if(ROUTER_DEBUG){
			if($r){
				BLog::addToLog('[Router]: Rules successfully parsed.');
				}else{
				BLog::addToLog('[Router]: Error of parsing rules!',LL_ERROR);
				}
			}
		if($r===false){
			header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
			header('Content-type: text/html; charset=utf-8');
			return $this->errorpage('404');
			}
		if(ROUTER_DEBUG){
			BLog::addToLog('[Router]: rules:'.var_export($this->rules,true));
			}
		$this->render_positions();
		switch($this->ctype){
			case CTYPE_HTML:
				$this->generatepage_html();
				break;
			case CTYPE_PLAINHTML:
				$this->generatepage_plainhtml();
				break;
			case CTYPE_JSON:
				$this->generatepage_json();
				break;
			case CTYPE_XML:
				$this->generatepage_xml();
				break;
			case CTYPE_DOCX:
				$this->generatepage_docx();
				break;
			case CTYPE_CSV:
				$this->generatepage_csv();
				break;
			case CTYPE_PDF:
				$this->generatepage_pdf();
				break;
			case CTYPE_REDIRECT301:
				$this->redirect301($this->redirectURL);
				break;
			case CTYPE_REDIRECT302:
				$this->redirect302($this->redirectURL);
				break;
			default:
				echo('Unknown content type!');
				break;
			}
		}
982513
public static function redirect($url, $args = null) {
        if (strpos($url, '\\') !== false) {
            $url = self::action($url);
        } else {
            $url = self::url($url);
        }
        if (!empty($args)) {
            $url .= '?' . http_build_query($args);
        }
        Response::redirect($url, '');
    }
26409
def stdout_redirector():
    
    old_stdout = sys.stdout
    sys.stdout = Stream()
    try:
        yield sys.stdout
    finally:
        sys.stdout.close()
        sys.stdout = old_stdout
902828
def open(self, url, *args, **kwargs):
        
        if self.__verbose == 1:
            sys.stdout.write('.')
            sys.stdout.flush()
        elif self.__verbose >= 2:
            print(url)

        resp = self.get(url, *args, **kwargs)
        self.__state = _BrowserState(page=resp.soup, url=resp.url,
                                     request=resp.request)
        return resp
369091
public function render(?string $url = null): void
	{
		// Get HTML element
		$el = $this->getElementPrototype();
		$el->addText($this->getElementText());
		$el->href($this->getHref());

		// Set URL
		if ($url !== null) {
			Validators::assert($url, 'string|url');
			$el->{'data-url'} = $url;
		} elseif ($this->url !== null) {
			$el->{'data-url'} = $this->url;
		}

		// List of default properties
		$properties = [
			'via' => $this->via,
			'text' => $this->text,
			'related' => $this->related,
			'count' => $this->count,
			'lang' => $this->lang,
			'counturl' => $this->counturl,
			'hashtags' => $this->hashtags,
			'size' => $this->size,
			'dnt' => $this->dnt,
		];

		// Merge with custom properties
		$properties = array_merge($properties, $this->getProperties());

		// Set properties as data attributes
		foreach ($properties as $key => $value) {
			if ($value !== null && !empty($value)) {
				$el->{'data-' . $key} = $value;
			}
		}

		echo $el;
	}
572870
protected function _open($url)
    {
        set_error_handler(function ($code, $message) {
            $this->_connectionErrors[] = $message;
        });
        try {
            $this->_stream = fopen($url, 'rb', false, $this->_context);
        } finally {
            restore_error_handler();
        }

        if (!$this->_stream || !empty($this->_connectionErrors)) {
            throw new Exception(implode("\n", $this->_connectionErrors));
        }
    }
230782
private function execute($remote, $url)
    {
        /** @var ConfigurationDataResponse $configurationData */
        $configurationData = $this->queryBus->handle(new ConfigurationDataFinder());
        $prePushResponse = $configurationData->getPrePush();

        if (true === $prePushResponse->isPrePush()) {
            $this->output->writeln(self::PRE_PUSH_HOOK);
            $this->executeOriginalHook($remote, $url, $prePushResponse->getErrorMessage());

            $phpunitResponse = $prePushResponse->getPhpUnit();

            if (true === $phpunitResponse->isPhpunit()) {
                $this->commandBus->handle(
                    new PhpUnitTool(
                        $phpunitResponse->isPhpunitRandomMode(),
                        $phpunitResponse->getPhpunitOptions(),
                        $prePushResponse->getErrorMessage()
                    )
                );

                $phpunitStrictCoverageResponse = $prePushResponse->getPhpUnitStrictCoverage();

                if (true === $phpunitStrictCoverageResponse->isPhpunitStrictCoverage()) {
                    $this->commandBus->handle(
                        new StrictCoverage(
                            $phpunitStrictCoverageResponse->getMinimum(),
                            $prePushResponse->getErrorMessage()
                        )
                    );
                }

                $phpunitGuardCoverageResponse = $prePushResponse->getPhpUnitGuardCoverage();

                if (true === $phpunitGuardCoverageResponse->isEnabled()) {
                    $this->commandBus->handle(
                        new GuardCoverage($phpunitGuardCoverageResponse->getWarningMessage())
                    );
                }
            }

            $this->output->writeln(GoodJobLogoResponse::paint($prePushResponse->getRightMessage()));
        }
    }
848216
public function openUrl($url, $print = true)
    {
        $browserOption = $this->input->hasOption('browser') ? $this->input->getOption('browser') : null;
        $open = true;
        $success = false;

        // If the user wants to pipe the output to another command, stop here.
        if ($this->input->hasOption('pipe') && $this->input->getOption('pipe')) {
            $open = false;
            $print = true;
        }
        // Check if the user has requested not to use a browser.
        elseif ($browserOption === '0') {
            $open = false;
        }
        // Check for a display (if not on Windows or OS X).
        elseif (!$this->hasDisplay()) {
            $open = false;
            $this->stdErr->writeln('Not opening URL (no display found)', OutputInterface::VERBOSITY_VERBOSE);
        }

        // Open the URL.
        if ($open && ($browser = $this->getBrowser($browserOption))) {
            $success = $this->shell->executeSimple($browser . ' ' . escapeshellarg($url)) === 0;
        }

        // Print the URL.
        if ($print) {
            $this->output->writeln($url);
        }

        return $success;
    }
384847
protected function open()
    {
        if (isset($this->options['stdin'])) {
            $this->input = $this->options['stdin'];
        } else {
            $this->input = fopen('php://stdin', 'r');
        }
        if (isset($this->options['stdout'])) {
            $this->output = $this->options['stdout'];
        } else {
            $this->output = fopen('php://stdout', 'w');
        }
        while (true) {
            $line = $this->read($this->input);
            if ($this->isEndOfEnvironmentVariables($line)) {
                break;
            }
            $this->readEnvironmentVariable($line);
        }
        $this->logger->debug(print_r($this->variables, true));
    }
292665
public function redirect($url)
    {
        $location = $this->_request->getBasePath();
        $location = str_replace('//', '/', "{$location}/{$url}");
        $this->_response->setStatusCode(302);
        $header = new GenericHeader('Location', $location);
        $this->_response->getHeaders()->addHeader($header);
        return $this->disableRendering();
    }
1107112
public static function stderr($text, $nl = true, $quit = -200): void
    {
        self::write($text, $nl, $quit, [
            'stream' => \STDERR,
        ]);
    }