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; }
/** * Send response to browser with json content type */ public function sendResponse() { $this->_response = Mage::app()->getResponse(); //check redirect if ($this->_response->isRedirect()) { $headers = $this->_response->getHeaders(); $redirect = ''; foreach ($headers as $header) { if ("Location" == $header["name"]) { $redirect = $header["value"]; break; } } if ($redirect) { $this->setRedirect($redirect); } } $this->_response->clearHeaders(); $this->_response->setHeader('Content-Type', 'application/json'); $this->_response->clearBody(); $this->_response->setBody($this->toJson()); $this->_response->sendResponse(); exit; }
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")); }
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; } }
/** * Performs a HTTP redirection to specified URL with additional data. * It may generate redirected request using GET or POST HTTP method. * The function never returns. * * @param string $url URL to redirect to * @param array $params additional variable/value pairs to send * @param Zend_Controller_Response_Abstract $response * @param string $method redirection method ('GET' or 'POST') */ public static function redirect($url, $params = null, Zend_Controller_Response_Abstract $response = null, $method = 'GET') { $url = Zend_OpenId::absoluteUrl($url); $body = ""; if (null === $response) { #require_once "Zend/Controller/Response/Http.php"; $response = new Zend_Controller_Response_Http(); } if ($method == 'POST') { $body = "<html><body onLoad=\"document.forms[0].submit();\">\n"; $body .= "<form method=\"POST\" action=\"{$url}\">\n"; if (is_array($params) && count($params) > 0) { foreach ($params as $key => $value) { $body .= '<input type="hidden" name="' . $key . '" value="' . $value . "\">\n"; } } $body .= "<input type=\"submit\" value=\"Continue OpenID transaction\">\n"; $body .= "</form></body></html>\n"; } else { if (is_array($params) && count($params) > 0) { if (strpos($url, '?') === false) { $url .= '?' . self::paramsToQuery($params); } else { $url .= '&' . self::paramsToQuery($params); } } } if (!empty($body)) { $response->setBody($body); } else { if (!$response->canSendHeaders()) { $response->setBody("<script language=\"JavaScript\"" . " type=\"text/javascript\">window.location='{$url}';" . "</script>"); } else { $response->setRedirect($url); } } $response->sendResponse(); if (self::$exitOnRedirect) { exit; } }
/** * Inserts JSON data into the given response. * * @param Zend_Controller_Response_Http $response */ protected function insertJsonInto(Zend_Controller_Response_Http $response) { $data = new stdClass(); $data->a = 'b'; $data->c = 'd'; $response->setBody(json_encode($data)); }
public function action(array $query, $path, $url, Am_Request $request, Zend_Controller_Response_Http $response) { switch ($query['action']) { case 'delete-file': $upload = $this->getDi()->uploadTable->load($query['path']); $usage = $this->getDi()->uploadTable->findUsage($upload); if (!empty($usage)) { $response->setBody($this->renderWarning($usage, $url)); } else { $upload->delete(); $response->setRedirect($url); } break; default: throw new Am_Exception_InputError('unknown action!'); } }
public function run(Zend_Controller_Response_Abstract $response = null) { $args = array($this); $this->runCallback(self::CB_BEFORE_RUN, $args); if ($response === null) { $response = new Zend_Controller_Response_Http(); } $this->response = $response; $action = $this->getCurrentAction(); $this->request->setActionName($action); ob_start(); $this->actionRun($action); if ($this->response->isRedirect() && $this->completeRequest->isXmlHttpRequest()) { $url = null; foreach ($response->getHeaders() as $header) { if ($header['name'] == 'Location') { $url = $header['value']; } } $code = $response->getHttpResponseCode(); // change request to ajax response $response->clearAllHeaders(); $response->clearBody(); $response->setHttpResponseCode(200); $response->setHeader("Content-Type", "application/json; charset=UTF-8", true); $response->setBody(Am_Controller::getJson(array('ngrid-redirect' => $url, 'status' => $code))); //throw new Am_Exception_Redirect($url); } else { $response->appendBody(ob_get_clean()); } unset($this->response); return $response; }
/** * Handles logic for caching pages. Currently checks the root block for the * "CachePageFlag". Pages are only cached if the user is not logged in and does * not have items in their cart. * * @param $observer * @return void */ public function cachePage(Zend_Controller_Response_Http $response) { // Check if cache flag is set $rootBlock = Mage::app()->getLayout()->getBlock('root'); if ($rootBlock && $rootBlock->getCachePageFlag()) { if ($this->passesConditions($rootBlock->getCachePageConditions())) { $cache = Mage::app()->getCache(); $id = $this->generateFPCId(); if ($rootBlock->getCachePageExpires() > 0) { $expires = $rootBlock->getCachePageExpires(); } else { //default expires $expires = Mage::getStoreConfig(Brim_PageCache_Model_Config::XML_PATH_EXPIRES); } $storageObject = Mage::getModel('brim_pagecache/storage'); if (Mage::getStoreConfig(Brim_PageCache_Model_Config::XML_PATH_ENABLE_MINIFY_HTML)) { // Minify the response body. Helps save on cache storage space // Basic grouped product page 34k in size was about 28K minified, $minifyBody = Brim_PageCache_Model_Minify_HTML::minify($response->getBody()); $response->setBody($minifyBody); } $storageObject->setResponse($response); /** * Block update data contains partial layouts for each block. Allows us to regenerate each one * with out loosing customizations. */ $storageObject->setBlockUpdateData($this->getBlockUpdateData()); // Set the expected expires time for this page $date = Mage::app()->getLocale()->date()->addSecond($expires); $storageObject->setData(self::RESPONSE_HEADER_EXPIRES_DATE, $date->get(Zend_Date::RFC_1123)); $storageObject->setData(self::RESPONSE_HEADER_EXPIRES, $expires); $storageObject->setData(self::RESPONSE_HEADER_CONDITIONS, $rootBlock->getCachePageConditions()); $storageObject->setData(self::RESPONSE_HEADER_STORE, Mage::app()->getStore()->getCode()); $storageObject->setData(self::RESPONSE_HEADER_ORIG_TIME, microtime(true) - self::$_start_time); $this->debug('Saving page with cache id : ' . $id); if (($product = Mage::registry('product')) != null) { $this->devDebug('Registering Tag: ' . self::FPC_TAG . '_PRODUCT_' . $product->getId()); $this->registerPageTags(self::FPC_TAG . '_PRODUCT_' . $product->getId()); } if (($category = Mage::registry('current_category')) != null && $product == null) { $this->devDebug('Registering Tag: ' . self::FPC_TAG . '_CATEGORY_' . $category->getId()); $this->registerPageTags(self::FPC_TAG . '_CATEGORY_' . $category->getId()); } $cache->save(serialize($storageObject), $id, $this->getPageTags(), $expires); } else { // failed conditions if ($response->canSendHeaders(false)) { $response->setHeader(self::RESPONSE_HEADER_FAILED, $this->_failed_conditions); } } } else { if ($response->canSendHeaders(false)) { // page not set to cache $response->setHeader(self::RESPONSE_HEADER_FAILED, 'no_cache'); } } }
public function testProcessRequestTrue() { $response = new Zend_Controller_Response_Http(); $response->setBody('Initial response body.'); $this->_requestProcessor->expects($this->any())->method('extractContent')->will($this->returnValue('Additional response text.')); $this->assertTrue($this->_model->processRequest($response)); $this->assertEquals('Initial response body.Additional response text.', $response->getBody()); }
$processor->initCallbackHandling(new Zend_Controller_Request_Http()); $logExtra = array(); $logMessage = false; try { if (!$processor->validateRequest($logMessage)) { $logType = 'error'; $response->setHttpResponseCode(500); } else { if (!$processor->validatePreConditions($logMessage)) { $logType = 'error'; } else { $logType = 'info'; $logMessage = $processor->processTransaction(); } } if (is_array($logMessage)) { $temp = $logMessage; list($logType, $logMessage) = $temp; } } catch (Exception $e) { $response->setHttpResponseCode(500); XenForo_Error::logException($e); $logType = 'error'; $logMessage = 'Exception: ' . $e->getMessage(); $logExtra['_e'] = $e; } if ($logType) { $processor->log($logType, $logMessage, $logExtra); } $response->setBody(htmlspecialchars($logMessage)); $response->sendResponse();
/** * Pretend to dispatch an HTTP request to a controller/action. * * @param Zend_Controller_Request_Abstract|null $request * @param Zend_Controller_Response_Abstract|null $response * @return Zend_Controller_Response_Abstract|void Response object */ public function dispatch(Zend_Controller_Request_Abstract $request = null, Zend_Controller_Response_Abstract $response = null) { $response = new Zend_Controller_Response_Http(); $response->setBody($request->getControllerName() . ':' . $request->getActionName()); if ($this->returnResponse()) { return $response; } $response->sendHeaders(); $response->outputBody(); }
public static function bootstrap($installDir) { if (self::testEnvironment() === false) { echo 'Environment fails to meet minimum requirements for this demo tutorial.'; return; } // where to find this application's configuration (using Conventional Modular Layout) $ds = DIRECTORY_SEPARATOR; // too much typing ;) if ($installDir[0] === '/') { $tmp = $installDir; } else { $tmp = dirname(__FILE__) . $ds . '..' . $ds . '..' . $ds . 'zfdemo' . $ds . $installDir; } // STAGE 0: Initializations / Loading Configuration ZFDemo_Log::log("looking for application directory in: realpath({$tmp}" . $ds . ')'); $appDir = realpath($tmp) . $ds; ZFDemo_Log::log('$appDir =' . $appDir); self::$registry = Zend_Registry::getInstance(); self::$registry['appDir'] = $appDir; if (!is_readable($appDir)) { ZFDemo_Log::log("ERROR: Application directory is not readable (path problem).\n", true); return false; } // this application's configuration information $configDir = realpath($appDir . $ds . 'config' . $ds) . $ds; self::$registry['configDir'] = $configDir; ZFDemo_Log::log('$configDir =' . $configDir); if (!is_readable($configDir)) { ZFDemo_Log::log("ERROR: Application configuration directory 'config' is not readable (path problem).\n", true); return false; } // persistent dynamic data, like log files or SQLite files $dataDir = realpath($appDir . $ds . 'data' . $ds) . $ds; self::$registry['dataDir'] = $dataDir; ZFDemo_Log::log('$dataDir =' . $dataDir); if (!is_readable("{$dataDir}")) { ZFDemo_Log::log("ERROR: Application 'data' directory is not readable (path problem).\n", true); return false; } // temporary data, like PHP session state files $temporaryDir = realpath($appDir . $ds . 'temporary' . $ds) . $ds; self::$registry['temporaryDir'] = $temporaryDir; ZFDemo_Log::log('$temporaryDir =' . $temporaryDir); if (!is_readable("{$temporaryDir}")) { ZFDemo_Log::log("ERROR: Application 'temporary' directory is not readable (path problem).\n", true); return false; } // add the application-specific source file path to PHP's include path for the Conventional Modular Layout set_include_path($appDir . PATH_SEPARATOR . get_include_path()); ZFDemo_Log::log("PHP Include Path = \n " . str_replace(':', "\n ", ini_get('include_path'))); self::$environment = 'sandbox'; // after this point, all defaults come from config files require 'Zend/Config/Ini.php'; $config = new Zend_Config_Ini($configDir . 'config.ini', self::$environment, true); ZFDemo_Log::log("config.ini=" . print_r($config->asArray(), true)); if (strpos($config->log, '/') !== 0) { $config->log = $dataDir . $config->log; } self::$registry['config'] = $config; // application configuration array date_default_timezone_set($config->timezone); $sessionConfig = new Zend_Config_Ini($configDir . 'Zend_Session.ini', self::$environment, true); $sessionConfig->save_path = $temporaryDir . $sessionConfig->save_path; ZFDemo_Log::log("Zend_Session.ini=" . print_r($sessionConfig->asArray(), true)); require 'Zend/Session.php'; Zend_Session::setOptions($sessionConfig->asArray()); Zend_Session::start(); /* * The zfdemo will not work unless the following code results creates a session file * in your save_path folder, * with file contents like: * foo|a:2:{s:3:"bar";s:5:"apple";s:4:"time";s:19:"2007-02-20 21:30:36";} */ $testSpace = new Zend_Session_Namespace('spaceFoo'); $testSpace->keyBar = 'valueBar'; $testSpace->time = time(); $testSpace->date = date('Y-m-d H:i:s'); // preemptively write session file now Zend_Session::writeClose(); self::testPdo($config); // sanity check connection and zfdemo tables using PDO // Now test using ZF's MySQL PDO DB adapter: require 'Zend/Db.php'; require 'Zend/Db/Adapter/Pdo/Mysql.php'; // setup our DB adapter $db = new Zend_Db_Adapter_Pdo_Mysql($config->db->asArray()); self::$registry['db'] = $db; self::testDb($db); // sanity check connection and zfdemo tables using Zend Db Adapter // STAGE 1: Prepare the front (primary) controller. require 'Zend/Controller/Front.php'; $frontController = Zend_Controller_Front::getInstance(); // manages the overall workflow $baseUrl = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], '/index.php')); ZFDemo_Log::log("baseUrl={$baseUrl}"); //$frontController->setBaseUrl($baseUrl); $frontController->setControllerDirectory(array('default' => $appDir . 'default' . $ds . 'controllers', 'forum' => $appDir . 'forum' . $ds . 'controllers')); // Initialize views require 'Zend/View.php'; self::$view = new Zend_View(); self::$view->sectionName = basename($installDir); // e.g. "section1_install" self::$view->setScriptPath($appDir . 'default' . $ds . 'views'); self::$view->showLog = true; ZFDemo_Log::log("scriptPaths=\n " . implode("\n ", self::$view->getScriptPaths())); $frontController->setParam('view', self::$view); // STAGE 2: Find the right action and execute it. // Use routes to calculate controllers and actions to execute // Dispatch calculated actions of the selected controllers $frontController->returnResponse(true); // return the response (do not echo it to the browser) // Use UTF-8. See "1. Content-type, Charset, DOCTYPE" in NOTES.txt require_once 'Zend/Controller/Response/Http.php'; $response = new Zend_Controller_Response_Http(); $response->setHeader('Content-type', 'text/html; charset=utf-8', true); $response->setBody(self::$view->render('header.php')); try { require_once 'Zend/Controller/Request/Http.php'; $request = new Zend_Controller_Request_Http(); // show exceptions immediately, instead of adding to the response $frontController->throwExceptions(true); // without this no exceptions are thrown // similar to "running" the configured MVC "program" $frontController->dispatch($request, $response); } catch (Zend_Controller_Dispatcher_Exception $exception) { self::analyzeError($frontController->getDispatcher(), $exception, $request, $response); return false; } // STAGES 3 to 5 occur in an action controller: /zfdemo/forum/*/controllers/*Controller.php // STAGE 6 occurs in a view template: /zfdemo/forum/*/views/*.phtml /** * STAGE 7: Render results in response to request. */ $response->renderExceptions(true); // show any excpetions in the visible output (i.e. debug mode) // OR: Handle exceptions thrown in the dispatch loop. // Examine the exception type, and then redirect to an error page. ksort($_SERVER); self::$view->SERVER = $_SERVER; self::$view->log = ZFDemo_Log::get(); $response->appendBody(self::$view->render('footer.php'), 'footer'); //Zend::debug($frontController->getRequest());exit // debug the request object //Zend_Debug::dump($response);exit; // examine the inner details of the response object $response->sendResponse(); // send final results to browser, including headers }
/** * test postDispatch() */ public function testPostDispatch() { $response = new Zend_Controller_Response_Http(); $response->setBody('<form method="post" action="/"></form>'); Zend_Controller_Front::getInstance()->setResponse($response); $formHelperToken = new Idun_Form_Helper_Token(array('tokenKey' => 'testTokenKey')); $formTokenHelper = new Idun_Controller_Plugin_FormToken($formHelperToken); $formTokenHelper->postDispatch(new Zend_Controller_Request_Http()); $token = current($_SESSION['Idun_Form_Helper_Token']['tokens']); $this->assertEquals('<form method="post" action="/">' . '<div><input type="hidden" name="testTokenKey" value="' . $token . '" /></div>' . '</form>', $response->getBody()); }
protected function _sendResponse($httpCode, $code, $message) { // TODO Why is sometimes sending response twice??? :S if (self::$responseSent) { return; } if (!($response = Zend_Controller_Front::getInstance()->getResponse())) { $response = new Zend_Controller_Response_Http(); } $response->setHttpResponseCode($httpCode); if (!$response->getBody()) { $body = array('code' => $code, 'message' => $message); $response->setBody(Zend_Json::encode($body)); } if ($response->canSendHeaders()) { $response->clearHeaders(); $response->setHeader('Content-Type', 'application/json'); $response->sendResponse(); self::$responseSent = true; } exit; }
public function adminCancelAction(Am_Request $request, Zend_Controller_Response_Http $response, array $invokeArgs) { if (!$this->getDi()->authAdmin->getUserId()) { throw new Am_Exception_AccessDenied("Only admin access allowed"); } $invoice_id = $request->getInt('invoice_id'); $invoice = $this->getDi()->invoiceTable->load($invoice_id); if ($invoice->paysys_id != $this->getId()) { throw new Am_Exception_InternalError("Trying to cancel transaction - not 2CO one"); } $result = new Am_Paysystem_Result(); $payment = current($invoice->getPaymentRecords()); try { $this->cancelInvoice($payment, $result); } catch (Exception $e) { $result->setFailed($e->getMessage()); } $view = $this->getDi()->view; $view->title = ___("Subscription Cancelled"); $view->content = $result->isSuccess() ? ___("Success") : implode("<br />\n", $result->getErrorMessages()); $response->setBody($view->render('admin/layout.phtml')); }