Prepara la aplicación para procesar las peticiones http.
497181
public function preparar()
    {
        if (!$this->preparada) {
            // Validamos requisitos míminos
            if (!isset($this->dirApp)) {
                throw new \RuntimeException('Todavía no define directorio base de la aplicacion.');
            }

            // Validamos presencia de rutas
            if (!isset($this->archivoRutas)) {
                $this->archivoRutas = $this->dirApp . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'rutas.php';
            }
            if (!is_file($this->archivoRutas)) {
                throw new \RuntimeException('No fue encontrado el archivo de rutas.');
            }

            // Preparamos enrutador
            $this->enrutador = new Enrutador();
            $this->enrutador->definirUriBase($this->uriBase);
            $this->enrutador->importarRutas(require $this->archivoRutas);

            // Preparamos gestores de errores
            $this->whoops = new Run();
            $this->whoops->pushHandler(new PrettyPageHandler());
            $this->whoops->writeToOutput(false);
            $this->whoops->allowQuit(false);

            set_error_handler(function($nivel, $mensaje, $archivo, $lineaArchivo){
                throw new \ErrorException($mensaje, 0, $nivel, $archivo, $lineaArchivo);
            });
            register_shutdown_function(function(){
                $error = error_get_last();
                if (is_array($error)) {
                    throw new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']);
                }
            });

            // Establecemos que la aplicación ya está preparada
            $this->preparada = true;
        }
    }
399030
private function prepare_url() {
    $parts = parse_url($this->request_settings['url']);

    $port   = isset($parts['port']) ? $parts['port'] : false;
    $scheme = $parts['scheme'];
    $host   = $parts['host'];
    $path   = isset($parts['path']) ? $parts['path'] : false;

    $port or $port = ($scheme == 'https') ? '443' : '80';

    if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
      $host = "$host:$port";
    }

    // the scheme and host MUST be lowercase
    $this->request_settings['url'] = strtolower("$scheme://$host");
    // but not the path
    $this->request_settings['url'] .= $path;
  }
448248
protected function prepareRequest()
    {
        $this->formatUrl();
        $this->validateInput();
        $this->addHeaders();
        $this->addRequestBody();
        $this->initOptions();
    }
1312885
public function process()
	{
		if( ( $name = $this->getView()->param( 'd_name' ) ) !== null )
		{
			$context = $this->getContext();
			$session = $context->getSession();
			$lastSeen = $session->get( 'aimeos/catalog/session/seen/list', [] );

			if( isset( $lastSeen[$name] ) )
			{
				$html = $lastSeen[$name];
				unset( $lastSeen[$name] );
				$lastSeen[$name] = $html;
			}
			else
			{
				/** client/html/catalog/session/seen/standard/maxitems
				 * Maximum number of products displayed in the "last seen" section
				 *
				 * This option limits the number of products that are shown in the
				 * "last seen" section after the user visited their detail pages. It
				 * must be a positive integer value greater than 0.
				 *
				 * @param integer Number of products
				 * @since 2014.03
				 * @category User
				 * @category Developer
				 */
				$max = $this->getContext()->getConfig()->get( 'client/html/catalog/session/seen/standard/maxitems', 6 );

				$lastSeen[$name] = $this->getHtml( $name );
				$lastSeen = array_slice( $lastSeen, -$max, $max, true );
			}

			$session->set( 'aimeos/catalog/session/seen/list', $lastSeen );

			foreach( $session->get( 'aimeos/catalog/session/seen/cache', [] ) as $key => $value ) {
				$session->set( $key, null );
			}
		}

		parent::process();
	}
