public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
 {
     if (defined('PROXY_CACHE_GENERATING') || isset($GLOBALS['__cache_publish']) || strpos($request->getURL(), 'admin/') !== false) {
         return;
     }
     $this->database = Db::getConn();
     $queries = $this->database->queryRecord;
     $dupes = $this->database->getDuplicateQueries();
     $str = "\n<!-- Total queries: " . count($queries) . "-->\n";
     $str .= "\n<!-- Duplicate queries: " . count($dupes) . "-->\n";
     $b = $response->getBody();
     if (strpos($b, '</html>')) {
         if (count($queries) > $this->queryThreshold) {
             // add a floating div with info about the stuff
             $buildQueryList = function ($source, $class) {
                 $html = '';
                 foreach ($source as $sql => $info) {
                     $html .= "\n<p class='{$class}' style='display: none; border-top: 1px dashed #000;'>{$info->count} : {$info->query}</p>\n";
                     if ($info->source) {
                         $html .= "\n<p class='{$class}' style='color: #a00; display: none; '>Last called from {$info->source}</p>\n";
                     }
                 }
                 return $html;
             };
             $html = $buildQueryList($queries, 'debug-query');
             $html .= $buildQueryList($dupes, 'debug-dupe-query');
             $div = '<div id="query-stat-debugger" ' . 'style="position: fixed; bottom: 0; right: 0; border: 2px solid red; background: #fff; ' . 'font-size: 8px; font-family: sans-serif; width: 100px; z-index: 2000; padding: 1em;' . 'overflow: auto; max-height: 500px;">' . '<p id="debug-all-queries-list">Total of ' . count($queries) . ' queries</p>' . '<p id="debug-dupe-queries-list">Total of ' . count($dupes) . ' duplicates</p>' . $html . '<script>' . 'jQuery("#debug-all-queries-list").click(function () {' . 'var elems = jQuery(this).parent().find(".debug-query");' . 'jQuery(this).parent().css("width", "40%");' . 'elems.toggle();' . '}); ' . 'jQuery("#debug-dupe-queries-list").click(function () {' . 'var elems = jQuery(this).parent().find(".debug-dupe-query");' . 'jQuery(this).parent().css("width", "40%");' . 'elems.toggle();' . '}); ' . '' . '' . '</script>' . '</div>';
             $b = str_replace('</body>', "{$div}</body>", $b);
         }
         $b = str_replace('</html>', "{$str}</html>", $b);
         $response->setBody($b);
     }
 }
 public function load($request)
 {
     $response = new SS_HTTPResponse();
     $response->addHeader('Content-Type', 'application/json');
     $response->setBody(Convert::array2json(array("_memberID" => Member::currentUserID())));
     return $response;
 }
 public function load($request)
 {
     $response = new SS_HTTPResponse();
     $response->addHeader('Content-Type', 'application/json');
     $response->setBody(Convert::array2json(call_user_func($this->source, $request->getVar('val'))));
     return $response;
 }
 public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
 {
     if ($this->convertUrls && $response && $response->getStatusCode() == 200) {
         // only convert if we have an HTML content type response
         $body = $response->getBody();
         // find urls inserted in content
         if (strpos($body, 'cdnfileid') > 0 && preg_match_all('/data-cdnfileid="(\\d+)"/', $body, $matches)) {
             $files = CdnImage::get()->filter('ID', $matches[1]);
             $fileIds = array();
             foreach ($files as $file) {
                 $url = $file->getUrl();
                 $filename = $file->Filename;
                 $body = str_replace("src=\"{$filename}\"", "src=\"{$url}\"", $body);
                 $fileIds[] = $file->ID;
             }
             $assets = ContentServiceAsset::get()->filter('SourceID', $matches[1]);
             foreach ($assets as $asset) {
                 $url = $asset->getUrl();
                 $filename = $asset->Filename;
                 // note the extra forward slash here, image_cached inserts it
                 $body = str_replace("src=\"/{$filename}\"", "src=\"{$url}\"", $body);
             }
             $response->setBody($body);
         }
     }
 }
 public function handleRequest(SS_HTTPRequest $request, DataModel $model = NULL)
 {
     $body = null;
     $lang = i18n::get_locale();
     $path = Config::inst()->get('UniversalErrorPage', 'DefaultPath');
     if (!$path) {
         $path = $this->defaultErrorPagePath;
     }
     $forCode = Config::inst()->get('UniversalErrorPage', $this->ErrorCode);
     $localeForCode = preg_replace('/\\.([a-z]+)$/i', '-' . $lang . '.$1', $forCode);
     $errorPages = array($localeForCode, $forCode, $path . "error-{$this->ErrorCode}-{$lang}.html", $path . "error-{$this->ErrorCode}-{$lang}.php", $path . "error-{$lang}.html", $path . "error-{$lang}.php", $path . 'error.html', $path . 'error.php');
     $this->extend('updateHandleRequest', $errorPages);
     // now check if any of the pages exist
     foreach ($errorPages as $errorPage) {
         if (!$body && file_exists($errorPage)) {
             $ext = pathinfo($errorPage, PATHINFO_EXTENSION);
             if ($ext == 'php') {
                 ob_start();
                 include $errorPage;
                 $body = ob_get_clean();
             } else {
                 $body = file_get_contents($errorPage);
             }
             break;
         }
     }
     if ($body) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode($this->ErrorCode);
         $response->setBody($body);
         return $response;
     }
     return parent::handleRequest($request, $model);
 }
 /**
  * Returns a JSON string of tags, for lazy loading.
  *
  * @param SS_HTTPRequest $request
  *
  * @return SS_HTTPResponse
  */
 public function suggest(SS_HTTPRequest $request)
 {
     $members = $this->getMembers($request->getVar('term'));
     $response = new SS_HTTPResponse();
     $response->addHeader('Content-Type', 'application/json');
     $response->setBody(json_encode($members));
     return $response;
 }
