Ejemplo n.º 1
0
 public function __construct()
 {
     $this->session = Injector::inst()->create('Session', array());
     $this->controller = new Controller();
     $this->controller->setSession($this->session);
     $this->controller->pushCurrent();
 }
 public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
 {
     // Bootstrap session so that Session::get() accesses the right instance
     $dummyController = new Controller();
     $dummyController->setSession($session);
     $dummyController->setRequest($request);
     $dummyController->pushCurrent();
     // Block non-authenticated users from setting the stage mode
     if (!Versioned::can_choose_site_stage($request)) {
         $permissionMessage = sprintf(_t("ContentController.DRAFT_SITE_ACCESS_RESTRICTION", 'You must log in with your CMS password in order to view the draft or archived content. ' . '<a href="%s">Click here to go back to the published site.</a>'), Controller::join_links(Director::baseURL(), $request->getURL(), "?stage=Live"));
         // Force output since RequestFilter::preRequest doesn't support response overriding
         $response = Security::permissionFailure($dummyController, $permissionMessage);
         $session->inst_save();
         $dummyController->popCurrent();
         // Prevent output in testing
         if (class_exists('SapphireTest', false) && SapphireTest::is_running_test()) {
             throw new SS_HTTPResponse_Exception($response);
         }
         $response->output();
         die;
     }
     Versioned::choose_site_stage();
     $dummyController->popCurrent();
     return true;
 }
 public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model)
 {
     $headerName = Config::inst()->get('ApiKeyRequestFilter', 'header_name');
     if ($key = $request->getHeader($headerName)) {
         try {
             $matchingKey = MemberApiKey::findByKey($key);
         } catch (LogicException $e) {
         }
         if ($matchingKey) {
             // Log-in can't have session injected, we need to to push $session into the global state
             $controller = new Controller();
             $controller->setSession($session);
             $controller->pushCurrent();
             $matchingKey->Member()->logIn();
             // Undo our global state manipulation
             $controller->popCurrent();
             $matchingKey->markUsed();
         } else {
             throw new SS_HTTPResponse_Exception("Bad X-API-Key", 400);
         }
     }
     return true;
 }
Ejemplo n.º 4
0
 /**
  * Push a controller onto the stack to mock a particular request
  *
  * @param Controller $controller
  * @param callback $callback
  */
 public function withController(Controller $controller, $callback)
 {
     $controller->pushCurrent();
     try {
         // Ensure failed test don't break state
         $callback($this);
     } catch (Exception $ex) {
     }
     $controller->popCurrent();
     if (!empty($ex)) {
         throw $ex;
     }
 }
