public static function p($status = 1, $msg = null, $data = [], $code = 200) { if (method_exists($msg, 'getMessage')) { $msg = $msg->getMessage(); } $response = new \Phalcon\Http\Response(); $response->setHeader("Content-Type", "application/json"); if ($status) { $response->setStatusCode(200); } else { $response->setStatusCode($code); } $response->setJsonContent(array('status' => $status == 1 ? 'success' : 'error', 'msg' => $msg, 'data' => $data)); $response->send(); }
/** * 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; }
/** * @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 }
public static function responseJson(array $data = array(), $state = 200) { $datetime = gmdate("D, d M Y H:i:s") . ' GMT'; $response = new \Phalcon\Http\Response(); $response->setHeader('Pragma', 'no-cache'); $response->setHeader('Cache-Control', 'no-cache, private, no-store, must-revalidate, pre-check=0, post-check=0, max-age=0, max-stale=0'); $response->setHeader('Last-Modified', $datetime); $response->setHeader('X-Frame-Options', 'SAMEORIGIN'); $response->setContentType('application/json', 'UTF-8'); $response->setExpires(new \DateTime()); $response->setStatusCode($state); $response->setEtag(md5($datetime)); $response->setJsonContent($data, JSON_UNESCAPED_UNICODE); $response->send(); // Force quit the dispatcher loop. exit; }
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 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 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 indexAction() { $response = new \Phalcon\Http\Response(); $response->setStatusCode(200, "OK"); // print get_class($this);exit; // 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; }
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; }
/** * 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; }
/** * 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(); } }
/** * 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'])); } }
$onlytestnet = ""; } $sql = sprintf("UPDATE cmd_nodes SET VersionID=%d WHERE KeepUpToDate=1{$onlytestnet}", $versionid); if ($result = $mysqli->query($sql)) { $info2 = $mysqli->info; if (is_null($info2)) { $info2 = true; } } else { $info2 = $mysqli->errno . ': ' . $mysqli->error; } //Change the HTTP status $response->setStatusCode(202, "Accepted"); $response->setJsonContent(array('status' => 'OK', 'data' => array('VersionId' => $versionid, "KeepUpToDate" => $info2))); } else { $response->setStatusCode(503, "Service Unavailable"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array($mysqli->errno . ': ' . $mysqli->error))); } } return $response; }); // ============================================================================ // End-point not found // ============================================================================ $app->notFound(function () use($app) { $response = new Phalcon\Http\Response(); $response->setStatusCode(404, "Not Found"); $response->setJsonContent(array('status' => 'ERROR', 'messages' => array('Unknown end-point'))); $response->send(); }); $app->handle();
$response->setStatusCode(500, "Internal Error"); $errors = array(); foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); //eliminamos un entidadcursosala por su id $application->delete('/api/entidadcursosalas/{id:[0-9]+}', function ($id) use($application) { //creamos la consulta con phql $phql = "DELETE FROM Entidadcursosala WHERE id = :id:"; $status = $application->modelsManager->executeQuery($phql, array('id' => $id)); //creamos una respuesta $response = new Phalcon\Http\Response(); //comprobamos si la eliminación se ha llevado a cabo correctamente if ($status->success() == true) { $response->setJsonContent(array('status' => 'OK')); } else { ////en otro caso cambiamos el estado http por un 500 $response->setStatusCode(500, "Internal Error"); $errors = array(); //mostramos los errores foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; });
$errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); // Send message to a selected user. $app->post('/chat/{sender}/{receiver}', function ($sender, $receiver) use($app) { $message = $app->request->getJsonRawBody(); $phql = "INSERT INTO Messages (sender_id, receiver_id, message_content)\n \t\tVALUES (:sender_id:, :receiver_id:, :message_content:)"; $status = $app->modelsManager->executeQuery($phql, array('sender_id' => $sender, 'receiver_id' => $receiver, 'message_content' => $message->message)); $response = new Phalcon\Http\Response(); if ($status->success() == true) { $phql = "SELECT * \n \t\t\tFROM Messages \n \t\t\tWHERE message_id = :message_id:"; $message = $app->modelsManager->executeQuery($phql, array('message_id' => $status->getModel()->message_id))->getFirst(); $response->setStatusCode(200, "Created"); $response->setJsonContent(array('status' => "OK", 'data' => $message)); } else { $response->setStatusCode(400, "Conflict"); $errors = array(); foreach ($status->getMessages() as $errorMessage) { $errors[] = $errorMessage->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); // Handles the cases where a non-existing resource is called. $app->notFound(function () use($app) { $app->response->setStatusCode(404, "Not Found")->sendHeaders(); echo "You've just typed me, and this is crazy, but this page was not found, so it doesn't exist maybe!";
/** * 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(); }
/** * Shows a post * * @param string $id */ public function showAction($id) { $cache = $this->di->get('viewCache'); $key = $this->createKey('posts', 'show', array($id)); $post = $cache->get($key); if ($post === null) { $post = Posts::findFirstByid($id); $cache->save($key, $post); } if (!$post) { $this->flashSession->error("post was not found"); $response = new \Phalcon\Http\Response(); $response->setStatusCode(404, "Not Found"); return $response->redirect("posts/index"); } $this->tag->prependTitle($post->title . " - "); $this->view->post = $post; }
public function getToken() { $response = new \Phalcon\Http\Response(); $response->setStatusCode(405); print_r($response->getStatusCode()); }
<?php $response = new Phalcon\Http\Response(); $response->setStatusCode(200, "OK"); $response->setContent("<html><body>Hello</body></html>"); $response->send();
public function runException(\Exception $ex) { $response = new \Phalcon\Http\Response(); $response->setStatusCode(400, 'Bad Request'); $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(); }