public function render() { $mime = $this->_getMimetype(); $contents = $this->FS->read($this->path); $this->httpResponse->setCacheable(); $this->httpResponse->addHeader("content-type: {$mime};charset=utf-8"); $this->httpResponse->setContent($contents); $this->httpResponse->send(); }
public function mEditMascota($mascota) { try { if (is_array($mascota)) { $mascota = (object) $mascota; } //print_r($mascota);die; $mascotaData = $this->find($mascota->uuid); $mascotaData->UUID_mascota = $mascota->uuid; $mascotaData->nombre = strip_tags($mascota->nombre); $mascotaData->UUID_clase_mascota = strip_tags($mascota->clase_mascota); $mascotaData->UUID_raza = strip_tags($mascota->raza); $mascotaData->description = strip_tags($mascota->description); $mascotaData->edad = strip_tags($mascota->edad); $mascotaData->sexo = strip_tags($mascota->sexo); $mascotaData->datos_adicionales = strip_tags($mascota->datos); $mascotaData->caracter = $mascota->caracter; $mascotaData->tiene_vacunas = $mascota->tiene_vacunas; $mascotaData->vacunas_cuales = $mascota->vacunas_cuales; $mascotaData->peso = $mascota->peso; $mascotaData->tamano = $mascota->tamano; $mascotaData->padre = $mascota->padre; $mascotaData->certificado = $mascota->certificado; if ($mascotaData->save()) { return HTTPResponse::response(0, 201); } } catch (exception $e) { return HTTPResponse::response(1, 500); } }
function __construct($code, $uri) { parent::__construct($code); $scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http'; $server = $_SERVER['SERVER_NAME']; header("Location: {$scheme}://{$server}{$uri}"); }
public function getNestedController() { if($this->urlParams['URLSegment']) { $SQL_URLSegment = Convert::raw2sql($this->urlParams['URLSegment']); $child = SiteTree::get_by_url($SQL_URLSegment); if(!$child) { if($child = $this->findOldPage($SQL_URLSegment)) { $url = Controller::join_links( Director::baseURL(), $child->URLSegment, $this->urlParams['Action'], $this->urlParams['ID'], $this->urlParams['OtherID'] ); $response = new HTTPResponse(); $response->redirect($url, 301); return $response; } $child = $this->get404Page(); } if($child) { if(isset($_REQUEST['debug'])) Debug::message("Using record #$child->ID of type $child->class with URL {$this->urlParams['URLSegment']}"); $controllerClass = "{$child->class}_Controller"; if($this->urlParams['Action'] && ClassInfo::exists($controllerClass.'_'.$this->urlParams['Action'])) { $controllerClass = $controllerClass.'_'.$this->urlParams['Action']; } if(ClassInfo::exists($controllerClass)) { $controller = new $controllerClass($child); } else { $controller = $child; } return $controller; } else { return new HTTPResponse("The requested page couldn't be found.",404); } } else { user_error("ModelAsController not geting a URLSegment. It looks like the site isn't redirecting to home", E_USER_ERROR); } }
/** * Envoyer la reponse HTTP. */ public function send() { //On definit le contenu de la reponse $this->contents = json_encode($this->responses, JSON_FORCE_OBJECT); $this->addHeader('Content-type: application/json; charset=utf-8'); //On va renvoyer du JSON parent::send(); //On envoie la reponse }
function flush() { $ts = !$this->getLastBuildDate() ? time() : $this->getLastBuildDate(); HTTPResponse::setLastModified($ts); $ctype = preg_match('/Mozilla/i', $_SERVER['USER_AGENT']) ? 'text/xml' : 'application/rss+xml'; header('Content-Type: ' . $ctype . '; charset="' . $this->CharSet . '"', true); $this->stream = new StdOutWriter(false); $this->compile(); $this->stream->dispose(); }
/** * @see HTTPRequest::execute() */ public function execute($path = '/', $method = HTTPRequestMethod::GET) { $targetURL = $this->httpConnection->getURI() . $path; $hasParameters = count($this->requestParameter) > 0; $query = $hasParameters ? http_build_query($this->requestParameter) : null; switch ($method) { case HTTPRequestMethod::PUT: case HTTPRequestMethod::POST: if ($method != HTTPRequestMethod::POST) { curl_setopt($this->curlResource, CURLOPT_CUSTOMREQUEST, $method); } else { curl_setopt($this->curlResource, CURLOPT_POST, 1); } if (empty($this->requestBody)) { curl_setopt($this->curlResource, CURLOPT_POSTFIELDS, $query); } else { if ($hasParameters) { $targetURL .= '?' . $query; } curl_setopt($this->curlResource, CURLOPT_POSTFIELDS, $this->requestBody); } curl_setopt($this->curlResource, CURLOPT_URL, $targetURL); break; case HTTPRequestMethod::DELETE: case HTTPRequestMethod::HEAD: case HTTPRequestMethod::OPTIONS: case HTTPRequestMethod::TRACE: curl_setopt($this->curlResource, CURLOPT_CUSTOMREQUEST, $method); case HTTPRequestMethod::GET: if ($hasParameters) { $targetURL .= '?' . $query; } curl_setopt($this->curlResource, CURLOPT_URL, $targetURL); break; default: throw new UnexpectedValueException('Método desconhecido'); } $resp = curl_exec($this->curlResource); $errno = curl_errno($this->curlResource); $error = curl_error($this->curlResource); if ($errno != 0) { throw new RuntimeException($error, $errno); } $this->httpResponse = new HTTPResponse(); $this->httpResponse->setRawResponse($resp); if ($this->httpResponse->hasResponseHeader('Set-Cookie')) { $cookieManager = $this->httpConnection->getCookieManager(); if ($cookieManager != null) { $cookieManager->setCookie($this->httpResponse->getHeader('Set-Cookie'), $this->httpConnection->getHostName()); } } $statusCode = $this->httpResponse->getStatusCode(); return $statusCode < 400; }
private static function autoconnect() { $cookie = self::$request->get_cookie(self::$AUTOCONNECT_COOKIE_NAME); $user_id = AutoConnectData::get_user_id_from_cookie($cookie); if ($user_id != Session::VISITOR_SESSION_ID) { return SessionData::create_from_user_id($user_id); } else { self::$response->delete_cookie(self::$AUTOCONNECT_COOKIE_NAME); return self::create_visitor(); } }
public function getNestedController() { $url = $this->request->getUrl(); $getVars = $this->request->getVars(); if(isset($getVars['url'])) unset($getVars['url']); if($getVars) $url .= '?' . http_build_query($getVars); if($url) { $SQL_URLSegment = Convert::raw2sql($url); $page = DataObject::get_one( 'Page', "`SiteTree`.LegacyURL = '{$SQL_URLSegment}'" ); if($page) { $response = new HTTPResponse(); $newUrl = Director::baseURL() . $page->URLSegment; $response->redirect($newUrl, 301); return $response; } } return parent::getNestedController(); }
/** * Envoyer la reponse HTTP. */ public function send() { //On arrete la temporisation de sortie if (ob_get_level() > 0) { ob_end_flush(); } //On definit le contenu de la reponse $this->contents = json_encode(array('success' => $this->success, 'channels' => $this->channels, 'out' => $this->out, 'data' => $this->data, 'js' => $this->js), JSON_FORCE_OBJECT); $this->addHeader('Content-type: application/json; charset=utf-8'); //On va renvoyer du JSON parent::send(); //On envoie la reponse }
/** * Stops the server cleanly. * * @access public * @return void */ public function stop() { if (strpos($this->request->get_remote_ip(), '127.0.0.') === 0) { // Send back a success message. We may not be successful, but this is our // last chance to send anything. $response = new HTTPResponse(200); $response->set_body('Server shut down.'); $this->write($response); // Close all listeners. $this->dispatcher->close_listeners(); // Stop the server loop. $this->dispatcher->get_server()->stop(time() - 1); } }
public function post_register() { session_start(); $this->data = Input::all(); $emailExist = $this->connection->mVerifyEmail($this->data["email"]); try { if (!$emailExist) { $this->data["UUID"] = UUID::getUUID(); if ($this->connection->mSave($this->data)) { //logea al usuario despues de ser registrado $user = $this->connection->mUserByEmail($this->data["email"]); //print_r($user);die; //print_r($this->data);die; try { $client = new Client(); $r = $client->post('http://dev.petmatch.club/email.php', ["body" => $this->data]); $r->getBody(); } catch (exception $e) { echo $e; } //$email = new Email(); //$email->sendEmail($this->data["email"],$this->data["nombre"]); /*$credentials = array( "email" => $this->data["email"], "password" => $this->data["password"] ); if (Auth::attempt($credentials)) { $_SESSION["email"] = $this->data["email"]; }*/ return HTTPResponse::response(0, 201); } } else { return json_encode(array("error" => 1, "message" => $this->data["email"] . " ya existe", "status" => 200)); } } catch (exception $e) { echo HTTPResponse::response(1, 500); } }
/** * Writes the background contents to the response. * * @access public * @param resource $socket * @param integer $ioevent * @param resource $process * @param boolean $split_headers * @return void */ public function background_write($socket, $ioevent, $process, $split_headers = false) { $attempts = 0; $chunk = ''; while ($tmp = @fread($socket, IOStream::MAX_BUFFER_SIZE)) { $chunk .= $tmp; } if (empty($chunk) && empty($this->_background_content)) { // Write an error response. $response = new HTTPResponse(500); $response->set_body('Trouble generating content.'); } else { $this->_background_content .= $chunk; // Check to see if the process has finished. $info = proc_get_status($process); if (!$info['running']) { // Make sure the proccess finished successfully. if ($info['exitcode'] !== 0) { $response = new HTTPResponse(500); } else { $response = new HTTPResponse($this->status); $config = $this->dispatcher->get_config(); $headers = array('Content-Type' => $this->_mime, 'Date' => date('D, d M Y H:i:s \\G\\M\\T'), 'Expires' => date('D, d M Y H:i:s \\G\\M\\T', time() + $config['CACHE_EXPIRATION']), 'Last-Modified' => date('D, d M Y H:i:s \\G\\M\\T', filemtime($this->_path)), 'Cache-Control' => 'max-age=' . $config['CACHE_EXPIRATION']); $response->add_headers($headers); } if ($split_headers) { // Split the chunk into headers and content. list($headers, $content) = explode("\r\n\r\n", $this->_background_content, 2); // Set the headers. foreach (explode("\r\n", $headers) as $header) { list($h, $v) = explode(':', $header); $response->add_header($h, trim($v)); } } else { $content = $this->_background_content; } // Add the body content. $response->set_body($content, false); } } if (isset($response) && $response instanceof HTTPResponse) { // Send the response. $this->write($response); // Remove the handler. $loop = $this->dispatcher->get_server()->get_loop(); $loop->remove_handler($socket); // Close the sockets. if (is_resource($socket)) { fclose($socket); } // Close the process. proc_close($process); // Clear the content. $this->_background_content = ''; } }
/** * @param HTTPResponse $response * @return string XML string containing the HTTP error message */ protected function getErrorMessage($response) { return "<error type=\"authentication\" code=\"" . $response->getStatusCode() . "\">" . $response->getStatusDescription() . "</error>"; }
/** * @param String $url * @param Array $data * @return String HTTPResponse */ function post($url, $postVars) { $ch = curl_init($url); if (!empty(RecaptchaField::$proxy_server)) { curl_setopt($ch, CURLOPT_PROXY, RecaptchaField::$proxy_server); if (!empty(RecaptchaField::$proxy_auth)) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, RecaptchaField::$proxy_auth); } } curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'reCAPTCHA/PHP'); // we need application/x-www-form-urlencoded curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postVars)); $response = curl_exec($ch); if (class_exists('SS_HTTPResponse')) { $responseObj = new SS_HTTPResponse(); } else { // 2.3 backwards compat $responseObj = new HTTPResponse(); } $responseObj->setBody($response); // 2.2. compat return $responseObj; }
public function getNestedController() { $url = Director::urlParams(); $hasUrlSegment = false; $parent = null; $counter = 1; foreach ($this->urlParams as $urlSegment) { $hasUrlSegment = true; $SQL_URLSegment = Convert::raw2sql($urlSegment); $filter = "URLSegment = '{$SQL_URLSegment}'"; if (isset($child)) { $filter .= "AND ParentID = {$child->ID}"; } else { $filter .= "AND ParentID = 0"; } $child = DataObject::get_one('SiteTree', $filter); if (!$child) { $key = $counter - 2; if ($key < 0) { $key = 0; } $this->mapParams($key); $c = new ModelAsController(); $this->request->setParams($this->urlParams); return $c->handleRequest($this->request); } if (isset($child->UrlParentID) && $child->UrlParentID != 0) { $parent = $child->UrlParent(); } else { if (isset($child->ParentID) && $child->ParentID != 0) { $parent = $child->Parent(); } else { $parent = null; } } if ($parent && $parent->URLSegment != 'home') { $keyint = $counter - 1; $key = "url" . $keyint; if (!isset($this->urlParams[$key]) || $parent->URLSegment != $this->urlParams[$key]) { $child = $this->get404Page(); break; } } $counter++; } if ($hasUrlSegment) { if (!$child) { if ($child = $this->findOldPage($SQL_URLSegment)) { $url = Controller::join_links(Director::baseURL(), $child->URLSegment, isset($this->urlParams['Action']) ? $this->urlParams['Action'] : null, isset($this->urlParams['ID']) ? $this->urlParams['ID'] : null, isset($this->urlParams['OtherID']) ? $this->urlParams['OtherID'] : null); $response = new HTTPResponse(); $response->redirect($url, 301); return $response; } $child = $this->get404Page(); } if ($child) { $this->mapParams(); if (isset($_REQUEST['debug'])) { Debug::message("Using record #{$child->ID} of type {$child->class} with URL {$this->urlParams['URLSegment']}"); } // set language if ($child->Locale) { Translatable::set_current_locale($child->Locale); } $controllerClass = "{$child->class}_Controller"; if ($this->urlParams['Action'] && ClassInfo::exists($controllerClass . '_' . $this->urlParams['Action'])) { $controllerClass = $controllerClass . '_' . $this->urlParams['Action']; } if (ClassInfo::exists($controllerClass)) { $controller = new $controllerClass($child); } else { $controller = $child; } return $controller; } else { return new HTTPResponse("The requested page couldn't be found.", 404); } } else { user_error("NestedUrlController not geting a URLSegment. It looks like the site isn't redirecting to home", E_USER_ERROR); } }
/** * Render the application. */ public function render() { $this->run(); $this->httpResponse->send(); }
/** * Tests whether a redirection has been requested. * @return string If redirect() has been called, it will return the URL redirected to. Otherwise, it will return null; */ function redirectedTo() { return $this->response->getHeader('Location'); }
/** * Logs stats for a new response. * * @access private * @param HTTPResponse $response * @return void */ private function _log_response(HTTPResponse $response) { $response->set_default_headers(); // Tally up the total bytes sent. if ($this->request instanceof WSRequest) { self::$_ws_bytes_sent += strlen($response->get_body()); } else { self::$_lp_bytes_sent += strlen($response); } }
/** * Process the given URL, creating the appropriate controller and executing it. * * Request processing is handled as folows: * - Director::direct() creates a new HTTPResponse object and passes this to Director::handleRequest(). * - Director::handleRequest($request) checks each of the Director rules and identifies a controller to handle this * request. * - Controller::handleRequest($request) is then called. This will find a rule to handle the URL, and call the rule * handling method. * - RequestHandler::handleRequest($request) is recursively called whenever a rule handling method returns a * RequestHandler object. * * In addition to request processing, Director will manage the session, and perform the output of the actual response * to the browser. * * @param $url String, the URL the user is visiting, without the querystring. * @uses handleRequest() rule-lookup logic is handled by this. * @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call. */ static function direct($url) { // Validate $_FILES array before merging it with $_POST foreach ($_FILES as $k => $v) { if (is_array($v['tmp_name'])) { foreach ($v['tmp_name'] as $tmpFile) { if ($tmpFile && !is_uploaded_file($tmpFile)) { user_error("File upload '{$k}' doesn't appear to be a valid upload", E_USER_ERROR); } } } else { if ($v['tmp_name'] && !is_uploaded_file($v['tmp_name'])) { user_error("File upload '{$k}' doesn't appear to be a valid upload", E_USER_ERROR); } } } $req = new HTTPRequest(isset($_SERVER['X-HTTP-Method-Override']) ? $_SERVER['X-HTTP-Method-Override'] : $_SERVER['REQUEST_METHOD'], $url, $_GET, array_merge((array) $_POST, (array) $_FILES), @file_get_contents('php://input')); // @todo find better way to extract HTTP headers if (isset($_SERVER['HTTP_ACCEPT'])) { $req->addHeader("Accept", $_SERVER['HTTP_ACCEPT']); } if (isset($_SERVER['CONTENT_TYPE'])) { $req->addHeader("Content-Type", $_SERVER['CONTENT_TYPE']); } if (isset($_SERVER['HTTP_REFERER'])) { $req->addHeader("Referer", $_SERVER['HTTP_REFERER']); } // Load the session into the controller $session = new Session($_SESSION); $result = Director::handleRequest($req, $session); $session->inst_save(); // Return code for a redirection request if (is_string($result) && substr($result, 0, 9) == 'redirect:') { $response = new HTTPResponse(); $response->redirect(substr($result, 9)); $response->output(); // Handle a controller } else { if ($result) { if ($result instanceof HTTPResponse) { $response = $result; } else { $response = new HTTPResponse(); $response->setBody($result); } // ?debug_memory=1 will output the number of bytes of memory used for this request if (isset($_REQUEST['debug_memory']) && $_REQUEST['debug_memory']) { echo number_format(memory_get_peak_usage(), 0); } else { $response->output(); } //$controllerObj->getSession()->inst_save(); } } }
/** * Construct an HTTPResponse that will deliver a file to the client */ static function send_file($fileData, $fileName, $mimeType = null) { if (!$mimeType) { $mimeType = HTTP::getMimeType($fileName); } $response = new HTTPResponse($fileData); $response->addHeader("Content-Type", "{$mimeType}; name=\"" . addslashes($fileName) . "\""); $response->addHeader("Content-disposition", "attachment; filename=" . addslashes($fileName)); $response->addHeader("Content-Length", strlen($fileData)); $response->addHeader("Pragma", ""); // Necessary because IE has issues sending files over SSL return $response; }
function html(HTTPResponse $response) { $response->addHeader("Content-type", "text/html; charset=" . self::$encoding); $response->addHeader("Vary", "Accept"); $content = $response->getBody(); $content = ereg_replace("<\\?xml[^>]+\\?>\n?", '', $content); $content = str_replace(array('/>', 'xml:lang', 'application/xhtml+xml'), array('>', 'lang', 'text/html'), $content); $content = ereg_replace('<!DOCTYPE[^>]+>', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', $content); $content = ereg_replace('<html xmlns="[^"]+"', '<html ', $content); $response->setBody($content); }
/** * Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the HTTP response */ function include_in_response(HTTPResponse $response) { $this->process_combined_files(); $jsRequirements = array(); $cssRequirements = array(); foreach (array_diff_key($this->javascript, $this->blocked) as $file => $dummy) { $path = $this->path_for_file($file); if ($path) { $jsRequirements[] = $path; } } $response->addHeader('X-Include-JS', implode(',', $jsRequirements)); foreach (array_diff_key($this->css, $this->blocked) as $file => $params) { $path = $this->path_for_file($file); if ($path) { $cssRequirements[] = isset($params['media']) ? "{$path}:##:{$params['media']}" : $path; } } $response->addHeader('X-Include-CSS', implode(',', $cssRequirements)); }
/** * Process the given URL, creating the appropriate controller and executing it. * * This method will: * - iterate over all of the rules given in {@link Director::addRules()}, and find the first one that matches. * - instantiate the {@link Controller} object required by that rule, and call {@link Controller::setURLParams()} to give the URL paramters to the controller. * - link the Controller's session to PHP's main session, using {@link Controller::setSession()}. * - call {@link Controller::run()} on that controller * - save the Controller's session back into PHP's main session. * - output the response to the browser, using {@link HTTPResponse::output()}. * * @param $url String, the URL the user is visiting, without the querystring. * @uses getControllerForURL() rule-lookup logic is handled by this. * @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call. */ function direct($url) { if (isset($_GET['debug_profile'])) { Profiler::mark("Director", "direct"); } $controllerObj = Director::getControllerForURL($url); if (is_string($controllerObj) && substr($controllerObj, 0, 9) == 'redirect:') { $response = new HTTPResponse(); $response->redirect(substr($controllerObj, 9)); $response->output(); } else { if ($controllerObj) { // Load the session into the controller $controllerObj->setSession(new Session($_SESSION)); $response = $controllerObj->run(array_merge((array) $_GET, (array) $_POST, (array) $_FILES)); $controllerObj->getSession()->inst_save(); if (isset($_GET['debug_profile'])) { Profiler::mark("Outputting to browser"); } $response->output(); if (isset($_GET['debug_profile'])) { Profiler::unmark("Outputting to browser"); } } } if (isset($_GET['debug_profile'])) { Profiler::unmark("Director", "direct"); } }
function handleConfirmation($request) { // Find the action handler $actions = Object::get_static($this->class, 'batch_actions'); $actionClass = $actions[$request->param('BatchAction')]; $actionHandler = new $actionClass(); // Sanitise ID list and query the database for apges $ids = split(' *, *', trim($request->requestVar('csvIDs'))); foreach ($ids as $k => $id) { $ids[$k] = (int) $id; } $ids = array_filter($ids); if ($actionHandler->hasMethod('confirmationDialog')) { $response = new HTTPResponse(json_encode($actionHandler->confirmationDialog($ids))); } else { $response = new HTTPResponse(json_encode(array('alert' => false))); } $response->addHeader("Content-type", "application/json"); return $response; }
/** * Logs stats for a new response. * * @access private * @param HTTPResponse $response * @return void */ private function _log_response(HTTPResponse $response) { $ip = $this->request->get_remote_ip(); $response->set_default_headers(); // Tally up the total bytes sent. if ($this->request->get_controller_method() == 'websocket') { if (!isset(self::$_ws_bytes_sent[$ip])) { self::$_ws_bytes_sent[$ip] = 0; } self::$_ws_bytes_sent[$ip] += strlen($response->get_body()); } elseif ($this->request->get_controller_method() == 'long_polling') { if (!isset(self::$_lp_bytes_sent[$ip])) { self::$_lp_bytes_sent[$ip] = 0; } self::$_lp_bytes_sent[$ip] += strlen($response); } elseif ($this->request->get_controller_method() == 'short_polling') { if (!isset(self::$_sp_bytes_sent[$ip])) { self::$_sp_bytes_sent[$ip] = 0; } self::$_sp_bytes_sent[$ip] += strlen($response); } }
/** * Throw an HTTP error instead of performing the normal processing * @todo This doesn't work properly right now. :-( */ function httpError($errorCode, $errorMessage = null) { $r = new HTTPResponse(); $r->setBody($errorMessage); $r->setStatuscode($errorCode); return $r; }
function html(HTTPResponse $response) { $response->addHeader("Content-Type", "text/html; charset=" . self::$encoding); $response->addHeader("Vary", "Accept"); $content = $response->getBody(); $hasXMLHeader = substr($content, 0, 5) == '<' . '?xml'; $content = ereg_replace("<\\?xml[^>]+\\?>\n?", '', $content); $content = str_replace(array('/>', 'xml:lang', 'application/xhtml+xml'), array('>', 'lang', 'text/html'), $content); // Only replace the doctype in templates with the xml header if ($hasXMLHeader) { $content = ereg_replace('<!DOCTYPE[^>]+>', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', $content); } $content = ereg_replace('<html xmlns="[^"]+"', '<html ', $content); $response->setBody($content); }
/** * Do an arbitrary HTTP action * * @throws HTTPMaxRedirectException * @throws HTTPRequestException * @throws HTTPResponseException * * @param string $method * What method to use: `GET`, `POST`, `PROPPATCH`... * @param string $url * Where to send the request. A full URI: http://server.com/path/ * @param array $vars * Query variables to send. An associative array with key/value pairs * @param array $headers * Additional request headers * @param string $data * Data to send as raw data in a SOAP call for instance * * @return HTTPResponse */ public function do_method($method, $uri, $vars = array(), $headers = array(), $data = null) { $host = null; $port = null; $path = null; $query = null; $body = null; $sock = null; $method = strtoupper($method); if ($this->recursions >= $this->max_redirects) { throw new HTTPMaxRedirectException("Redirect limit ({$this->max_redirects}) exceeded!"); } $request = array(); // It's an assignment if (!($request = parse_url($uri))) { throw new HTTPRequestException("Bad URL ({$uri}) as argument"); } if (!isset($request['host'])) { throw new HTTPRequestException("Missing host in URL ({$uri}) argument"); } $port = 0; $protocol = isset($request['scheme']) ? $request['scheme'] : false; if ($protocol != 'http') { switch ($protocol) { case 'https': if (!isset($request['port'])) { $port = 443; } break; } } $host = $request['host']; $query = isset($request['query']) ? $request['query'] : null; if (!$port) { $port = isset($request['port']) ? (int) $request['port'] : 80; } if (isset($request['user'])) { $this->username = $request['user']; } if (isset($request['pass'])) { $this->password = $request['pass']; } if (!empty($vars)) { $query = http_build_query($vars); } //! Default the request path to root $path = isset($request['path']) ? $request['path'] : '/'; $add_header = ""; if (!empty($headers)) { $this->request_headers = $headers + $this->request_headers; } foreach ($this->request_headers as $key => $val) { if (!is_string($key)) { throw new HTTPRequestException("Malformed header, missing key."); } if (empty($val)) { throw new HTTPRequestException("Malformed header, missing value " . "for key \"{$key}\""); } //! Due to a bug in PHP5.2? if ($key == 'Accept-Encoding') { continue; } $add_header .= "{$key}: {$val}\r\n"; } if ($this->username && $this->password) { $add_header .= "Authorization: Basic " . base64_encode($this->username . ':' . $this->password); } if ($this->cookie) { $c = $this->cookie->create_header($port == 443, $host, $path); if ($c !== false) { $add_header .= $c; } } switch ($method) { case 'GET': $path .= $query ? '?' . $query : ''; break; case 'POST': $body = empty($data) ? $query : urlencode($data); if (!isset($this->headers['Content-Type'])) { $add_header .= "Content-Type: application/x-www-form-urlencoded\r\n"; } $add_header .= "Content-Length: " . strlen($body) . "\r\n\r\n" . $body; break; default: $body = $data; if (!isset($this->headers['Content-Type'])) { $add_header .= "Content-Type: text/plain\r\n"; } $add_header .= "Content-Length: " . strlen($body) . "\r\n\r\n" . $body; break; } $header = "{$method} {$path} HTTP/{$this->version}\r\n" . "Host: {$host}\r\n{$add_header}\r\n"; // print ($header); $rawresponse = false; if ($this->cache > 0) { $rawresponse = $this->get_cache($header); } if ($rawresponse === false) { $errno = 0; $errstr = null; $proto = 'tcp'; switch ($protocol) { case 'https': $proto = 'ssl'; break; case 'ftp': $proto = 'ftp'; break; } //echo "+ Request: $proto://$host:$port$path\n"; if (!($sock = @stream_socket_client("{$proto}://{$host}:{$port}", $errno, $errstr, $this->timeout))) { $m = "Couldn't fetch {$host}! {$errstr} (errno: {$errno})"; throw new HTTPRequestException($m); } if (!is_resource($sock)) { throw new HTTPRequestException("Couldn't connect to {$host}"); } fputs($sock, $header); $rawresponse = ""; while (!feof($sock)) { $rawresponse .= fgets($sock, 512); } } else { $rawresponse = file_get_contents($rawresponse); } $resp = new HTTPResponse($rawresponse); $cookie = null; // It's an assignment if ($this->cookie && ($cookie = $resp->get_header('set-cookie'))) { $this->cookie->set($host, $cookie); } $status = $resp->status(); if ($status != 200) { //print_r ($resp); if ($status == 302 || $status == 301) { $location = $resp->get_header('location'); if ($location != $path && !strpos($location, '://')) { $url = $protocol . "://" . $host . $location; } else { $url = $location; } $headers["Referer"] = $url; if ($cookie) { $headers["Cookie"] = $cookie; } $this->recursions++; $vars = array(); //print_r ($headers); return $this->do_method($method, $url, $vars, $headers, $data); } } if ($this->cache > 0) { $this->write_cache($header, $rawresponse, $resp->status()); } $this->recursions = 0; return $resp; }
/** * Sends a 304 not modified response. * * @access private * @return httpresponse */ private function _304() { $config = $this->dispatcher->get_config(); $response = new HTTPResponse(304); $headers = array('Date' => date('D, d M Y H:i:s \\G\\M\\T'), 'Expires' => date('D, d M Y H:i:s \\G\\M\\T', time() + $config['CACHE_EXPIRATION']), 'Last-Modified' => date('D, d M Y H:i:s \\G\\M\\T', filemtime($this->_path)), 'Cache-Control' => 'max-age=' . $config['CACHE_EXPIRATION']); $response->add_headers($headers); return $response; }