Ejemplo n.º 5
0
    public function install($config)
    {
        ?>
		<html>
		<head>
			<meta charset="utf-8"/>
			<title>Installing SilverStripe...</title>
			<link rel="stylesheet" type="text/css" href="<?php 
        echo FRAMEWORK_NAME;
        ?>
/dev/install/css/install.css"/>
			<script src="<?php 
        echo FRAMEWORK_NAME;
        ?>
/thirdparty/jquery/jquery.js"></script>
		</head>
		<body>
		<div class="install-header">
			<div class="inner">
				<div class="brand">
					<span class="logo"></span>

					<h1>SilverStripe</h1>
				</div>
			</div>
		</div>

		<div id="Navigation">&nbsp;</div>
		<div class="clear"><!-- --></div>

		<div class="main">
			<div class="inner">
				<h2>Installing SilverStripe...</h2>

				<p>I am now running through the installation steps (this should take about 30 seconds)</p>

				<p>If you receive a fatal error, refresh this page to continue the installation</p>
				<ul>
<?php 
        $webserver = $this->findWebserver();
        $isIIS = $this->isIIS();
        $isApache = $this->isApache();
        flush();
        if (isset($config['stats'])) {
            if (file_exists(FRAMEWORK_NAME . '/silverstripe_version')) {
                $silverstripe_version = file_get_contents(FRAMEWORK_NAME . '/silverstripe_version');
            } else {
                $silverstripe_version = "unknown";
            }
            $phpVersion = urlencode(phpversion());
            $encWebserver = urlencode($webserver);
            $dbType = $config['db']['type'];
            // Try to determine the database version from the helper
            $databaseVersion = $config['db']['type'];
            $helper = $this->getDatabaseConfigurationHelper($dbType);
            if ($helper && method_exists($helper, 'getDatabaseVersion')) {
                $versionConfig = $config['db'][$dbType];
                $versionConfig['type'] = $dbType;
                $databaseVersion = urlencode($dbType . ': ' . $helper->getDatabaseVersion($versionConfig));
            }
            $url = "http://ss2stat.silverstripe.com/Installation/add?SilverStripe={$silverstripe_version}&PHP={$phpVersion}&Database={$databaseVersion}&WebServer={$encWebserver}";
            if (isset($_SESSION['StatsID']) && $_SESSION['StatsID']) {
                $url .= '&ID=' . $_SESSION['StatsID'];
            }
            @($_SESSION['StatsID'] = file_get_contents($url));
        }
        if (file_exists('mysite/_config.php')) {
            // Truncate the contents of _config instead of deleting it - we can't re-create it because Windows handles permissions slightly
            // differently to UNIX based filesystems - it takes the permissions from the parent directory instead of retaining them
            $fh = fopen('mysite/_config.php', 'wb');
            fclose($fh);
        }
        // Escape user input for safe insertion into PHP file
        $theme = isset($_POST['template']) ? addcslashes($_POST['template'], "\\'") : 'simple';
        $locale = isset($_POST['locale']) ? addcslashes($_POST['locale'], "\\'") : 'en_US';
        $type = addcslashes($config['db']['type'], "\\'");
        $dbConfig = $config['db'][$type];
        $dbConfig = array_map(create_function('$v', 'return addcslashes($v, "\\\'");'), $dbConfig);
        if (!isset($dbConfig['path'])) {
            $dbConfig['path'] = '';
        }
        if (!$dbConfig) {
            echo "<p style=\"color: red\">Bad config submitted</p><pre>";
            print_r($config);
            echo "</pre>";
            die;
        }
        // Write the config file
        global $usingEnv;
        if ($usingEnv) {
            $this->statusMessage("Setting up 'mysite/_config.php' for use with _ss_environment.php...");
            $this->writeToFile("mysite/_config.php", <<<PHP
<?php

global \$project;
\$project = 'mysite';

global \$database;
\$database = '{$dbConfig['database']}';

require_once('conf/ConfigureFromEnv.php');

// Set the site locale
i18n::set_locale('{$locale}');

PHP
);
        } else {
            $this->statusMessage("Setting up 'mysite/_config.php'...");
            // Create databaseConfig
            $lines = array($lines[] = "\t'type' => '{$type}'");
            foreach ($dbConfig as $key => $value) {
                $lines[] = "\t'{$key}' => '{$value}'";
            }
            $databaseConfigContent = implode(",\n", $lines);
            $this->writeToFile("mysite/_config.php", <<<PHP
<?php

global \$project;
\$project = 'mysite';

global \$databaseConfig;
\$databaseConfig = array(
{$databaseConfigContent}
);

// Set the site locale
i18n::set_locale('{$locale}');

PHP
);
        }
        $this->statusMessage("Setting up 'mysite/_config/config.yml'");
        $this->writeToFile("mysite/_config/config.yml", <<<YML
---
Name: mysite
After:
  - 'framework/*'
  - 'cms/*'
---
# YAML configuration for SilverStripe
# See http://doc.silverstripe.org/framework/en/topics/configuration
# Caution: Indentation through two spaces, not tabs
SSViewer:
  theme: '{$theme}'
YML
);
        if (!$this->checkModuleExists('cms')) {
            $this->writeToFile("mysite/code/RootURLController.php", <<<PHP
<?php

class RootURLController extends Controller {

\tpublic function index() {
\t\techo "<html>Your site is now set up. Start adding controllers to mysite to get started.</html>";
\t}

}
PHP
);
        }
        // Write the appropriate web server configuration file for rewriting support
        if ($this->hasRewritingCapability()) {
            if ($isApache) {
                $this->statusMessage("Setting up '.htaccess' file...");
                $this->createHtaccess();
            } elseif ($isIIS) {
                $this->statusMessage("Setting up 'web.config' file...");
                $this->createWebConfig();
            }
        }
        // Load the SilverStripe runtime
        $_SERVER['SCRIPT_FILENAME'] = dirname(realpath($_SERVER['SCRIPT_FILENAME'])) . '/' . FRAMEWORK_NAME . '/main.php';
        chdir(FRAMEWORK_NAME);
        // Rebuild the manifest
        $_GET['flush'] = true;
        // Show errors as if you're in development mode
        $_SESSION['isDev'] = 1;
        $this->statusMessage("Building database schema...");
        require_once 'core/Core.php';
        // Build database
        $con = new Controller();
        $con->pushCurrent();
        global $databaseConfig;
        DB::connect($databaseConfig);
        $dbAdmin = new DatabaseAdmin();
        $dbAdmin->init();
        $dbAdmin->doBuild(true);
        // Create default administrator user and group in database
        // (not using Security::setDefaultAdmin())
        $adminMember = Security::findAnAdministrator();
        $adminMember->Email = $config['admin']['username'];
        $adminMember->Password = $config['admin']['password'];
        $adminMember->PasswordEncryption = Security::config()->encryption_algorithm;
        try {
            $this->statusMessage('Creating default CMS admin account...');
            $adminMember->write();
        } catch (Exception $e) {
            $this->statusMessage(sprintf('Warning: Default CMS admin account could not be created (error: %s)', $e->getMessage()));
        }
        // Syncing filesystem (so /assets/Uploads is available instantly, see ticket #2266)
        // show a warning if there was a problem doing so
        try {
            $this->statusMessage('Creating initial filesystem assets...');
            Filesystem::sync();
        } catch (Exception $e) {
            $this->statusMessage(sprintf('Warning: Creating initial filesystem assets failed (error: %s)', $e->getMessage()));
        }
        $_SESSION['username'] = $config['admin']['username'];
        $_SESSION['password'] = $config['admin']['password'];
        if (!$this->errors) {
            if (isset($_SERVER['HTTP_HOST']) && $this->hasRewritingCapability()) {
                $this->statusMessage("Checking that friendly URLs work...");
                $this->checkRewrite();
            } else {
                require_once 'core/startup/ParameterConfirmationToken.php';
                $token = new ParameterConfirmationToken('flush');
                $params = http_build_query($token->params());
                $destinationURL = 'index.php/' . ($this->checkModuleExists('cms') ? "home/successfullyinstalled?{$params}" : "?{$params}");
                echo <<<HTML
\t\t\t\t<li>SilverStripe successfully installed; I am now redirecting you to your SilverStripe site...</li>
\t\t\t\t<script>
\t\t\t\t\tsetTimeout(function() {
\t\t\t\t\t\twindow.location = "{$destinationURL}";
\t\t\t\t\t}, 2000);
\t\t\t\t</script>
\t\t\t\t<noscript>
\t\t\t\t<li><a href="{$destinationURL}">Click here to access your site.</a></li>
\t\t\t\t</noscript>
HTML;
            }
        }
        return $this->errors;
    }
