/** * Renders the uncaught exception for AJAX consumption. * * @param Phalcon\Http\Response $response * @param \Exception $exceptio * @return void */ protected function renderAJAX(Response $response, Exception $exception) { if ($this->config->debug) { $response->setJsonContent(['_exception' => $exception->getMessage() . ': ' . $exception->getTraceAsString()]); } else { $response->setJsonContent(['status' => false]); } }
public function indexAction($name) { $response = new Response(); $this->getData($name); if (!$this->result) { $response->setJsonContent(array('status' => 'NOT-FOUND')); } else { $response->setJsonContent(array('status' => 'FOUND', 'data' => $this->result)); } return $response; }
function getContent($robots) { //Create a response $response = new Response(); $data = array(); foreach ($robots as $robot) { array_push($data, $robot); } if ($data == false || count($data) == 0) { $response->setJsonContent(array('status' => 'NOT-FOUND')); } else { $response->setJsonContent(array('status' => 'FOUND', 'data' => $data)); } return $response; }
protected function jsonResponse($data) { $response = new Response(); $response->setContentType('application/json', 'UTF-8'); $response->setJsonContent($data); return $response; }
public function returnResult($result, $errorMessage = null) { $response = new Response(); $result = ['result' => $result, 'status' => $errorMessage === null ? self::SUCCESS_RESPONSE : self::FAILED_RESPONSE, 'error_message' => (string) $errorMessage]; $response->setJsonContent($result); return $response; }
/** * 发送数据 * @param mixed $result */ private static function sendResult($result) { $response = new Response(); $response->setHeader('Content-Type', 'application/json; charset=UTF-8'); $response->setHeader('Access-Control-Allow-Origin', '*'); $response->setJsonContent($result); $response->send(); exit; }
public function setJsonContent($content, $jsonOptions = 0, $depth = 512) { parent::setJsonContent($content, $jsonOptions, $depth); $this->setHeader('Access-Control-Allow-Origin', '*'); $this->setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'); $this->setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization'); $this->setHeader('E-Tag', md5($this->getContent())); $this->setContentType('application/json'); }
public function sendResponse() { if ($this->di->has('view')) { $this->di->get('view')->disable(); } $response = new Response(); $response->setContentType('application/json', 'utf8'); $response->setJsonContent($this->getResponse()); $response->send(); }
public function response($data = array(), $status = 200, $token = null) { $response = new Response(); $response->setStatusCode($status); $response->setContent(!empty($this->_statuses[$status]) ? $this->_statuses[$status] : null); $response->setHeader('Content-type', 'application/json'); $response->setHeader('api-version', '1.0'); $response->setHeader('singou-token', $token); $response->setJsonContent($data); return $response; }
/** * Votes for a poll option * * @param int $id Post ID * @param int $option Option ID * @return Response */ public function voteAction($id = 0, $option = 0) { $response = new Response(); if (!$this->checkTokenGetJson('post-' . $id)) { $csrfTokenError = ['status' => 'error', 'message' => 'This post is outdated. Please try to vote again.']; return $response->setJsonContent($csrfTokenError); } if (!($post = Posts::findFirstById($id))) { $contentNotExist = ['status' => 'error', 'message' => 'Poll does not exist']; return $response->setJsonContent($contentNotExist); } if (!($user = Users::findFirstById($this->session->get('identity')))) { $contentlogIn = ['status' => 'error', 'message' => 'You must log in first to vote']; return $response->setJsonContent($contentlogIn); } if (!($option = PostsPollOptions::findFirstById($option))) { $optionNotFound = ['status' => 'error', 'message' => 'Please select one option from the list below']; return $response->setJsonContent($optionNotFound); } if ($post->isParticipatedInPoll($user->id)) { $contentAlreadyVote = ['status' => 'error', 'message' => 'You have already voted this post']; return $response->setJsonContent($contentAlreadyVote); } $pollVote = new PostsPollVotes(); $pollVote->posts_id = $post->id; $pollVote->users_id = $user->id; $pollVote->options_id = $option->id; if (!$pollVote->save()) { foreach ($pollVote->getMessages() as $message) { /** @var \Phalcon\Mvc\Model\Message $message */ $contentError = ['status' => 'error', 'message' => $message->getMessage()]; return $response->setJsonContent($contentError); } } if ($post->users_id != $user->id) { $post->user->increaseKarma(Karma::SOMEONE_DID_VOTE_MY_POLL); $user->increaseKarma(Karma::VOTE_ON_SOMEONE_ELSE_POLL); } if (!$post->save()) { foreach ($post->getMessages() as $message) { /** @var \Phalcon\Mvc\Model\Message $message */ $contentErrorSave = ['status' => 'error', 'message' => $message->getMessage()]; return $response->setJsonContent($contentErrorSave); } } $viewCache = $this->getDI()->getShared('viewCache'); $viewCache->delete('post-' . $post->id); $viewCache->delete('poll-votes-' . $post->id); $viewCache->delete('poll-options-' . $post->id); $contentOk = ['status' => 'OK']; return $response->setJsonContent($contentOk); }
/** * Method Http accept: DELETE */ public function deleteAction() { $modelName = $this->modelName; $model = $modelName::findFirst($this->id); //delete if exists the object if ($model != false) { if ($model->delete() == true) { $this->response->setJsonContent(array('status' => "OK")); } else { $this->response->setStatusCode(409, "Conflict"); $errors = array(); foreach ($model->getMessages() as $message) { $errors[] = $this->language[$message->getMessage()] ? $this->language[$message->getMessage()] : $message->getMessage(); } $this->response->setJsonContent(array('status' => "ERROR", 'messages' => $errors)); } } else { $this->response->setStatusCode(409, "Conflict"); $this->response->setJsonContent(array('status' => "ERROR", 'messages' => array("O elemento não existe"))); } return $this->response; }
function res($req, $res) { $response = new Response(); $response->setContentType('application/json'); switch ($req) { case 'INDEX': if ($res == false) { $response->setJsonContent(array('status' => 'NOT-FOUND')); } else { $response->setJsonContent(array('status' => 'FOUND', 'data' => $res)); } break; case 'READ': if ($res == false) { $response->setJsonContent(array('status' => 'NOT-FOUND')); } else { $response->setJsonContent(array('status' => 'FOUND', 'data' => $res)); } break; default: if ($res->success() == true) { switch ($req) { case 'CREATE': $response->setStatusCode(201, 'Created'); break; case 'UPDATE': $response->setStatusCode(200, 'Update Successfully'); break; case 'DELETE': $response->setStatusCode(205, 'Delete Successfully'); break; } $response->setJsonContent(array('status' => 'OK')); } else { $response->setStatusCode(409, 'Conflict'); $errors = array(); foreach ($res->getMessages() as $message) { $errors[] = $message->getMEssage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } break; } return $response; }
function joinAction($id) { $response = new Response(); if (!$id) { $error = array("status" => "error", "message" => "No id was specified."); return $response->setJsonContent($error); } $league = Leagues::findFirst("id = '{$id}'"); if (!$league) { $error = array("status" => "error", "message" => "The league does not exist."); return $response->setJsonContent($error); } $uid = $this->session->get('user'); $lid = $league->id; $userLeague = UserLeagues::findFirst("lid = '{$lid}' AND uid = '{$uid}'"); if ($userLeague) { $error = array("status" => "error", "message" => "You are already a member of this league."); return $response->setJsonContent($error); } $userLeague = new UserLeagues(); $userLeague->uid = $uid; $userLeague->lid = $lid; if (!$userLeague->create()) { $error = array("status" => "error", "message" => "There was an error creating the league membership."); return $response->setJsonContent($error); } $success = array("status" => "success"); return $response->setJsonContent($success); }
} else { throw new \Exception('É necessário estar registrado no sistema para realizar requisições2.', StatusCodes::NAO_AUTORIZADO); } } else { return true; } } }); $app->setEventsManager($eventsManager); $app->error(function ($exception) { $response = new Response(); $response->setContentType('application/json', 'UTF-8'); $response->setStatusCode($exception->getCode()); $response->setHeader("Access-Control-Allow-Origin", "*"); $response->setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE"); $response->setHeader("Access-Control-Allow-Headers", "Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type"); $response->setJsonContent(['error' => $exception->getMessage()]); $response->send(); return false; }); $app->after(function () use($app) { $return = $app->getReturnedValue(); if ($return instanceof Response) { $return->send(); } else { $response = new Response(); $response->setContentType('application/json', 'UTF-8'); $response->setJsonContent($return); $response->send(); } });
/** * @param array $data * @param int $status * @return Response */ public function response($data = array(), $status = 200) { $response = new Response(); $response->setStatusCode($status); $response->setContent(!empty($this->_statuses[$status]) ? $this->_statuses[$status] : null); $response->setHeader('Content-type', 'application/json'); $response->setHeader('api-version', '1.0'); $devDebug = $this->request->get('devDebug'); if (true == $devDebug) { $profiles = $this->getDI()->get('profiler')->getProfiles(); foreach ($profiles as $profile) { $data['SQL Statement'] = $profile->getSQLStatement(); $data['Start Time'] = $profile->getInitialTime(); $data['Final Time'] = $profile->getFinalTime(); $data['Total Elapsed Time'] = $profile->getTotalElapsedSeconds(); } } $response->setJsonContent($data, JSON_PRETTY_PRINT); return $response; }
<?php use Phalcon\Mvc\Micro; use Phalcon\Http\Response; $app = new Micro(); $app->get('/api/frameworks', function () { $response = new Response(); $response->setContentType('application/json'); $data = [['name' => 'Zend', 'version' => '2.4.8'], ['name' => 'Symfony', 'version' => '2.7.5'], ['name' => 'Silex', 'version' => '1.3.4'], ['name' => 'Phalcon', 'version' => '2.0.8']]; $response->setJsonContent($data); return $response; }); $app->notFound(function () use($app) { $app->response->setStatusCode(404, 'Not Found')->sendHeaders(); echo 'The requested resource is not found'; }); $app->handle();
/** * Update widget order * * @return PResponse * @throws Exception */ public function updateWidgetOrderAction() { $response = new PResponse(); $content = ''; $response->setHeader("Content-Type", "application/json"); if ($this->request->isAjax()) { $widget_id = $this->request->getPost('widget_id', 'int'); $newIndex = $this->request->getPost('index', 'int'); $sidebar = str_replace(' ', '', $this->request->getPost('sidebar_name', ['string', 'striptags'])); if ($widget_id && $newIndex && $sidebar) { /** * @var CoreWidgetValues $widget */ $widget = CoreWidgetValues::findFirst($widget_id); /** * @var CoreSidebars $CoreSidebars */ $CoreSidebars = CoreSidebars::findFirst(['conditions' => 'sidebar_base_name = ?1', 'bind' => [1 => $sidebar]]); if ($widget && $CoreSidebars) { /** * @var CoreTemplates $defaultFrontendTemplate */ $defaultFrontendTemplate = CoreTemplates::findFirst("location = 'frontend' AND published = 1"); $themeName = $defaultFrontendTemplate->base_name; $widget->reOder('sidebar_base_name = ?1', [1 => $CoreSidebars->sidebar_base_name]); $widget->reOder('sidebar_base_name = ?1', [1 => $widget->sidebar_base_name]); if ($widget->ordering > $newIndex) { $queryUp = "UPDATE core_widget_values SET ordering = ordering + 1 WHERE ordering >= {$newIndex} AND theme_name = '{$themeName}' AND sidebar_base_name = '{$sidebar}'"; $queryDown = "UPDATE core_widget_values SET ordering = ordering - 1 WHERE ordering < {$newIndex} AND theme_name = '{$themeName}' AND sidebar_base_name = '{$sidebar}'"; } elseif ($widget->ordering < $newIndex) { $queryUp = "UPDATE core_widget_values SET ordering = ordering + 1 WHERE ordering > {$newIndex} AND theme_name = '{$themeName}' AND sidebar_base_name = '{$sidebar}'"; $queryDown = "UPDATE core_widget_values SET ordering = ordering - 1 WHERE ordering <= {$newIndex} AND theme_name = '{$themeName}' AND sidebar_base_name = '{$sidebar}'"; } if (isset($queryUp) && isset($queryDown)) { $this->db->execute($queryUp); $this->db->execute($queryDown); } $widget->ordering = $newIndex; $widget->sidebar_base_name = $CoreSidebars->sidebar_base_name; if ($widget->save()) { $content = '1'; $widget->reOder('sidebar_base_name = ?1', [1 => $sidebar]); $widget->reOder('sidebar_base_name = ?1', [1 => $CoreSidebars->sidebar_base_name]); } else { //Do something } } } } $response->setJsonContent($content); return $response; }
/** * Accepts a reply as correct answer */ public function acceptAction($id = 0) { $response = new Response(); /** * Find the post using get */ $postReply = PostsReplies::findFirstById($id); if (!$postReply) { $contentNotExist = array('status' => 'error', 'message' => 'Post reply does not exist'); return $response->setJsonContent($contentNotExist); } $user = Users::findFirstById($this->session->get('identity')); if (!$user) { $contentLogIn = array('status' => 'error', 'message' => 'You must log in first to vote'); return $response->setJsonContent($contentLogIn); } if ($postReply->accepted == 'Y') { $contentAlready = array('status' => 'error', 'message' => 'This reply is already accepted as answer'); return $response->setJsonContent($contentAlready); } if ($postReply->post->deleted) { $contentDeleted = array('status' => 'error', 'message' => 'Post associated to the reply is deleted'); return $response->setJsonContent($contentDeleted); } if ($postReply->post->accepted_answer == 'Y') { $contentAlreadyAnswer = array('status' => 'error', 'message' => 'This post already has an accepted answer'); return $response->setJsonContent($contentAlreadyAnswer); } if ($postReply->post->users_id != $user->id && $user->moderator != 'Y') { $contentCorrect = array('status' => 'error', 'message' => 'You can\'t accept this answer as correct'); return $response->setJsonContent($contentCorrect); } if ($postReply->post->users_id != $postReply->users_id) { $postReply->post->user->karma += Karma::SOMEONE_ELSE_ACCEPT_YOUR_REPLY; $postReply->post->user->votes_points += Karma::SOMEONE_ELSE_ACCEPT_YOUR_REPLY; $points = 30 + intval(abs($user->karma - $postReply->user->karma) / 1000); $parametersBounty = array('users_id = ?0 AND posts_replies_id = ?1', 'bind' => array($postReply->users_id, $postReply->id)); $postBounty = PostsBounties::findFirst($parametersBounty); if ($postBounty) { $points += $postBounty->points; } $postReply->user->karma += $points; $postReply->user->votes_points += $points; if ($postReply->users_id != $user->id && $postReply->post->users_id != $user->id) { $user->karma += Karma::SOMEONE_ELSE_ACCEPT_YOUR_REPLY; $user->votes_points += Karma::SOMEONE_ELSE_ACCEPT_YOUR_REPLY; } } $postReply->accepted = 'Y'; $postReply->post->accepted_answer = 'Y'; if ($postReply->save()) { if (!$user->save()) { foreach ($user->getMessages() as $message) { $contentError = array('status' => 'error', 'message' => $message->getMessage()); return $response->setJsonContent($contentError); } } } if ($user->id != $postReply->users_id) { $activity = new ActivityNotifications(); $activity->users_id = $postReply->users_id; $activity->posts_id = $postReply->post->id; $activity->posts_replies_id = $postReply->id; $activity->users_origin_id = $user->id; $activity->type = 'A'; $activity->save(); } $contentOk = array('status' => 'OK'); return $response->setJsonContent($contentOk); }
<?php /** * Local variables * @var \Phalcon\Mvc\Micro $app */ use Phalcon\Http\Response; /** * get all entry */ $app->get('/todoEntries', function () { $response = new Response(); $response->setStatusCode(403, "Unauthorized"); $response->setJsonContent(array('status' => 'ERROR', 'data' => Users::sayHello(), 'message' => 'failed to access')); return $response; }); /** * search entry with name */ $app->get('/todoEntries/search/{name}', function ($name) { // TODO: token必須 }); /** * get specific entry */ $app->get('/todoEntries/{id:[0-9]+}', function ($id) { // TODO: token必須 }); /** * add entry */
public function listAction() { $response = new Response(); $response->setHeader('Content-Type', 'application/json'); $datas = array(); if ($this->request->get('active') == '1') { $profiles = Profiles::find(array("active = 'Y'", "columns" => 'id, name, active')); } else { $profiles = Profiles::find(array("columns" => 'id, name, active')); } foreach ($profiles as $profile) { $datas[] = $profile; } $response->setJsonContent($datas); return $response; }
/** * Finds related posts */ public function findRelatedAction() { $response = new Response(); $indexer = new Indexer(); $results = $indexer->search(['title' => $this->request->getPost('title')], 5); $contentOk = ['status' => 'OK', 'results' => $results]; return $response->setJsonContent($contentOk); }
/** * @Get("") */ public function getAction() { $response = new Response(); $response->setJsonContent(User::find()); return $response; }
<?php /** * Local variables * @var \Phalcon\Mvc\Micro $app */ use Phalcon\Http\Response; /** * get all entry */ $app->get('/users', function () { $response = new Response(); $response->setStatusCode(200, "OK"); $response->setJsonContent(array('status' => 'OK', 'data' => Users::sayHello(), 'message' => 'success to access')); return $response; }); /** * search entry with name */ $app->get('/users/search/{name}', function ($name) { }); /** * get specific entry */ $app->get('/users/{id:[0-9]+}', function ($id) { }); /** * add entry */ $app->post('/users', function () { // TODO: token�K�{
//Set request object $di->set("request", "Phalcon\\Http\\Request", true); //Instantiate Phalcon Micro framework $app = new Micro(); $app->setDI($di); //Create response object $response = new Response(); /** * Get random image */ $app->get('/images/random', function () use($app, $response) { $manager = $app->getDI()->get('modelsManager'); $minMax = $manager->createBuilder()->from('Images')->columns('min(id) as minimum, max(id) as maximum')->getQuery()->getSingleResult(); $id = rand($minMax->minimum, $minMax->maximum); $image = new Images(); $response->setJsonContent($image->getImageInfo($id)); $response->send(); }); /** * Get specific image */ $app->get('/image/{id:[0-9]+}', function ($id) use($app, $response) { $image = new Images(); $response->setJsonContent($image->getImageInfo($id)); $response->send(); }); /** * Get latest tags */ $app->get('/tags/latest', function () use($app, $response) { $request = $app->getDI()->get('request');
public function setJsonContent($content, $jsonOptions = 0) { return parent::setJsonContent($content, $jsonOptions); }
//$response->setJsonContent($image->imagesTags); $images = Images::findById($id); //(['limit' => 10]); $data = []; $i = 0; foreach ($images as $image) { foreach ($image->getImagesTags() as $tag) { foreach ($tag->getTags() as $tag2) { $data[$i]['id'] = $image; $data[$i]['tag'] = $tag2; $data[$i]['imageTagId'] = $tag; $i++; } } } $response->setJsonContent($data); }); $app->get('/images/{offset:[0-9]+}/{limit:[0-9]+}', function ($offset, $limit) use($response) { $robots = Images::find(['offset' => $offset, 'limit' => $limit]); $data = []; foreach ($robots as $robot) { $data[] = $robot; } $response->setJsonContent($data); }); $app->get('/img_resize/{id:[0-9]+}', function ($id) use($app, $response) { $image = Images::findFirstById($id); if (count($image) > 0) { $resized_file = str_replace('http://hack4dk.dr.dk/', '/home/ubuntu/workspace/resized_images/', $image->url); $percent = 0.2; if (!file_exists($resized_file)) {
public function setJsonContent($content, $jsonOptions = 0, $depth = 512) { parent::setJsonContent($content, $jsonOptions, $depth); $this->setContentType('application/json', 'UTF-8'); $this->setHeader('E-Tag', md5($this->getContent())); }
/** * @param Response $response * @param ModelInterface $book */ private function createErrorResponse(Response $response, ModelInterface $book) { $response->setStatusCode(409, "Conflict"); $errors = []; foreach ($book->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(['status' => 'ERROR', 'messages' => $errors]); }
$response->setJsonContent(array('status' => 'OK')); } else { //Change the HTTP status $response->setStatusCode(409, "Conflict"); //Send errors to the client $errors = array(); foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; }); $app->delete('/jadwal/{id}', function ($id) use($app) { $phql = "DELETE FROM Jadwal WHERE id_jadwal = :id:"; $status = $app->modelsManager->executeQuery($phql, array('id' => $id)); //Create a response $response = new Response(); if ($status->success() == true) { $response->setJsonContent(array('status' => 'OK')); } else { //Change the HTTP status $response->setStatusCode(409, "Conflict"); $errors = array(); foreach ($status->getMessages() as $message) { $errors[] = $message->getMessage(); } $response->setJsonContent(array('status' => 'ERROR', 'messages' => $errors)); } return $response; });
/** * Get menu item * * @return \Phalcon\Http\Response * REST service return menu item information */ public function getMenuItemsAction() { /** * @var MenuItems[] $menuItems */ $menuItems = MenuItems::find(['id in (' . $this->request->getPost('ids') . ')']); $response = new Response(); $response->setHeader('Content-Type', 'application/json'); if (count($menuItems) > 0 && method_exists($menuItems, 'toArray')) { $response->setJsonContent($menuItems->toArray()); } else { $response->setJsonContent([]); } return $response; }