/**
  * Generates a request based on the current apache variables.
  * @throws Exception
  */
 public static function generate()
 {
     $headers = new Map(apache_request_headers());
     $method = $_SERVER['REQUEST_METHOD'];
     $path = $_SERVER['REQUEST_URI'];
     switch ($headers->get('Content-Type', null)) {
         case 'application/json':
             $data = file_get_contents('php://input');
             $values = json_decode($data, true);
             $params = new Map($values);
             break;
         case 'application/x-www-form-urlencoded':
             $params = new Map($_POST);
             break;
         default:
             if ($method === 'GET') {
                 $params = new Map($_GET);
             } else {
                 if ($method === 'POST' || $method === 'PUT') {
                     $params = new Map($_POST);
                 } else {
                     $params = new Map();
                 }
             }
             break;
     }
     return new Request($path, $method, $headers, $params);
 }
 protected function beforeAction($action)
 {
     $sql = "INSERT INTO mandrillWebhookLog SET `GET` = :GET, `POST` = :POST, `SERVER`=:SERVER, `headers` = :headers";
     $cmnd = Yii::app()->db->createCommand($sql);
     $cmnd->execute(['GET' => print_r($_GET, true), 'POST' => print_r($_POST, true), 'SERVER' => print_r($_SERVER, true), 'headers' => print_r(apache_request_headers(), true)]);
     return parent::beforeAction($action);
 }
Example #3
0
 /**
  * Return array of HTTP headers from the current request
  * @return array|false
  */
 public static function getHeaders()
 {
     if (self::$headers === null) {
         if (function_exists('apache_request_headers')) {
             $headers = apache_request_headers();
         } else {
             $headers = array();
             if (isset($_SERVER['CONTENT_TYPE'])) {
                 $headers['Content-Type'] = $_SERVER['CONTENT_TYPE'];
             }
             if (isset($_ENV['CONTENT_TYPE'])) {
                 $headers['Content-Type'] = $_ENV['CONTENT_TYPE'];
             }
             foreach ($_SERVER as $key => $value) {
                 if (substr($key, 0, 5) == "HTTP_") {
                     // this is chaos, basically it is just there to capitalize the first
                     // letter of every word that is not an initial HTTP and strip HTTP
                     // code from przemek
                     $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
                     $headers[$key] = $value;
                 }
             }
         }
         self::$headers = $headers;
     }
     return self::$headers;
 }
Example #4
0
function get_if_none_match()
{
    $headers = apache_request_headers();
    if (isset($headers["If-None-Match"])) {
        return $headers["If-None-Match"];
    }
}
 private function fromRequestHeaders(Request $request)
 {
     $header = null;
     if (!$request->headers->has('authorization')) {
         // The Authorization header may not be passed to PHP by Apache;
         // Trying to obtain it through apache_request_headers()
         if (function_exists('apache_request_headers')) {
             $headers = apache_request_headers();
             if (is_array($headers)) {
                 // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
                 $headers = array_combine(array_map('ucwords', array_keys($headers)), array_values($headers));
                 if (isset($headers['Authorization'])) {
                     $header = $headers['Authorization'];
                 }
             }
         }
     } else {
         $header = $request->headers->get('authorization');
     }
     if (!$header) {
         return null;
     }
     if (!preg_match('/' . preg_quote('Bearer', '/') . '\\s(\\S+)/', $header, $matches)) {
         return null;
     }
     $token = $matches[1];
     return $token;
 }
Example #6
0
 /**
  * Calls the execute method, passing the raw post data, after setting up CORS
  */
 public function run()
 {
     $headers = apache_request_headers();
     if (count($this->corsHosts)) {
         $origin = false;
         if (isset($headers['Origin'])) {
             $origin = $headers['Origin'];
         } elseif (isset($headers['Referer'])) {
             $parts = parse_url($headers['Referer']);
             $origin = sprintf('%s://%s', isset($parts['scheme']) ? $parts['scheme'] : 'http', $parts['host']);
         }
         if ($origin) {
             $this->setCorsOrigin($origin);
         }
     }
     $contents = file_get_contents('php://input');
     $request = new Request($contents);
     $response = $this->execute($request);
     if ($response->code != 200) {
         header('HTTP/1.0 ' . $response->code, true, $response->code);
     }
     if (isset($response->contentType)) {
         header('Content-Type: ' . $response->contentType);
     }
     if (isset($response->headers)) {
         foreach ($response->headers as $header => $value) {
             header($header . ': ' . $value);
         }
     }
     if (isset($response->content)) {
         echo $response->content;
     }
 }