950637
private static function work() {

		$domain = null;
		$found  = false;

		if($request = static :: getUrl()) {

			$routes = static :: getRoutes();

			foreach($routes as $identifier => $route) {
				
				$domains = $route -> getDomain();
				$found 	 = false;

				if(null === $domains || 0 === count($domains)) {
					$found = true;
				}

				if(true === is_array($domains)) {

					foreach($domains as $host) {

						if(1 === preg_match('#'. str_replace('#', '\#', $host) .'#', Request :: parseUrl('host'))) {
							
							$found  = true;
							$domains = $host;

							break;
						}
					}
				}

				if(true === $found) {

					if(Request :: getMethod() !== null && Request :: getMethod() !== $route -> getMethod() && $route -> getMethod() !== 'any') {
						continue;
					}

					$path = $request -> trimPath();

					if(true === $route -> getStrict()) {

						if(null !== $request -> getQuery()) {
							$path .= '?' . $request -> getQuery();
						}
					}

					if(preg_match('#^'. str_replace('#', '\#', $route -> getMatch()) .'$#', $path, $match)) {

						array_shift($match);

						$match = array_map(function($tmp) {
							return ltrim($tmp, '\/');
						}, $match);

						$match = array_unique($match);
						
						static :: setRoute($route);
						static :: setParams($match);

						//Check if route is viewable
						if(true === $route -> isViewable() || null === $route -> getViewable() || true === static :: getRedirect()) {
							
							new MVC($route, $match);
							return true;
						}

						break;
					}
				}
			}
		}

		//Prevent to many redirects
		if(static :: $redirected > 50) {
			return trigger_error('Prevented to many redirects. This usually happens when there are no routes to match and the 404 will trigger the same 404 in a loop.', E_USER_ERROR);
		}

		//Update redirected
		static :: $redirected++;

		//Trigger 404 if route exists
		if(true === $found && $route = static :: $error['default'][404]) {

			$route -> viewable(true);

			$redirect = static :: redirect($route -> getIdentifier()) -> domain($domain);
			$method   = Request :: getMethod();

			if(true === is_callable([$redirect, $method])) {
				
				call_user_func_array([$redirect, $method], []);
				return true;
			}
		}

		//Else set HTTP status 404
		Response :: setStatus(404);

		return false;
	}
10070
public function setupFormats()
    {
//through HTTP_ACCEPT
        if (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], '*/*') === false) {
            foreach ($this->outputFormats as $formatCode => $formatMethod) {
                if (strpos($_SERVER['HTTP_ACCEPT'], $formatCode) !== false) {
                    $this->outputFormat = $formatCode;
                    break;
                }
            }
        }

//through uri suffix
        if (preg_match('/\.(\w+)$/i', $this->getUrl(), $matches)) {
            if (isset($this->outputFormats[$matches[1]])) {
                $this->outputFormat = $matches[1];
                $url = $this->getUrl();
                $this->setUrl(substr($url, 0, (strlen($this->outputFormat) * -1) - 1));
            }
        }

//through _format parametr
        if (isset($_GET['_format'])) {
            if (isset($this->outputFormats[$_GET['_format']])) {
                $this->outputFormat = $_GET['_format'];
            }
        }

        return $this;
    }
515403
static function processLinksInText($input, $stripTags=false, $blankTarget=true) {

		if ($stripTags) $input=strip_tags($input);

		//Add protocol to www links without one. We use ahttp to strip it later
		$input = preg_replace("~([^\w\/:-_]|^)(www\.[^<>,\s\)]+\.\w+)~i","\\1ahttp://\\2", $input);

		//Make classical links
		$input = preg_replace("~([a-zA-Z]{2,10}):\/\/([^<>,\s\)]+)~i","<a href=\"\\0\"".($blankTarget?" target=\"_blank\"":"").">\\0</a>", $input);

		//Strip ahttp back
		$input = str_replace("href=\"ahttp://","href=\"http://", $input);
		$input = str_replace("ahttp://","", $input);

		//E-mailové odkazy
		$input = preg_replace('~[\w\.\-]+@[^<>\s]+[\w]~',"<a href=\"mailto:\\0\">\\0</a>", $input);
		$input=trim($input);

		return $input;
	}
129534
def ConsultarTipoActividad(self, sep="||"):
        ""
        ret = self.client.tipoActividadConsultar(
                        auth={
                            'token': self.Token, 'sign': self.Sign,
                            'cuit': self.Cuit, },
                            )['tipoActividadReturn']
        self.__analizar_errores(ret)
        array = ret.get('tiposActividad', [])
        return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
                    (it['codigoDescripcion']['codigo'], 
                     it['codigoDescripcion']['descripcion']) 
               for it in array]
363892
public function execute(): void
    {
        if ($this->oLocaleService::ENABLE_SNIFF_URL) {

            /**
             * Manipulate the URL
             * Remove the /{language} element from the URL once the Locale service has initialsied
             * so that this doesn't affect normal routing of the application.
             *
             * @todo (Pablo - 2019-03-08) - Check if this breaks on systems where the app isn't at the root of the domain
             */

            $oUrl = $this->parseUrl($this->getUrl());

            //  If the detected language is the same as the default language then remove it form the URL and repeat
            if ($oUrl->language === $this->oLocaleService::DEFAULT_LANGUAGE) {
                header(
                    'Location: /' . $oUrl->url,
                    true,
                    HttpCodes::STATUS_TEMPORARY_REDIRECT
                );
                exit(0);
            }

            //  Save the original URL, should it be needed
            $_SERVER['ORIGINAL_URL'] = $this->getUrl();

            //  Update the $_SERVER values so the rest of the system continues as normal
            if (array_key_exists('PATH_INFO', $_SERVER)) {
                $_SERVER['PATH_INFO'] = '/' . $oUrl->path;
            }
            if (array_key_exists('REQUEST_URI', $_SERVER)) {
                $_SERVER['REQUEST_URI'] = '/' . $oUrl->url;
            }
        }
    }
