/** * @param $data response to send back as JSON with Callback * @param bool|true $success * @param int $status_code of response default 200 * @param string $status_message of response default OK */ public function response($data, $success = true, $status_code = 200, $status_message = "OK") { //new response $response = new \Phalcon\Http\Response(); //header('Access-Control-Allow-Origin: *'); $response->setStatusCode($status_code, $status_message); $response->setContentType('application/json', 'utf-8'); $response->setHeader('Access-Control-Allow-Origin', '*'); //encode call $json = json_encode(array('success' => $success, 'data' => $data)); //set response to send back check for callback $response->setContent(isset($_GET['callback']) ? "{$_GET['callback']}({$json})" : $json); $response->send(); exit; //kill from other processing }
/** * Create a Response object with related parameters * * @param string $content * @param int $status * @param string $contentType * @param null $message * @return \Phalcon\Http\Response */ protected function createResponse($content = self::NO_CONTENT, $status = self::STATUS_OK, $contentType = self::JSON, $message = null) { $response = new \Phalcon\Http\Response(); // Allow CORS $response->setHeader(self::HEADER_ALLOW_ORIGIN, "*"); // set new token to protected api if (!in_array($this->dispatcher->getActionName(), $this->publicAction) && !in_array($this->dispatcher->getActionName(), $this->authErrAction)) { $response->setHeader(self::HEADER_ACCESS_TOKEN, $this->session->get("loggedInUser")->access_token); } if ($message) { $response->setStatusCode($status, $message); } else { $response->setStatusCode($status, self::$MESSAGES[$status]); } if ($content !== self::NO_CONTENT) { $response->setHeader(self::HEADER_CONTENT_TYPE, $contentType); if ($contentType == BaseRestApiController::JSON) { $response->setJsonContent($content); } else { $response->setContent($content); } } return $response; }
public function applicationsAction() { $date = new DateTime("now"); if ($this->request->isPost() and $this->request->isAjax()) { $start_from = $this->request->getPost('start_from', 'int'); $type = $this->request->getPost('type', 'int'); if ($type == 1) { $apps = Application::find(array('conditions' => 'confirmed = 0 and term >= ?1', 'order' => 'term DESC', 'limit' => '5', 'offset' => $start_from, 'bind' => array(1 => $date->format('Y.m.d')))); } else { if ($type == 2) { $apps = Application::find(array('conditions' => 'confirmed = 1 and term >= ?1', 'order' => 'term DESC', 'limit' => '5', 'offset' => $start_from, 'bind' => array(1 => $date->format('Y.m.d')))); } else { if ($type == 3) { $apps = Application::find(array('conditions' => 'confirmed = 1 and term < ?1', 'order' => 'term DESC', 'limit' => '5', 'offset' => $start_from, 'bind' => array(1 => $date->format('Y.m.d')))); } else { $apps = array(); } } } $services = array(); $users = array(); foreach ($apps as $key => $app) { $str = ""; $a_ss = ApplicationService::find(array('conditions' => 'application_id = ?1', 'bind' => array(1 => $app->id))); foreach ($a_ss as $a_s) { $service = Service::findFirst(array('conditions' => 'id = ?1', 'bind' => array(1 => $a_s->service_id))); $str .= $service->name . ', '; } $services[$key] = substr($str, 0, -2) . '.'; $car = Car::findFirst(array('conditions' => 'number = ?1', 'bind' => array(1 => $app->car))); $users[$key] = User::findFirst(array('conditions' => 'id = ?1', 'bind' => array(1 => $car->owner))); } if (count($apps) > 0) { $view = clone $this->view; $view->start(); $view->setRenderLevel(View::LEVEL_ACTION_VIEW); $view->setParamToView('apps', $apps); $view->setParamToView('type', $type); $view->setParamToView('services', $services); $view->setParamToView('users', $users); $view->render('admin', 'applications'); $view->finish(); $content = $view->getContent(); $this->view->disable(); $status = 200; $description = 'OK'; $headers = array(); $contentType = 'application/json'; $content = json_encode($content); $response = new \Phalcon\Http\Response(); $response->setStatusCode($status, $description); $response->setContentType($contentType, 'UTF-8'); $response->setContent($content); foreach ($headers as $key => $value) { $response->setHeader($key, $value); } return $response; } else { return 0; } } }
public function loadMoreAction() { if ($this->request->isPost() && $this->request->isAjax()) { $start_from = $this->request->getPost('start_from', 'int'); $type = $this->request->getPost('type', 'int'); $posts = Post::find(array('conditions' => 'is_service = ?1', 'bind' => array(1 => $type), 'order' => 'id DESC', 'limit' => 10, 'offset' => $start_from)); $tags = array(); foreach ($posts as $index => $post) { $pts = PostTag::find(array('conditions' => 'post_id = ?1', 'bind' => array(1 => $post->id))); $tags[$index] = array(); foreach ($pts as $pt) { $tags[$index][] = Tag::findFirst(array('conditions' => 'id = ?1', 'bind' => array(1 => $pt->tag_id))); } } if (count($posts) > 0) { $view = clone $this->view; $view->start(); $view->setRenderLevel(View::LEVEL_ACTION_VIEW); $view->setParamToView('posts', $posts); $view->setParamToView('tags', $tags); $view->render('index', 'loadMore'); $view->finish(); $content = $view->getContent(); $this->view->disable(); $status = 200; $description = 'OK'; $headers = array(); $contentType = 'application/json'; $content = json_encode($content); $response = new \Phalcon\Http\Response(); $response->setStatusCode($status, $description); $response->setContentType($contentType, 'UTF-8'); $response->setContent($content); foreach ($headers as $key => $value) { $response->setHeader($key, $value); } return $response; } else { return 0; } } }
public function prepareTimePickerAction() { if ($this->request->isPost() && $this->request->isAjax()) { $date = $this->request->getPost('date'); $termin = strtotime($date) + 9 * 60 * 60; $termins = array(); for ($i = 0; $i < 20; $i++) { $apps = Application::find(array('conditions' => 'term = ?1', 'bind' => array(1 => date("Y.m.d H:i", $termin)))); if (count($apps) >= 4) { $termins[date("H:i", $termin)] = 1; } else { $termins[date("H:i", $termin)] = 0; } $termin += 30 * 60; } $view = clone $this->view; $view->start(); $view->setRenderLevel(View::LEVEL_ACTION_VIEW); $view->setParamToView('termins', $termins); $view->render('user', 'prepareTimePicker'); $view->finish(); $content = $view->getContent(); $this->view->disable(); $status = 200; $description = 'OK'; $headers = array(); $contentType = 'application/json'; $content = json_encode($content); $response = new \Phalcon\Http\Response(); $response->setStatusCode($status, $description); $response->setContentType($contentType, 'UTF-8'); $response->setContent($content); foreach ($headers as $key => $value) { $response->setHeader($key, $value); } return $response; } }
public function deleteAction() { $response = new \Phalcon\Http\Response(); $delete_url = $this->request->getPost("delete_url"); $status = Git::deleteRepository($delete_url, $this->session->get('token')); return $response->setContent($status); }
public function indexAction() { $html = $this->view->render('login/index'); $response = new \Phalcon\Http\Response(); $response->setContent($html); return $response; }
public function getAction() { // Getting a response instance $response = new \Phalcon\Http\Response(); $feed = $response->setContent($feed->asString()); //Return the response return $response; }
public function deleteAction($id) { $response = new \Phalcon\Http\Response(); $response->setStatusCode(200, "OK"); $response->setContent("Town deleted"); $town = Town::findFirst($id); if (!$town) { $response->setStatusCode(204, "No Content"); $response->setContent(""); } else { if (!$town->delete()) { $response->setStatusCode(403, "Forbidden"); $response->setContent("Cannot delete town"); } } return $response; }
public function table1Action() { $this->view->disable(); if ($this->request->isAjax() == true) { $response = new \Phalcon\Http\Response(); $response->setContentType('application/json', 'UTF-8'); $db_data = new Data(); $response->setContent($db_data->get_table_data_json($this->request->getPost(), $this->config->table_1->toArray())); return $response; } }
public function indexAction() { $client = new Everyman\Neo4j\Client('localhost', 7474); $this->view->disable(); //Create a response instance $response = new \Phalcon\Http\Response(); //Set the content of the response $response->setContent(json_encode($client->getServerInfo())); $response->setContentType('application/json', 'UTF-8'); //Return the response return $response; }
protected function respondWithStatusCode($code = HttpStatusCode::OK, $message = null) { $this->view->disable(); $response = new \Phalcon\Http\Response(); $response->setStatusCode($code, HttpStatusCode::getMessage($code)); if ($this->request->isAjax() || $this->clientAcceptsJson()) { $data = new \stdClass(); $data->message = $message; $response->setContentType("application/json", "utf-8"); $response->setJsonContent($data, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK); } else { $response->setContent($message); } return $response; }
public function indexAction() { $client = new Client('localhost', 7474); $lat = $this->request->getQuery("lat", "float", 0.0); $lng = $this->request->get('lng', "float", 0.0); $distance = $this->request->get('distance', "float", 500); $offset = $this->request->get('offset', "int", 0); $limit = $this->request->get('limit', "int", 5); $cache =& $this->di->get('cache'); $redis_key = implode('|', array('AirportsController', 'indexAction', $lat, $lng, $distance, $offset, $limit)); try { // If Redis is connected - try to get result. $result = $cache->get($redis_key); $cache_connected = true; } catch (Exception $e) { $result = false; $cache_connected = false; } if ($result) { $result = unserialize($result); } else { $result = array(); $query = sprintf("START n=node:geom('withinDistance:[%s, %s, %s]')\n MATCH n-[r:AVAILABLE_DESTINATION]->()\n RETURN DISTINCT n\n SKIP %s LIMIT %s", number_format($lat, 6), number_format($lng, 6), number_format($distance, 1), $offset, $limit); $query = new Cypher\Query($client, $query); $query = $query->getResultSet(); foreach ($query as $row) { $item = array('id' => $row['n']->getId(), 'distance' => _distance($row['n']->getProperties()['latitude'], $row['n']->getProperties()['longitude'], $lat, $lng)); foreach ($row['n']->getProperties() as $key => $value) { $item[$key] = $value; } $result[] = $item; } if ($cache_connected) { $cache->set($redis_key, serialize($result)); } } $this->view->disable(); $response = new \Phalcon\Http\Response(); // Set the content of the response. $response->setContent(json_encode(array('json_list' => $result))); $response->setContentType('application/json', 'UTF-8'); return $response; }
/** * Process response * @param mixed $options array('status', 'message', 'data', 'allow') * @return mixed */ public function processResponse($options = array()) { if (empty($options)) { return false; } // Create a response $response = new Phalcon\Http\Response(); // set allow response field if (!empty($options['allow']) && is_array($options['allow'])) { $response->setRawHeader("Allow: " . implode(",", $options['allow'])); } // Set the Content-Type header $response->setContentType('application/json'); $response->setStatusCode($options['status']); // 204 response code should not contain http body if ($options['status'] != 204 && !empty($options['payload'])) { $response->setContent(json_encode($options['payload'])); } return $response; }
public function beforeDispatch(Event $event, Dispatcher $dispatcher) { $controller = $dispatcher->getControllerName(); /* if you are attempting to access login controller, allow it to execute */ if ($controller == "login" || $controller == "register") { return; } /* get the username/password from the post */ $request = new \Phalcon\Http\Request(); $username = $request->getPost("username"); $password = $request->getPost("password"); $auth_model = new Users(); /* authenticate if attempt to login has been made */ if (!empty($username) && !empty($password)) { $this->authenticate($username, $password, $auth_model); } /* logout auth */ if ($controller == "logout") { $this->session->set("authorize", serialize((object) array())); $response = new \Phalcon\Http\Response(); $response->redirect()->sendHeaders(); exit; } /* if authentication failed for some reason */ if (!$this->isAuthenticated()) { if ($request->isAjax()) { /* send failure response */ $response = new \Phalcon\Http\Response(); $response->setContent(json_encode(array('error' => 'invalid_auth')))->send(); exit; } else { /* stay on the login page */ $dispatcher->forward(array('controller' => 'login', 'action' => 'index')); return false; } } }
$gatewaysArray = array(); foreach ($gateways as $gateway) { $gatewayArray = $gateway->toArray(); unset($gatewayArray['ID']); $gatewaysArray[] = $gatewayArray; } // Pass the content of a file $response->setContent(json_encode($gatewaysArray)); return $response; }); $app->get('/gateways/{eui}', function ($eui) use($app) { $response = new Phalcon\Http\Response(); $response->setContentType('application/json'); $gateway = Gateway::findFirstByEui($eui); if (empty($gateway)) { $response->setContent('Gateway not found'); $response->setStatusCode(404, "Not Found"); return $response; } $gatewayArray = $gateway->toArray(); $gatewayArray['entries_in_last_24h'] = '<to be implemented>'; unset($gatewayArray['ID']); // Pass the content of a file $response->setContent(json_encode($gatewayArray)); return $response; }); /** * Not found handler */ $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders();
/** * Initializes the router */ protected function initRouter() { $config = $this->di['config']; // Not-Found Handler $this->app->notFound(function () { // Create a response $response = new Phalcon\Http\Response(); // Set the Content-Type header $response->setContentType('application/json'); $response->setStatusCode(404, "Not Found"); $response->setContent(json_encode(array('status' => 'failure', 'data' => array(), 'error' => array('code' => 404, 'message' => 'Invalid endpoint request')))); return $response; }); // Define the routes from config foreach ($config['routes'] as $items) { // load routes based on controller/action $className = $items['controller']; $myController = new $className(); $this->app->{$items}['method']($items['route'], array($myController, $items['action'])); } }
<?php // Getting a response instance $response = new \Phalcon\Http\Response(); //Set status code $response->setStatusCode(404, "Not Found"); //Set the content of the response $response->setContent("Sorry, the page doesn't exist"); //Send response to the client $response->send();
<?php $response = new Phalcon\Http\Response(); $response->setStatusCode(200, "OK"); $response->setContent("<html><body>Hello</body></html>"); $response->send();
public function searchAction() { // get latitude and longitude via google maps api service. $request = $this->request; $this->view->disable(); $response = new \Phalcon\Http\Response(); $res = $_GET["location"]; // $_GET parameter $address = urlencode($res); $Response = array('success' => $res); $url = "https://maps.google.com/maps/api/geocode/json?sensor=true&address={$address}&key=AIzaSyBSR4ZUyKhxVcN3eMNzQWnm8YSdP-KE8uM"; $Res = file_get_contents($url); $resp = json_decode($Res, true); $lat = $resp['results'][0]['geometry']['location']['lat']; $lng = $resp['results'][0]['geometry']['location']['lng']; $res = array("lat" => $lat, "lng" => $lng); $response->setContent(json_encode($res)); $response->setContentType('application/json', 'UTF-8'); return $response; }
<?php $app->get('/show/data', function () { //Create a response $response = new Phalcon\Http\Response(); //Set the Content-Type header $response->setContentType('text/plain'); //Pass the content of a file $response->setContent(file_get_contents("data.txt")); //Return the response return $response; });
/** * Render the exception. * * @param mixed $e * @param int $status_code * @return mixed */ public function render($e, $status_code = null) { if (is_cli()) { dd(['message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine()]); return; } $content = (new ExceptionHandler(config()->app->debug))->getHtml($e); if (di()->has('response')) { $response = di()->get('response'); } else { $response = new \Phalcon\Http\Response(); } if (method_exists($e, 'getStatusCode')) { $response->setStatusCode($e->getStatusCode()); } # here, if the $status_code is not empty # that means we should over-ride the current status code # using the provided one if ($status_code) { $response->setStatusCode($status_code); } $response->setContent($content); return $response->send(); }
/** * Main run block that executes the micro application * */ public function run() { // Handle any routes not found $this->notFound(function () { $response = new \Phalcon\Http\Response(); $response->setStatusCode(404, 'Not Found')->sendHeaders(); $response->setContent('Page doesn\'t exist.'); $response->send(); }); $this->handle(); }
/** * Run the application. * * @throws Exception Service exceptions that have bubbled to the surface. * * @return void */ public function run() { // Capture runtime errors register_shutdown_function(['\\Eyas\\Utilities\\Debug\\PhpError', 'runtimeShutdown']); try { // Record any php warnings/errors set_error_handler(['\\Eyas\\Utilities\\Debug\\PhpError', 'errorHandler']); // Setup App (dependency injector, configuration variables and autoloading resources/classes) $this->setConfig($this->getConfigPath() . '/' . $this->getConfigFileName()); // Get Authentication Headers $clientId = $this->request->getHeader('API_ID'); $time = $this->request->getHeader('API_TIME'); $hash = $this->request->getHeader('API_HASH'); $privateKey = \Eyas\Mvc\Model\Api::findFirst(array('public_id' => $clientId))->private_key; $data = (array) $this->request->getJsonRawBody(); if (isset($data['_url'])) { // remove _url from the user submitted data unset($data['_url']); } $message = new \Eyas\Micro\Messages\Auth($clientId, $time, $hash, $data); // Setup HMAC Authentication callback to validate user before routing message // Failure to validate will stop the process before going to proper Restful Route $this->setEvents(new \Eyas\Events\Api\HmacAuthenticate($message, $privateKey)); // Setup RESTful Routes $this->setRoutes($this->getConfigPath() . '/' . $this->getRoutesFileName()); // Handle any routes not found $this->notFound(function () { $response = new \Phalcon\Http\Response(); $response->setStatusCode(501, 'Not Implemented')->sendHeaders(); $response->setContent('The method requested has not been implemented.' . ' It may be in the future.'); $response->send(); }); $this->handle(); } catch (\Exception $e) { // Do Something I guess, return Server Error message $this->response->setStatusCode(500, "Server Error"); $this->response->setContent($e->getMessage()); $this->response->send(); } }