function api_auth_oauth2_get_access_token(&$method)
{
    # https://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-20#section-2.1
    $require_header = $GLOBALS['cfg']['api_oauth2_require_authentication_header'];
    $check_header = $GLOBALS['cfg']['api_oauth2_check_authentication_header'];
    if ($require_header || $check_header) {
        $headers = apache_request_headers();
        $token = null;
        if (!isset($headers['authorization'])) {
            if ($require_header) {
                return null;
            }
        } else {
            if (preg_match("/Bearer\\s+([a-zA-Z0-9\\+\\/\\=]+)\$/", $headers['authorization'], $m)) {
                $token = $m[1];
                $token = base64_decode($token);
            }
        }
        if ($token || $require_header) {
            return $token;
        }
    }
    if ($GLOBALS['cfg']['api_oauth2_allow_get_parameters']) {
        return request_str('access_token');
    }
    return post_str('access_token');
}
 public function cleantalk_get_real_ip()
 {
     if (function_exists('apache_request_headers')) {
         $headers = apache_request_headers();
     } else {
         $headers = $_SERVER;
     }
     if (array_key_exists('X-Forwarded-For', $headers)) {
         $the_ip = explode(",", trim($headers['X-Forwarded-For']));
         $the_ip = trim($the_ip[0]);
         $this->ip_str_array[] = $the_ip;
         $this->ip_array[] = sprintf("%u", ip2long($the_ip));
     }
     if (array_key_exists('HTTP_X_FORWARDED_FOR', $headers)) {
         $the_ip = explode(",", trim($headers['HTTP_X_FORWARDED_FOR']));
         $the_ip = trim($the_ip[0]);
         $this->ip_str_array[] = $the_ip;
         $this->ip_array[] = sprintf("%u", ip2long($the_ip));
     }
     $the_ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
     $this->ip_str_array[] = $the_ip;
     $this->ip_array[] = sprintf("%u", ip2long($the_ip));
     if (isset($_GET['sfw_test_ip'])) {
         $the_ip = $_GET['sfw_test_ip'];
         $this->ip_str_array[] = $the_ip;
         $this->ip_array[] = sprintf("%u", ip2long($the_ip));
     }
     //$this->ip_str=$the_ip;
     //$this->ip=sprintf("%u", ip2long($the_ip));
     //print sprintf("%u", ip2long($the_ip));
 }
Example #9
0
 public function fromGlobals()
 {
     global $argv;
     $this->params(isset($argv) ? $argv : []);
     $this->servers($_SERVER);
     $this->protocol(strtoupper($this->server('SERVER_PROTOCOL')));
     $this->method(strtoupper($this->server('REQUEST_METHOD')));
     foreach ($this->servers() as $name => $value) {
         if (preg_match('/^HTTP_(.*)$/', $name, $match)) {
             $this->header(str_replace('_', '-', $match[1]), $value);
         }
     }
     if (function_exists('apache_request_headers')) {
         foreach (apache_request_headers() as $name => $value) {
             $this->header($name, $value);
         }
     }
     $this->scheme($this->server('HTTPS') == 'on' ? self::SCHEME_HTTPS : self::SCHEME_HTTP);
     $this->host($this->server('SERVER_NAME'));
     $this->port($this->server('SERVER_PORT'));
     list($full) = explode('?', $this->server('REQUEST_URI'));
     $path = isset($_GET['_']) ? $_GET['_'] : ltrim($full, '/');
     $full = explode('/', $full);
     $path = explode('/', $path);
     $base = array_slice($full, 0, count($full) - count($path));
     $this->base(implode('/', $base) . '/');
     $this->path(implode('/', $path));
     $this->queryParams($this->_clean($_GET));
     $this->bodyParams(\Coast\array_merge_smart($this->_clean($_POST), $this->_restructure($_FILES)));
     $this->body(file_get_contents('php://input'));
     $this->cookies($_COOKIE);
     return $this;
 }