예제 #7
0
 function testContentLengthHeader()
 {
     $r = new SS_HTTPResponse('123ü');
     $this->assertNotNull($r->getHeader('Content-Length'), 'Content-length header is added');
     $this->assertEquals(5, $r->getHeader('Content-Length'), 'Header matches actual content length in bytes');
     $r->setBody('1234ü');
     $this->assertEquals(6, $r->getHeader('Content-Length'), 'Header is updated when body is changed');
 }
 /**
  * Filter executed AFTER a request
  *
  * @param SS_HTTPRequest $request Request container object
  * @param SS_HTTPResponse $response Response output object
  * @param DataModel $model Current DataModel
  * @return boolean Whether to continue processing other filters. Null or true will continue processing (optional)
  */
 public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     if (!self::isEnabled()) {
         return true;
     }
     $body = $response->getBody();
     $response->setBody(self::replaceCDN($body));
     return true;
 }
 public function postRequest(\SS_HTTPRequest $request, \SS_HTTPResponse $response, \DataModel $model)
 {
     $time = sprintf('%.3f ms', microtime(true) - $this->start);
     $response->addHeader('X-SilverStripe-Time', $time);
     $b = $response->getBody();
     if (strpos($b, '</html>')) {
         $b = str_replace('</html>', "\n<!-- Generated in {$time} -->\n</html>", $b);
         $response->setBody($b);
     }
 }
 /**
  * Require basic authentication.  Will request a username and password if none is given.
  *
  * Used by {@link Controller::init()}.
  *
  * @throws SS_HTTPResponse_Exception
  *
  * @param string $realm
  * @param string|array $permissionCode Optional
  * @param boolean $tryUsingSessionLogin If true, then the method with authenticate against the
  *  session log-in if those credentials are disabled.
  * @return Member $member
  */
 public static function requireLogin($realm, $permissionCode = null, $tryUsingSessionLogin = true)
 {
     $isRunningTests = class_exists('SapphireTest', false) && SapphireTest::is_running_test();
     if (!Security::database_is_ready() || Director::is_cli() && !$isRunningTests) {
         return true;
     }
     /*
      * Enable HTTP Basic authentication workaround for PHP running in CGI mode with Apache
      * Depending on server configuration the auth header may be in HTTP_AUTHORIZATION or
      * REDIRECT_HTTP_AUTHORIZATION
      *
      * The follow rewrite rule must be in the sites .htaccess file to enable this workaround
      * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
      */
     $authHeader = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) ? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] : null);
     $matches = array();
     if ($authHeader && preg_match('/Basic\\s+(.*)$/i', $authHeader, $matches)) {
         list($name, $password) = explode(':', base64_decode($matches[1]));
         $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
         $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
     }
     $member = null;
     if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
         $member = MoreAdminsAuthenticator::authenticate(array('Email' => $_SERVER['PHP_AUTH_USER'], 'Password' => $_SERVER['PHP_AUTH_PW']), null);
     }
     if (!$member && $tryUsingSessionLogin) {
         $member = Member::currentUser();
     }
     // If we've failed the authentication mechanism, then show the login form
     if (!$member) {
         $response = new SS_HTTPResponse(null, 401);
         $response->addHeader('WWW-Authenticate', "Basic realm=\"{$realm}\"");
         if (isset($_SERVER['PHP_AUTH_USER'])) {
             $response->setBody(_t('BasicAuth.ERRORNOTREC', "That username / password isn't recognised"));
         } else {
             $response->setBody(_t('BasicAuth.ENTERINFO', "Please enter a username and password."));
         }
         // Exception is caught by RequestHandler->handleRequest() and will halt further execution
         $e = new SS_HTTPResponse_Exception(null, 401);
         $e->setResponse($response);
         throw $e;
     }
     if ($permissionCode && !Permission::checkMember($member->ID, $permissionCode)) {
         $response = new SS_HTTPResponse(null, 401);
         $response->addHeader('WWW-Authenticate', "Basic realm=\"{$realm}\"");
         if (isset($_SERVER['PHP_AUTH_USER'])) {
             $response->setBody(_t('BasicAuth.ERRORNOTADMIN', "That user is not an administrator."));
         }
         // Exception is caught by RequestHandler->handleRequest() and will halt further execution
         $e = new SS_HTTPResponse_Exception(null, 401);
         $e->setResponse($response);
         throw $e;
     }
     return $member;
 }
 /**
  * Adds Intercom script tags just before the body
  */
 public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     $mime = $response->getHeader('Content-Type');
     if (!$mime || strpos($mime, 'text/html') !== false) {
         $intercomScriptTags = (new intercomScriptTags())->forTemplate();
         if ($intercomScriptTags) {
             $content = $response->getBody();
             $content = preg_replace("/(<\\/body[^>]*>)/i", $intercomScriptTags . "\\1", $content);
             $response->setBody($content);
         }
     }
 }
 public function member()
 {
     $EmailAddress = "";
     $Member = "";
     // Make sure the access is POST, not GET
     if (!$this->request->isPOST()) {
         return $this->httpError(403, 'Access Denied.');
     }
     if (!defined('APPSEC')) {
         return $this->httpError(403, 'Access Denied.');
     }
     // Make sure the APPSEC shared secret matches
     if ($this->request->postVar('APPSEC') != APPSEC) {
         return $this->httpError(403, 'Access Denied.');
     }
     // Pull email address from POST variables
     $EmailAddress = $this->request->postVar('email');
     // Sanitize the input
     $EmailAddress = convert::raw2sql($EmailAddress);
     // If an email address was provided, try to find a member with it
     if ($EmailAddress) {
         $Member = Member::get()->filter('Email', $EmailAddress)->first();
     }
     $response = new SS_HTTPResponse();
     // If a member was found return status 200 and 'OK'
     if ($Member && $Member->isFoundationMember()) {
         $response->setStatusCode(200);
         $response->setBody('OK');
         $response->output();
     } elseif ($EmailAddress) {
         $response->setStatusCode(404);
         $response->setBody('No Member Found.');
         $response->output();
     } else {
         $response->setStatusCode(500);
         $response->setBody('An error has occurred retrieving a member.');
         $response->output();
     }
 }
 public function load($request)
 {
     $response = new SS_HTTPResponse();
     $response->addHeader('Content-Type', 'application/json');
     $items = call_user_func($this->source, $request->getVar('val'));
     $results = array();
     if ($items) {
         foreach ($items as $k => $v) {
             $results[] = array('k' => $k, 'v' => $v);
         }
     }
     $response->setBody(Convert::array2json($results));
     return $response;
 }
 /**
  * Get all content as a javascript-compatible string (only if there is an Ajax-Request present).
  * Falls back to {non_ajax_content}, {redirect_url} or Director::redirectBack() (in this order).
  * 
  * @return string
  */
 static function respond()
 {
     $response = new SS_HTTPResponse();
     // we don't want non-ajax calls to receive javascript
     if (isset($_REQUEST['forcehtml'])) {
         $response->setBody(self::$non_ajax_content);
     } else {
         if (isset($_REQUEST['forceajax']) || Director::is_ajax()) {
             $response->addHeader('Content-Type', 'text/javascript');
             $response->setBody(self::get_javascript());
         } elseif (!empty(self::$non_ajax_content)) {
             $response->setBody(self::$non_ajax_content);
         } elseif (!empty(self::$redirect_url)) {
             Director::redirect(self::$redirect_url);
             return null;
         } elseif (!Director::redirected_to()) {
             Director::redirectBack();
             return null;
         } else {
             return null;
         }
     }
     return $response;
 }