1287220
final public function web()
    {
        $request = Request::createFromGlobals();
        $response = $this->handle($request);
        $response->send();
        $this->terminate($request, $response);
    }
1362234
public static function crearDesdeGlobales()
    {
        // Preparamos Metodo
        if (isset($_SERVER['REQUEST_METHOD'])) {
            $metodo = $_SERVER['REQUEST_METHOD'];
        } else {
            $metodo = 'GET';
        }

        // Preparamos URL
        $url = '';
        if (!empty($_SERVER['HTTPS'])) {
            if ($_SERVER['HTTPS'] !== 'off') {
                $url .= 'https';
            } else {
                $url .= 'http';
            }
        } else {
            if ($_SERVER['SERVER_PORT'] == 443) {
                $url .= 'https';
            } else {
                $url .= 'http';
            }
        }
        $url .= '://';
        if (isset($_SERVER['HTTP_HOST'])) {
            $url .= $_SERVER['HTTP_HOST'];
        } else {
            $url .= $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
        }
        $url .= $_SERVER['REQUEST_URI'];

        // Preparamos cabeceras
        $cabeceras = [];
        foreach ($_SERVER as $nombre => $valor) {
            if (substr($nombre, 0, 5) == 'HTTP_') {
                $nombre = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($nombre, 5)))));
                $cabeceras[$nombre] = $valor;
            } else if ($nombre == 'CONTENT_MD5') {
                $cabeceras['Content-Md5'] = $valor;
            } else if ($nombre == 'CONTENT_TYPE') {
                $cabeceras['Content-Type'] = $valor;
            } else if ($nombre == 'CONTENT_LENGTH') {
                $cabeceras['Content-Length'] = $valor;
            }
        }
        if (!isset($cabeceras['Authorization'])) {
            if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
                $cabeceras['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
            } elseif (isset($_SERVER['PHP_AUTH_USER'])) {
                $temp = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
                $cabeceras['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $temp);
            } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
                $cabeceras['Authorization'] = $_SERVER['PHP_AUTH_DIGEST'];
            }
        }

        // Preparamos parámetros según método
        $parametros = [];
        if ($metodo != 'GET') {
            $parametros = self::procesarParametros(file_get_contents('php://input'), $cabeceras['Content-Type'], $_POST);
        }

        // Preparamos galletas
        $galletas = [];
        if (!empty($_COOKIE)) {
            $galletas = $_COOKIE;
        }

        // Preparamos archivos
        $archivos = [];
        if (!empty($_FILES)) {
            $archivos = self::prepararArchivos($_FILES);
        }

        // Iniciamos instancia de petición con los datos ya preparados
        $peticion = new Peticion($url, $metodo, $parametros, $cabeceras, $galletas, $archivos);


        // Preparamos IP del cliente
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $peticion->cliente_ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
            $peticion->cliente_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $peticion->cliente_ip = $_SERVER['REMOTE_ADDR'];
        }


        // Retornamos instancia iniciada
        return $peticion;
    }
37947
function getBrowser()
    {
        $sys = $this->server['HTTP_USER_AGENT'];
        if (stripos($sys, "Firefox/") > 0)
        {
            preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
            $exp[0] = "Firefox";
            $exp[1] = $b[1];
        }
        elseif (stripos($sys, "Maxthon") > 0)
        {
            preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
            $exp[0] = "傲游";
            $exp[1] = $aoyou[1];
        }
        elseif (stripos($sys, "MSIE") > 0)
        {
            preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
            $exp[0] = "IE";
            $exp[1] = $ie[1];
        }
        elseif (stripos($sys, "OPR") > 0)
        {
            preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
            $exp[0] = "Opera";
            $exp[1] = $opera[1];
        }
        elseif (stripos($sys, "Edge") > 0)
        {
            preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
            $exp[0] = "Edge";
            $exp[1] = $Edge[1];
        }
        elseif (stripos($sys, "Chrome") > 0)
        {
            preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
            $exp[0] = "Chrome";
            $exp[1] = $google[1];
        }
        elseif (stripos($sys, 'rv:') > 0 && stripos($sys, 'Gecko') > 0)
        {
            preg_match("/rv:([\d\.]+)/", $sys, $IE);
            $exp[0] = "IE";
            $exp[1] = $IE[1];
        }
        else
        {
            $exp[0] = "Unkown";
            $exp[1] = "";
        }

        return $exp[0] . '(' . $exp[1] . ')';
    }
