本文整理汇总了PHP中SS_HTTPResponse::setBody方法的典型用法代码示例。如果您正苦于以下问题:PHP SS_HTTPResponse::setBody方法的具体用法?PHP SS_HTTPResponse::setBody怎么用?PHP SS_HTTPResponse::setBody使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SS_HTTPResponse
的用法示例。
在下文中一共展示了SS_HTTPResponse::setBody方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: postRequest
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);
}
}
示例2: load
public function load($request)
{
$response = new SS_HTTPResponse();
$response->addHeader('Content-Type', 'application/json');
$response->setBody(Convert::array2json(array("_memberID" => Member::currentUserID())));
return $response;
}
示例3: load
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;
}
示例4: postRequest
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);
}
}
}
示例5: handleRequest
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);
}
示例6: suggest
/**
* 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: postRequest
/**
* 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;
}
示例8: postRequest
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);
}
}
示例9: requireLogin
/**
* 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;
}
示例10: postRequest
/**
* 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);
}
}
}
示例11: member
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();
}
}
示例12: load
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;
}
开发者ID:helpfulrobot,项目名称:sheadawson-silverstripe-dependentdropdownfield,代码行数:14,代码来源:DependentDropdownField.php
示例13: respond
/**
* 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;
}
示例14: response_for
/**
* 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;
}
}
示例15: requireLogin
/**
* 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;
}