예제 #15
0
 /**
  * Get a {@link SS_HTTPResponse} to response to a HTTP error code if an {@link ErrorPage} for that code is present.
  *
  * @param int $statusCode
  * @return SS_HTTPResponse
  */
 public static function response_for($statusCode)
 {
     // first attempt to dynamically generate the error page
     if ($errorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = {$statusCode}")) {
         return ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
     }
     // then fall back on a cached version
     $cachedPath = self::get_filepath_for_errorcode($statusCode, class_exists('Translatable') ? Translatable::get_current_locale() : null);
     if (file_exists($cachedPath)) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode($statusCode);
         $response->setBody(file_get_contents($cachedPath));
         return $response;
     }
 }
예제 #16
0
파일: BasicAuth.php 프로젝트: vinstah/body
 /**
  * Require basic authentication.  Will request a username and password if none is given.
  *
  * Used by {@link Controller::init()}.
  *
  * @throws SS_HTTPResponse_Exception
  *
  * @param string $realm
  * @param string|array $permissionCode Optional
  * @param boolean $tryUsingSessionLogin If true, then the method with authenticate against the
  *  session log-in if those credentials are disabled.
  * @return Member $member
  */
 public static function requireLogin($realm, $permissionCode = null, $tryUsingSessionLogin = true)
 {
     $isRunningTests = class_exists('SapphireTest', false) && SapphireTest::is_running_test();
     if (!Security::database_is_ready() || Director::is_cli() && !$isRunningTests) {
         return true;
     }
     $matches = array();
     if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
         list($name, $password) = explode(':', base64_decode($matches[1]));
         $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
         $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
     }
     $member = null;
     if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
         $member = MemberAuthenticator::authenticate(array('Email' => $_SERVER['PHP_AUTH_USER'], 'Password' => $_SERVER['PHP_AUTH_PW']), null);
     }
     if (!$member && $tryUsingSessionLogin) {
         $member = Member::currentUser();
     }
     // If we've failed the authentication mechanism, then show the login form
     if (!$member) {
         $response = new SS_HTTPResponse(null, 401);
         $response->addHeader('WWW-Authenticate', "Basic realm=\"{$realm}\"");
         if (isset($_SERVER['PHP_AUTH_USER'])) {
             $response->setBody(_t('BasicAuth.ERRORNOTREC', "That username / password isn't recognised"));
         } else {
             $response->setBody(_t('BasicAuth.ENTERINFO', "Please enter a username and password."));
         }
         // Exception is caught by RequestHandler->handleRequest() and will halt further execution
         $e = new SS_HTTPResponse_Exception(null, 401);
         $e->setResponse($response);
         throw $e;
     }
     if ($permissionCode && !Permission::checkMember($member->ID, $permissionCode)) {
         $response = new SS_HTTPResponse(null, 401);
         $response->addHeader('WWW-Authenticate', "Basic realm=\"{$realm}\"");
         if (isset($_SERVER['PHP_AUTH_USER'])) {
             $response->setBody(_t('BasicAuth.ERRORNOTADMIN', "That user is not an administrator."));
         }
         // Exception is caught by RequestHandler->handleRequest() and will halt further execution
         $e = new SS_HTTPResponse_Exception(null, 401);
         $e->setResponse($response);
         throw $e;
     }
     return $member;
 }