Ejemplo n.º 6
0
	function install($config) {
		if(isset($_SERVER['HTTP_HOST'])) {
			?>
<html>
	<head>
		<title>PHP 5 is required</title>
		<link rel="stylesheet" type="text/css" href="themes/blackcandy/css/layout.css" />
		<link rel="stylesheet" type="text/css" href="themes/blackcandy/css/typography.css" />
		<link rel="stylesheet" type="text/css" href="themes/blackcandy/css/form.css" />
		<link rel="stylesheet" type="text/css" href="sapphire/dev/install/install.css" />
		<script src="jsparty/jquery/jquery.js"></script>
	</head>
	<body>
		<div id="BgContainer">
			<div id="Container">
				<div id="Header">
					<h1>SilverStripe CMS Installation</h1>
				</div>

				<div id="Navigation">&nbsp;</div>
				<div class="clear"><!-- --></div>

				<div id="Layout">
					<div class="typography">
						<h1>Installing SilverStripe...</h1>
						<p>I am now running through the installation steps (this should take about 30 seconds)</p>
						<p>If you receive a fatal error, refresh this page to continue the installation</p>
						<ul>
<?php
		} else {
			echo "SILVERSTRIPE COMMAND-LINE INSTALLATION\n\n";
		}
		
		flush();
		
		if(isset($_POST['stats'])) {
			if(file_exists('sapphire/silverstripe_version')) {
				$sapphireVersionFile = file_get_contents('sapphire/silverstripe_version');
				if(strstr($sapphireVersionFile, "/sapphire/trunk")) {
					$silverstripe_version = "trunk";
				} else {
					preg_match("/sapphire\/(?:(?:branches)|(?:tags))(?:\/rc)?\/([A-Za-z0-9._-]+)\/silverstripe_version/", $sapphireVersionFile, $matches);
					$silverstripe_version = $matches[1];
				}
			} else {
				$silverstripe_version = "unknown";
			}
			
			$phpVersion = urlencode(phpversion());
			$conn = @mysql_connect($config['mysql']['server'], null, null);
			$databaseVersion = urlencode('MySQL ' . mysql_get_server_info());
			$webserver = urlencode($_SERVER['SERVER_SOFTWARE']);
			
			$url = "http://ss2stat.silverstripe.com/Installation/add?SilverStripe=$silverstripe_version&PHP=$phpVersion&Database=$databaseVersion&WebServer=$webserver";
			
			if(isset($_SESSION['StatsID']) && $_SESSION['StatsID']) {
				$url .= '&ID=' . $_SESSION['StatsID'];
			}
			
			@$_SESSION['StatsID'] = file_get_contents($url);
		}
		
		if(file_exists('mysite/_config.php')) {
			unlink('mysite/_config.php');
		}
		$theme = isset($_POST['template']) ? $_POST['template'] : 'blackcandy';
		// Write the config file
		global $usingEnv;
		if($usingEnv) {
			$this->statusMessage("Creating 'mysite/_config.php' for use with _ss_environment.php...");
			$this->createFile("mysite/_config.php", <<<PHP
<?php

global \$project;
\$project = 'mysite';

global \$database;
\$database = "{$config['mysql']['database']}";

require_once("conf/ConfigureFromEnv.php");

// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.com/themes/
SSViewer::set_theme('$theme');

?>
PHP
			);

			
		} else {
			$this->statusMessage("Creating 'mysite/_config.php'...");
		
			$devServers = $this->var_export_array_nokeys(explode("\n", $_POST['devsites']));
		
			$escapedPassword = addslashes($config['mysql']['password']);
			$this->createFile("mysite/_config.php", <<<PHP
<?php

global \$project;
\$project = 'mysite';

global \$databaseConfig;
\$databaseConfig = array(
	"type" => "$config[database]",
	"server" => "{$config['mysql']['server']}", 
	"username" => "{$config['mysql']['username']}", 
	"password" => "{$escapedPassword}", 
	"database" => "{$config['mysql']['database']}",
);

// Sites running on the following servers will be
// run in development mode. See
// http://doc.silverstripe.com/doku.php?id=devmode
// for a description of what dev mode does.
Director::set_dev_servers($devServers);

// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.com/themes/
SSViewer::set_theme('$theme');

?>
PHP
			);
		}

		$this->statusMessage("Creating '.htaccess' file...");
		
		$this->createHtaccess();

		// Load the sapphire runtime
		$_SERVER['SCRIPT_FILENAME'] = dirname(realpath($_SERVER['SCRIPT_FILENAME'])) . '/sapphire/main.php';
		chdir('sapphire');

		// Rebuild the manifest
		$_GET['flush'] = true;
		// Show errors as if you're in development mode
		$_SESSION['isDev'] = 1;

		require_once('core/Core.php');
	
		$this->statusMessage("Building database schema...");

		// Build database
		$con = new Controller();
		$con->pushCurrent();

		global $databaseConfig;
		DB::connect($databaseConfig);
		
		$dbAdmin = new DatabaseAdmin();
		$dbAdmin->init();
		
		$_REQUEST['username'] = $config['admin']['username'];
		$_REQUEST['password'] = $config['admin']['password'];
		$dbAdmin->doBuild(true);
		
		$adminmember = DataObject::get_one('Member',"`Email`= '".$_REQUEST['admin']['username']."'");
		if($adminmember) {
			$adminmember->FirstName = $_REQUEST['admin']['firstname'];
			$adminmember->Surname = $_REQUEST['admin']['surname'];
			$adminmember->write();
		}
		
		// Syncing filesystem (so /assets/Uploads is available instantly, see ticket #2266)
		FileSystem::sync();

		$_SESSION['username'] = $config['admin']['username'];
		$_SESSION['password'] = $config['admin']['password'];
		
		if(!$this->errors) {
			if(isset($_SERVER['HTTP_HOST'])) {
				$this->statusMessage("Checking that friendly URLs work...");
				$this->checkModRewrite();
			} else {
				echo "\n\nSilverStripe successfully installed\n";
			}
		}
		
		return $this->errors;
	}
    function install($config)
    {
        if (isset($_SERVER['HTTP_HOST'])) {
            ?>
<html>
	<head>
		<title>Installing SilverStripe...</title>
		<link rel="stylesheet" type="text/css" href="themes/blackcandy/css/layout.css" />
		<link rel="stylesheet" type="text/css" href="themes/blackcandy/css/typography.css" />
		<link rel="stylesheet" type="text/css" href="themes/blackcandy/css/form.css" />
		<link rel="stylesheet" type="text/css" href="sapphire/dev/install/install.css" />
		<script src="sapphire/thirdparty/jquery/jquery.js"></script>
	</head>
	<body>
		<div id="BgContainer">
			<div id="Container">
				<div id="Header">
					<h1>SilverStripe CMS Installation</h1>
				</div>

				<div id="Navigation">&nbsp;</div>
				<div class="clear"><!-- --></div>

				<div id="Layout">
					<div class="typography">
						<h1>Installing SilverStripe...</h1>
						<p>I am now running through the installation steps (this should take about 30 seconds)</p>
						<p>If you receive a fatal error, refresh this page to continue the installation</p>
						<ul>
<?php 
        } else {
            echo "SILVERSTRIPE COMMAND-LINE INSTALLATION\n\n";
        }
        $webserver = $this->findWebserver();
        $isIIS = $this->isIIS();
        $isApache = $this->isApache();
        flush();
        if (isset($config['stats'])) {
            if (file_exists('sapphire/silverstripe_version')) {
                $sapphireVersionFile = file_get_contents('sapphire/silverstripe_version');
                if (strstr($sapphireVersionFile, "/sapphire/trunk")) {
                    $silverstripe_version = "trunk";
                } else {
                    preg_match("/sapphire\\/(?:(?:branches)|(?:tags))(?:\\/rc)?\\/([A-Za-z0-9._-]+)\\/silverstripe_version/", $sapphireVersionFile, $matches);
                    $silverstripe_version = $matches[1];
                }
            } else {
                $silverstripe_version = "unknown";
            }
            $phpVersion = urlencode(phpversion());
            $encWebserver = urlencode($webserver);
            $dbType = $config['db']['type'];
            // Try to determine the database version from the helper
            $databaseVersion = $config['db']['type'];
            $helper = $this->getDatabaseConfigurationHelper($dbType);
            if ($helper && method_exists($helper, 'getDatabaseVersion')) {
                $databaseVersion = urlencode($dbType . ': ' . $helper->getDatabaseVersion($config['db'][$dbType]));
            }
            $url = "http://ss2stat.silverstripe.com/Installation/add?SilverStripe={$silverstripe_version}&PHP={$phpVersion}&Database={$databaseVersion}&WebServer={$encWebserver}";
            if (isset($_SESSION['StatsID']) && $_SESSION['StatsID']) {
                $url .= '&ID=' . $_SESSION['StatsID'];
            }
            @($_SESSION['StatsID'] = file_get_contents($url));
        }
        if (file_exists('mysite/_config.php')) {
            // Truncate the contents of _config instead of deleting it - we can't re-create it because Windows handles permissions slightly
            // differently to UNIX based filesystems - it takes the permissions from the parent directory instead of retaining them
            $fh = fopen('mysite/_config.php', 'wb');
            fclose($fh);
        }
        $theme = isset($_POST['template']) ? $_POST['template'] : 'blackcandy';
        $locale = isset($_POST['locale']) ? $_POST['locale'] : 'en_US';
        $type = $config['db']['type'];
        $dbConfig = $config['db'][$type];
        if (!$dbConfig) {
            echo "<p style=\"color: red\">Bad config submitted</p><pre>";
            print_r($config);
            echo "</pre>";
            die;
        }
        // Write the config file
        global $usingEnv;
        if ($usingEnv) {
            $this->statusMessage("Setting up 'mysite/_config.php' for use with _ss_environment.php...");
            $this->writeToFile("mysite/_config.php", <<<PHP
<?php

global \$project;
\$project = 'mysite';

global \$database;
\$database = '{$dbConfig['database']}';

require_once('conf/ConfigureFromEnv.php');

MySQLDatabase::set_connection_charset('utf8');

// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.org/themes/
SSViewer::set_theme('{$theme}');

// Set the site locale
i18n::set_locale('{$locale}');

// enable nested URLs for this site (e.g. page/sub-page/)
SiteTree::enable_nested_urls();
PHP
);
        } else {
            $this->statusMessage("Setting up 'mysite/_config.php'...");
            $escapedPassword = addslashes($dbConfig['password']);
            $this->writeToFile("mysite/_config.php", <<<PHP
<?php

global \$project;
\$project = 'mysite';

global \$databaseConfig;
\$databaseConfig = array(
\t"type" => '{$type}',
\t"server" => '{$dbConfig['server']}', 
\t"username" => '{$dbConfig['username']}', 
\t"password" => '{$escapedPassword}', 
\t"database" => '{$dbConfig['database']}',
\t"path" => '{$dbConfig['path']}',
);

// Sites running on the following servers will be
// run in development mode. See
// http://doc.silverstripe.org/doku.php?id=configuration
// for a description of what dev mode does.
Director::set_dev_servers(array(
\t'localhost',
\t'127.0.0.1'
));

MySQLDatabase::set_connection_charset('utf8');

// This line set's the current theme. More themes can be
// downloaded from http://www.silverstripe.org/themes/
SSViewer::set_theme('{$theme}');

// Set the site locale
i18n::set_locale('{$locale}');

// enable nested URLs for this site (e.g. page/sub-page/)
SiteTree::enable_nested_urls();
PHP
);
        }
        // Write the appropriate web server configuration file for rewriting support
        if ($this->hasRewritingCapability()) {
            if ($isApache) {
                $this->statusMessage("Setting up '.htaccess' file...");
                $this->createHtaccess();
            } elseif ($isIIS) {
                $this->statusMessage("Setting up 'web.config' file...");
                $this->createWebConfig();
            }
        }
        // Load the sapphire runtime
        $_SERVER['SCRIPT_FILENAME'] = dirname(realpath($_SERVER['SCRIPT_FILENAME'])) . '/sapphire/main.php';
        chdir('sapphire');
        // Rebuild the manifest
        $_GET['flush'] = true;
        // Show errors as if you're in development mode
        $_SESSION['isDev'] = 1;
        require_once 'core/Core.php';
        $this->statusMessage("Building database schema...");
        // Build database
        $con = new Controller();
        $con->pushCurrent();
        global $databaseConfig;
        DB::connect($databaseConfig);
        $dbAdmin = new DatabaseAdmin();
        $dbAdmin->init();
        $dbAdmin->doBuild(true);
        // Create default administrator user and group in database
        // (not using Security::setDefaultAdmin())
        $adminMember = Security::findAnAdministrator();
        $adminMember->Email = $config['admin']['username'];
        $adminMember->Password = $config['admin']['password'];
        $adminMember->PasswordEncryption = Security::get_password_encryption_algorithm();
        // @todo Exception thrown if database with admin already exists with same Email
        try {
            $adminMember->write();
        } catch (Exception $e) {
        }
        // Syncing filesystem (so /assets/Uploads is available instantly, see ticket #2266)
        Filesystem::sync();
        $_SESSION['username'] = $config['admin']['username'];
        $_SESSION['password'] = $config['admin']['password'];
        if (!$this->errors) {
            if (isset($_SERVER['HTTP_HOST']) && $this->hasRewritingCapability()) {
                $this->statusMessage("Checking that friendly URLs work...");
                $this->checkRewrite();
            } else {
                echo <<<HTML
\t\t\t\t<li>SilverStripe successfully installed; I am now redirecting you to your SilverStripe site...</li>
\t\t\t\t<script>
\t\t\t\t\tsetTimeout(function() {
\t\t\t\t\t\twindow.location = "index.php/home/successfullyinstalled?flush=1";
\t\t\t\t\t}, 2000);
\t\t\t\t</script>
\t\t\t\t<noscript>
\t\t\t\t<li><a href="index.php/home/successfullyinstalled?flush=1">Click here to access your site.</li>
\t\t\t\t</noscript>
HTML;
            }
        }
        return $this->errors;
    }
