/** * 发送数据 * @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 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; }
public function rawAction() { $plain_response = new Response(); $plain_response->setHeader("Content-Type", "text/plain"); $plain_response->setContent($this->paste->content); return $plain_response; }
public function __construct() { parent::__construct(); parent::setHeader('Access-Control-Allow-Origin', '*'); parent::setHeader('Access-Control-Allow-Headers', 'X-Requested-With'); $this->setStatusCode(self::DEFAULT_STATUS_CODE); }
/** * 创建JSON格式的Http响应 * * @param integer $status 状态码, 该状态码采用HTTP状态码近似, 但为数据输出. 该Http响应的状态码始终为200 * @param string $explain 状态描述 * @param array $data 响应数据 * @return Response */ public function responseJson($status = 200, $explain = '', $data = array()) { $response = new Response(); $response->setStatusCode(200, 'OK'); $response->setHeader("Content-Type", "text/json"); $contents = array('statusCode' => $status, 'explain' => $explain, 'original_val' => isset($_GET['original_val']) ? $_GET['original_val'] : $this->request->getPost('original_val', null, ''), 'data' => (object) $data); $response->setContent(json_encode($contents, true)); return $response; }
public function handleAction() { $debugbar = $this->debugbar; $debugbar->enable(); $openHandler = new OpenHandler($debugbar); $data = $openHandler->handle(null, false, false); $response = new Response($data, 200); $response->setHeader('Content-Type', 'application/json'); return $response; }
/** * 向Client发送响应的资源 */ public function send() { if (is_array($this->resource) || is_object($this->resource)) { $this->response->setHeader('Content-Type', 'text/json'); $this->response->setContent(json_encode($this->resource, true)); } else { $this->response->setContent($this->resource); } $this->response->send(); }
public function toResponse() { $response = new Response($this->getMessage(), $this->getCode()); $headers = $this->getHeaders(); foreach ($headers as $name => $value) { if (is_numeric($name)) { list($name, $value) = explode(':', $value); } $response->setHeader(trim($name), trim($value)); } return $response; }
/** * PHPWebDevelopers\Api\Common\Http\Response constructor * * @param string $content * @param int $code * @param string $status */ public function __construct($content = null, $code = null, $status = null) { parent::__construct($content, $code, $status); $request = new PhalconRequest(); //@TODO Security fail!! Please do not go with this BETA $origin = $request->getHeader("ORIGIN"); if (!empty($origin)) { parent::setHeader("Access-Control-Allow-Origin", $origin); } parent::setContentType(self::CONTENT_TYPE_JSON, self::CHARSET); parent::setHeader("Access-Control-Allow-Methods", self::ALLOW_METHODS); parent::setHeader("Access-Control-Allow-Headers", self::ALLOW_HEADERS); parent::setHeader("Access-Control-Allow-Credentials", self::ALLOW_CREDENTIALS); }
/** * 返回所有国家 * @api /country/ * @return [type] [description] */ public function indexAction() { $countries = Countries::find(); $requestCnt = array_pick($this->request->getAcceptableContent(), 'accept', true); if (in_array('application/json', $requestCnt)) { $response = new Response(); $response->setHeader("Content-Type", "application/json"); echo json_encode($countries->toArray()); $this->view->disable(); } else { $this->view->setVar('countries', $countries); $this->view->setVar('title', '世界国家'); } }
/** * Выполняет все плагины по цепочке * * @param \Phalcon\Http\Request $request * @return string */ public function process(Request $request) { $response = new Response(); $pluginResult = new PluginResult(); foreach ($this->_arPlugins as $plugin) { $pluginResult = $plugin->process($request, $pluginResult); if ($pluginResult->terminate) { break; } } if ($pluginResult->error) { $response->setStatusCode($pluginResult->errorCode, $pluginResult->errorMessage); $response->setContent($pluginResult->errorMessage); return $response; } else { $response->setStatusCode(200, "OK"); } $callback = $request->getQuery('callback'); $result = ''; if ($callback) { $response->setHeader('Content-Type', 'application/javascript'); $result .= $callback . '('; } else { $response->setHeader('Content-Type', 'application/json'); } $result .= json_encode(array('searchContext' => $pluginResult->searchContext, 'result' => $pluginResult->result)); if ($callback) { $result .= ');'; } if ($pluginResult->fileToSend) { $response->setFileToSend($pluginResult->fileToSend, 'data.txt'); } else { $response->setContent($result); } return $response; }
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; }
/** * Generate the website robots.txt */ public function indexAction() { $response = new Response(); $expireDate = new \DateTime(); $expireDate->modify('+1 month'); $response->setExpires($expireDate); $response->setHeader('Content-Type', "text/plain; charset=UTF-8"); $baseUrl = rtrim($this->config->site->url, '/'); $content = <<<EOL User-agent: * Allow: / Sitemap: {$baseUrl}/sitemap EOL; $response->setContent($content); return $response; }
/** * Handles the RSS action. Constructs the rss feed of the latest posts. The * number of posts to return is stored in the configuration section * * @return Response */ public function rssAction() { $feed = new RSS2(); $feed->setEncoding('UTF-8'); $feed->setTitle($this->config->rss->title); $feed->setDescription($this->config->rss->description); $feed->setLink($this->getFullUrl()); $posts = $this->finder->getLatest(1); foreach ($posts as $post) { $feedItem = new Item(); $feedItem->setTitle($post->getTitle()); $feedItem->setLink($this->getFullUrl('/post/' . $post->getSlug())); $feedItem->setDescription($post->getContent()); $feedItem->setDate($post->getDate()); $feed->addItem($feedItem); } $response = new Response(); $response->setHeader('Content-Type', 'application/xml'); $response->setContent($feed->generateFeed()); return $response; }
/** * Generate the website sitemap */ public function indexAction() { $response = new Response(); $expireDate = new \DateTime(); $expireDate->modify('+1 day'); $response->setExpires($expireDate); $response->setHeader('Content-Type', "application/xml; charset=UTF-8"); $sitemap = new \DOMDocument("1.0", "UTF-8"); $urlset = $sitemap->createElement('urlset'); $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); $urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $baseUrl = $this->config->site->url; $url = $sitemap->createElement('url'); $url->appendChild($sitemap->createElement('loc', $baseUrl)); $url->appendChild($sitemap->createElement('changefreq', 'daily')); $url->appendChild($sitemap->createElement('priority', '1.0')); $urlset->appendChild($url); $karmaSql = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies'; $parametersPosts = ['conditions' => 'deleted != 1', 'columns' => "id, slug, modified_at, {$karmaSql} AS karma", 'order' => 'karma DESC']; $posts = Posts::find($parametersPosts); $parametersKarma = ['column' => $karmaSql, 'conditions' => 'deleted != 1']; $karma = Posts::maximum($parametersKarma); $modifiedAt = new \DateTime(); $modifiedAt->setTimezone(new \DateTimeZone('UTC')); foreach ($posts as $post) { $modifiedAt->setTimestamp($post->modified_at); $postKarma = $post->karma / ($karma + 100); $url = $sitemap->createElement('url'); $href = trim($baseUrl, '/') . '/discussion/' . $post->id . '/' . $post->slug; $url->appendChild($sitemap->createElement('loc', $href)); $valuePriority = $postKarma > 0.7 ? sprintf("%0.1f", $postKarma) : sprintf("%0.1f", $postKarma + 0.25); $url->appendChild($sitemap->createElement('priority', $valuePriority)); $url->appendChild($sitemap->createElement('lastmod', $modifiedAt->format('Y-m-d\\TH:i:s\\Z'))); $urlset->appendChild($url); } $sitemap->appendChild($urlset); $response->setContent($sitemap->saveXML()); return $response; }
BaseController::auth(); $request = new \Phalcon\Http\Request(); $meta_value = $request->getPut('meta_value') or $meta_value = ''; BaseController::run(new UserMetaController(), 'putUserMetaAction', array($uid, $meta_key, $meta_value)); }); $app->delete('/api/user/meta/{uid:[0-9]+}/{meta_key:[0-9a-zA-Z_]+}', function ($uid, $meta_key) { BaseController::auth(); BaseController::run(new UserMetaController(), 'deleteUserMetaAction', array($uid, $meta_key)); }); /** * SSO API */ $app->get('/api/sso/ticket', function () use($app) { $var_name = isset($_GET['var']) ? $_GET['var'] : 'il_passport_ticket'; $response = new Response(); $response->setHeader("Content-Type", "text/javascript"); if ($app->session->has("auth")) { $auth = $app->session->get("auth"); $response->setContent("; var {$var_name} = \"{$auth['ticket']}\";"); } else { $response->setContent("; var {$var_name} = null;"); } $response->send(); }); $app->get('/api/sso/status/{ticket:[0-9A-Z]+}', function ($ticket) { BaseController::auth(); BaseController::run(new SsoController(), 'getStatusAction', array($ticket)); }); $app->put('/api/sso/status/{ticket:[0-9A-Z]+}', function ($ticket) { }); $app->delete('/api/sso/status/{ticket:[0-9A-Z]+}', function ($ticket) {
return true; } } 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();
/** * 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; }
/** * @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; }
/** * Sitemap generator */ public function sitemapAction() { $this->view->disable(); $cacheKey = 'post-sitemap.cache'; $sitemap = $this->utils->cacheGet($cacheKey); if (null === $sitemap) { /** * All posts */ $template = 'http://www.niden.net/post/%s'; $posts = $this->finder->getPosts(); $data = []; foreach ($posts as $post) { $data[] = ['location' => sprintf($template, $post['slug']), 'lastModified' => $post['date'], 'changeFrequency' => 'monthly', 'priority' => 0.5]; } $sitemap = $this->viewSimple->render('posts/sitemap', ['sitemap' => $data]); $this->cache->save($cacheKey, $sitemap); } $response = new Response(); $response->setHeader('Content-Type', 'application/xml'); $response->setContent($sitemap); return $response; }
public function setHeader($name, $value) { return parent::setHeader($name, $value); }
/** * 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; }
/** * Add specified headers to a response. **/ protected function addResponseHeaders(Micro $app, Response $response) { $appConfig = $app->getDI()->get(Application::DI_CONFIG); if (isset($appConfig['cors'])) { $response->setHeader('Access-Control-Allow-Origin', $appConfig['cors']); } //Attach headers always to request. foreach (static::$headers as $headerKey => $headerValue) { $response->setHeader($headerKey, $headerValue); } return $this; }
public function download($url, $destination = "", $file_name = "") { // check URL and get token if necessary preg_match("/(.*)periscope\\.tv\\/w\\/(.*)/", trim($url), $output_array); if (isset($output_array[2])) { $periscope_token = $output_array[2]; } else { preg_match("/(.*)watchonperiscope\\.com\\/broadcast\\/(.*)/", trim($url), $output_array); if (isset($output_array[2])) { try { $watchonperiscope_response = $this->_guzzle->get("https://watchonperiscope.com/api/accessChannel?broadcast_id=" . $output_array[2])->getBody(); } catch (\GuzzleHttp\Exception\ServerException $e) { throw new \Exception("URL error: Invalid watchonperiscope.com URL", 2); } $watchonperiscope_json = json_decode($watchonperiscope_response, true); if (!isset($watchonperiscope_json["error"])) { preg_match("/(.*)periscope\\.tv\\/w\\/(.*)/", $watchonperiscope_json["share_url"], $output_array); $periscope_token = $output_array[2]; } else { throw new \Exception("URL error: Invalid watchonperiscope.com URL", 2); } } else { throw new \Exception("URL error: Unsupported URL", 1); } } // construct filename and destination if ($file_name == "") { try { $periscope_details_response = $this->_guzzle->get("https://api.periscope.tv/api/v2/getBroadcastPublic?broadcast_id=" . $periscope_token)->getBody(); } catch (\GuzzleHttp\Exception\ClientException $e) { throw new \Exception("Periscope error: Invalid token", 3); } $periscope_details_json = json_decode($periscope_details_response, true); $periscope_user = $periscope_details_json["user"]["username"]; $periscope_start_time = $periscope_details_json["broadcast"]["start"]; $date = substr($periscope_start_time, 0, 10); $hours = substr($periscope_start_time, 11, 2); $mins = substr($periscope_start_time, 14, 2); $file_name = $periscope_user . "_" . $date . "_" . $hours . "_" . $mins . ".ts"; } else { $file_name = rtrim($file_name, ".ts") . ".ts"; } if ($destination == "") { $destination = __DIR__ . "/"; } else { $destination = rtrim($destination, "/") . "/"; } // set up cookies try { $periscope_cookies_response = $this->_guzzle->get("https://api.periscope.tv/api/v2/getAccessPublic?broadcast_id=" . $periscope_token)->getBody(); } catch (\GuzzleHttp\Exception\ClientException $e) { throw new \Exception("Periscope error: Invalid token", 3); } $periscope_cookies_json = json_decode($periscope_cookies_response, true); $replay_url = $periscope_cookies_json["replay_url"]; $base_url = str_replace("/playlist.m3u8", "", $replay_url); $cookies = array(); foreach ($periscope_cookies_json["cookies"] as $cookie) { $cookies[$cookie["Name"]] = $cookie["Value"]; } $cookie_jar = new \GuzzleHttp\Cookie\CookieJar(); $periscope_cookies = $cookie_jar::fromArray($cookies, "replay.periscope.tv"); // download playlist and all chunks $periscope_playlist_response = $this->_guzzle->get($replay_url, ["cookies" => $periscope_cookies])->getBody()->getContents(); preg_match_all("/chunk_(.*)\\.ts/", $periscope_playlist_response, $chunk_array); $tmp_folder = $destination . "/" . bin2hex(openssl_random_pseudo_bytes(16)) . "/"; shell_exec("mkdir " . $tmp_folder); $path = $destination . $file_name; if (!file_exists($path)) { shell_exec("cat " . $tmp_folder . $chunk_array[0][0] . " >> " . $path); } $response = new Response(); $filetype = filetype($path); $filesize = filesize($path); while (ob_get_level()) { ob_end_clean(); } $response->setHeader("Content-Description", 'File Transfer'); $response->setHeader("Cache-Control", 'must-revalidate, post-check=0, pre-check=0'); $response->setHeader("Content-Disposition", 'attachment; filename=' . $file_name); $response->setHeader("Content-Type", $filetype); $response->setHeader("Content-Length", $filesize); $response->setHeader("Content-Transfer-Encoding", 'binary'); $response->setHeader("Expires", '0'); $response->setHeader("Pragma", 'public'); $response->setFileToSend($path, null, false); $response->send(); foreach ($chunk_array[0] as $chunk) { $chunk_response = $this->_guzzle->get($base_url . "/" . $chunk, ["cookies" => $periscope_cookies])->getBody()->getContents(); //, 'stream' => true // $chunk_size = $chunk_response->getHeader('content-length'); // $body = $chunk_response->getBody(); // // while ( ! $body->eof()) { // echo $body->read($chunk_size[0]); // } file_put_contents($tmp_folder . $chunk, $chunk_response); $chunk_size = filesize($tmp_folder . $chunk); if (file_exists($path)) { shell_exec("cat " . $path . ' ' . $tmp_folder . $chunk . " >> " . $path); } $fh = fopen($tmp_folder . $chunk, "rb"); echo fread($fh, $chunk_size); while (ob_get_level()) { ob_end_clean(); } flush(); fclose($fh); } // clean up shell_exec("rm -rf " . $tmp_folder); exit; return $destination . $file_name; }
public function deleteAction() { $response = new Response(); $response->setHeader('Content-Type', 'application/json'); if ($this->request->isPost()) { $id = $this->request->getPost('id', 'int'); $user = Users::findFirstById($id); if (!$user) { $response->setJsonContent(array('status' => 'error', 'messages' => '没有对应的用户')); } if (!$user->delete()) { $response->setJsonContent(array('status' => 'error', 'messages' => '删除时发生错误')); } else { $response->setJsonContent(array('status' => 'success', 'messages' => '')); } } return $response; }
$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)) { //Lets create folder structure if it doesn't exist if (!file_exists(dirname($resized_file))) { mkdir('./' . dirname($resized_file), '0777', true); } $image = new \Eventviva\ImageResize($image->url); $image->resizeToWidth(800); $image->save($resized_file); } //echo 'her' . $resized_file; $response->setHeader('Content-Type', 'image/jpeg'); $response->send(); readfile($resized_file); } $response->setJsonContent(['could not load image!']); }); $app->handle(); $response->send();
/** * Create an invoice download response. * * @param array $data */ public function download(array $data) { $filename = $data['product'] . '_' . $this->date()->month . '_' . $this->date()->year . '.pdf'; $response = new Response(); $response->setHeader('Content-Description', 'File Transfer'); $response->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"'); $response->setStatusCode(200, 'OK'); $response->setContent($this->pdf($data)); $response->setContentType('application/pdf'); return $response->send(); }
/** * Create an issue of a product. * @param long $productId - the unique ID of the product * @return an HttpResponse contains data validation result */ public function createIssueAction($productId) { $issueTitle = $this->getFilteredContent(strip_tags($this->request->getPost('issueTitle'))); $issueCategorySlug = $this->getFilteredContent(strip_tags($this->request->getPost('issueCategory'))); $productVersion = $this->getFilteredContent(strip_tags($this->request->getPost('productVersion'))); $issueDescription = $this->getFilteredContent(strip_tags($this->request->getPost('issueDescription'))); $isTokenValid = $this->security->checkToken(); $productService = ServiceFactory::getService('ProductService'); $issueService = ServiceFactory::getService('IssueService'); $product = $productService->getProductObjectUsingId($productId); $hunter = $this->getCurrentUserObject($this->session); if ($product == NULL) { $this->forward('errors/resourceNotFound'); return; } $result = $issueService->createIssue($product, $productVersion, $issueCategorySlug, $hunter, $issueTitle, $issueDescription, $isTokenValid); if ($isTokenValid) { $result['csrfTokenKey'] = $this->security->getTokenKey(); $result['csrfToken'] = $this->security->getToken(); } if ($isSuccessful) { $issueId = $result['issueId']; $ipAddress = $this->request->getClientAddress(); $this->logger->log(sprintf('Issue #%d created by User[%s] at %s.', $issueId, $hunter, $ipAddress), Logger::INFO); } $response = new Response(); $response->setHeader('Content-Type', 'application/json'); $response->setContent(json_encode($result)); return $response; }
/** * * @param type $fileName * @param type $fileTemp * @return type */ private function download($fileName, $fileTemp) { $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER); $response = new Response(); $response->setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); $response->setHeader('Content-Disposition', 'attachment;filename="' . $fileName . '"'); $response->setHeader('Cache-Control', 'max-age=0'); //$response->setHeader('Cache-Control', 'max-age=1'); $response->setContent(file_get_contents($fileTemp)); unlink($fileTemp); return $response->send(); }
/** * Add specified headers to a response. **/ protected function addResponseHeaders(Micro $app, Response $response) { $appConfig = $app->getDI()->get(Application::DI_CONFIG); if (isset($appConfig['cors'])) { $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ''; $origins = explode(';', $appConfig['cors']); $origins = array_map('trim', $origins); if (in_array($origin, $origins)) { $response->setHeader('Access-Control-Allow-Origin', $origin); } } else { $response->setHeader('Access-Control-Allow-Origin', '*'); } //Attach headers always to request. foreach (static::$headers as $headerKey => $headerValue) { $response->setHeader($headerKey, $headerValue); } return $this; }