예제 #17
0
	/**
	 * Executes this controller, and return an {@link SS_HTTPResponse} object with the result.
	 * 
	 * This method first does a few set-up activities:
	 *  - Push this controller ont to the controller stack - 
	 *    see {@link Controller::curr()} for information about this.
	 *  - Call {@link init()}
	 *  - Defer to {@link RequestHandler->handleRequest()} to determine which action
	 *    should be executed
	 * 
	 * Note: $requestParams['executeForm'] support was removed, 
	 * make the following change in your URLs: 
	 * "/?executeForm=FooBar" -> "/FooBar" 
	 * Also make sure "FooBar" is in the $allowed_actions of your controller class.
	 * 
	 * Note: You should rarely need to overload run() - 
	 * this kind of change is only really appropriate for things like nested
	 * controllers - {@link ModelAsController} and {@link RootURLController} 
	 * are two examples here.  If you want to make more
	 * orthodox functionality, it's better to overload {@link init()} or {@link index()}.
	 * 
	 * Important: If you are going to overload handleRequest, 
	 * make sure that you start the method with $this->pushCurrent()
	 * and end the method with $this->popCurrent().  
	 * Failure to do this will create weird session errors.
	 * 
	 * @param $request The {@link SS_HTTPRequest} object that is responsible 
	 *  for distributing request parsing.
	 * @return SS_HTTPResponse The response that this controller produces, 
	 *  including HTTP headers such as redirection info
	 */
	function handleRequest(SS_HTTPRequest $request, DataModel $model) {
		if(!$request) user_error("Controller::handleRequest() not passed a request!", E_USER_ERROR);
		
		$this->pushCurrent();
		$this->urlParams = $request->allParams();
		$this->request = $request;
		$this->response = new SS_HTTPResponse();
		$this->setModel($model);
		
		$this->extend('onBeforeInit');

		// Init
		$this->baseInitCalled = false;	
		$this->init();
		if(!$this->baseInitCalled) user_error("init() method on class '$this->class' doesn't call Controller::init().  Make sure that you have parent::init() included.", E_USER_WARNING);

		$this->extend('onAfterInit');
		
		// If we had a redirection or something, halt processing.
		if($this->response->isFinished()) {
			$this->popCurrent();
			return $this->response;
		}

		$body = parent::handleRequest($request, $model);
		if($body instanceof SS_HTTPResponse) {
			if(isset($_REQUEST['debug_request'])) Debug::message("Request handler returned SS_HTTPResponse object to $this->class controller; returning it without modification.");
			$this->response = $body;
			
		} else {
			if(is_object($body)) {
				if(isset($_REQUEST['debug_request'])) Debug::message("Request handler $body->class object to $this->class controller;, rendering with template returned by $body->class::getViewer()");
			   $body = $body->getViewer($request->latestParam('Action'))->process($body);
			}
			
			$this->response->setBody($body);
		}


		ContentNegotiator::process($this->response);
		HTTP::add_cache_headers($this->response);

		$this->popCurrent();
		return $this->response;
	}