59043
protected function buildRequestHeader()
  {
    // Create header
    $headerlines = array();
    
    // Methode(GET or POST)
    if (count($this->post_data) > 0) $request_type = "POST";
    else $request_type = "GET";
    
    // HTTP protocol
    if ($this->http_protocol_version == PHPCrawlerHTTPProtocols::HTTP_1_1) $http_protocol_verison = "1.1";
    else $http_protocol_verison = "1.0";
    
    if ($this->proxy != null)
    {
      // A Proxy needs the full qualified URL in the GET or POST headerline.
      $headerlines[] = $request_type." ".$this->UrlDescriptor->url_rebuild ." HTTP/1.0\r\n";
    }
    else
    {
      $query = $this->prepareHTTPRequestQuery($this->url_parts["path"].$this->url_parts["file"].$this->url_parts["query"]);
      $headerlines[] = $request_type." ".$query." HTTP/".$http_protocol_verison."\r\n";
    }
    
    $headerlines[] = "Host: ".$this->url_parts["host"]."\r\n";
    
    $headerlines[] = "User-Agent: ".str_replace("\n", "", $this->userAgentString)."\r\n";
    $headerlines[] = "Accept: */*\r\n";
    
    // Request GZIP-content
    if ($this->request_gzip_content == true)
    {
      $headerlines[] = "Accept-Encoding: gzip, deflate\r\n";
    }
    
    // Referer
    if ($this->UrlDescriptor->refering_url != null)
    {
      $headerlines[] = "Referer: ".$this->UrlDescriptor->refering_url."\r\n";
    }
    
    // Cookies
    $cookie_header = $this->buildCookieHeader();
    if ($cookie_header != null) 
      $headerlines[] = $this->buildCookieHeader();
    
    // Authentication
    if ($this->url_parts["auth_username"] != "" && $this->url_parts["auth_password"] != "")
    {
      $auth_string = base64_encode($this->url_parts["auth_username"].":".$this->url_parts["auth_password"]);
      $headerlines[] = "Authorization: Basic ".$auth_string."\r\n";
    }
    
    // Proxy authentication
    if ($this->proxy != null && $this->proxy["proxy_username"] != null)
    {
      $auth_string = base64_encode($this->proxy["proxy_username"].":".$this->proxy["proxy_password"]);
      $headerlines[] = "Proxy-Authorization: Basic ".$auth_string."\r\n";
    }
    
    $headerlines[] = "Connection: close\r\n";
    
    // Wenn POST-Request
    if ($request_type == "POST")
    {
      // Post-Content bauen
      $post_content = $this->buildPostContent();
      
      $headerlines[] = "Content-Type: multipart/form-data; boundary=---------------------------10786153015124\r\n";
      $headerlines[] = "Content-Length: ".strlen($post_content)."\r\n\r\n";
      $headerlines[] = $post_content;
    }
    else
    {
      $headerlines[] = "\r\n";
    }

    return $headerlines;
  }
465557
private function handleHTTP()
    {
    	try
    	{
			$method = new ReflectionMethod($this->classname, $_REQUEST["svc"]);
    	}
    	catch (Exception $ex)
    	{
    		echo '{ error: "Method does not exists" }';
    		exit;
    	}
		if (!$method->isPublic())
		{
    		echo '{ error: "Method is not public" }';
			exit;
		}

		$params = $method->getParameters();
		$paramValues = array();
		$missingParams = array();
		foreach ($params as $param)
		{
			$paramName = $param->getName();
			$paramValue = ( isset($_REQUEST[$paramName]) ? $_REQUEST[$paramName] : null);
			if (is_null($paramValue) && $param->isDefaultValueAvailable())
			{
				$paramValue = $param->getDefaultValue();
			}
			if (is_null($paramValue))
			{
				$missingParams[] = $paramName;
			}
			else
			{
				$paramValues[$paramName] = $paramValue;
			}
		}
		if (count($missingParams) > 0)
		{
			echo '{ error: "Missing params", parameters: [ "' . implode('","', $missingParams) . '"] }';
		}
		else
		{
			try
			{
				$result = $method->invokeArgs($this, $paramValues);
				if (is_array($result))
				{
					echo json_encode($result);
				}
				elseif (is_object($result))
				{
					echo '{ error: "Return type is not supported" } ';
				}
				else
				{
					echo $result;
				}
			}
			catch (Exception $ex)
			{
				echo '{ error: "' . $ex->getMessage() . '" }';
			}
		}
    }