Example #10
0
 public function register(Container $container)
 {
     $oauthDataStore = new TestDataStore();
     $oauthServer = new Server($oauthDataStore);
     $oauthServer->add_signature_method(new SignatureHmacSha1());
     $container['app']->before(function (Request $request) use($oauthServer) {
         // Construct the full URL including port
         // This will be normalized by the OAuthRequest class
         $url = ($request->isSecure() ? 'https' : 'http') . '://' . $request->getHost() . ':' . $request->getPort() . $request->getPathInfo();
         $method = $request->getMethod();
         // The request parameters are collected as follows:
         // 1. GET parameters from the URL query string
         // 2. Request body parameters (only for requests with Content-Type of application/x-www-form-urlencoded)
         // 3. Parameters in the OAuth HTTP Authorization header
         // The parameters are filtered, sorted and concatenated by the OAuth\Request class
         $params = $request->query->all();
         if ($method == 'POST' && $request->headers->has('Content-Type') && $request->headers->get('Content-Type') == 'application/x-www-form-urlencoded') {
             $bodyParams = Util::parse_parameters($request->getContent());
             $params = array_merge($params, $bodyParams);
         }
         // Authorization header is excluded from Symfony Request object
         // Therefore need to look at Apache headers directly
         $apacheHeaders = apache_request_headers();
         if (isset($apacheHeaders['Authorization']) && substr($apacheHeaders['Authorization'], 0, 6) == 'OAuth ') {
             $authParams = Util::split_header($apacheHeaders['Authorization']);
             $params = array_merge($params, $authParams);
         }
         $oauthRequest = new Request($method, $url, $params);
         $oauthServer->verify_request($oauthRequest);
     });
 }
