Skip to content

Commit

Permalink
API Remove OutputMiddleware
Browse files Browse the repository at this point in the history
API Move environment / global / ini management into Environment class
API Move getTempFolder into TempFolder class
API Implement HTTPRequestBuilder / CLIRequestBuilder
BUG Restore SS_ALLOWED_HOSTS check in original location
API CoreKernel now requires $basePath to be passed in
API Refactor installer.php to use application to bootstrap
API move memstring conversion globals to Convert
BUG Fix error in CoreKernel nesting not un-nesting itself properly.
  • Loading branch information
Damian Mooyman committed Jun 20, 2017
1 parent bba9791 commit 12bd31f
Show file tree
Hide file tree
Showing 27 changed files with 2,548 additions and 2,432 deletions.
18 changes: 11 additions & 7 deletions cli-script.php
@@ -1,19 +1,23 @@
<?php

// CLI specific bootstrapping
use SilverStripe\Control\CLIRequestBuilder;
use SilverStripe\Core\AppKernel;
use SilverStripe\Core\HTTPApplication;
use SilverStripe\Core\Startup\OutputMiddleware;
use SilverStripe\Control\HTTPRequest;

require __DIR__ . '/src/includes/cli.php';
require __DIR__ . '/src/includes/autoload.php';

// Ensure that people can't access this from a web-server
if (!in_array(PHP_SAPI, ["cli", "cgi", "cgi-fcgi"])) {
echo "cli-script.php can't be run from a web request, you have to run it on the command-line.";
die();
}

// Build request and detect flush
$request = HTTPRequest::createFromEnvironment();
$request = CLIRequestBuilder::createFromEnvironment();

// Default application
$kernel = new AppKernel();
$kernel = new AppKernel(BASE_PATH);
$app = new HTTPApplication($kernel);
$app->addMiddleware(new OutputMiddleware());
$app->handle($request);
$response = $app->handle($request);
$response->output();
13 changes: 13 additions & 0 deletions docs/en/04_Changelogs/4.0.0.md
Expand Up @@ -1248,6 +1248,7 @@ After (`mysite/_config/config.yml`):
#### <a name="overview-general-api"></a>General and Core API Additions / Changes

