ENHANCEMENT: Updated cli-script handling to be more in line with web calls, and improved Director::setBaseURL() calls.

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@63321 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Sam Minnee 2008-09-29 23:41:50 +00:00
parent 150d41b4c7
commit 2af039785c
5 changed files with 193 additions and 180 deletions

View File

@ -1,11 +1,6 @@
#!/usr/bin/php5
<?php
if(isset($_SERVER['HTTP_HOST'])) {
echo "cli-script.php can't be run from a web request, you have to run it on the command-line.";
die();
}
/**
* File similar to main.php designed for command-line scripts
*
@ -15,6 +10,20 @@ if(isset($_SERVER['HTTP_HOST'])) {
* @subpackage core
*/
/**
* Ensure that people can't access this from a web-server
*/
if(isset($_SERVER['HTTP_HOST'])) {
echo "cli-script.php can't be run from a web request, you have to run it on the command-line.";
die();
}
/**
* Identify the cli-script.php file and change to its container directory, so that require_once() works
*/
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
chdir(dirname($_SERVER['SCRIPT_FILENAME']));
/**
* Process arguments and load them into the $_GET and $_REQUEST arrays
* For example,
@ -41,106 +50,23 @@ if(isset($_SERVER['argv'][2])) {
$_REQUEST = $_GET;
}
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
chdir(dirname($_SERVER['SCRIPT_FILENAME']));
/**
* Include Sapphire's core code
*/
require_once("core/Core.php");
header("Content-type: text/html; charset=\"utf-8\"");
if(function_exists('mb_http_output')) {
mb_http_output('UTF-8');
mb_internal_encoding('UTF-8');
}
// figure out the server configuration
if( preg_match( '/(test\.totallydigital\.co\.nz|dev\.totallydigital\.co\.nz\/test)(.*)/', $_SERVER['SCRIPT_FILENAME'], $nameMatch ) ) {
$_SERVER['SCRIPT_NAME'] = $nameMatch[2];
$_SERVER['HTTP_HOST'] = $nameMatch[1];
$envType = 'test';
} elseif( preg_match( '/dev\.totallydigital\.co\.nz(.*)/', $_SERVER['SCRIPT_FILENAME'], $nameMatch ) ) {
$_SERVER['SCRIPT_NAME'] = $nameMatch[1];
$envType = 'dev';
} elseif( preg_match( '/\/sites\/[^\/]+\/www(.*)/', $_SERVER['SCRIPT_FILENAME'], $nameMatch ) ) {
$_SERVER['SCRIPT_NAME'] = $nameMatch[1];
$envType = 'live';
} elseif( preg_match( '/\/sites\/[^\/]+(.*)/', $_SERVER['SCRIPT_FILENAME'], $nameMatch ) ) {
$_SERVER['SCRIPT_NAME'] = $nameMatch[1];
} elseif(isset($_SERVER['SCRIPT_NAME'])) {
$envType = 'live';
} else {
echo "Error: could not determine server configuration {$_SERVER['SCRIPT_FILENAME']}\n";
exit();
}
// set request method (doesn't allow POST through cli)
$_SERVER['REQUEST_METHOD'] = "GET";
if($_REQUEST && get_magic_quotes_gpc()) {
stripslashes_recursively($_REQUEST);
}
if(isset($_REQUEST['trace'])) apd_set_pprof_trace();
require_once("core/ManifestBuilder.php");
require_once("core/ClassInfo.php");
require_once('core/Object.php');
require_once('core/control/Director.php');
require_once('filesystem/Filesystem.php');
require_once("core/Session.php");
Session::start();
$envFiles = array('../_ss_environment.php', '../../_ss_environment.php', '../../../_ss_environment.php');
foreach($envFiles as $envFile) {
if(file_exists($envFile)) {
include($envFile);
break;
}
}
// Find the URL of this script
if(isset($_FILE_TO_URL_MAPPING)) {
$fullPath = $testPath = $_SERVER['SCRIPT_FILENAME'];
while($testPath && $testPath != "/") {
if(isset($_FILE_TO_URL_MAPPING[$testPath])) {
$url = $_FILE_TO_URL_MAPPING[$testPath] . substr($fullPath,strlen($testPath));
$_SERVER['HTTP_HOST'] = parse_url($url, PHP_URL_HOST);
$_SERVER['SCRIPT_NAME'] = parse_url($url, PHP_URL_PATH);
$_SERVER['REQUEST_PORT'] = parse_url($url, PHP_URL_PORT);
break;
}
$testPath = dirname($testPath);
}
}
if(ManifestBuilder::staleManifest()){
ManifestBuilder::compileManifest();
}
require_once(MANIFEST_FILE);
if(isset($_GET['debugmanifest'])) Debug::show(file_get_contents(MANIFEST_FILE));
//if(!isset(Director::$environment_type) && $envType) Director::set_environment_type($envType);
// Load error handlers
Debug::loadErrorHandlers();
// We don't have a session in cli-script, but this prevents errors
$_SESSION = null;
// Connect to database
require_once("core/model/DB.php");
DB::connect($databaseConfig);
// Get the request URL
// Get the request URL from the querystring arguments
$url = $_SERVER['argv'][1];
$_SERVER['REQUEST_URI'] = "/$url";
$_SERVER['REQUEST_URI'] = BASE_URL . '/' . $url;
// Direct away - this is the "main" function, that hands control to the apporopriate controllerx
// Direct away - this is the "main" function, that hands control to the apporopriate controller
Director::direct($url);
?>