Example #11
0
function process_cache($expire = 300, $arrVary = array())
{
    if ($_COOKIE['debug']) {
        return;
    }
    $headers = apache_request_headers();
    $client_time = isset($headers['If-Modified-Since']) ? strtotime($headers['If-Modified-Since']) : 0;
    $now = time();
    //$now=gmmktime();
    $now_list = time() - $expire;
    //$now_list=gmmktime()-$expire;
    /*http cache for SQ*/
    if ($arrVary) {
        header('Vary: ' . implode(', ', $arrVary));
        foreach ($arrVary as $k => $v) {
            header("{$k}: {$v}");
        }
    }
    if ($client_time < $now and $client_time > $now_list) {
        header('Cache-Control: public');
        header('Pragma: public');
        header('Expires: ' . gmdate('D, d M Y H:i:s', $client_time + $expire) . ' GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $client_time) . ' GMT', true, 304);
        exit(0);
    } else {
        header('Cache-Control: public');
        header('Pragma: public');
        header('Expires: ' . gmdate('D, d M Y H:i:s', $now + $expire) . ' GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $now) . ' GMT', true, 200);
    }
}
Example #12
0
function personaConectada()
{
    $header = apache_request_headers();
    $c = new Conexion();
    $conectado = $c->bd->usuario()->select("persona.id")->where("api_key:api_key=?", $header['API_KEY'])->fetch();
    return $conectado["id"];
}
Example #13
0
function checkToken($mysqli, $phone)
{
    $headers = apache_request_headers();
    //var_dump($headers);
    $data = explode(":", $headers['Token']);
    $token = $headers['Token'];
    $status = $data[1];
    if ($phone == "" or $token == "") {
        $output_arr["id"] = 601;
        $output_arr["name"] = "Not all parameters set";
        return $output_arr;
    }
    $sql = "SELECT phone FROM Tokens WHERE phone={$phone} AND token='{$token}'";
    $result = $mysqli->query($sql);
    $myrow = db2Array($result);
    if (!$myrow[0]['phone']) {
        $output_arr["id"] = 607;
        $output_arr["name"] = "Invalid TOKEN or PHONE";
        return $output_arr;
    } else {
        $data['status'] = $status;
        $data['token'] = $token;
        return $data;
    }
}
Example #14
0
 public static function getUsuario()
 {
     $headers = apache_request_headers();
     $token = explode(" ", $headers["Authorization"]);
     $usuario = JWT::decode(trim($token[1], '"'), "complejodeportivo", 'HS256');
     return $usuario;
 }
 public function verifyAndHandleRequest()
 {
     try {
         $headerBearerToken = NULL;
         $queryBearerToken = NULL;
         // look for headers
         if (function_exists("apache_request_headers")) {
             $headers = apache_request_headers();
         } elseif (isset($_SERVER)) {
             $headers = $_SERVER;
         } else {
             $headers = array();
         }
         // look for query parameters
         $query = isset($_GET) && is_array($_GET) ? $_GET : array();
         return $this->verifyRequest($headers, $query);
     } catch (RemoteResourceServerException $e) {
         // send response directly to client, halt execution of calling script as well
         $e->setRealm($this->_getConfigParameter("realm", FALSE, "Resource Server"));
         header("HTTP/1.1 " . $e->getResponseCode());
         if (NULL !== $e->getAuthenticateHeader()) {
             // for "internal_server_error" responses no WWW-Authenticate header is set
             header("WWW-Authenticate: " . $e->getAuthenticateHeader());
         }
         header("Content-Type: application/json");
         die($e->getContent());
     }
 }
Example #16
0
/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
function authenticate(\Slim\Route $route)
{
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();
    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        $db = new DBHandler();
        // get the api key
        $apikey = $headers['Authorization'];
        // validating api key
        if (!$db->isValidApiKey($apikey)) {
            // api key is not present in users table
            $response["error"] = true;
            $response["message"] = "Zugriff verweigert! Falscher API-Key!";
            echoRespnse(401, $response);
            $app->stop();
        } else {
            global $userid;
            // get user primary key id
            $user = $db->getUserId($apikey);
            if ($user != NULL) {
                $userid = $user;
            }
        }
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Zugriff verweigert! API-Key fehlt!";
        echoRespnse(400, $response);
        $app->stop();
    }
}
Example #17
0
function checkSecurity()
{
    $requestHeaders = apache_request_headers();
    $authorizationHeader = $requestHeaders['Authorization'];
    //    echo print_r(apache_request_headers());
    if ($authorizationHeader == null) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
    // // validate the token
    $pre_token = str_replace('Bearer ', '', $authorizationHeader);
    $token = str_replace('"', '', $pre_token);
    $secret = 'uiglp';
    global $decoded_token;
    try {
        $decoded_token = JWT::decode($token, base64_decode(strtr($secret, '-_', '+/')), false);
        //        $decoded_token = JWT::decode($token, 'uiglp');
    } catch (UnexpectedValueException $ex) {
        header('HTTP/1.0 401 Unauthorized');
        echo "Invalid token";
        exit;
    }
    // // validate that this token was made for us
    if ($decoded_token->aud != 'uiglp') {
        header('HTTP/1.0 401 Unauthorized');
        echo "Invalid token";
        exit;
    }
}
Example #18
0
 function index()
 {
     $fn = substr($this->uri->uri_string(), 1);
     if (file_exists($fn)) {
         if (function_exists('apache_request_headers')) {
             $headers = apache_request_headers();
         }
         // Checking if the client is validating his cache and if it is current.
         if (isset($headers['If-Modified-Since']) && strtotime($headers['If-Modified-Since']) == filemtime($fn)) {
             // Client's cache IS current, so we just respond '304 Not Modified'.
             header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($fn)) . ' GMT', true, 304);
         } else {
             // Image not cached or cache outdated, we respond '200 OK' and output the image.
             header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($fn)) . ' GMT', true, 200);
             header('Content-Length: ' . filesize($fn));
             $this->load->helper('file');
             $mime = get_mime_by_extension($fn);
             header('Content-Type: $mime');
             print file_get_contents($fn);
         }
     } else {
         $this->output->set_header("HTTP/1.0 404 Not Found");
         echo "Not found";
     }
 }
Example #19
0
/**
 * @description Valida que el rol del usuario sea el correcto
 * @param $requerido
 */
