/** * */ protected function sendHeaders() { http_response_code($this->httpResponseCode); foreach ($this->headers as $name => $value) { header($name . ': ' . $value); } }
/** * Convert request to data result * * @access public * @fixme Authentication / request validation * @return void */ public function get($forecast = false, $data = false) { $validRequest = $this->_validateRequest() !== False; $validAuth = $this->_validateAuth() !== False; $post = $data !== false ? $data : $this->input->post(); $post["download"] = false; if (isset($post["region"])) { $post["multiple"] = true; } else { $post["multiple"] = false; } if ($validRequest && $validAuth) { $source = new Source($post); $res = $source->get($this->_user); if ($forecast != false) { if ($this->_user) { $result = $source->gatherForecast($this->_user); if (isset($result[0])) { array_push($res, $result[0]); } } } echo json_encode($res); } else { http_response_code(400); echo json_encode(["message" => $this->_message]); } exit; }
public function input() { if ($this->input === NULL) { $in = file_get_contents("php://input"); if ($in != "" && $in != NULL) { $this->input = json_decode($in, true); if (json_last_error() != JSON_ERROR_NONE) { // we have to do a raw write here... http_response_code(400); if (config('app.debug') === true) { \Log::debug("Invalid JSON in this request: " . $in); } echo json_encode(["message" => "Error: Malformed JSON"]); exit; } if (isset($this->input['payload']) && !empty($this->input['payload'])) { $this->payload = $this->input['payload']; } if (isset($this->input['meta']) && !empty($this->input['meta'])) { $this->meta = $this->input['meta']; } } else { $this->input = ""; } } return $this->input; }
function response_error($msg) { http_response_code(400); $response = (object) ['msg' => $msg]; echo json_encode($response); exit(1); }
private function set_headers() { header("HTTP/1.1" . $this->_code . " " . http_response_code($this->get_status_message())); //http_response_code($this->get_status_message()); header("Content-Type:" . $this->_content_type); $this->logger->write("INFO :", "_code......" . $this->_code . "get_status_message..." . $this->get_status_message() . "_content_type...." . $this->_content_type); }
function dumpError($error) { http_response_code(500); echoHtmlHead(); echo "<h3 style=\"background-color:orangered;padding:10px;\">{$error}</h3>"; exit(1); }
public function OnLoadPageData() { require_once 'stoolball/competition-manager.class.php'; $manager = new CompetitionManager($this->GetSettings(), $this->GetDataConnection()); if ($this->season_id) { $manager->ReadById(null, array($this->season_id)); } else { $manager->ReadById(array($this->competition_id)); } $this->competition = $manager->GetFirst(); $this->season = $this->competition->GetWorkingSeason(); unset($manager); # If the competition was requested, redirect to the current season if ($this->competition_id) { http_response_code(303); header("Location: " . $this->season->GetMapUrl()); return; } $this->has_map = count($this->season->GetTeams()); # Get other seasons require_once 'stoolball/season-manager.class.php'; $a_comp_ids = array($this->competition->GetId()); $o_season_manager = new SeasonManager($this->GetSettings(), $this->GetDataConnection()); $o_season_manager->ReadByCompetitionId($a_comp_ids); $a_other_seasons = $o_season_manager->GetItems(); $this->competition->SetSeasons(array()); foreach ($a_other_seasons as $season) { if ($season->GetId() == $this->season->GetId()) { $this->competition->AddSeason($this->season, true); } else { $this->competition->AddSeason($season, false); } } }
function create_topic($request) { Authenticator::assert_manager_or_professor($request->cookies['authToken']); $msg = new Messages($GLOBALS['locale']); try { $raw_input = $request->getBody(); $content_type = explode(';', $request->type)[0]; if ($content_type !== 'application/json') { Util::output_errors_and_die('', 415); } $input_data = json_decode($raw_input, true); if (empty($input_data)) { Util::output_errors_and_die('', 400); } $model = new Model(); if (!isset($input_data['name'])) { $input_data['name'] = ''; } $topic_id = $model->create_topic($input_data['name']); if ($topic_id) { http_response_code(201); header('Content-Type: text/plain'); echo '/topics/' . $topic_id; die; } else { Util::output_errors_and_die('', 400); } } catch (ConflictException $e) { Util::output_errors_and_die($e->getMessage(), 409); } catch (DatabaseException $e) { Util::output_errors_and_die($e->getMessage(), 503); } catch (Exception $e) { Util::output_errors_and_die($e->getMessage(), 400); } }
/** * Sent HTTP headers and HTTP response code. */ protected function sendHeaders() { http_response_code($this->status); foreach ($this->headers as $name => $value) { header("{$name}: {$value}"); } }
static function throw400($msg) { http_response_code(400); header('Content-Type: text/plain'); echo $msg; exit; }
public function combineChunks($uploadDirectory, $name = null) { $uuid = $_POST['qquuid']; if ($name === null) { $name = $this->getName(); } $targetFolder = $this->chunksFolder . DIRECTORY_SEPARATOR . $uuid; $totalParts = isset($_REQUEST['qqtotalparts']) ? (int) $_REQUEST['qqtotalparts'] : 1; $targetPath = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name)); $this->uploadName = $name; if (!file_exists($targetPath)) { mkdir(dirname($targetPath), 0777, true); } $target = fopen($targetPath, 'wb'); for ($i = 0; $i < $totalParts; $i++) { $chunk = fopen($targetFolder . DIRECTORY_SEPARATOR . $i, "rb"); stream_copy_to_stream($chunk, $target); fclose($chunk); } // Success fclose($target); for ($i = 0; $i < $totalParts; $i++) { unlink($targetFolder . DIRECTORY_SEPARATOR . $i); } rmdir($targetFolder); if (!is_null($this->sizeLimit) && filesize($targetPath) > $this->sizeLimit) { unlink($targetPath); http_response_code(413); return array("success" => false, "uuid" => $uuid, "preventRetry" => true); } return array("success" => true, "uuid" => $uuid); }
/** * This is a general purpose hook, allowing modules to respond to routes * of the form module.php?mod=FOO&mod_action=BAR * * @param string $mod_action */ public function modAction($mod_action) { switch ($mod_action) { case 'admin_config': $this->config(); break; case 'admin_delete': $this->delete(); $this->config(); break; case 'admin_edit': $this->edit(); break; case 'admin_movedown': $this->movedown(); $this->config(); break; case 'admin_moveup': $this->moveup(); $this->config(); break; case 'show': $this->show(); break; default: http_response_code(404); } }
function sendErrorAndDie($code, $msg) { error_log($msg); include 'error.php'; http_response_code($code); die; }
function test_auto_marking_sc($request) { Authenticator::assert_manager_or_professor($request->cookies['authToken']); $msg = new Messages($GLOBALS['locale'], '/new-question/errors'); try { $model = new Model(); $raw_input = $request->getBody(); $content_type = explode(';', $request->type)[0]; if ($content_type !== 'application/json') { Util::output_errors_and_die($msg->_('invalid-format'), 415); } $input_data = json_decode($raw_input, true); if (empty($input_data) || !isset($input_data['question']) || !isset($input_data['source-code']) || !is_string($input_data['source-code'])) { Util::output_errors_and_die($msg->_('invalid-format'), 400); } $extra = !empty($input_data['extra']) ? $input_data['extra'] : []; $qd = $input_data['question']; set_empty_if_undefined($qd['type']); if ($qd['type'] != 'source-code') { Util::output_errors_and_die('', 400); } $q = new QuestionSC($qd, Question::FROM_USER, $extra); $q->mark_automatically(array('source-code' => $input_data['source-code']), $log, $result); http_response_code(200); header('Content-Type: application/json'); echo my_json_encode($result); } catch (DatabaseException $e) { Util::output_errors_and_die($e->getMessage(), 503); } catch (Exception $e) { Util::output_errors_and_die($e->getMessage(), 400); } }
function initDashboard() { include_once ABSPATH . "/php/CDBConn.php"; include_once ABSPATH . "/php/hostconfig.php"; $conn = new CDBConn($jet_ip, $db_name, $db_user, "qwerty123"); if (!$conn->connect_no_localhost()) { http_response_code(503); exit; } $cur_login = $_SESSION['g_username']; $get_hostel_id_sql = "SELECT hostel_id FROM users WHERE login = '******'"; $conn->run_query($get_hostel_id_sql); $line = $conn->fetch_array(); // We almost now from which hostel is user $hostel_id = $line['hostel_id']; // in case if hostel id is not set, it's an indicator that hostel definetely has not been configured yet. if ($hostel_id === NULL) { header("Location: /configure/index.php"); exit; } $get_is_configured_sql = "SELECT is_configured FROM hostels WHERE id = {$hostel_id}"; $conn->run_query($get_is_configured_sql); $line = $conn->fetch_array(); $is_configured = $line['is_configured']; // This is the case when user almost configured not if ($is_configured === 'f') { header("Location: /configure/index.php"); // exit(); } $conn->close(); }
function init() { try { $connection_string = 'mysql:host=' . \Idno\Core\Idno::site()->config()->dbhost . ';dbname=' . \Idno\Core\Idno::site()->config()->dbname . ';charset=utf8'; if (!empty(\Idno\Core\Idno::site()->config()->dbport)) { $connection_string .= ';port=' . \Idno\Core\Idno::site()->config()->dbport; } $this->client = new \PDO($connection_string, \Idno\Core\Idno::site()->config()->dbuser, \Idno\Core\Idno::site()->config()->dbpass, array(\PDO::MYSQL_ATTR_LOCAL_INFILE => 1)); $this->client->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); //$this->client->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false); } catch (\Exception $e) { error_log($e->getMessage()); if (!empty(\Idno\Core\Idno::site()->config()->forward_on_empty)) { header('Location: ' . \Idno\Core\Idno::site()->config()->forward_on_empty); exit; } else { http_response_code(500); if (\Idno\Core\Idno::site()->config()->debug) { $message = '<p>' . $e->getMessage() . '</p>'; $message .= '<p>' . $connection_string . '</p>'; } error_log($e->getMessage()); include \Idno\Core\Idno::site()->config()->path . '/statics/db.php'; exit; } } $this->database = \Idno\Core\Idno::site()->config()->dbname; $this->checkAndUpgradeSchema(); }
/** * @return void */ public function createAction() { if ($this->isAJAX() && $this->isRequestMethod('POST')) { $status = 400; $data = array("error" => 'bad_request'); $request = json_decode(file_get_contents('php://input')); if (filter_var($request->{'_csrf_token_register'}, FILTER_SANITIZE_STRING) && filter_var($request->{'_username'}, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[a-zA-Z0-9]{3,15}$/'))) && filter_var($request->{'_password'}, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[a-zA-Z0-9]{6,20}$/')))) { $status = 400; $data = array("error" => 'bad_request'); $csrf_token_register = htmlspecialchars($request->{'_csrf_token_register'}, ENT_QUOTES); if ($csrf_token_register == hash('sha256', Security::getCSRFToken('csrf_token_register'))) { $username = htmlspecialchars($request->{'_username'}, ENT_QUOTES); $password = htmlspecialchars($request->{'_password'}, ENT_QUOTES); $user = $this->loadModel('User'); $user->Username = $username; $user->Password = $password; $status = 409; $data = array('error' => 'username_is_taken'); if (!$user->isUsernameTaken()) { $id = $user->Save(array('username' => $username, 'password' => $user->Password)); if ($id > 0) { $role = $this->loadModel('Role'); $role->Save(array('user_id' => $id, 'role_id' => 1)); $status = 201; $data = array('id' => $id); } } } } http_response_code($status); echo json_encode($data); } else { Helper::redirectTo(WEB . 'register'); } }
public function setHeader($header, $value) { $code = http_response_code(); header($header . ': ' . $value, true); http_response_code($code); $this->flushed = false; }
/** * Create the chart controller * * @param int $show_full needed for use by charts module */ public function __construct($show_full = 1) { global $WT_TREE; parent::__construct(); $rootid = Filter::get('rootid', WT_REGEX_XREF); $this->root = Individual::getInstance($rootid, $WT_TREE); if (!$this->root) { // Missing root individual? Show the chart for someone. $this->root = $this->getSignificantIndividual(); } if (!$this->root || !$this->root->canShowName()) { http_response_code(404); $this->error_message = I18N::translate('This individual does not exist or you do not have permission to view it.'); } // Extract parameter from form if ($show_full) { $this->show_full = Filter::getInteger('show_full', 0, 1, $WT_TREE->getPreference('PEDIGREE_FULL_DETAILS')); } else { $this->show_full = 0; } $this->box = new \stdClass(); if ($this->showFull()) { $this->box->width = Theme::theme()->parameter('chart-box-x'); $this->box->height = Theme::theme()->parameter('chart-box-y'); } else { $this->box->width = Theme::theme()->parameter('compact-chart-box-x'); $this->box->height = Theme::theme()->parameter('compact-chart-box-y'); } }
/** * Used from an external API call to wp admin ajax to handle * freemius installations and uninstallations * */ public static function maybe_a_freemius_webhook() { $input = @file_get_contents('php://input'); $event_json = json_decode($input); if (!isset($event_json->id)) { self::ajax_fail('Hey man! This be no webhook.'); exit; } require_once EDD_SEGMENT_PATH . '/controllers/add-ons/freemius-sdk/Freemius.php'; $fs = new Freemius_Api('plugin', EDD_SEG_IO_FREEMIUS_PLUGIN_ID, EDD_SEG_IO_FREEMIUS_PUBLIC_KEY, EDD_SEG_IO_FREEMIUS_PRIVATE_KEY); $fs_event = $fs->Api("/events/{$event_json->id}.json"); $props = array('email' => $fs_event->objects->user->email, 'name' => $fs_event->objects->user->first . ' ' . $fs_event->objects->user->last, 'site_url' => $fs_event->objects->install->url); switch ($fs_event->type) { case 'install.installed': self::new_install($props); break; case 'install.uninstalled': $fs_uninstall = $fs->Api("/installs/{$fs_event->install_id}/uninstall.json"); $props['uninstall_code'] = $fs_uninstall->reason_id; $props['uninstall_reason'] = $fs_uninstall->reason; $props['uninstall_reason_info'] = $fs_uninstall->reason_info; self::new_uninstall($props); break; } http_response_code(200); exit; }
/** * Get the application's representation output. * * @return string The content of the representations output buffer. */ public function render() { // Set the proper HTTP Response Code. http_response_code($this->representation->status()); // Return the representation output. return $this->representation->output(); }
/** * Serve the documentation * * @throws Exception */ public static function serve() { $daux = new Daux(Daux::LIVE_MODE); $daux->initializeConfiguration(); $class = $daux->getProcessorClass(); if (!empty($class)) { $daux->setProcessor(new $class($daux, new NullOutput(), 0)); } // Set this critical configuration // for the tree generation $daux->getParams()['index_key'] = 'index'; // Improve the tree with a processor $daux->generateTree(); $server = new static($daux); try { $page = $server->handle($_REQUEST); } catch (NotFoundException $e) { http_response_code(404); $page = new ErrorPage('An error occured', $e->getMessage(), $daux->getParams()); } if ($page instanceof RawPage) { header('Content-type: ' . MimeType::get($page->getFile())); // Transfer file in 1024 byte chunks to save memory usage. if ($fd = fopen($page->getFile(), 'rb')) { while (!feof($fd)) { echo fread($fd, 1024); } fclose($fd); } return; } header('Content-type: text/html; charset=utf-8'); echo $page->getContent(); }
public function __construct($response, $data) { //ob_start('ob_gzhandler'); // SUCCESS RESPONSE CODE http_response_code(200); header("Content-Type: application/json; charset=utf-8"); header("Transfer-Encoding : deflate"); header("Content-Encoding : deflate"); // Wrap or no Wrap? // No Wrap is suggested by many, but can be used to measure time processed etc. // $response['timestamp'] = time(); // $response['processing_speed'] = microtime(true) - $GLOBALS['start']; // If ?callback is provided, encapsulate in ( ) for JSONP. if (isset($_GET['callback'])) { /* header("Access-Control-Allow-Orgin: *"); // allow any origin (Ip address ) to request our API header("Access-Control-Allow-Methods: *"); // allow any method from any origin to be sent to our API */ header("Content-Type: application/json"); echo $_GET['callback'] . "(" . json_encode($response) . ");"; } else { $response = array("success" => 1, "extra" => $response); echo json_encode($response, JSON_UNESCAPED_UNICODE); } // If response is empty throw error. Probably caused by our system, so counts as Internal Error. exit; }
function abort($msg) { header("Content-type: application/json"); http_response_code(500); echo json_encode($msg); exit; }
/** * setup configuration for Doctrine Dbal. * * @param array $db_config array config for override the default configuration. */ public function setupConfigurationDbal(array $db_config = []) { $dbal_config = new Configuration(); if (empty($db_config)) { //setup connection configuration. $config = new SystemConfig(); $config->load('db'); $db_params = $config->get('ALL', 'db'); unset($config, $db_params['table_prefix']); } else { $db_params = $db_config; unset($db_params['table_prefix']); } $dbal_config->setSQLLogger(new \System\Libraries\Db\Logger()); try { $this->Conn = DriverManager::getConnection($db_params, $dbal_config); $this->Conn->connect(); } catch (\Doctrine\DBAL\DBALException $e) { http_response_code(500); echo $e->getMessage(); exit; } $this->Conn->setFetchMode(\PDO::FETCH_OBJ); unset($dbal_config, $db_params); }
public function run($request, $verb = 'GET') { if (!in_array($verb, $this->cachedVerbs)) { return parent::run($request, $verb); } $key = call_user_func($this->keyGenerator, $request, $verb); try { $cached = $this->cache->get($key, $this->cacheNamespace); http_response_code($cached['code']); foreach ($cached['head'] as $head) { header($head); } echo $cached['body']; return $cached['rtrn']; } catch (\Exception $e) { ob_start(); $rtrn = parent::run($request, $verb); $body = ob_get_contents(); $head = headers_list(); $code = http_response_code(); ob_end_clean(); if (!$code || $code === 200) { $this->cache->set($key, ['rtrn' => $rtrn, 'head' => $head, 'body' => $body, 'code' => $code], $this->cacheNamespace, $this->cacheTimeout); } echo $body; return $rtrn; } }
public function route(Request $request = null) { $response = null; try { if ($request === null) { $request = Request::generate(); } $request->method = strtolower($request->method); if (!array_key_exists($request->method, $this->handlers) || $this->handlers[$request->method] === null) { throw new MethodNotAllowedException(); } $handler = $this->handlers[$request->method]; $response = $handler($request, $this->services); } catch (HTTPException $e) { $response = $e; } catch (Exception $e) { throw $e; $response = new InternalServerException(null, null, $e); } $response = $this->normalizeResponse($response); http_response_code($response->code); foreach ($response->headers as $key => $value) { header($key . ':' . $value); } echo $this->encodeResponse($response); }
public function getDescription() { $torrent_hashes = rtrim(rtrim($this->hashes, '/'), ','); $torrent_hashes = $this->shrinkWrapper->escape($torrent_hashes); $torrent_hashes = '\'' . $torrent_hashes . '\''; $hash = $this->hashes; $shrinkWrap = $this->shrinkWrapper; $results = $shrinkWrap->query("SELECT SQL_NO_CACHE description FROM descriptions WHERE torrent_hash = {$torrent_hashes} LIMIT 1"); if (empty($results)) { $pageJson = json_decode(file_get_contents("http://getstrike.net/api/v2/torrents/page/?hash={$hash}"), true); $torrent_page = $pageJson[0]["torrent_page"]; $kickassHTML = $this->get_url($torrent_page); $kickAssDescription = $this->get_string_between($kickassHTML, "<div class=\"textcontent\" id=\"desc\">", "<h2>"); $content = str_replace("//kastatic.com/images/blank.gif", "http://getstrike.net/img/blank.gif", $kickAssDescription); if (!strlen($content)) { $content = "This torrent has no description"; } $storecontent = base64_encode($content); $insertDescription = $shrinkWrap->query("REPLACE INTO descriptions (torrent_hash, description) VALUES ({$torrent_hashes}, '{$storecontent}')"); http_response_code(200); $json = "{\"statuscode\":200,\"message\":\"{$storecontent}\"}"; echo $json; } else { http_response_code(200); $message = $results[0]["description"]; $json = "{\"statuscode\":200,\"message\":\"{$message}\"}"; echo $json; } }
/** * Set the http status code for the response and optionally a message containing more information */ function set_status($code, $msg = false) { global $response; $response["status"] = $msg ? $msg : $response["status"]; $response["code"] = $code; http_response_code($code); }
function verificaRotas() { session_start(); require_once "scripts/funcoes-layout.php"; if ($_SESSION["logado"] == 1) { setLogado(true); } else { setLogado(false); } /* Verificação de rotas */ /*Pega as informações da URL*/ $rota = parse_url("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); /* Passa o path da URL para validação, removendo a primeira barra */ $path = preg_replace("/^\\/{1}/", "", $rota['path']); if ($path == "") { $path = "home.php"; } else { $path .= ".php"; $rotasCpanel = ["cpanel.php", "login.php", "edit-paginas.php"]; if (in_array($path, $rotasCpanel) && $_SESSION["logado"] != 1) { $path = "acesso-negado.php"; } if (!file_exists($path)) { http_response_code(404); $path = "404.php"; } } return $path; }