* Minimum PHP version raised to 5.6 (with support for PHP 7.x)
* Dropped support for PHP safe mode (removed php 5.4).
* Once PHP versions become [unsupported by the PHP Project](http://php.net/supported-versions.php)),
we drop support for those versions in the [next minor release](/contributing/release-process
This means PHP 5.6 and PHP 7.0 support will become unsupported in Dec 2018.
Expand Down Expand Up @@ -1339,6 +1340,18 @@ After (`mysite/_config/config.yml`):

#### <a name="overview-general-removed"></a>General and Core Removed API

* Many global methods have been refactored into `Environment` or `Convert` class.
* `increase_xdebug_nesting_level_to` removed (functionality has been inlined into `AppKernel`)
* `set_increase_time_limit_max` moved to `Environment::setTimeLimitMax()`
* `get_increase_time_limit_max` moved to `Environment::getTimeLimitMax()`
* `set_increase_memory_limit_max` moved to `Environment::setMemoryLimitMax()`
* `get_increase_memory_limit_max` moved to `Environment::getMemoryLimitMax()`
* `increase_time_limit_to` moved to `Environment::increaseTimeLimitTo()`
* `increase_memory_limit_to` moved to `Environment::increaseMemoryLimitTo()`
* `translate_memstring` moved to `Convert::memstring2bytes`.
* `getTempFolder` moved to `TempFolder::getTempFolder()`
* `getTempParentFolder` removed.
* `getTempFolderUsername` removed.
* `CMSMain::buildbrokenlinks()` action is removed.
* `Injector::unregisterAllObjects()` has been removed. Use `unregisterObjects` to unregister
groups of objects limited by type instead.
Expand Down
11 changes: 5 additions & 6 deletions main.php
@@ -1,19 +1,18 @@
<?php

use SilverStripe\Control\HTTPRequestBuilder;
use SilverStripe\Core\AppKernel;
use SilverStripe\Core\HTTPApplication;
use SilverStripe\Core\Startup\ErrorControlChainMiddleware;
use SilverStripe\Core\Startup\OutputMiddleware;
use SilverStripe\Control\HTTPRequest;

require __DIR__ . '/src/includes/autoload.php';

// Build request and detect flush
$request = HTTPRequest::createFromEnvironment();
$request = HTTPRequestBuilder::createFromEnvironment();

// Default application
$kernel = new AppKernel();
$kernel = new AppKernel(BASE_PATH);
$app = new HTTPApplication($kernel);
$app->addMiddleware(new OutputMiddleware());
$app->addMiddleware(new ErrorControlChainMiddleware($app));
$app->handle($request);
$response = $app->handle($request);
$response->output();
69 changes: 69 additions & 0 deletions src/Control/CLIRequestBuilder.php
@@ -0,0 +1,69 @@
<?php

namespace SilverStripe\Control;

/**
* CLI specific request building logic
*/
class CLIRequestBuilder extends HTTPRequestBuilder
{
protected static function cleanEnvironment(array $variables)
{
// Create all blank vars
foreach (['_REQUEST', '_GET', '_POST', '_SESSION', '_SERVER', '_COOKIE', '_ENV', '_FILES'] as $key) {
if (!isset($variables[$key])) {
$variables[$key] = [];
};
}

// We update the $_SERVER variable to contain data consistent with the rest of the application.
$variables['_SERVER'] = array_merge(array(
'SERVER_PROTOCOL' => 'HTTP/1.1',
'HTTP_ACCEPT' => 'text/plain;q=0.5',
'HTTP_ACCEPT_LANGUAGE' => '*;q=0.5',
'HTTP_ACCEPT_ENCODING' => '',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1;q=0.5',
'SERVER_SIGNATURE' => 'Command-line PHP/' . phpversion(),
'SERVER_SOFTWARE' => 'PHP/' . phpversion(),
'SERVER_ADDR' => '127.0.0.1',
'REMOTE_ADDR' => '127.0.0.1',
'REQUEST_METHOD' => 'GET',
'HTTP_USER_AGENT' => 'CLI',
), $variables['_SERVER']);

/**
* Process arguments and load them into the $_GET and $_REQUEST arrays
* For example,
* sake my/url somearg otherarg key=val --otherkey=val third=val&fourth=val
*
* Will result in the following get data:
* args => array('somearg', 'otherarg'),
* key => val
* otherkey => val
* third => val
* fourth => val
*/
if (isset($variables['_SERVER']['argv'][2])) {
$args = array_slice($variables['_SERVER']['argv'], 2);
foreach ($args as $arg) {
if (strpos($arg, '=') == false) {
$variables['_GET']['args'][] = $arg;
} else {
$newItems = array();
parse_str((substr($arg, 0, 2) == '--') ? substr($arg, 2) : $arg, $newItems);
$variables['_GET'] = array_merge($variables['_GET'], $newItems);
}
}
$_REQUEST = array_merge($_REQUEST, $variables['_GET']);
}

// Set 'url' GET parameter
if (isset($variables['_SERVER']['argv'][1])) {
$variables['_GET']['url'] = $variables['_SERVER']['argv'][1];
$variables['_SERVER']['REQUEST_URI'] = $variables['_SERVER']['argv'][1];
}

// Parse rest of variables as standard
return parent::cleanEnvironment($variables);
}
}
40 changes: 13 additions & 27 deletions src/Control/Director.php
Expand Up @@ -4,6 +4,7 @@

use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Kernel;
use SilverStripe\Dev\Deprecation;
Expand Down Expand Up @@ -122,6 +123,14 @@ class Director implements TemplateGlobalProvider
*/
public static function direct(HTTPRequest $request)
{
// check allowed hosts
if (getenv('SS_ALLOWED_HOSTS') && !static::is_cli()) {
$allowedHosts = explode(',', getenv('SS_ALLOWED_HOSTS'));
if (!in_array(static::host(), $allowedHosts)) {
return new HTTPResponse('Invalid Host', 400);
}
}

// Pre-request
$output = RequestProcessor::singleton()->preRequest($request);
if ($output === false) {
Expand Down Expand Up @@ -231,9 +240,9 @@ public static function mockRequest(
};

// backup existing vars, and create new vars
$existingVars = static::envToVars();
$existingVars = Environment::getVariables();
$finally[] = function () use ($existingVars) {
static::varsToEnv($existingVars);
Environment::setVariables($existingVars);
};
$newVars = $existingVars;

Expand Down Expand Up @@ -307,15 +316,15 @@ public static function mockRequest(
$newVars['_REQUEST'] = array_merge($newVars['_GET'], $newVars['_POST']);

// Create new request
$request = HTTPRequest::createFromVariables($newVars, $body);
$request = HTTPRequestBuilder::createFromVariables($newVars, $body);
if ($headers) {
foreach ($headers as $k => $v) {
$request->addHeader($k, $v);
}
}

// Apply new vars to environment
static::varsToEnv($newVars);
Environment::setVariables($newVars);

try {
// Normal request handling
Expand Down Expand Up @@ -385,29 +394,6 @@ protected static function handleRequest(HTTPRequest $request)
return new HTTPResponse('No URL rule was matched', 404);
}

/**
* Extract env vars prior to modification
*
* @return array List of all super globals
*/
public static function envToVars()
{
// Suppress return by-ref
return array_merge($GLOBALS, []);
}

/**
* Restore a backed up or modified list of vars to $globals
*
* @param array $vars
*/
public static function varsToEnv(array $vars)
{
foreach ($vars as $key => $value) {
$GLOBALS[$key] = $value;
}
}

/**
* Return the {@link SiteTree} object that is currently being viewed. If there is no SiteTree
* object to return, then this will return the current controller.
Expand Down

0 comments on commit 12bd31f

Please sign in to comment.