public function testDisplay() { $this->_response->expects($this->atLeastOnce())->method('sendHeaders'); $this->_request->expects($this->atLeastOnce())->method('getHeader'); $stat = (include __DIR__ . '/_files/timers.php'); $this->_output->display($stat); $actualHeaders = $this->_response->getHeaders(); $this->assertNotEmpty($actualHeaders); $actualProtocol = false; $actualProfilerData = false; foreach ($actualHeaders as $oneHeader) { $headerName = $oneHeader['name']; $headerValue = $oneHeader['value']; if (!$actualProtocol && $headerName == 'X-Wf-Protocol-1') { $actualProtocol = $headerValue; } if (!$actualProfilerData && $headerName == 'X-Wf-1-1-1-1') { $actualProfilerData = $headerValue; } } $this->assertNotEmpty($actualProtocol, 'Cannot get protocol header'); $this->assertNotEmpty($actualProfilerData, 'Cannot get profiler header'); $this->assertContains('Protocol/JsonStream', $actualProtocol); $this->assertRegExp('/"Type":"TABLE","Label":"Code Profiler \\(Memory usage: real - \\d+, emalloc - \\d+\\)"/', $actualProfilerData); $this->assertContains('[' . '["Timer Id","Time","Avg","Cnt","Emalloc","RealMem"],' . '["root","0.080000","0.080000","1","1,000","50,000"],' . '[". init","0.040000","0.040000","1","200","2,500"],' . '[". . init_store","0.020000","0.010000","2","100","2,000"],' . '["system","0.030000","0.015000","2","400","20,000"]' . ']', $actualProfilerData); }
protected function _initFrontControllerOutput() { $front = $this->bootstrap('FrontController')->getResource('FrontController'); $response = new Zend_Controller_Response_Http(); $response->setHeader('Content-Type', 'text/html; charset=UTF-8', true); $front->setResponse($response); }
/** * Send the file to the client (Download) * * @param string|array $options Options for the file(s) to send * @throws \UnexpectedValueException * @throws \InvalidArgumentException * @return void */ public function send($options = null) { if (is_string($options)) { $filepath = $options; } else { if (is_array($options) && isset($options['filepath'])) { $filepath = $options['filepath']; } else { throw new \InvalidArgumentException("Filename is not set."); } } if (!is_file($filepath) || !is_readable($filepath)) { throw new \InvalidArgumentException("File '{$filepath}' does not exists."); } $mimeType = $this->mime->getMimeType($filepath); $this->response->setHeader('Content-length', filesize($filepath)); $this->response->setHeader('Content-Type', $mimeType); $this->response->sendHeaders(); $handle = fopen($filepath, 'r'); if ($handle) { while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer; } if (!feof($handle)) { throw new \UnexpectedValueException("Unexpected end of file"); } fclose($handle); } }
/** Initialise the response and set gzip status */ protected function _initResponse() { $response = new Zend_Controller_Response_Http(); $response->setHeader('X-Powered-By', 'Dan\'s magic army of elves')->setHeader('Host', 'finds.org.uk')->setHeader('X-Compression', 'gzip')->setHeader('Accept-Encoding', 'gzip, deflate')->setHeader('Expires', gmdate('D, d M Y H:i:s', time() + 2 * 3600) . ' GMT', true); $frontController = Zend_Controller_Front::getInstance(); $frontController->setResponse($response); }
public function init() { $registry = Zend_Registry::getInstance(); $config = $registry->get("config"); $sysCache = $registry->get("sysCache"); $cacheFiles = new Ml_Cache_Files($sysCache); Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . '/controllers/helpers'); $frontController = $this->getBootstrap()->getResource('FrontController'); $dispatcher = $frontController->getDispatcher(); $request = $frontController->getRequest(); $router = $frontController->getRouter(); $router->removeDefaultRoutes(); $compat = new Zend_Controller_Router_Route_Module(array(), $dispatcher, $request); $router->addRoute(HOST_MODULE, $compat); $routerConfig = $cacheFiles->getConfigIni(APPLICATION_PATH . '/configs/' . HOST_MODULE . 'Routes.ini'); $router->addConfig($routerConfig, "apiroutes"); Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . '/modules/' . HOST_MODULE . '/controllers/helpers'); $loadOauthStore = Zend_Controller_Action_HelperBroker::getStaticHelper("LoadOauthstore"); $loadOauthStore->setinstance(); $loadOauthStore->preloadServer(); $frontController->setBaseUrl($config['apiroot'])->setParam('noViewRenderer', true)->addModuleDirectory(APPLICATION_PATH . '/modules')->addControllerDirectory(APPLICATION_PATH . '/modules/' . HOST_MODULE . '/controllers'); $response = new Zend_Controller_Response_Http(); if (filter_input(INPUT_GET, "responseformat", FILTER_UNSAFE_RAW) == 'json') { $contentType = 'application/json'; } else { $contentType = 'text/xml'; } $response->setHeader('Content-Type', $contentType . '; charset=utf-8', true); $frontController->setResponse($response); }
public static function prepareDiscoveryParams(array &$params, Zend_Controller_Response_Http $response, $topicType, $topicId, $selfLink, $subscriptionOption) { if (!bdApi_Option::getSubscription($topicType)) { // subscription for this topic type has been disabled return false; } // subscription discovery $hubLink = bdApi_Data_Helper_Core::safeBuildApiLink('subscriptions', null, array('hub.topic' => bdApi_Model_Subscription::getTopic($topicType, $topicId), 'oauth_token' => '')); $response->setHeader('Link', sprintf('<%s>; rel=hub', $hubLink)); $response->setHeader('Link', sprintf('<%s>; rel=self', $selfLink)); // subscription info if (!empty($subscriptionOption)) { $subscriptionOption = @unserialize($subscriptionOption); if (!empty($subscriptionOption['subscriptions'])) { /* @var $session bdApi_Session */ $session = XenForo_Application::getSession(); $clientId = $session->getOAuthClientId(); foreach ($subscriptionOption['subscriptions'] as $subscription) { if ($subscription['client_id'] == $clientId) { $params['subscription_callback'] = $subscription['callback']; } } } } return true; }
/** * Send the file to the client (Download) * * @param string|array $options Options for the file(s) to send * @return void */ public function send($options = null) { if (is_string($options)) { $filepath = $options; } else { if (is_array($options)) { $filepath = $options['filepath']; } else { throw new Exception("Filename is not set."); } } if (!is_file($filepath) || !is_readable($filepath)) { throw new Exception("File '{$filepath}' does not exists."); } $mimeType = $this->_detectMimeType(array('name' => $filepath)); $response = new Zend_Controller_Response_Http(); $response->setHeader('Content-length', filesize($filepath)); $response->setHeader('Content-Type', $mimeType); $response->sendHeaders(); $handle = fopen($filepath, 'r'); if ($handle) { while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer; } if (!feof($handle)) { throw new Exception("Error: unexpected fgets() fail."); } fclose($handle); } }
/** * Creates a response object, sets the Content-Type header and assigns the * response to the front controller. * * @return null */ protected function _initResponseCharset() { $front = Zend_Controller_Front::getInstance(); $response = new Zend_Controller_Response_Http(); $response->setHeader('Content-Type', 'text/html; charset=utf-8', false); $front->setResponse($response); }
public function directAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs) { if ($request->getFiltered('INVNUM', $request->getFiltered('INVOICE')) == '') { $response->setRedirect($this->getRootUrl() . '/thanks'); } else { parent::directAction($request, $response, $invokeArgs); } }
public function thanksAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs) { $log = $this->logRequest($request, 'POSTBACK [thanks]'); if ($this->invoice = $this->getDi()->invoiceTable->findFirstByPublicId($request->getFiltered('referer'))) { $log->setInvoice($this->invoice)->update(); $response->setRedirect($this->getReturnUrl()); return; } throw new Am_Exception_InputError("Invoice not found"); }
protected function _initResponse() { $options = $this->getOptions(); if (!isset($options['response']['defaultContentType'])) { return; } $response = new Zend_Controller_Response_Http(); $response->setHeader('Content-Type', $options['response']['defaultContentType'], true); $this->bootstrap('FrontController'); $this->getResource('FrontController')->setResponse($response); }
protected function _initResponse() { // Ensure front controller instance is present, and fetch it $this->bootstrap('FrontController'); $front = $this->getResource('FrontController'); /* @var $front Zend_Controller_Front */ // Initialize and set the response object $response = new Zend_Controller_Response_Http(); $response->setHeader('Content-Type', 'text/html; charset=UTF-8', true); $front->setResponse($response); return $response; }
protected function _error($message = null, $statusCode = self::REST_STATUS_BAD_REQUEST) { if (is_numeric($statusCode)) { $statusCode = intval($statusCode); } $this->_response->clearAllHeaders()->clearBody(); $this->_response->setHttpResponseCode(intval($statusCode))->setHeader('Content-Type', 'application/json', true); if (!empty($message)) { $this->_response->setBody(json_encode($message)); } $this->_response->sendResponse(); exit; }
protected function _initModifiedFrontController() { $options = $this->getOption('resources'); if (!isset($options['modifiedFrontController']['contentType'])) { return; } $this->bootstrap('FrontController'); $front = $this->getResource('FrontController'); //$front->addModuleDirectory(APPLICATION_PATH . '/modules'); $response = new Zend_Controller_Response_Http(); $response->setHeader('Content-Type', $options['modifiedFrontController']['contentType'], true); $front->setResponse($response); }
public function directAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs) { if ($request->getActionName() == 'thanks') { if ($this->getConfig('debugLog')) { Am_Di::getInstance()->errorLogTable->log('NetBilling Form [response-thanks]:' . json_encode($request->getParams())); } $this->invoice = $this->getDi()->invoiceTable->findFirstByPublicId($request->getFiltered('Ecom_ConsumerOrderID')); $url = $request->get('Ecom_Ezic_Response_StatusCode') == 0 || $request->get('Ecom_Ezic_Response_StatusCode') == 'F' ? $this->getCancelUrl() : $this->getReturnUrl(); $response->setRedirect($url); } else { parent::directAction($request, $response, $invokeArgs); } }
protected function sendCsv($filename, array $rows, Zend_Controller_Response_Http $response, $delimiter = "\t") { $response->setHeader('Cache-Control', 'maxage=3600')->setHeader('Pragma', 'no-cache')->setHeader('Content-type', 'text/csv')->setHeader('Content-Disposition', 'attachment; filename=' . $filename); foreach ($rows as &$r) { if (is_array($r)) { $out = ""; foreach ($r as $s) { $out .= ($out ? $delimiter : "") . '"' . str_replace('"', "'", $s) . '"'; } $out .= "\r\n"; $r = $out; } } $response->appendBody(implode("", $rows)); }
public function testCustomInflectorUsesViewRendererTargetWhenPassedInWithReferenceFlag() { $this->request->setModuleName('bar') ->setControllerName('index') ->setActionName('test'); $controller = new Bar_IndexController($this->request, $this->response, array()); $this->helper->view->addBasePath($this->basePath . '/_files/modules/bar/views'); require_once 'Zend/Filter/PregReplace.php'; require_once 'Zend/Filter/Word/UnderscoreToSeparator.php'; $inflector = new Zend_Filter_Inflector('test.phtml'); $inflector->addRules(array( ':module' => array('Word_CamelCaseToDash', 'stringToLower'), ':controller' => array('Word_CamelCaseToDash', new Zend_Filter_Word_UnderscoreToSeparator(DIRECTORY_SEPARATOR), 'StringToLower'), ':action' => array( 'Word_CamelCaseToDash', new Zend_Filter_PregReplace('/[^a-z0-9]+/i', '-'), 'StringToLower' ), )); $this->helper->setInflector($inflector, true); $this->helper->render(); $body = $this->response->getBody(); $this->assertContains('Rendered index/test.phtml in bar module', $body); }
/** * Fixes CGI only one Status header allowed bug * * @link http://bugs.php.net/bug.php?id=36705 * */ public function sendHeaders() { if (!$this->canSendHeaders()) { AO::log('HEADERS ALREADY SENT: ' . mageDebugBacktrace(true, true, true)); return $this; } if (substr(php_sapi_name(), 0, 3) == 'cgi') { $statusSent = false; foreach ($this->_headersRaw as $i => $header) { if (stripos($header, 'status:') === 0) { if ($statusSent) { unset($this->_headersRaw[$i]); } else { $statusSent = true; } } } foreach ($this->_headers as $i => $header) { if (strcasecmp($header['name'], 'status') === 0) { if ($statusSent) { unset($this->_headers[$i]); } else { $statusSent = true; } } } } parent::sendHeaders(); }
public function testPreDispatchNonWhitelistedActionViaAjaxRequest() { $this->request->setHeader('X_REQUESTED_WITH', 'XMLHttpRequest')->setModuleName('default')->setControllerName('foo')->setActionName('home'); $this->plugin->preDispatch($this->request); $this->assertEquals(500, $this->response->getHttpResponseCode()); $this->assertEquals(json_encode(array('redirect' => '/user/login')), $this->response->getBody()); }
public function directAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs) { $invoice = $this->getDi()->invoiceTable->findBySecureId($request->getFiltered('id'), $this->getId()); if (!$invoice) { throw new Am_Exception_InputError(___("Sorry, seems you have used wrong link")); } $view = new Am_View(); $html = $this->getConfig('html', 'SITE OWNER DID NOT PROVIDE INSTRUCTIONS FOR OFFLINE PAYMENT YET'); $tpl = new Am_SimpleTemplate(); $tpl->invoice = $invoice; $tpl->user = $this->getDi()->userTable->load($invoice->user_id); $tpl->invoice_id = $invoice->invoice_id; $tpl->cancel_url = REL_ROOT_URL . '/cancel?id=' . $invoice->getSecureId('CANCEL'); $view->content = $tpl->render($html); $view->title = $this->getTitle(); $response->setBody($view->render("layout.phtml")); }
/** * Renders page-level debugging output and replaces the original view content * with it. Alternatively, it could inject itself into the view content. * * @param string $originalContent Original, rendered view content * * @return string Replacement rendered view content */ public function renderDebugOutput($originalContent) { $this->_response->clearHeaders(); $this->_response->setHttpResponseCode(200); $this->_response->setHeader('Content-Type', 'text/html; charset=UTF-8', true); $this->_response->setHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT', true); return XenForo_Debug::getDebugPageWrapperHtml(XenForo_Debug::getDebugHtml()); }
/** * Prepare response body before caching * * @param Zend_Controller_Response_Http $response * @return string */ public function prepareContent(Zend_Controller_Response_Http $response) { $content = $response->getBody(); $placeholders = array(); preg_match_all(Enterprise_PageCache_Model_Container_Placeholder::HTML_NAME_PATTERN, $content, $placeholders, PREG_PATTERN_ORDER); $placeholders = array_unique($placeholders[1]); try { foreach ($placeholders as $definition) { $this->_placeholder = Mage::getModel('enterprise_pagecache/container_placeholder', $definition); $content = preg_replace_callback($this->_placeholder->getPattern(), array($this, '_getPlaceholderReplacer'), $content); } $this->_placeholder = null; } catch (Exception $e) { $this->_placeholder = null; throw $e; } return $content; }
public function testCorrectViewHelperPathShouldBePropagatedWhenSubControllerInvokedInDefaultModule() { require_once $this->basePath . '/_files/modules/default/controllers/Admin/HelperController.php'; $this->request->setControllerName('admin_helper')->setActionName('render'); $controller = new Admin_HelperController($this->request, $this->response, array()); $this->helper->render(); $body = $this->response->getBody(); $this->assertContains('SampleZfHelper invoked', $body, 'Received ' . $body); }
public function testPostDispatchDoesNotRenderViewWhenNoViewRendererSet() { $this->request->setModuleName('bar')->setControllerName('index')->setActionName('index'); $this->front->setParam('noViewRenderer', true); $controller = new Bar_IndexController($this->request, $this->response, array()); $this->helper->postDispatch(); $body = $this->response->getBody(); $this->assertTrue(empty($body)); }
protected function _parseLocationHeaderValue() { $headers = $this->response->getHeaders(); foreach ($headers as $header) { if ('Location' == $header['name']) { return $header['value']; } } }
/** * output body * * @return void */ public function outputBody() { $callback = $this->outputBodyCallback; if (is_callable($callback)) { $callback($this, self::CHUNK_SIZE); } else { parent::outputBody(); } }
/** * Challenge Client * * Sets a 401 Unauthorized response code, and creates the * appropriate Authenticate header(s) to prompt for credentials. * * @return Zend_Auth_Result Always returns a non-identity Auth result */ protected function _challengeClient() { $this->_response->setHttpResponseCode(401); // Send a challenge in each acceptable authentication scheme foreach ($this->_schemes as $scheme => $callback) { $this->_response->setHeader('WWW-Authenticate', $scheme); } return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, array(), array('Invalid or absent credentials; challenging client')); }
public function testPostDispatchQuitsWithFalseUserErrorHandlerParam() { $front = Zend_Controller_Front::getInstance(); $front->resetInstance(); $front->setParam('noErrorHandler', true); $this->response->setException(new Zend_Controller_Dispatcher_Exception('Testing controller exception')); $this->request->setModuleName('foo')->setControllerName('bar')->setActionName('baz'); $this->plugin->postDispatch($this->request); $this->assertNull($this->request->getParam('error_handler')); }
public function __construct($msg = '', $code = 0, Exception $previous = null) { // just pass ahead if it was throw from the CLI if (php_sapi_name() == "cli") { return parent::__construct($msg, (int) $code, $previous); } else { parent::__construct($msg, (int) $code, $previous); $response = new Zend_Controller_Response_Http(); $response->setHttpResponseCode(500); ob_get_clean(); ob_start(); require APPLICATION_PATH . "/layout/scripts/exception.phtml"; $outputBuffer = ob_get_clean(); $response->setBody($outputBuffer); $response->sendResponse(); trigger_error($msg, E_USER_ERROR); exit; } }
/** * Sends all headers * * @return Enlight_Controller_Response_ResponseHttp */ public function sendHeaders() { if (count($this->_cookies)) { $this->canSendHeaders(true); foreach ($this->_cookies as $name => $cookie) { setcookie($name, $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httpOnly']); } } return parent::sendHeaders(); }