예제 #18
0
 /**
  * Get a {@link SS_HTTPResponse} to response to a HTTP error code if an
  * {@link ErrorPage} for that code is present. First tries to serve it 
  * through the standard SilverStripe request method. Falls back to a static
  * file generated when the user hit's save and publish in the CMS
  *
  * @param int $statusCode
  *
  * @return SS_HTTPResponse
  */
 public static function response_for($statusCode)
 {
     // first attempt to dynamically generate the error page
     $errorPage = ErrorPage::get()->filter(array("ErrorCode" => $statusCode))->first();
     if ($errorPage) {
         Requirements::clear();
         Requirements::clear_combined_files();
         return ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
     }
     // then fall back on a cached version
     $cachedPath = self::get_filepath_for_errorcode($statusCode, class_exists('Translatable') ? Translatable::get_current_locale() : null);
     if (file_exists($cachedPath)) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode($statusCode);
         $response->setBody(file_get_contents($cachedPath));
         return $response;
     }
 }
 /**
  * Filter executed AFTER a request
  *
  * @param SS_HTTPRequest $request Request container object
  * @param SS_HTTPResponse $response Response output object
  * @param DataModel $model Current DataModel
  * @return boolean Whether to continue processing other filters. Null or true will continue processing (optional)
  */
 public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     $code = $response->getStatusCode();
     $error_page_path = Director::baseFolder() . "/errors_pages/ui/{$code}/index.html";
     if (!$request->isAjax() && file_exists($error_page_path)) {
         //clean buffer
         ob_clean();
         $page_file = fopen($error_page_path, "r") or die("Unable to open file!");
         $body = fread($page_file, filesize($error_page_path));
         fclose($page_file);
         // set content type
         $response->addHeader('Content-Type', 'text/html');
         $response->setBody($body);
         $response->setStatusCode(200);
         return true;
     }
     return true;
 }
 /**
  * Filter executed AFTER a request
  *
  * @param SS_HTTPRequest $request   Request container object
  * @param SS_HTTPResponse $response Response output object
  * @param DataModel $model          Current DataModel
  * @return boolean Whether to continue processing other filters. Null or true will continue processing (optional)
  */
 public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model)
 {
     $debugbar = DebugBar::getDebugBar();
     if (!$debugbar) {
         return;
     }
     // All queries have been displayed
     if (DebugBar::getShowQueries()) {
         exit;
     }
     $script = DebugBar::renderDebugBar();
     // If the bar is not renderable, return early
     if (!$script) {
         return;
     }
     // Inject init script into the HTML response
     $body = $response->getBody();
     if (strpos($body, '</body>') !== false) {
         $body = str_replace('</body>', $script . '</body>', $body);
         $response->setBody($body);
     }
     // Ajax support
     if (Director::is_ajax() && !headers_sent()) {
         if (DebugBar::IsAdminUrl() && !DebugBar::config()->enabled_in_admin) {
             return;
         }
         // Skip anything that is not a GET request
         if (!$request->isGET()) {
             return;
         }
         // Always enable in admin because everything is mostly loaded through ajax
         if (DebugBar::config()->ajax || DebugBar::IsAdminUrl()) {
             $headers = $debugbar->getDataAsHeaders();
             // Prevent throwing js errors in case header size is too large
             if (is_array($headers)) {
                 $debugbar->sendDataInHeaders();
             }
         }
     }
 }
 protected function write(array $record)
 {
     ini_set('display_errors', 0);
     // TODO: This coupling isn't ideal
     // See https://github.com/silverstripe/silverstripe-framework/issues/4484
     if (\Controller::has_curr()) {
         $response = \Controller::curr()->getResponse();
     } else {
         $response = new SS_HTTPResponse();
     }
     // If headers have been sent then these won't be used, and may throw errors that we wont' want to see.
     if (!headers_sent()) {
         $response->setStatusCode($this->statusCode);
         $response->addHeader("Content-Type", $this->contentType);
     } else {
         // To supress errors aboot errors
         $response->setStatusCode(200);
     }
     $response->setBody($record['formatted']);
     $response->output();
     return false === $this->bubble;
 }
 /**
  *	Display an error page on invalid request.
  *
  *	@parameter <{ERROR_CODE}> integer
  *	@parameter <{ERROR_MESSAGE}> string
  */
 public function httpError($code, $message = null)
 {
     // Determine the error page for the given status code.
     $errorPages = ClassInfo::exists('SiteTree') ? ErrorPage::get()->filter('ErrorCode', $code) : null;
     // Allow extension customisation.
     $this->extend('updateErrorPages', $errorPages);
     // Retrieve the error page response.
     if ($errorPages && ($errorPage = $errorPages->first())) {
         Requirements::clear();
         Requirements::clear_combined_files();
         $response = ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
         throw new SS_HTTPResponse_Exception($response, $code);
     } else {
         if ($errorPages && file_exists($cachedPage = ErrorPage::get_filepath_for_errorcode($code, class_exists('Translatable') ? Translatable::get_current_locale() : null))) {
             $response = new SS_HTTPResponse();
             $response->setStatusCode($code);
             $response->setBody(file_get_contents($cachedPage));
             throw new SS_HTTPResponse_Exception($response, $code);
         } else {
             return parent::httpError($code, $message);
         }
     }
 }
 public function handleView($request)
 {
     if ($request->getExtension() != 'gif') {
         $this->httpError(404);
     }
     $newsletter = DataObject::get_one('Newsletter', sprintf('"Token" = \'%s\'', Convert::raw2sql($request->param('Newsletter'))));
     $user = DataObject::get_one('Member', sprintf('"NewsletterTrackingToken" = \'%s\'', Convert::raw2sql($request->param('User'))));
     if (!$newsletter || !$user) {
         $this->httpError(404);
     }
     $view = new NewsletterView();
     $view->IP = $request->getIP();
     $view->NewsletterID = $newsletter->ID;
     $view->MemberID = $user->ID;
     $view->write();
     $gif = '';
     foreach (self::$one_px_gif as $byte) {
         $gif .= chr($byte);
     }
     $response = new SS_HTTPResponse();
     $response->addHeader('Content-Type', 'image/gif');
     $response->setBody($gif);
     return $response;
 }