function validateRol($requerido)
{
    global $jwt_enabled;
    if ($jwt_enabled == false) {
        return;
    }
    $requestHeaders = apache_request_headers();
    $authorizationHeader = isset($requestHeaders['Authorization']) ? $requestHeaders['Authorization'] : null;
    //    echo print_r(apache_request_headers());
    if ($authorizationHeader == null) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
    // // validate the token
    $pre_token = str_replace('Bearer ', '', $authorizationHeader);
    $token = str_replace('"', '', $pre_token);
    global $secret;
    global $decoded_token;
    $decoded_token = JWT::decode($token, $secret, true);
    $rol = $decoded_token->data->rol;
    if ($rol > $requerido) {
        header('HTTP/1.0 401 Unauthorized');
        echo "No authorization header sent";
        exit;
    }
}
Example #20
0
/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
function authenticate(\Slim\Route $route)
{
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();
    // Verifying Authorization Header
    //    if (isset($headers['Authorization'])) {
    $db = new DbHandler();
    // get the api key
    //$api_key = $headers['Authorization'];
    // validating api key
    if ($_SESSION['user_id'] == 0) {
        // api key is not present in users table
        $response["error"] = true;
        $response["message"] = "Access Denied. Invalid session";
        echoRespnse(401, $response);
        $app->stop();
    } else {
        // get user primary key id
        $user_id = $_SESSION['user_id'];
    }
    //    } else {
    //        // api key is missing in header
    //        $response["error"] = true;
    //        $response["message"] = "Api session is misssing";
    //        echoRespnse(400, $response);
    //        $app->stop();
    //    }
}
Example #21
0
 function __construct()
 {
     parent::__construct();
     $this->load->library('uri');
     $this->load->helper('file');
     $segments = $this->uri->segment_array();
     array_shift($segments);
     $path = APPPATH . '../assets';
     foreach ($segments as $segment) {
         $path .= '/' . $segment;
     }
     if (realpath($path) !== false) {
         $data = read_file($path);
         if (php_sapi_name() == 'apache2handler' || php_sapi_name() == 'apache') {
             $headers = apache_request_headers();
             if (isset($headers['If-Modified-Since']) && !empty($headers['If-Modified-Since'])) {
                 header('Not Modified', true, 304);
                 exit;
             }
         }
         header('Content-Type: ' . get_mime_by_extension(basename($path)));
         header('Cache-Control: max-age=3600, must-revalidate');
         header('Last-Modified: ' . standard_date('DATE_COOKIE', filemtime($path)));
         echo $data;
         exit;
     } else {
         show_error('Asset does not exist in repository.', 404);
     }
 }
Example #22
0
 /**
  * Parses the the HTTP request headers and returns an array containing
  * key value pairs. This method is slow, but provides an accurate
  * representation of the HTTP request.
  *
  *      // Get http headers into the request
  *      $request->headers = HTTP::request_headers();
  *
  * @return  HTTP_Header
  */
 public static function request_headers()
 {
     // If running on apache server
     if (function_exists('apache_request_headers')) {
         // Return the much faster method
         return new HTTP_Header(apache_request_headers());
     } elseif (extension_loaded('http')) {
         // Return the much faster method
         return new HTTP_Header(http_get_request_headers());
     }
     // Setup the output
     $headers = array();
     // Parse the content type
     if (!empty($_SERVER['CONTENT_TYPE'])) {
         $headers['content-type'] = $_SERVER['CONTENT_TYPE'];
     }
     // Parse the content length
     if (!empty($_SERVER['CONTENT_LENGTH'])) {
         $headers['content-length'] = $_SERVER['CONTENT_LENGTH'];
     }
     foreach ($_SERVER as $key => $value) {
         // If there is no HTTP header here, skip
         if (strpos($key, 'HTTP_') !== 0) {
             continue;
         }
         // This is a dirty hack to ensure HTTP_X_FOO_BAR becomes x-foo-bar
         $headers[str_replace(array('HTTP_', '_'), array('', '-'), $key)] = $value;
     }
     return new HTTP_Header($headers);
 }
