/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreateClient() { $hU = new HttpUtils(); if ($hU->isAjaxRequest() == false) { Response::error("not allowed ;)"); } if (isset($_POST["clientName"]) == false || isset($_POST["clientEmail"]) == false) { Response::ok(CJSON::encode(array("resultado" => Constants::RESULTADO_OPERACION_FALLA, "detalle" => "Faltan parámetros obligatorios"))); } $cl = Cliente::model()->findAll("email=:email", array(':email' => $_POST["clientEmail"])); if (sizeof($cl) > 0) { Response::ok(CJSON::encode(array("resultado" => Constants::RESULTADO_OPERACION_FALLA, "detalle" => "Cliente {$_POST["clientEmail"]} ya registrado en el sistema"))); } $cl = new Cliente(); $cl->surname = ""; $cl->comments = ""; $cl->streetaddress = ""; $cl->name = $_POST["clientName"]; $cl->email = $_POST["clientEmail"]; if ($cl->save()) { Response::ok(CJSON::encode(array("resultado" => Constants::RESULTADO_OPERACION_EXITO, "detalle" => "Cliente {$cl->email} registrado con éxito"))); } else { Response::ok(CJSON::encode(array("resultado" => Constants::RESULTADO_OPERACION_FALLA, "detalle" => "Error registrando cliente {$cl->email} en el sistema"))); } }
/** * description: Hidrata el array $arguments con la informacion enviada desde el cliente dependiendo del * metodo que se trate. */ public function actionProcessRequest() { $hU = new HttpUtils(); $this->httpMethod = $hU->getHttpRequestMethod(); switch ($this->httpMethod) { case HttpUtils::METHOD_GET: $this->arguments = $_GET; $this->processGet(); break; case HttpUtils::METHOD_HEAD: $this->arguments = $_GET; $this->processHead(); break; case HttpUtils::METHOD_POST: $json = file_get_contents('php://input'); $this->arguments = CJSON::decode($json); if ($this->arguments == null) { $this->arguments = $_POST; } $this->processPost(); break; case HttpUtils::METHOD_PUT: $this->processPut(); break; case HttpUtils::METHOD_DELETE: parse_str(file_get_contents('php://input'), $this->arguments); $this->processDelete(); break; } }
protected function onData($data, $id) { global $arConfig; if (!$this->usermgr->GetUser($id)) { $this->usermgr->AddUser($id); } if (!$this->usermgr->GetUser($id)->IsWebsocketInited()) { $headers = HttpUtils::ParseHeaders($data); $hash = base64_encode(pack('H*', sha1($headers['Sec-WebSocket-Key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); $answer = "HTTP/1.1 101 Switching Protocols\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "Sec-WebSocket-Accept: " . $hash . "\r\n\r\n"; $this->Send($answer, $id); $this->usermgr->GetUser($id)->InitWebSocketConnection(); } else { $decoded_data = $this->decode($data); Logger::getInstance()->outDebug("WebSocket: Receive data: " . var_export($decoded_data, true)); switch ($decoded_data['type']) { case 'text': $data = json_decode($decoded_data['payload']); $handlerName = $data->{'opcode'}; if (method_exists('PacketHandler', $handlerName)) { PacketHandler::$handlerName($data->{'data'}, $id, $this); } else { Logger::getInstance()->outError("Websocket: Got unknown packet: " . $handlerName); $packet = array('opcode' => 'smsg_error', 'data' => array('message' => 'received unknown packet')); $this->Send($packet, $id); } break; case 'close': $this->Close($id); break; } } }
public static function init() { if (empty($_SERVER['SERVER_PROTOCOL'])) { $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1'; } self::$protocolVersion = floatval(substr($_SERVER['SERVER_PROTOCOL'], -3, strlen($_SERVER['SERVER_PROTOCOL']))); }
protected function doExecute() { $params = array('url' => $this->url); if ($this->group !== '') { $params['group'] = $this->group; } else { $params['group'] = null; } $rules = Rule::find(array($params)); if ($rules) { $contextMap = array(RuleConditionExpressionOperand::CONTEXT_TYPE_REQUEST => $_REQUEST, RuleConditionExpressionOperand::CONTEXT_TYPE_GET => $_GET, RuleConditionExpressionOperand::CONTEXT_TYPE_POST => $_POST, RuleConditionExpressionOperand::CONTEXT_TYPE_HEADER => HttpUtils::getHttpHeaders(), RuleConditionExpressionOperand::CONTEXT_TYPE_COOKIE => $_COOKIE); $matcher = new RuleResponseMatcher(); foreach ($rules as $rule) { $res = $matcher->match($rule, $contextMap); if (isset($res)) { if (is_array($res) || is_object($res)) { $this->setReturnType(self::RETURN_TYPE_JSON); return $this->success($rule->res); } else { return $res; } } } } $this->setReturnType(self::RETURN_TYPE_JSON); return $this->error(1, 'can\'t match any url for [' . $this->url . ']'); }
private function reloadConfiguration($instance, $serverKey) { if (HttpUtils::isLocal()) { // Update the .htaccess file with the new route settings updateHtaccess($instance); // Update the configuration RESTConfigurationLoader::reloadConfiguration($serverKey); } }
/** * Check if an ip is in an array of ip ranges * @param string $requestIp * @param array $range * @return bool */ public static function ipIsInRange($requestIp, array $range) { foreach ($range as $ip) { if (HttpUtils::checkIp4($requestIp, $ip) === true) { return true; } } return false; }
/** * @param String $name * @return mixed */ public static function getRestParam($name) { $param = Yii::app()->request->getParam($name); if (is_null($param)) { $args = HttpUtils::getHttpArgs(); if (isset($args[$name])) { $param = $args[$name]; } } return $param; }
public function render() { $status_header = 'HTTP/1.1 ' . $this->_status . ' ' . HttpUtils::getStatusCodeMessage($this->_status); header($status_header); foreach ($this->_headers as $header) { header($header); } header('Content-type: ' . $this->_content_type); echo json_encode($this->_body); Yii::app()->end(); }
private function doMethod($s) { curl_setopt($s, CURLOPT_HTTPHEADER, $this->requestHeaders); curl_setopt($s, CURLOPT_HEADER, TRUE); curl_setopt($s, CURLOPT_RETURNTRANSFER, TRUE); foreach ($this->options as $option => $value) { curl_setopt($s, $option, $value); } $out = curl_exec($s); $this->status = curl_getinfo($s, CURLINFO_HTTP_CODE); $this->responseHeaders = curl_getinfo($s, CURLINFO_HEADER_OUT); curl_close($s); list($this->responseHeaders, $content) = HttpUtils::decodeOut($out); // if ($this->status != self::HTTP_OK) { // throw new \Exception("http error: {$this->status}", $this->status); // } return $content; }
<?php require_once dirname(__FILE__) . "/root.php"; require_once __ROOT__ . "/settings.php"; require_once __ROOT__ . "/inc/commons/uploadutils.php"; require_once __ROOT__ . "/inc/nugetreader.php"; require_once __ROOT__ . "/inc/commons/url.php"; if (!empty($_SERVER['HTTP_X_NUGET_APIKEY'])) { HttpUtils::ApiError('403', 'Invalid request'); die; } $message = ""; ?> <html><body> <script type="text/javascript"> <?php if (!$loginController->IsLoggedIn) { ?> parent.packagesUploadControllerCallback("fail-unathorized","none","none"); <?php } else { if (UploadUtils::IsUploadRequest()) { $uploader = new UploadUtils(Settings::$PackagesRoot, array("nupkg"), Settings::$MaxUploadBytes); $result = $uploader->Upload("fileName"); $fileName = basename($result["name"], ".nupkg"); $message = ""; if ($result["hasError"] == true) { $message = "Failed uploading '" . $result["name"] . "'."; $message .= "Error is: " . $result["errorMessage"]; if ($result["errorCode"] != null) { $message .= "Error code is:" . $result["errorCode"] . ".";
<?php require_once dirname(__FILE__) . "/../../root.php"; require_once __ROOT__ . "/settings.php"; require_once __ROOT__ . "/inc/api_users.php"; require_once __ROOT__ . "/inc/commons/url.php"; if (!$loginController->Admin) { $uid = UrlUtils::GetRequestParam("UserId"); if ($uid != $loginController->UserId) { HttpUtils::ApiError(500, "Unauthorized"); } } $api = new UsersApi(); $id = UrlUtils::GetRequestParamOrDefault("UserId", "get"); $api->Execute();
public function actionUpdateState($id) { $transaction = Yii::app()->db->beginTransaction(); try { $model = $this->loadModel($id); $hU = new HttpUtils(); if (strcmp($hU->getHttpRequestMethod(), HttpUtils::METHOD_POST) == 0) { if ($model->enabled == 1) { $model->enabled = 0; } else { $model->enabled = 1; } if ($model->save()) { $this->audit->logAudit(Yii::app()->user->id, new DateTime(), AppConstants::AUDIT_OBJECT_USER, AppConstants::AUDIT_OPERATION_EDIT, $model->nick); $this->render('/site/successfullOperation', array('header' => 'Usuario modificado con éxito', 'message' => 'Haga click en volver para regresar a la gestión de usuarios', 'returnUrl' => Yii::app()->createUrl('user/admin'), 'viewUrl' => Yii::app()->createUrl("user/view", array("id" => $model->nick)))); $transaction->commit(); return; } } if ($model->enabled == 1) { $header = 'Bloquear usuario'; $message = "¿Esta seguro que desea bloquear el usuario {$model->nick}?"; } else { $header = 'Desbloquear usuario'; $message = "¿Esta seguro que desea desbloquear el usuario {$model->nick}?"; } $transaction->commit(); $this->render('changeState', array('header' => $header, 'message' => $message)); } catch (Exception $exc) { Yii::log($exc->getMessage(), DBLog::LOG_LEVEL_ERROR); $transaction->rollback(); } }
public static final function flushToClient() { $ETag = md5(implode(';', self::$files)); $gzip = GZIP_OUT ? '.gz' : ''; $cachedFile = CACHE_PATH . 'css#' . $ETag; header('Expires: ' . gmdate('D, d M Y H:i:s \\G\\M\\T', time() + (DEVELOPER_MODE ? 0 : 60 * 60 * 24))); header('Cache-Control: public'); header('Content-Type: text/css; charset: utf-8'); if (!DEVELOPER_MODE && is_file($cachedFile . $gzip) && filemtime($cachedFile . $gzip) > self::$mtime) { if ($gzip) { header('Content-Encoding: gzip'); } header('Content-Length:' . filesize($cachedFile . $gzip)); if ($status = HttpUtils::entityCache($ETag, self::$mtime)) { HttpHeaders::flush($status); } else { readfile($cachedFile . $gzip); } exit; } $buffer = ''; foreach (self::$files as $file) { $buffer .= file_get_contents($file); } $buffer = preg_replace('#((url\\(|src=)["\']?)(../)?images/#', '$1' . BASEHREF . 'themes/' . self::$theme . '/images/', $buffer); $buffer = trim(preg_replace('#\\s+#', ' ', $buffer)); $buffer = preg_replace('#/\\*.*?\\*/#s', '', $buffer); $buffer = preg_replace('#\\s*[^{}]+{\\s*}\\s*#', '', $buffer); $buffer = preg_replace('#\\s*([{},;:])\\s*#', '$1', $buffer); $buffer = str_replace(';}', '}', $buffer); if (GZIPSUPPORT && ($gz = gzopen($cachedFile . '.gz', 'w9'))) { gzwrite($gz, $buffer); gzclose($gz); } file_put_contents($cachedFile, $buffer); if (is_file($cachedFile . $gzip) || !$gzip) { if ($gzip) { header('Content-Encoding: gzip'); } header('Content-Length:' . filesize($cachedFile . $gzip)); exit(readfile($cachedFile . $gzip)); } else { ob_start('ob_gzhandler'); exit($buffer); } }
private function validateRequest($serverKey, $token, $method, $language, $version) { // If the request comes from the local computer, then don't require authorization, // otherwise check the headers if (HttpUtils::isLocal()) { return true; } else { if (empty($serverKey)) { throw new MashapeException(EXCEPTION_EMPTY_SERVERKEY, EXCEPTION_XML_CODE); } $url = MASHAPE_TOKEN_VALIDATION_URL . "?" . QUERY_PARAM_TOKEN . "=" . $token . "&" . QUERY_PARAM_SERVERKEY . "=" . $serverKey . "&" . QUERY_PARAM_METHOD . "=" . $method . "&" . QUERY_PARAM_LANGUAGE . "=" . $language . "&" . QUERY_PARAM_VERSION . "=" . $version; $response = HttpUtils::makeHttpRequest($url); if (empty($response)) { throw new MashapeException(EXCEPTION_EMPTY_REQUEST, EXCEPTION_SYSTEM_ERROR_CODE); } $validationResponse = json_decode($response); if (empty($validationResponse)) { throw new MashapeException(EXCEPTION_JSONDECODE_REQUEST, EXCEPTION_SYSTEM_ERROR_CODE); } if (!empty($validationResponse->errors)) { $error = $validationResponse->errors[0]; throw new MashapeException($error->message, $error->code); } $authorization = $validationResponse->authorized; $GLOBALS[UID] = $validationResponse->uid; if ($authorization == true) { return true; } else { return false; } } }
$token = strtoupper(trim(trim($_SERVER['HTTP_X_NUGET_APIKEY'], "{"), "}")); $db = new UserDb(); $os = new ObjectSearch(); $os->Parse("Token eq '{" . $token . "}'", $db->GetAllColumns()); $users = $db->GetAllRows(1, 0, $os); if (sizeof($users) != 1) { HttpUtils::ApiError('403', 'Invalid API key'); die; } $user = $users[0]; $uploader = new UploadUtils(Settings::$PackagesRoot, array("nupkg"), Settings::$MaxUploadBytes, true); $uploader->allowAll = true; $result = $uploader->Upload("package"); if ($result['hasError']) { throw new Exception($result['errorCode']); } $fileName = basename($result["name"], ".nupkg"); $nugetReader = new NugetManager(); $parsedNuspec = $nugetReader->LoadNuspecFromFile($result["destination"]); $parsedNuspec->UserId = $user->Id; $nuspecData = $nugetReader->SaveNuspec($result["destination"], $parsedNuspec); // All done! header('HTTP/1.1 201 Created'); } catch (Exception $ex) { if (array_key_exists("destination", $result)) { unlink($result["destination"]); } unlink($temp_file); HttpUtils::ApiError('500', $ex->getMessage()); die; }
/** * @TODO: This is an integration test with www.mashape.com * This test could fail if the site is unreachable (maintenance, dns, proxy, firewall etc.) * The external resource should be mocked * ~ dluc */ function testMakeHttpRequest() { $response = HttpUtils::makeHttpRequest("http://www.mashape.com"); $this->assertFalse(empty($response)); }
public function RawRequest() { global $v2BatchDebug; if (!array_key_exists('CONTENT_TYPE', $_SERVER) && UrlUtils::RequestMethod() != "post") { HttpUtils::ApiError(405, "The HTTP verb used is not allowed."); } $a_data = array(); // read incoming data $input = file_get_contents('php://input'); if ($v2BatchDebug) { file_put_contents("batch.log", "REQUEST:" . $input . "\r\n", FILE_APPEND); file_put_contents("batch.log", "\r\n", FILE_APPEND); } // grab multipart boundary from content type header preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches); // content type is probably regular form-encoded if (!count($matches)) { return null; } $boundary = $matches[1]; $parsed = $this->ParseData($boundary, $input); $result = array(); if ($v2BatchDebug) { file_put_contents("batch.log", "PARSING:" . sizeof($parsed) . "\r\n", FILE_APPEND); file_put_contents("batch.log", "\r\n", FILE_APPEND); } for ($i = 0; $i < sizeof($parsed); $i++) { $item = $parsed[$i]; $item->ResultStatus = 200; if ($item->Method == "get") { $item->ResultData = HttpUtils::HttpGet($item->Action); } else { if ($item->Method == "get") { $item->ResultData = HttpUtils::HttpPost($item->Action, $item->Data, "application/atom+xml"); } } array_push($result, $item); } $response = Batcher::Elaborate($result); if ($v2BatchDebug) { file_put_contents("batch.log", "RESULT:" . $response . "\r\n", FILE_APPEND); file_put_contents("batch.log", "\r\n", FILE_APPEND); } }
private static function execRequest($httpMethod, $url, $parameters, $authHandlers, $contentType, $encodeJson) { // first, collect the headers and parameters we'll need from the authentication handlers list($headers, $authParameters) = HttpUtils::handleAuthentication($authHandlers); if (is_array($parameters)) { $parameters = array_merge($parameters, $authParameters); } // prepare the request $ch = curl_init(); if ($httpMethod == HttpMethod::GET) { $url = UrlUtils::buildUrlWithQueryString($url, $parameters); } else { $data = HttpUtils::buildDataForContentType($contentType, $parameters, $headers); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($ch); if (curl_error($ch)) { throw new MashapeClientException(EXCEPTION_CURL . ":" . curl_error($ch), EXCEPTION_CURL_CODE); } $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $responseHeaders = curl_getinfo($ch, CURLINFO_HEADER_OUT); curl_close($ch); return new MashapeResponse($response, $httpCode, $responseHeaders, $encodeJson); }
require_once __ROOT__ . "/inc/commons/url.php"; require_once __ROOT__ . "/inc/commons/http.php"; require_once __ROOT__ . "/inc/api_nuget.php"; $id = UrlUtils::GetRequestParamOrDefault("id", null); $version = UrlUtils::GetRequestParamOrDefault("version", null); if ($id == null || $version == null) { HttpUtils::ApiError(500, "Wrong data. Missing param."); } if (strlen($id) == 0 || strlen($version) == 0) { HttpUtils::ApiError(500, "Wrong data. Empty id or version."); } $query = "Id eq '" . $id . "' and Version eq '" . $version . "'"; $db = new NuGetDb(); $os = new PhpNugetObjectSearch(); $os->Parse($query, $db->GetAllColumns()); $allRows = $db->GetAllRows(1, 0, $os); if (sizeof($allRows) == 0) { HttpUtils::ApiError(404, "Not found."); } $file = $allRows[0]->Id . "." . $allRows[0]->Version . ".nupkg"; $path = Path::Combine(Settings::$PackagesRoot, $file); if (!file_exists($path)) { HttpUtils::ApiError(404, "Not found " . $file); } header('Content-Type: application/zip'); header('Content-Disposition: attachment; filename=' . basename($path)); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($path)); readfile($path);
private function validateRequest($serverKey) { // If the request comes from the local computer, then don't require authorization, // otherwise check the headers if (HttpUtils::isLocal()) { return true; } else { $providedServerkey = HttpUtils::getHeader(HEADER_SERVER_KEY); if (empty($serverKey)) { throw new MashapeException(EXCEPTION_EMPTY_SERVERKEY, EXCEPTION_XML_CODE); } if ($providedServerkey != null && md5($serverKey) == $providedServerkey) { return true; } return false; } }
public static function handleAPI($instance, $serverKey) { header("Content-type: application/json"); try { if ($instance == null) { throw new MashapeException(EXCEPTION_INSTANCE_NULL, EXCEPTION_SYSTEM_ERROR_CODE); } $requestMethod = isset($_SERVER['REQUEST_METHOD']) ? strtolower($_SERVER['REQUEST_METHOD']) : null; $params; if ($requestMethod == 'post') { $params = array_merge(self::getAllParams($_GET), self::getAllParams($_POST)); } else { if ($requestMethod == 'get') { $params = self::getAllParams($_GET); } else { if ($requestMethod == 'put' || $requestMethod == 'delete') { $params = HttpUtils::parseQueryString(file_get_contents("php://input")); } else { throw new MashapeException(EXCEPTION_NOTSUPPORTED_HTTPMETHOD, EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE); } } } $operation = isset($params[OPERATION]) ? $params[OPERATION] : null; unset($params[OPERATION]); // remove the operation parameter if (empty($operation)) { $operation = "call"; } if ($operation != null) { $result; switch (strtolower($operation)) { case "discover": header("Content-type: application/xml"); $discover = new Discover(); $result = $discover->handle($instance, $serverKey, $params, $requestMethod); break; case "call": $call = new Call(); $result = $call->handle($instance, $serverKey, $params, $requestMethod); break; default: throw new MashapeException(EXCEPTION_NOTSUPPORTED_OPERATION, EXCEPTION_NOTSUPPORTED_OPERATION_CODE); } $jsonpCallback = isset($params[CALLBACK]) ? $params[CALLBACK] : null; if (empty($jsonpCallback)) { // Print the output echo $result; } else { if (self::validateCallback($jsonpCallback)) { echo $jsonpCallback . '(' . $result . ')'; } else { throw new MashapeException(EXCEPTION_INVALID_CALLBACK, EXCEPTION_SYSTEM_ERROR_CODE); } } } else { // Operation not supported throw new MashapeException(EXCEPTION_NOTSUPPORTED_OPERATION, EXCEPTION_NOTSUPPORTED_OPERATION_CODE); } } catch (Exception $e) { //If it's an ApizatorException then print the specific code if ($e instanceof MashapeException) { header("Content-type: application/json"); $code = $e->getCode(); switch ($code) { case EXCEPTION_XML_CODE: header("HTTP/1.0 500 Internal Server Error"); break; case EXCEPTION_INVALID_HTTPMETHOD_CODE: header("HTTP/1.0 405 Method Not Allowed"); break; case EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE: header("HTTP/1.0 405 Method Not Allowed"); break; case EXCEPTION_NOTSUPPORTED_OPERATION_CODE: header("HTTP/1.0 501 Not Implemented"); break; case EXCEPTION_METHOD_NOTFOUND_CODE: header("HTTP/1.0 404 Not Found"); break; case EXCEPTION_AUTH_INVALID_CODE: self::setUnauthorizedResponse(); break; case EXCEPTION_AUTH_INVALID_SERVERKEY_CODE: self::setUnauthorizedResponse(); break; case EXCEPTION_REQUIRED_PARAMETERS_CODE: header("HTTP/1.0 200 OK"); break; case EXCEPTION_GENERIC_LIBRARY_ERROR_CODE: header("HTTP/1.0 500 Internal Server Error"); break; case EXCEPTION_INVALID_APIKEY_CODE: self::setUnauthorizedResponse(); break; case EXCEPTION_EXCEEDED_LIMIT_CODE: self::setUnauthorizedResponse(); break; case EXCEPTION_SYSTEM_ERROR_CODE: header("HTTP/1.0 500 Internal Server Error"); break; } echo JsonUtils::serializeError($e->getMessage(), $code); } else { //Otherwise print a "generic exception" code header("HTTP/1.0 500 Internal Server Error"); echo JsonUtils::serializeError($e->getMessage(), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE); } } }
private static function sendRequest($Request, $options = array()) { if (!empty($Request->body)) { $Request->headers['Content-Length'] = strlen($Request->body); } if (empty($Request->headers['Host'])) { $Request->headers['Host'] = $Request->host; } if (empty($Request->timeout)) { $Request->timeout = HttpUtils::DEFAULT_TIMEOUT; } if (empty($Request->port)) { $Request->port = 80; } $req = "{$Request->method} {$Request->path} HTTP/1.0\r\n"; foreach ($Request->headers as $key => $val) { $req .= "{$key}: {$val}\r\n"; } $req .= "\r\n" . (!empty($Request->body) ? $Request->body : ''); $errno = $errstr = null; $f = @fsockopen($Request->host, $Request->port, $errno, $errstr, $Request->timeout); if (!$f) { $Response = new StdClass(); $Response->isError = "Connecting to {$Request->host}:{$Request->port} failed: {$errstr}, {$errno}"; return $Response; } stream_set_blocking($f, 0); fputs($f, $req); $res = ''; while (!feof($f)) { $res .= fgets($f, 1024); } fclose($f); return HttpUtils::parseHttpResponse($res, $options); }
public static final function flushToClient() { $ETag = md5(implode(';', self::$files)); $gzip = GZIP_OUT ? '.gz' : ''; $cachedFile = CACHE_PATH . 'js#' . $ETag; header('Expires: ' . gmdate('D, d M Y H:i:s \\G\\M\\T', time() + (DEVELOPER_MODE ? 0 : 60 * 60 * 24))); header('Cache-Control: public'); header('Content-Type: application/javascript; charset: utf-8'); if (!DEVELOPER_MODE && is_file($cachedFile . $gzip) && filemtime($cachedFile . $gzip) > self::$mtime) { if ($gzip) { header('Content-Encoding: gzip'); } header('Content-Length:' . filesize($cachedFile . $gzip)); if ($status = HttpUtils::entityCache($ETag, self::$mtime)) { HttpHeaders::flush($status); } else { readfile($cachedFile . $gzip); } exit; } $buffer = ''; foreach (self::$files as $file) { $buffer .= file_get_contents($file); } $buffer = preg_replace('#^(\\s+)#m', '', $buffer); $buffer = preg_replace('#[\\r\\n]+#', '', $buffer); $buffer = str_replace(';}', '}', $buffer); if (GZIPSUPPORT && ($gz = gzopen($cachedFile . '.gz', 'w9'))) { gzwrite($gz, $buffer); gzclose($gz); } file_put_contents($cachedFile, $buffer); if (is_file($cachedFile . $gzip) || !$gzip) { if ($gzip) { header('Content-Encoding: gzip'); } header('Content-Length:' . filesize($cachedFile . $gzip)); exit(readfile($cachedFile . $gzip)); } else { ob_start('ob_gzhandler'); exit($buffer); } }
public function Execute() { header('Content-Type: application/json'); $action = UrlUtils::GetRequestParamOrDefault("action", null); $packageId = UrlUtils::GetRequestParamOrDefault("id", "angularjs"); $version = UrlUtils::GetRequestParamOrDefault("version", "1.0.3"); $data = array(); switch ($action) { case 'resources': //header("Location: https://api.nuget.org/v3/index.json"); $data = $this->Resources(); break; case 'searchServices': //header("Location: https://api-search.nuget.org/"); $data = $this->SearchServices(); break; case 'searchResources': //header("Location: https://api-search.nuget.org/search"); $data = $this->SearchResources(); break; case 'searchFields': $data = "Location: https://api-search.nuget.org/search/fields"; break; case 'searchQuery': $data = "Location: https://api-search.nuget.org/search/query"; break; case 'searchDiag': $data = "Location: https://api-search.nuget.org/search/diag"; break; case 'packages': $data = "Location: https://api.nuget.org/v3/registration0/" . $packageId . "/index.json"; break; case 'package': $data = "Location: https://api.nuget.org/v3/registration0/" . $packageId . "/" . $version . ".json"; break; default: HttpUtils::ApiError(404, "Not found"); break; } echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); die; }
function _getupdates($action) { if ($action != "getupdates") { return; } HttpUtils::ApiError(404, "Not found"); }
function Upload($fileId = "file") { $files = NULL; $files = $_FILES; $isRealFile = true; if (!array_key_exists($fileId, $files)) { $files = HttpUtils::RawRequest(); $isRealFile = false; } $guid = Utils::NewGuid(); $toret = array(); $toret["hasError"] = false; $toret["errorCode"] = null; $toret["errorMessage"] = ""; $toret["name"] = $files[$fileId]["name"]; if (array_key_exists("mime", $files[$fileId])) { $toret["mime"] = $files[$fileId]["type"]; } if (array_key_exists("size", $files[$fileId])) { $toret["sizeBytes"] = $files[$fileId]["size"]; } $exploded = explode(".", $toret["name"]); $extension = end($exploded); if ($toret["sizeBytes"] >= $this->maxSize) { $toret["hasError"] = true; $toret["errorMessage"] = "Max size is '" . $this->maxSize . "' bytes. File size is '" . $toret["sizeBytes"] . "'."; } else { if ($this->allowAll <= 0 && !in_array($extension, $this->allowedExts)) { $toret["hasError"] = true; $toret["errorMessage"] = "Extension '" . $extension . "' not allowed. " . "The allowed ones are '" . implode(", ", $this->allowedExts) . "'"; } else { if (array_key_exists("error", $files[$fileId]) && $files[$fileId]["error"] > 0) { //TODO Error translations http://php.net/manual/en/features.file-upload.errors.php $toret["hasError"] = true; $toret["errorCode"] = $files[$fileId]["error"]; } else { $toret["tmpName"] = $files[$fileId]["tmp_name"]; if (file_exists($this->destinationDir . "/" . $guid)) { unlink($this->destinationDir . "/" . $guid); } $toret["destination"] = $this->destinationDir . "/" . $guid; if ($isRealFile) { if (!move_uploaded_file($toret["tmpName"], $toret["destination"])) { $toret["hasError"] = true; $toret["errorMessage"] = 'Cannot move file from ' . $toret["tmpName"] . ' to ' . $toret["destination"]; $toret["errorCode"] = UPLOAD_ERR_CANT_WRITE; } } else { if (!rename($toret["tmpName"], $toret["destination"])) { $toret["hasError"] = true; $toret["errorMessage"] = 'Cannot rename file from ' . $toret["tmpName"] . ' to ' . $toret["destination"]; $toret["errorCode"] = UPLOAD_ERR_CANT_WRITE; } } } } } if ($toret["hasError"]) { unlink($toret["tmpName"]); } return $toret; }
<?php require_once dirname(__FILE__) . "/../../root.php"; require_once __ROOT__ . "/settings.php"; require_once __ROOT__ . "/inc/api_users.php"; require_once __ROOT__ . "/inc/commons/url.php"; require_once __ROOT__ . "/inc/commons/http.php"; require_once __ROOT__ . "/inc/api_nuget.php"; require_once __ROOT__ . "/inc/api_nugetv3.php"; $api = new ApiNugetBaseV3(); $api->Initialize(dirname(__FILE__)); $api->Execute(); HttpUtils::ApiError(404, "Not found");
public function actionUpdateState($id) { $model = $this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); $hU = new HttpUtils(); if (strcmp($hU->getHttpRequestMethod(), HttpUtils::METHOD_POST) == 0) { if ($model->enabled == 1) { $model->enabled = 0; } else { $model->enabled = 1; } if ($model->save()) { $this->audit->logAudit(Yii::app()->user->id, new DateTime(), Constants::AUDITORIA_OBJETO_USUARIO, Constants::AUDITORIA_OPERACION_MODIFICACION, $model->nick); $this->render('/site/successfullOperation', array('header' => 'Usuario modificado con éxito', 'message' => 'Haga click en volver para regresar a la gestión de usuarios', 'returnUrl' => Yii::app()->createUrl('user/admin'), 'viewUrl' => Yii::app()->createUrl("user/view", array("id" => $model->nick)))); return; } } if ($model->enabled == 1) { $header = 'Bloquear usuario'; $message = "¿Esta seguro que desea bloquear el usuario {$model->nick}?"; } else { $header = 'Desbloquear usuario'; $message = "¿Esta seguro que desea desbloquear el usuario {$model->nick}?"; } $this->render('changeState', array('header' => $header, 'message' => $message)); }