예제 #24
0
 public function sendSignupConfirmation($request)
 {
     $body = $this->request->getBody();
     $json = json_decode($body, true);
     if (!$this->securityToken->checkRequest($request)) {
         $response = new SS_HTTPResponse();
         $response->setStatusCode(403);
         $response->addHeader('Content-Type', 'application/json');
         $response->setBody(json_encode("Error"));
         return $response;
     }
     $this->securityToken->reset();
     $to = $json['email'];
     $news_update_email_from = defined('NEWS_UPDATE_EMAIL_FROM') ? NEWS_UPDATE_EMAIL_FROM : '*****@*****.**';
     $user_name = sprintf('%s %s', $json['first_name'], $json['last_name']);
     $email = EmailFactory::getInstance()->buildEmail('*****@*****.**', $to, 'Thank you for subscribing to OpenStack Foundation News updates');
     $email->setTemplate('NewsPageSignupConfirmationEMail');
     $email->populateTemplate(array('UserName' => $user_name, 'NewsUpdateEmailFrom' => $news_update_email_from));
     $email->send();
     return 'OK';
 }
예제 #25
0
 /**
  * Process the given URL, creating the appropriate controller and executing it.
  *
  * Request processing is handled as follows:
  * - Director::direct() creates a new SS_HTTPResponse object and passes this to
  *   Director::handleRequest().
  * - Director::handleRequest($request) checks each of the Director rules and identifies a controller
  *   to handle this request.
  * - Controller::handleRequest($request) is then called.  This will find a rule to handle the URL,
  *   and call the rule handling method.
  * - RequestHandler::handleRequest($request) is recursively called whenever a rule handling method
  *   returns a RequestHandler object.
  *
  * In addition to request processing, Director will manage the session, and perform the output of
  * the actual response to the browser.
  *
  * @uses handleRequest() rule-lookup logic is handled by this.
  * @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call.
  *
  * @param string $url
  * @param DataModel $model
  *
  * @throws SS_HTTPResponse_Exception
  */
 public static function direct($url, DataModel $model)
 {
     // Validate $_FILES array before merging it with $_POST
     foreach ($_FILES as $k => $v) {
         if (is_array($v['tmp_name'])) {
             $v = ArrayLib::array_values_recursive($v['tmp_name']);
             foreach ($v as $tmpFile) {
                 if ($tmpFile && !is_uploaded_file($tmpFile)) {
                     user_error("File upload '{$k}' doesn't appear to be a valid upload", E_USER_ERROR);
                 }
             }
         } else {
             if ($v['tmp_name'] && !is_uploaded_file($v['tmp_name'])) {
                 user_error("File upload '{$k}' doesn't appear to be a valid upload", E_USER_ERROR);
             }
         }
     }
     $req = new SS_HTTPRequest(isset($_SERVER['X-HTTP-Method-Override']) ? $_SERVER['X-HTTP-Method-Override'] : $_SERVER['REQUEST_METHOD'], $url, $_GET, ArrayLib::array_merge_recursive((array) $_POST, (array) $_FILES), @file_get_contents('php://input'));
     $headers = self::extract_request_headers($_SERVER);
     foreach ($headers as $header => $value) {
         $req->addHeader($header, $value);
     }
     // Initiate an empty session - doesn't initialize an actual PHP session until saved (see below)
     $session = Injector::inst()->create('Session', isset($_SESSION) ? $_SESSION : array());
     // Only resume a session if its not started already, and a session identifier exists
     if (!isset($_SESSION) && Session::request_contains_session_id()) {
         $session->inst_start();
     }
     $output = Injector::inst()->get('RequestProcessor')->preRequest($req, $session, $model);
     if ($output === false) {
         // @TODO Need to NOT proceed with the request in an elegant manner
         throw new SS_HTTPResponse_Exception(_t('Director.INVALID_REQUEST', 'Invalid request'), 400);
     }
     $result = Director::handleRequest($req, $session, $model);
     // Save session data. Note that inst_save() will start/resume the session if required.
     $session->inst_save();
     // Return code for a redirection request
     if (is_string($result) && substr($result, 0, 9) == 'redirect:') {
         $url = substr($result, 9);
         if (Director::is_cli()) {
             // on cli, follow SilverStripe redirects automatically
             return Director::direct(str_replace(Director::absoluteBaseURL(), '', $url), DataModel::inst());
         } else {
             $response = new SS_HTTPResponse();
             $response->redirect($url);
             $res = Injector::inst()->get('RequestProcessor')->postRequest($req, $response, $model);
             if ($res !== false) {
                 $response->output();
             }
         }
         // Handle a controller
     } elseif ($result) {
         if ($result instanceof SS_HTTPResponse) {
             $response = $result;
         } else {
             $response = new SS_HTTPResponse();
             $response->setBody($result);
         }
         $res = Injector::inst()->get('RequestProcessor')->postRequest($req, $response, $model);
         if ($res !== false) {
             $response->output();
         } else {
             // @TODO Proper response here.
             throw new SS_HTTPResponse_Exception("Invalid response");
         }
         //$controllerObj->getSession()->inst_save();
     }
 }