Ejemplo n.º 8
0
	function install($config) {
?>
<html>
	<head>
		<title>Installing SilverStripe...</title>
		<link rel="stylesheet" type="text/css" href="<?php echo FRAMEWORK_NAME; ?>/dev/install/css/install.css" />
		<script src="<?php echo FRAMEWORK_NAME; ?>/thirdparty/jquery/jquery.js"></script>
	</head>
	<body>
		<div class="install-header">
			<div class="inner">
				<div class="brand">
					<span class="logo"></span>
					<h1>SilverStripe</h1>
				</div>
			</div>	
		</div>

		<div id="Navigation">&nbsp;</div>
		<div class="clear"><!-- --></div>

		<div class="main">
			<div class="inner">
				<h2>Installing SilverStripe...</h2>
				<p>I am now running through the installation steps (this should take about 30 seconds)</p>
				<p>If you receive a fatal error, refresh this page to continue the installation</p>
				<ul>
<?php

		$webserver = $this->findWebserver();
		$isIIS = $this->isIIS();
		$isApache = $this->isApache();

		flush();

		if(isset($config['stats'])) {
			if(file_exists(FRAMEWORK_NAME . '/silverstripe_version')) {
				$silverstripe_version = file_get_contents(FRAMEWORK_NAME . '/silverstripe_version');
			} else {
				$silverstripe_version = "unknown";
			}

			$phpVersion = urlencode(phpversion());
			$encWebserver = urlencode($webserver);
			$dbType = $config['db']['type'];

			// Try to determine the database version from the helper
			$databaseVersion = $config['db']['type'];
			$helper = $this->getDatabaseConfigurationHelper($dbType);
			if($helper && method_exists($helper, 'getDatabaseVersion')) {
				$databaseVersion = urlencode($dbType . ': ' . $helper->getDatabaseVersion($config['db'][$dbType]));
			}

			$url = "http://ss2stat.silverstripe.com/Installation/add?SilverStripe=$silverstripe_version&PHP=$phpVersion&Database=$databaseVersion&WebServer=$encWebserver";

			if(isset($_SESSION['StatsID']) && $_SESSION['StatsID']) {
				$url .= '&ID=' . $_SESSION['StatsID'];
			}

			@$_SESSION['StatsID'] = file_get_contents($url);
		}

		if(file_exists('mysite/_config.php')) {
			// Truncate the contents of _config instead of deleting it - we can't re-create it because Windows handles permissions slightly
			// differently to UNIX based filesystems - it takes the permissions from the parent directory instead of retaining them
			$fh = fopen('mysite/_config.php', 'wb');
			fclose($fh);
		}
		$theme = isset($_POST['template']) ? $_POST['template'] : 'simple';
		$locale = isset($_POST['locale']) ? $_POST['locale'] : 'en_US';
		$type = $config['db']['type'];
		$dbConfig = $config['db'][$type];
		if(!isset($dbConfig['path'])) $dbConfig['path'] = '';
		if(!$dbConfig) {
			echo "<p style=\"color: red\">Bad config submitted</p><pre>";
			print_r($config);
			echo "</pre>";
			die();
		}

		// Write the config file
		global $usingEnv;
		if($usingEnv) {

			$this->statusMessage("Setting up 'mysite/_config.php' for use with _ss_environment.php...");
			$this->writeToFile("mysite/_config.php", <<<PHP
<?php

global \$project;
\$project = 'mysite';

global \$database;
\$database = '{$dbConfig['database']}';

require_once('conf/ConfigureFromEnv.php');

MySQLDatabase::set_connection_charset('utf8');

// Set the current theme. More themes can be downloaded from
// http://www.silverstripe.org/themes/
SSViewer::set_theme('$theme');

// Set the site locale
i18n::set_locale('$locale');

// Enable nested URLs for this site (e.g. page/sub-page/)
if (class_exists('SiteTree')) SiteTree::enable_nested_urls();
PHP
			);

		} else {
			$this->statusMessage("Setting up 'mysite/_config.php'...");
			$escapedPassword = addslashes($dbConfig['password']);
			$this->writeToFile("mysite/_config.php", <<<PHP
<?php

global \$project;
\$project = 'mysite';

global \$databaseConfig;
\$databaseConfig = array(
	"type" => '{$type}',
	"server" => '{$dbConfig['server']}',
	"username" => '{$dbConfig['username']}',
	"password" => '{$escapedPassword}',
	"database" => '{$dbConfig['database']}',
	"path" => '{$dbConfig['path']}',
);

MySQLDatabase::set_connection_charset('utf8');

// Set the current theme. More themes can be downloaded from
// http://www.silverstripe.org/themes/
SSViewer::set_theme('$theme');

// Set the site locale
i18n::set_locale('$locale');

// Enable nested URLs for this site (e.g. page/sub-page/)
if (class_exists('SiteTree')) SiteTree::enable_nested_urls();
PHP
			);
		}

		if (!$this->checkModuleExists('cms')) {
			$this->writeToFile("mysite/code/RootURLController.php", <<<PHP
<?php

class RootURLController extends Controller {

	function index() {
		echo "<html>Your site is now set up. Start adding controllers to mysite to get started.</html>";
	}

}
PHP
			);
		}

		// Write the appropriate web server configuration file for rewriting support
		if($this->hasRewritingCapability()) {
			if($isApache) {
				$this->statusMessage("Setting up '.htaccess' file...");
				$this->createHtaccess();
			} elseif($isIIS) {
				$this->statusMessage("Setting up 'web.config' file...");
				$this->createWebConfig();
			}
		}

		// Load the SilverStripe runtime
		$_SERVER['SCRIPT_FILENAME'] = dirname(realpath($_SERVER['SCRIPT_FILENAME'])) . '/' . FRAMEWORK_NAME . '/main.php';
		chdir(FRAMEWORK_NAME);

		// Rebuild the manifest
		$_GET['flush'] = true;
		// Show errors as if you're in development mode
		$_SESSION['isDev'] = 1;

		$this->statusMessage("Building database schema...");

		require_once 'core/Core.php';

		// Build database
		$con = new Controller();
		$con->pushCurrent();

		global $databaseConfig;
		DB::connect($databaseConfig);

		$dbAdmin = new DatabaseAdmin();
		$dbAdmin->init();

		$dbAdmin->doBuild(true);

		// Create default administrator user and group in database
		// (not using Security::setDefaultAdmin())
		$adminMember = Security::findAnAdministrator();
		$adminMember->Email = $config['admin']['username'];
		$adminMember->Password = $config['admin']['password'];
		$adminMember->PasswordEncryption = Security::get_password_encryption_algorithm();

		try {
			$this->statusMessage('Creating default CMS admin account...');
			$adminMember->write();
		} catch(Exception $e) {
			$this->statusMessage(
				sprintf('Warning: Default CMS admin account could not be created (error: %s)', $e->getMessage())
			);
		}

		// Syncing filesystem (so /assets/Uploads is available instantly, see ticket #2266)
		// show a warning if there was a problem doing so
		try {
			$this->statusMessage('Creating initial filesystem assets...');
			Filesystem::sync();
		} catch(Exception $e) {
			$this->statusMessage(
				sprintf('Warning: Creating initial filesystem assets failed (error: %s)', $e->getMessage())
			);
		}

		$_SESSION['username'] = $config['admin']['username'];
		$_SESSION['password'] = $config['admin']['password'];

		if(!$this->errors) {
			if(isset($_SERVER['HTTP_HOST']) && $this->hasRewritingCapability()) {
				$this->statusMessage("Checking that friendly URLs work...");
				$this->checkRewrite();
			} else {
				$destinationURL = 'index.php/' .
					($this->checkModuleExists('cms') ? 'home/successfullyinstalled?flush=1' : '?flush=1');

				echo <<<HTML
				<li>SilverStripe successfully installed; I am now redirecting you to your SilverStripe site...</li>
				<script>
					setTimeout(function() {
						window.location = "$destinationURL";
					}, 2000);
				</script>
				<noscript>
				<li><a href="$destinationURL">Click here to access your site.</li>
				</noscript>
HTML;
			}
		}

		return $this->errors;
	}
 function testPullRegionWithRenderContext()
 {
     // this is a dirty dirty mess. sorry.
     $req = new SS_HTTPRequest('GET', '/test1');
     $req->addHeader(AjaxHTTPResponse::PULL_HEADER, 'TestProductGroupItem:BUYABLE');
     $req->addHeader('X-Requested-With', 'XMLHttpRequest');
     $ctrl = new Controller();
     $ctrl->pushCurrent();
     $ctrl->setRequest($req);
     $ctrl->setDataModel(DataModel::inst());
     $ctrl->setURLParams(array());
     $ctrl->init();
     $response = $ctrl->getAjaxResponse();
     $response->addRenderContext('BUYABLE', new ArrayData(array('Title' => 'Test Product', 'Link' => '/test-product', 'Price' => 29.99)));
     $data = json_decode($response->getBody(), true);
     $ctrl->popCurrent();
     $this->assertNotEmpty($data[AjaxHTTPResponse::REGIONS_KEY]['TestProductGroupItem']);
 }