Example #23
0
 /**
  * Lets the browser render an image file
  * @param String $path The path to the image file
  * @param String $timestamp Cache timestamp - if not provided, this will have to be found out (at the cost of disk access)
  * @param String $mime The image mimetype - if not provided, this will have to be found out (at the cost of disk access)
  * @return Void
  */
 public function show($path, $timestamp = null, $mime = null)
 {
     $headers = function_exists('apache_request_headers') ? apache_request_headers() : array();
     if (is_null($timestamp)) {
         $timestamp = $this->_readTimestampFromFile($path);
     }
     if (is_null($mime)) {
         $mime = $this->_readMimeTypeFromFile($path);
     }
     header("Content-Type: {$mime}");
     header("Cache-Control: maxage=" . 24 * 60 * 60 . ', must-revalidate');
     //In seconds
     header("Pragma: public");
     // Checking if the client is validating his cache and if it is current.
     if (isset($headers['If-Modified-Since']) && strtotime($headers['If-Modified-Since']) == $timestamp) {
         // Client's cache IS current, so we just respond '304 Not Modified'.
         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $timestamp) . ' GMT', true, 304);
     } else {
         // Image not cached or cache outdated, we respond '200 OK' and output the image.
         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $timestamp) . ' GMT', true, 200);
         header('Content-Length: ' . filesize($path));
         $resource = fopen($path, 'rb');
         rewind($resource);
         fpassthru($resource);
         fclose($resource);
     }
 }
 /**
  * Serve a webdav request
  *
  * @access public
  * @param  string  
  */
 function ServeRequest($base = false)
 {
     // special treatment for litmus compliance test
     // reply on its identifier header
     // not needed for the test itself but eases debugging
     foreach (apache_request_headers() as $key => $value) {
         if (stristr($key, "litmus")) {
             error_log("Litmus test {$value}");
             header("X-Litmus-reply: " . $value);
         }
     }
     // set root directory, defaults to webserver document root if not set
     if ($base) {
         $this->base = realpath($base);
         // TODO throw if not a directory
     } else {
         if (!$this->base) {
             $this->base = $_SERVER['DOCUMENT_ROOT'];
         }
     }
     // establish connection to property/locking db
     mysql_connect($this->db_host, $this->db_user, $this->db_passwd) or die(mysql_error());
     mysql_select_db($this->db_name) or die(mysql_error());
     // TODO throw on connection problems
     // let the base class do all the work
     parent::ServeRequest();
 }
Example #25
0
function getHTTPUser()
{
    // This code is copied from phpMyID. Thanks to the phpMyID dev(s).
    if (function_exists('apache_request_headers') && ini_get('safe_mode') == false) {
        $arh = apache_request_headers();
        $hdr = $arh['Authorization'];
    } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
        $hdr = $_SERVER['PHP_AUTH_DIGEST'];
    } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $hdr = $_SERVER['HTTP_AUTHORIZATION'];
    } elseif (isset($_ENV['PHP_AUTH_DIGEST'])) {
        $hdr = $_ENV['PHP_AUTH_DIGEST'];
    } elseif (isset($_REQUEST['auth'])) {
        $hdr = stripslashes(urldecode($_REQUEST['auth']));
    } else {
        $hdr = null;
    }
    $digest = substr($hdr, 0, 7) == 'Digest ' ? substr($hdr, strpos($hdr, ' ') + 1) : $hdr;
    if (!is_null($digest)) {
        $hdr = array();
        preg_match_all('/(\\w+)=(?:"([^"]+)"|([^\\s,]+))/', $digest, $mtx, PREG_SET_ORDER);
        foreach ($mtx as $m) {
            if ($m[1] == "username") {
                return $m[2] ? $m[2] : str_replace("\\\"", "", $m[3]);
            }
        }
    }
    return $_SERVER['PHP_AUTH_USER'];
}
Example #26
0
 /**
  * Observer post dispatching
  * 
  * @param Varien_Event_Observer $event
  */
 public function postdispatch(Varien_Event_Observer $event)
 {
     /* @var $controller Mage_Core_Controller_Varien_Action */
     $controller = $event->getControllerAction();
     if (!$controller->getRequest()->getHeader('X-Requested-With')) {
         return;
     }
     $param = array();
     if (function_exists('apache_request_headers')) {
         $headers = apache_request_headers();
     } elseif (function_exists('getallheader')) {
         $headers = getallheader();
     } else {
         $headers = $_SERVER;
     }
     foreach ($headers as $headerName => $headerValue) {
         $headerName = strtolower($headerName);
         if (!preg_match('/pascalsystem(.*)/', $headerName, $regs)) {
             continue;
         }
         $param[str_replace('_', '.', $regs[1])] = $headerValue;
     }
     //orginal magento ajax request
     if (!count($param)) {
         return;
     }
     $layout = Mage::app()->getLayout();
     $blocks = array();
     foreach ($param as $blockName => $selector) {
         $temp = $layout->getBlock($blockName);
         $blocks[$blockName] = array('selector' => $selector, 'html' => $temp ? $temp->toHtml() : '');
     }
     echo json_encode($blocks);
     exit;
 }