예제 #26
0
 /**
  * Handles formatting and output error message
  * then exit.
  * 
  * @param  RESTfulAPI_Error $error Error object to return
  */
 public function error(RESTfulAPI_Error $error)
 {
     $answer = new SS_HTTPResponse();
     $body = $this->serializer->serialize($error->body);
     $answer->setBody($body);
     $answer->setStatusCode($error->code, $error->message);
     $answer->addHeader('Content-Type', $this->serializer->getcontentType());
     $answer = $this->setAnswerCORS($answer);
     // save controller's response then return/output
     $this->response = $answer;
     return $answer;
 }
예제 #27
0
 public function getNavigationMenu()
 {
     $menu_html = $this->renderWith('Navigation_menu', array('WidgetCall' => true))->getValue();
     $data = array('html' => $menu_html);
     $jsonp = "jsonCallback(" . json_encode($data) . ")";
     $response = new SS_HTTPResponse();
     $response->setStatusCode(200);
     $response->addHeader('Content-Type', 'application/javascript');
     $response->setBody($jsonp);
     return $response;
 }
 /**
  * Enable BasicAuth in a similar fashion as BasicAuth class
  * 
  * @return boolean
  * @throws SS_HTTPResponse_Exception
  */
 protected function basicAuth()
 {
     $username = self::config()->username;
     $password = self::config()->password;
     if (!$username || !$password) {
         return true;
     }
     $authHeader = null;
     if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
         $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
     } else {
         if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
             $authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
         }
     }
     $matches = array();
     if ($authHeader && preg_match('/Basic\\s+(.*)$/i', $authHeader, $matches)) {
         list($name, $password) = explode(':', base64_decode($matches[1]));
         $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
         $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
     }
     $authSuccess = false;
     if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
         if ($_SERVER['PHP_AUTH_USER'] == $username && $_SERVER['PHP_AUTH_PW'] == $password) {
             $authSuccess = true;
         }
     }
     if (!$authSuccess) {
         $realm = "Enter your credentials";
         $response = new SS_HTTPResponse(null, 401);
         $response->addHeader('WWW-Authenticate', "Basic realm=\"{$realm}\"");
         if (isset($_SERVER['PHP_AUTH_USER'])) {
             $response->setBody(_t('BasicAuth.ERRORNOTREC', "That username / password isn't recognised"));
         } else {
             $response->setBody(_t('BasicAuth.ENTERINFO', "Please enter a username and password."));
         }
         // Exception is caught by RequestHandler->handleRequest() and will halt further execution
         $e = new SS_HTTPResponse_Exception(null, 401);
         $e->setResponse($response);
         throw $e;
     }
     return $authSuccess;
 }
 /**
  * Returns a JSON string of tags, for lazy loading.
  *
  * @param SS_HTTPRequest $request
  *
  * @return SS_HTTPResponse
  */
 public function suggest(SS_HTTPRequest $request)
 {
     $tags = $this->getTags($request->getVar('term'));
     $response = new SS_HTTPResponse();
     $response->addHeader('Content-Type', 'application/json');
     $response->setBody(json_encode(array('items' => $tags)));
     return $response;
 }