View File

@ -1,11 +1,91 @@
<?php
/**
* This file contains several methods that control the core behaviour of Sapphire.
* This file is the Sapphire bootstrap. It will get your environment ready to call Director::direct().
*
* It takes care of:
* - Including _ss_environment.php
* - Normalisation of $_SERVER values
* - Initialisation of TEMP_FOLDER, BASE_URL, BASE_PATH, and other SilverStripe defines
* - Checking of PHP memory limit
* - Including all the files needed to get the manifest built
* - Building and including the manifest
*
* @todo This file currently contains a lot of bits and pieces, and its various responsibilities should probably be
* moved into different subsystems.
* @todo A lot of this stuff is very order-independent; for example, the require_once calls have to happen after the defines.'
* This could be decoupled.
* @package sapphire
* @subpackage core
*/
///////////////////////////////////////////////////////////////////////////////
// ENVIRONMENT CONFIG
/**
* Include _ss_environment.php files
*/
$envFiles = array('../_ss_environment.php', '../../_ss_environment.php', '../../../_ss_environment.php');
foreach($envFiles as $envFile) {
if(file_exists($envFile)) {
include($envFile);
break;
}
}
///////////////////////////////////////////////////////////////////////////////
// GLOBALS AND DEFINE SETTING
/**
* A blank HTTP_HOST value is used to detect command-line execution.
* We update the $_SERVER variable to contain data consistent with the rest of the application.
*/
if(!isset($_SERVER['HTTP_HOST'])) {
// HTTP_HOST, REQUEST_PORT, SCRIPT_NAME, and PHP_SELF
if(isset($_FILE_TO_URL_MAPPING)) {
$fullPath = $testPath = $_SERVER['SCRIPT_FILENAME'];
while($testPath && $testPath != "/") {
if(isset($_FILE_TO_URL_MAPPING[$testPath])) {
$url = $_FILE_TO_URL_MAPPING[$testPath] . substr($fullPath,strlen($testPath));
$_SERVER['HTTP_HOST'] = parse_url($url, PHP_URL_HOST);
$_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'] = parse_url($url, PHP_URL_PATH);
$_SERVER['REQUEST_PORT'] = parse_url($url, PHP_URL_PORT);
break;
}
$testPath = dirname($testPath);
}
}
// Everything else
$serverDefaults = 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',
);
$_SERVER = array_merge($serverDefaults, $_SERVER);
/**
* If we have an HTTP_HOST value, then we're being called from the webserver and there are some things that
* need checking
*/
} else {
/**
* Fix magic quotes setting
*/
if (get_magic_quotes_gpc()) {
if($_REQUEST) stripslashes_recursively($_REQUEST);
if($_GET) stripslashes_recursively($_GET);
if($_POST) stripslashes_recursively($_POST);
}
}
/**
* Define system paths
*/
@ -38,6 +118,69 @@ define('PR_HIGH',100);
define('PR_MEDIUM',50);
define('PR_LOW',10);
/**
* Ensure we have enough memory
*/
$memString = ini_get("memory_limit");
switch(strtolower(substr($memString, -1))) {
case "k":
$memory = round(substr($memString, 0, -1)*1024);
break;
case "m":
$memory = round(substr($memString, 0, -1)*1024*1024);
break;
case "g":
$memory = round(substr($memString, 0, -1)*1024*1024*1024);
break;
default:
$memory = round($memString);
}
// Check we have at least 32M
if ($memory < (32 * 1024 * 1024)) {
// Increase memory limit
ini_set('memory_limit', '32M');
}
///////////////////////////////////////////////////////////////////////////////
// INCLUDES
require_once("core/ManifestBuilder.php");
require_once("core/ClassInfo.php");
require_once('core/Object.php');
require_once('core/control/Director.php');
require_once('filesystem/Filesystem.php');
require_once("core/Session.php");
///////////////////////////////////////////////////////////////////////////////
// MANIFEST
/**
* Build the manifest
*/
if(ManifestBuilder::staleManifest()){
ManifestBuilder::compileManifest();
}
require_once(MANIFEST_FILE);
/**
* ?debugmanifest=1 hook
*/
if(isset($_GET['debugmanifest'])) Debug::show(file_get_contents(MANIFEST_FILE));
///////////////////////////////////////////////////////////////////////////////
// POST-MANIFEST COMMANDS
/**
* Load error handlers
*/
Debug::loadErrorHandlers();
///////////////////////////////////////////////////////////////////////////////
// HELPER FUNCTIONS
/**
* Returns the temporary folder that sapphire/silverstripe should use for its cache files
* This is loaded into the TEMP_FOLDER define on start up

View File

@ -276,7 +276,8 @@ class Director {
if(substr($url,0,4) != "http") {
if($url[0] != "/") $url = Director::baseURL() . $url;
$url = self::protocolAndHost() . $url;
// Sometimes baseURL() can return a full URL instead of just a path
if(substr($url,0,4) != "http") $url = self::protocolAndHost() . $url;
}
return $url;
@ -289,7 +290,7 @@ class Director {
*/
static function protocolAndHost() {
if(self::$alternateBaseURL) {
if(preg_match('/^(http[^:]*:\/\/[^\/]+)\//', self::$alternateBaseURL, $matches)) {
if(preg_match('/^(http[^:]*:\/\/[^\/]+)(\/|$)/', self::$alternateBaseURL, $matches)) {
return $matches[1];
}
}

View File

@ -35,16 +35,6 @@
* @see Director::direct()
*/
/**
* Include _ss_environment.php file
*/
$envFiles = array('../_ss_environment.php', '../../_ss_environment.php', '../../../_ss_environment.php');
foreach ($envFiles as $envFile) {
if (@file_exists($envFile)) {
include($envFile);
break;
}
}
/**
* Include Sapphire's core code
@ -57,44 +47,6 @@ if (function_exists('mb_http_output')) {
mb_internal_encoding('UTF-8');
}
if (get_magic_quotes_gpc()) {
if($_REQUEST) stripslashes_recursively($_REQUEST);
if($_GET) stripslashes_recursively($_GET);
if($_POST) stripslashes_recursively($_POST);
}
if (isset($_REQUEST['trace'])) {
apd_set_pprof_trace();
}
// Ensure we have enough memory
$memString = ini_get("memory_limit");
switch(strtolower(substr($memString, -1))) {
case "k":
$memory = round(substr($memString, 0, -1)*1024);
break;
case "m":
$memory = round(substr($memString, 0, -1)*1024*1024);
break;
case "g":
$memory = round(substr($memString, 0, -1)*1024*1024*1024);
break;
default:
$memory = round($memString);
}
// Check we have at least 32M
if ($memory < (32 * 1024 * 1024)) {
// Increase memory limit
ini_set('memory_limit', '32M');
}
require_once("core/ClassInfo.php");
require_once('core/Object.php');
require_once('core/control/Director.php');
require_once('filesystem/Filesystem.php');
require_once("core/Session.php");
// If this is a dev site, enable php error reporting
// This is necessary to force developers to acknowledge and fix
// notice level errors (you can override this directive in your _config.php)
@ -104,6 +56,7 @@ if (Director::isDev()) {
Session::start();
// Apache rewrite rules use this
if (isset($_GET['url'])) {
$url = $_GET['url'];
@ -114,23 +67,16 @@ if (isset($_GET['url'])) {
if ($_GET) $_REQUEST = array_merge((array)$_REQUEST, (array)$_GET);
}
require_once("core/ManifestBuilder.php");
if (ManifestBuilder::staleManifest()) {
ManifestBuilder::compileManifest();
// Fix glitches in URL generation
if (substr($url, 0, strlen(BASE_URL)) == BASE_URL) $url = substr($url, strlen(BASE_URL));
if (isset($_GET['debug_profile'])) {
Profiler::init();
Profiler::mark('all_execution');
Profiler::mark('main.php init');
}
require_once(MANIFEST_FILE);
if (isset($_GET['debugmanifest'])) Debug::show(file_get_contents(MANIFEST_FILE));
if (isset($_GET['debug_profile'])) Profiler::init();
if (isset($_GET['debug_profile'])) Profiler::mark('all_execution');
if (isset($_GET['debug_profile'])) Profiler::mark('main.php init');
// Load error handlers
Debug::loadErrorHandlers();
// Connect to database
require_once("core/model/DB.php");
@ -138,12 +84,9 @@ if (isset($_GET['debug_profile'])) Profiler::mark('DB::connect');
DB::connect($databaseConfig);
if (isset($_GET['debug_profile'])) Profiler::unmark('DB::connect');
// Get the request URL
if (substr($url, 0, strlen(BASE_URL)) == BASE_URL) $url = substr($url, strlen(BASE_URL));
if (isset($_GET['debug_profile'])) Profiler::unmark('main.php init');
// Direct away - this is the "main" function, that hands control to the appropriate controller
if (isset($_GET['debug_profile'])) Profiler::unmark('main.php init');
Director::direct($url);
if (isset($_GET['debug_profile'])) {

View File

@ -26,25 +26,25 @@ class DirectorTest extends SapphireTest {
unlink($tempFilePath);
}
/*
public function testAlternativeBaseURL() {
// relative base URLs
Director::setBaseURL('/relativebase');
$this->assertEquals(Director::baseURL(), '/relativebase');
$this->assertEquals(Director::absoluteBaseURL(), BASE_URL . '/relativebase');
$this->assertEquals(Director::absoluteURL('subfolder'), $origBaseURL . '/relativebase/subfolder');
// absolute base URLs
Director::setBaseURL('http://www.example.org');
$this->assertEquals(Director::baseURL(), 'http://www.example.org');
$this->assertEquals(Director::absoluteBaseURL(), 'http://www.example.org');
$this->assertEquals(Director::absoluteURL('subfolder'), 'http://www.example.org/subfolder');
// relative base URLs - you should end them in a /
Director::setBaseURL('/relativebase/');
$this->assertEquals('/relativebase/', Director::baseURL());
$this->assertEquals(Director::protocolAndHost() . '/relativebase/', Director::absoluteBaseURL());
$this->assertEquals(Director::protocolAndHost() . '/relativebase/subfolder/test', Director::absoluteURL('subfolder/test'));
// absolute base URLs - you should end them in a /
Director::setBaseURL('http://www.example.org/');
$this->assertEquals('http://www.example.org/', Director::baseURL());
$this->assertEquals('http://www.example.org/', Director::absoluteBaseURL());
$this->assertEquals('http://www.example.org/subfolder/test', Director::absoluteURL('subfolder/test'));
// Setting it to false restores functionality
Director::setBaseURL(false);
$this->assertEquals(Director::baseURL(), BASE_URL);
$this->assertEquals(Director::absoluteBaseURL(BASE_URL), BASE_URL);
$this->assertEquals(Director::absoluteURL('subfolder'), BASE_URL . '/subfolder');
$this->assertEquals(BASE_URL.'/', Director::baseURL());
$this->assertEquals(Director::protocolAndHost().BASE_URL.'/', Director::absoluteBaseURL(BASE_URL));
$this->assertEquals(Director::protocolAndHost().BASE_URL . '/subfolder/test', Director::absoluteURL('subfolder/test'));
}
*/
}
?>