Example #27
0
function authenticate(\Slim\Route $route)
{
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();
    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        $db = new UserDbHandler();
        // get the api key
        $api_key = $headers['Authorization'];
        // validating api key
        if (!$db->isValidApiKey($api_key)) {
            // api key is not present in users table
            $response["error"] = true;
            $response["message"] = "Access Denied. Invalid Api key";
            echoResponse(401, $response);
            $app->stop();
        } else {
            global $user_id;
            // get user primary key id
            $user = $db->getUserId($api_key);
            if ($user != NULL) {
                $user_id = $user["id"];
            }
        }
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Api key is misssing";
        echoResponse(400, $response);
        $app->stop();
    }
}
Example #28
0
 /**
  * Return the value of the given HTTP header. Pass the header name as the
  * plain, HTTP-specified header name. Ex.: Ask for 'Accept' to get the
  * Accept header, 'Accept-Encoding' to get the Accept-Encoding header.
  *
  * @param string HTTP header name
  * @return string|false HTTP header value, or false if not found
  * @throws Zend_Controller_Request_Exception
  */
 public function getHeader($header)
 {
     if (empty($header)) {
         require_once 'Zend/Controller/Request/Exception.php';
         throw new Zend_Controller_Request_Exception('An HTTP header name is required');
     }
     // Try to get it from the $_SERVER array first
     $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
     if (!empty($_SERVER[$temp])) {
         return $_SERVER[$temp];
     }
     // Try to get it from the $_SERVER array first
     $temp = 'REDIRECT_HTTP_' . strtoupper(str_replace('-', '_', $header));
     if (!empty($_SERVER[$temp])) {
         return $_SERVER[$temp];
     }
     // This seems to be the only way to get the Authorization header on
     // Apache
     if (function_exists('apache_request_headers')) {
         $headers = apache_request_headers();
         if (!empty($headers[$header])) {
             return $headers[$header];
         }
     }
     return false;
 }
Example #29
0
function apache_request_headers_()
{
    if (!function_exists('apache_request_headers')) {
        return default_request_headers_();
    }
    return apache_request_headers();
}
Example #30
0
 /**
  * Creates an request from the current call
  *
  * @return common_http_Request
  * @throws common_exception_Error
  */
 public static function currentRequest()
 {
     if (php_sapi_name() == 'cli') {
         throw new common_exception_Error('Cannot call ' . __FUNCTION__ . ' from command line');
     }
     $scheme = !isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on" ? 'http' : 'https';
     $url = $scheme . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
     $method = $_SERVER['REQUEST_METHOD'];
     if ($_SERVER['REQUEST_METHOD'] == self::METHOD_GET) {
         $params = $_GET;
     } else {
         $params = $_POST;
     }
     if (function_exists('apache_request_headers')) {
         $headers = apache_request_headers();
     } else {
         $headers = array();
         if (isset($_SERVER['CONTENT_TYPE'])) {
             $headers['Content-Type'] = $_SERVER['CONTENT_TYPE'];
         }
         if (isset($_ENV['CONTENT_TYPE'])) {
             $headers['Content-Type'] = $_ENV['CONTENT_TYPE'];
         }
         foreach ($_SERVER as $key => $value) {
             if (substr($key, 0, 5) == "HTTP_") {
                 // this is chaos, basically it is just there to capitalize the first
                 // letter of every word that is not an initial HTTP and strip HTTP
                 // code from przemek
                 $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
                 $headers[$key] = $value;
             }
         }
     }
     return new self($url, $method, $params, $headers);
 }