예제 #30
0
 /**
  * Process the given URL, creating the appropriate controller and executing it.
  * 
  * Request processing is handled as follows:
  *  - Director::direct() creates a new SS_HTTPResponse object and passes this to Director::handleRequest().
  *  - Director::handleRequest($request) checks each of the Director rules and identifies a controller to handle this 
  *    request.
  *  - Controller::handleRequest($request) is then called.  This will find a rule to handle the URL, and call the rule
  *    handling method.
  *  - RequestHandler::handleRequest($request) is recursively called whenever a rule handling method returns a
  *    RequestHandler object.
  *
  * In addition to request processing, Director will manage the session, and perform the output of the actual response
  * to the browser.
  * 
  * @param $url String, the URL the user is visiting, without the querystring.
  * @uses handleRequest() rule-lookup logic is handled by this.
  * @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call.
  */
 static function direct($url)
 {
     // Validate $_FILES array before merging it with $_POST
     foreach ($_FILES as $k => $v) {
         if (is_array($v['tmp_name'])) {
             $v = ArrayLib::array_values_recursive($v['tmp_name']);
             foreach ($v as $tmpFile) {
                 if ($tmpFile && !is_uploaded_file($tmpFile)) {
                     user_error("File upload '{$k}' doesn't appear to be a valid upload", E_USER_ERROR);
                 }
             }
         } else {
             if ($v['tmp_name'] && !is_uploaded_file($v['tmp_name'])) {
                 user_error("File upload '{$k}' doesn't appear to be a valid upload", E_USER_ERROR);
             }
         }
     }
     $req = new SS_HTTPRequest(isset($_SERVER['X-HTTP-Method-Override']) ? $_SERVER['X-HTTP-Method-Override'] : $_SERVER['REQUEST_METHOD'], $url, $_GET, array_merge((array) $_POST, (array) $_FILES), @file_get_contents('php://input'));
     // @todo find better way to extract HTTP headers
     if (isset($_SERVER['HTTP_ACCEPT'])) {
         $req->addHeader("Accept", $_SERVER['HTTP_ACCEPT']);
     }
     if (isset($_SERVER['CONTENT_TYPE'])) {
         $req->addHeader("Content-Type", $_SERVER['CONTENT_TYPE']);
     }
     if (isset($_SERVER['HTTP_REFERER'])) {
         $req->addHeader("Referer", $_SERVER['HTTP_REFERER']);
     }
     // Load the session into the controller
     $session = new Session(isset($_SESSION) ? $_SESSION : null);
     $result = Director::handleRequest($req, $session);
     $session->inst_save();
     // Return code for a redirection request
     if (is_string($result) && substr($result, 0, 9) == 'redirect:') {
         $response = new SS_HTTPResponse();
         $response->redirect(substr($result, 9));
         $response->output();
         // Handle a controller
     } else {
         if ($result) {
             if ($result instanceof SS_HTTPResponse) {
                 $response = $result;
             } else {
                 $response = new SS_HTTPResponse();
                 $response->setBody($result);
             }
             // ?debug_memory=1 will output the number of bytes of memory used for this request
             if (isset($_REQUEST['debug_memory']) && $_REQUEST['debug_memory']) {
                 Debug::message(sprintf("Peak memory usage in bytes: %s", number_format(memory_get_peak_usage(), 0)));
             } else {
                 $response->output();
             }
             //$controllerObj->getSession()->inst_save();
         }
     }
 }