952046
public function process()
    {
        $logger = $this->getLogger();
        $logger->log("Starting...\n");

        $formatter = $this->createFormatter();
        $parser    = $this->createParser();
        $outputDir = $this->configuration->get('output');
        $sources   = $this->configuration->getSources();
        $count     = count($sources);

        $logger->log("Using {$outputDir} as output directory.\n\n");

        foreach ($sources as $pinocchio) {
            $outputFile = $outputDir . '/' . $pinocchio->getOutputFilename($this->configuration->get('source'));

            $logger->log("Processing {$pinocchio->getTitle()} into {$outputFile}...");

            $formatter->format($parser->parse($pinocchio), $outputFile);

            $logger->log(" Done\n");
        }

        if (!$this->configuration->get('skipIndex')) {
            $logger->log("\nCreating index page at {$outputDir}/index.html.\n");

            $this->createIndexFile($sources, $outputDir);
        }

        $logger->log("\nFinished processing {$count} source files.\n");
    }
674034
private function setSystemConfigsCurrentApplication(){
		//verifica use_https
		if($this->getUseHttps()!='On' && $this->getUseHttps()!='Off'){
			$this->setUseHttps('Off');
		}
		//verifica use_www
		if($this->getUseWww()!='On' && $this->getUseWww()!='Off'){
			$this->setUseWww('Off');
		}
		//verifica address_uri
		if($this->getAddressUri()=='' || preg_match('/^http/', $this->getAddressUri()) || preg_match('/^www/', $this->getAddressUri())){
			throw new \Exception("setSystemConfigsCurrentApplication() Valor de address_uri deve conter a url da aplicação sem http e sem www. ex: google.com");
		}
		//define url padrão da aplicação
		$this->setPathBaseHref(($this->getUseHttps()=='On'?'https://':'http://').($this->getUseWww()=='On'?'www.':'').$this->getAddressUri());

		$tmp=explode('/', preg_replace('/^[\/]*(.*?)[\/]*$/', '\\1', $_SERVER['REQUEST_URI']));

		$k=array_search('public', $tmp);
		if($k!=''){
			unset($tmp[$k]);
		}


        if($this->getUseHttps()=='On' || (preg_match('/^www/', $this->getAddressUri()) && $this->getUseWww()=='Off') || (!preg_match('/^www/', $this->getAddressUri()) && $this->getUseWww()=='On') || $k!=''){
            if(
            	(!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on") || 
            	(preg_match('/^www/', $_SERVER["HTTP_HOST"])===1 && $this->getUseWww()=='Off') || 
            	(preg_match('/^www/', $_SERVER["HTTP_HOST"])===0 && $this->getUseWww()=='On')
            ){
               header('Location: '.($this->getUseHttps()=='On'?'https://':'http://').($this->getUseWww()=='On'?'www.':'').$this->getAddressUri()); exit;
            }
        }


	}
13440
protected function httpProcessHeaders()
    {
        $this->req->attrs->paramsDone = true;
        if (isset($this->req->attrs->server['HTTP_CONNECTION'])
            && preg_match('~(?:^|\W)Upgrade(?:\W|$)~i', $this->req->attrs->server['HTTP_CONNECTION'])
            && isset($this->req->attrs->server['HTTP_UPGRADE'])
            && (strtolower($this->req->attrs->server['HTTP_UPGRADE']) === 'websocket')
        ) {
            if ($this->pool->WS) {
                $this->pool->WS->inheritFromRequest($this->req, $this);
            }
            return false;
        }

        $this->req = Daemon::$appResolver->getRequest(
            $this->req,
            $this,
            isset($this->pool->config->responder->value) ? $this->pool->config->responder->value : null
        );

        if ($this->req instanceof \stdClass) {
            $this->endRequest($this->req, 0, 0);
            return false;
        } else {
            if ($this->pool->config->sendfile->value
                && (!$this->pool->config->sendfileonlybycommand->value || isset($this->req->attrs->server['USE_SENDFILE']))
                && !isset($this->req->attrs->server['DONT_USE_SENDFILE'])
            ) {
                $req = $this->req;

                FileSystem::tempnam(
                    $this->pool->config->sendfiledir->value,
                    $this->pool->config->sendfileprefix->value,
                    function ($fn) use ($req) {
                        FileSystem::open($fn, 'wb', function ($file) use ($req) {
                            $req->sendfp = $file;
                        });
                        $req->header('X-Sendfile: ' . $fn);
                    }
                );
            }
            $this->req->callInit();
        }
        return true;
    }