Beispiel #1
0
 /**
  * Test add header functionality on response object.
  */
 public function testAddHeaderToResponseObject()
 {
     $contentLength = rand(0, 100000);
     $this->response->addHeader(HttpProtocol::HEADER_X_POWERED_BY, 'PhpUnit');
     $this->response->addHeader(HttpProtocol::HEADER_CONTENT_TYPE, $contentLength);
     $this->assertSame('PhpUnit', $this->response->getHeader(HttpProtocol::HEADER_X_POWERED_BY));
     $this->assertSame($contentLength, $this->response->getHeader(HttpProtocol::HEADER_CONTENT_TYPE));
 }
Beispiel #2
0
 public static function parseFile(HttpResponse &$_RESPONSE, $file, array $SERVER, array &$_GET, array &$_POST, array &$_COOKIE, array &$_FILES)
 {
     global $PRISM;
     // Restore session?
     if (isset($_COOKIE['PrismSession']) && isset(self::$sessions[$_COOKIE['PrismSession']]) && self::$sessions[$_COOKIE['PrismSession']][0] > time() && self::$sessions[$_COOKIE['PrismSession']][1] == $SERVER['REMOTE_ADDR']) {
         $_SESSION = self::$sessions[$_COOKIE['PrismSession']][2];
         // Sessions only last for one request. We rewrite it later on if needed.
         unset(self::$sessions[$_COOKIE['PrismSession']]);
     }
     // Change working dir to docRoot
     chdir($PRISM->http->getDocRoot());
     $prismScriptNameHash = md5($PRISM->http->getDocRoot() . $file);
     $prismScriptMTime = filemtime($PRISM->http->getDocRoot() . $file);
     clearstatcache();
     // Run script from cache?
     if (isset(self::$scriptCache[$prismScriptNameHash]) && self::$scriptCache[$prismScriptNameHash][0] == $prismScriptMTime) {
         ob_start();
         eval(self::$scriptCache[$prismScriptNameHash][1]);
         $html = ob_get_contents();
         ob_end_clean();
     } else {
         // Validate the php file
         $parseResult = validatePHPFile($PRISM->http->getDocRoot() . $file);
         if ($parseResult[0]) {
             // Run the script from disk
             $prismPhpScript = preg_replace(array('/^<\\?(php)?/', '/\\?>$/'), '', file_get_contents($PRISM->http->getDocRoot() . $file));
             ob_start();
             eval($prismPhpScript);
             $html = ob_get_contents();
             ob_end_clean();
             // Cache the php file
             self::$scriptCache[$prismScriptNameHash] = array($prismScriptMTime, $prismPhpScript);
         } else {
             $eol = "\r\n";
             $html = '<html>' . $eol;
             $html .= '<head><title>Error parsing page</title></head>' . $eol;
             $html .= '<body bgcolor="white">' . $eol;
             $html .= '<center><h4>' . implode("<br />\r\n", $parseResult[1]) . '</h4></center>' . $eol;
             $html .= '<hr><center>PRISM v' . PHPInSimMod::VERSION . '</center>' . $eol;
             $html .= '</body>' . $eol;
             $html .= '</html>' . $eol;
             unset(self::$scriptCache[$prismScriptNameHash]);
         }
     }
     // Should we store the session?
     if (isset($_SESSION) && $_SESSION != '') {
         $sessionID = sha1(createRandomString(128, RAND_BINARY) . time());
         self::$sessions[$sessionID] = array(time() + PRISM_SESSION_TIMEOUT, $SERVER['REMOTE_ADDR'], $_SESSION);
         $_RESPONSE->setCookie('PrismSession', $sessionID, time() + PRISM_SESSION_TIMEOUT, '/', $SERVER['SERVER_NAME']);
     } else {
         if (isset($_COOKIE['PrismSession'])) {
             $_RESPONSE->setCookie('PrismSession', '', 0, '/', $SERVER['SERVER_NAME']);
         }
     }
     unset($_SESSION);
     // Restore the working dir
     chdir(ROOTPATH);
     // Use compression?
     if ($html != '' && isset($SERVER['HTTP_ACCEPT_ENCODING'])) {
         $encoding = '';
         if (strpos($SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) {
             $encoding = 'x-gzip';
         } else {
             if (strpos($SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
                 $encoding = 'gzip';
             }
         }
         if ($encoding) {
             $_RESPONSE->addHeader('Content-Encoding: ' . $encoding);
             return gzencode($html, 1);
         } else {
             return $html;
         }
     } else {
         return $html;
     }
 }
 /**
  *	Parses the raw HTTP response and returns a response object
  **/
 protected function parseResponse($output, $ch = null)
 {
     $response = new HttpResponse();
     if ($output) {
         $lines = explode("\n", $output);
         $isHeader = true;
         $buffer = array();
         foreach ($lines as $line) {
             if ($isHeader) {
                 if (preg_match('/^\\s*$/', $line)) {
                     // Header/body separator
                     $isHeader = false;
                 } else {
                     // This is a real HTTP header
                     if (preg_match('/^([^:]+)\\:(.*)$/', $line, $matches)) {
                         //echo "HEADER: [", $matches[1], ']: [', $matches[2], "]\n";
                         $name = trim($matches[1]);
                         $value = trim($matches[2]);
                         $response->addHeader($name, $value);
                     } else {
                         // This is the status response
                         //echo "HEADER: ", trim($line), "\n";
                         if (preg_match('/^(HTTP\\/\\d\\.\\d) (\\d*) (.*)$/', trim($line), $matches)) {
                             $response->setStatus($matches[2]);
                             $response->setStatusMsg($matches[3]);
                             $response->setVersion($matches[1]);
                         }
                     }
                 }
             } else {
                 $buffer[] = $line;
             }
         }
         // The buffer is the HTTP Entity Body
         $response->setBody(implode("\n", $buffer));
     } else {
         $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         if ($statusCode == 0) {
             $response->setStatus(502);
             $response->setStatusMsg('CURL Error');
         } else {
             $response->setStatus($statusCode);
             $response->setStatusMsg('CURL Response');
         }
     }
     return $response;
 }
Beispiel #4
0
 private function &serveFile()
 {
     // Serve file - we can do this using the writeFile() method, which is memory friendly
     $r = new HttpResponse($this->httpRequest->SERVER['httpVersion'], 200);
     // Cache?
     $useCache = false;
     $scriptnameHash = md5($this->http->getDocRoot() . $this->httpRequest->SERVER['SCRIPT_NAME']);
     if (isset($this->httpRequest->headers['Cache-Control']) || isset($this->httpRequest->headers['Pragma'])) {
         $ifModifiedSince = isset($this->httpRequest->headers['If-Modified-Since']) ? (int) strtotime($this->httpRequest->headers['If-Modified-Since']) : 0;
         $cacheControl = isset($this->httpRequest->headers['Cache-Control']) ? $this->httpRequest->parseHeaderValue($this->httpRequest->headers['Cache-Control']) : array();
         $pragma = isset($this->httpRequest->headers['Pragma']) ? $this->httpRequest->parseHeaderValue($this->httpRequest->headers['Pragma']) : array();
         // Detect 'If-Modified-Since' (weak) cache validator (http1.1)
         if ($ifModifiedSince > 0) {
             if (isset($this->http->cache[$scriptnameHash])) {
                 if ($this->http->cache[$scriptnameHash] == $ifModifiedSince) {
                     // File has not been changed - tell the browser to use the cache (send a 304)
                     $useCache = true;
                 }
             } else {
                 $scriptMTime = filemtime($this->http->getDocRoot() . $this->httpRequest->SERVER['SCRIPT_NAME']);
                 $this->http->cache[$scriptnameHash] = $scriptMTime;
                 if ($scriptMTime == $ifModifiedSince) {
                     // File has not been changed - tell the browser to use the cache (send a 304)
                     $useCache = true;
                 }
             }
         } else {
             if (isset($cacheControl['max-age']) && $cacheControl['max-age'] == 0 && $cacheControl != 'no-cache' && $pragma != 'no-cache' && isset($this->http->cache[$scriptnameHash])) {
                 $scriptMTime = filemtime($this->http->getDocRoot() . $this->httpRequest->SERVER['SCRIPT_NAME']);
                 if ($this->http->cache[$scriptnameHash] == $scriptMTime) {
                     // File has not been changed - tell the browser to use the cache (send a 304)
                     $useCache = true;
                 } else {
                     // File has been updated - store new mtime in cache
                     $this->http->cache[$scriptnameHash] = $scriptMTime;
                 }
                 clearstatcache();
             }
         }
     }
     if ($useCache) {
         $r->setResponseCode(304);
         $this->write($r->getHeaders());
     } else {
         $scriptMTime = filemtime($this->http->getDocRoot() . $this->httpRequest->SERVER['SCRIPT_NAME']);
         $r->addHeader('Content-Type: ' . $this->getMimeType());
         $r->addHeader('Last-Modified: ' . date('r', $scriptMTime));
         if (isset($this->httpRequest->SERVER['HTTP_RANGE'])) {
             console('HTTP_RANGE HEADER : ' . $this->httpRequest->SERVER['HTTP_RANGE']);
             $exp = explode('=', $this->httpRequest->SERVER['HTTP_RANGE']);
             $startByte = (int) substr($exp[1], 0, -1);
             $r->addHeader('Content-Length: ' . (filesize($this->http->getDocRoot() . $this->httpRequest->SERVER['SCRIPT_NAME']) - $startByte));
             $this->write($r->getHeaders());
             $this->writeFile($this->http->getDocRoot() . $this->httpRequest->SERVER['SCRIPT_NAME'], $startByte);
         } else {
             $r->addHeader('Content-Length: ' . filesize($this->http->getDocRoot() . $this->httpRequest->SERVER['SCRIPT_NAME']));
             $this->write($r->getHeaders());
             $this->writeFile($this->http->getDocRoot() . $this->httpRequest->SERVER['SCRIPT_NAME']);
         }
         // Store the filemtime in $cache
         if (!isset($this->http->cache[$scriptnameHash])) {
             $this->http->cache[$scriptnameHash] = $scriptMTime;
         }
         clearstatcache();
     }
     return $r;
 }
 /**
  * route 
  * 
  * @access public
  * @return void
  */
 public function route()
 {
     global $app;
     $controllerName = $this->_command->getControllerName();
     if (!$this->routeExists($controllerName)) {
         $controllerName = 'error';
     }
     include 'controllers/' . $controllerName . '.php';
     // Only log analytics data for non-login pages here
     if (strcasecmp($controllerName, 'login') !== 0) {
         if ($app->getConfiguration()->logAnalytics() == true) {
             $analyticsData = array();
             $analyticsData['time'] = time();
             $analyticsData['session'] = session_id();
             $analyticsData['page'] = $controllerName;
             $GLOBALS['routeLogger']->info(json_encode($analyticsData));
         }
     }
     $controllerClass = $controllerName . 'Controller';
     $controller = new $controllerClass($this->_command);
     //$controller->addPreProcessor();
     try {
         $params = $controller->getParams();
         $request = new HttpRequest($params);
         $request->parse();
         $controller->execute($request);
     } catch (MissingParamsException $mpe) {
         $response = new HttpResponse();
         $response->addHeader('HTTP/1.1 400 Bad Request');
         $response->send();
     } catch (ServiceException $sxe) {
         $response = new HttpResponse();
         $response->sendError($sxe->getMessage());
     } catch (ClientException $cxe) {
         $response = new HttpResponse();
         $response->sendError($cxe->getMessage(), $cxe->getCode());
     }
 }
 private function readHeader()
 {
     // read header
     while (($line = $this->conn->getLine()) !== null) {
         if ($line === false) {
             return $this->finish('BROKEN');
         }
         if ($line === '') {
             $this->headerOK = true;
             $this->chunkLeft = 0;
             return $this->readBody();
         }
         HttpClient::debug('read header line: ', $line);
         if (!strncmp('HTTP/', $line, 5)) {
             $line = trim(substr($line, strpos($line, ' ')));
             list($this->res->status, $this->res->statusText) = explode(' ', $line, 2);
             $this->res->status = intval($this->res->status);
         } else {
             if (!strncasecmp('Set-Cookie: ', $line, 12)) {
                 $cookie = $this->parseCookieLine($line);
                 if ($cookie !== false) {
                     $this->res->setRawCookie($cookie['name'], $cookie['value']);
                     $this->cli->setRawCookie($cookie['name'], $cookie['value'], $cookie['expires'], $cookie['domain'], $cookie['path']);
                 }
             } else {
                 list($k, $v) = explode(':', $line, 2);
                 $this->res->addHeader($k, trim($v));
             }
         }
     }
 }
Beispiel #7
0
<?php

require_once "errors.php";
require_once "Exceptions.php";
require_once "db.php";
require_once 'HttpRequest.php';
require_once 'HttpResponse.php';
require_once 'Authenticator.php';
require_once 'Router.php';
require_once 'Trips.php';
$resp = new HttpResponse();
try {
    $db = new mysqli($dbhost, $dbuser, $dbpw, $dbdb);
    $req = new HttpRequest();
    $auth = new Authenticator($db, $req);
    //the router handles all of the other stuff (loading controller etc.)
    $router = new Router($req, $resp, $db, $auth);
    $content = $router->executeRoute();
    $resp->write($content);
    $resp->flush();
} catch (Exception $e) {
    $resp->setStatus(400);
    $resp->addHeader('error', $e->getMessage());
    $resp->write('{"exception" : "' . $e->getMessage() . ' [' . $e->getFile() . '#' . $e->getLine() . ']"}');
    $resp->flush();
}