Exemplo n.º 1
0
 /**
  * Check if database needs to be built, and build it if it does.
  */
 static function autoBuild()
 {
     $dataClasses = ClassInfo::subclassesFor('DataObject');
     $lastBuilt = self::lastBuilt();
     foreach ($dataClasses as $class) {
         if (filemtime(getClassFile($class)) > $lastBuilt) {
             $da = new DatabaseAdmin();
             $da->doBuild(true);
             return;
         }
     }
 }
 /**
  * @param \Symfony\Component\Console\Input\InputInterface   $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  * @return void
  * @throws \Exception
  */
 protected function execute(Input\InputInterface $input, Output\OutputInterface $output)
 {
     if ($input->getOption('dev-build')) {
         $output->writeln('Building database');
         $databaseAdmin = new \DatabaseAdmin();
         $databaseAdmin->doBuild(true);
         $output->writeln('Database built');
     }
     // Get mode
     if ($input->getOption('mode')) {
         $mode = $input->getOption('mode');
     } else {
         $mode = \Director::get_environment_type();
     }
     $container = $this->createContainer();
     $this->loadConfig($container, $mode);
     $output->writeln($this->dumpContainer($container, $mode, $input->getOption('debug')));
 }
 /**
  * Test {@link Object::add_extension()} has loaded DataObjectDecorator statics correctly.
  */
 function testAddExtensionLoadsStatics()
 {
     // Object::add_extension() will load DOD statics directly, so let's try adding a decorator on the fly
     Object::add_extension('DataObjectDecoratorTest_Player', 'DataObjectDecoratorTest_PlayerDecorator');
     // Now that we've just added the decorator, we need to rebuild the database
     $da = new DatabaseAdmin();
     $da->doBuild(true, false, true);
     // Create a test record with decorated fields, writing to the DB
     $player = new DataObjectDecoratorTest_Player();
     $player->setField('Name', 'Joe');
     $player->setField('DateBirth', '1990-5-10');
     $player->Address = '123 somewhere street';
     $player->write();
     unset($player);
     // Pull the record out of the DB and examine the decorated fields
     $player = DataObject::get_one('DataObjectDecoratorTest_Player', "Name = 'Joe'");
     $this->assertEquals($player->DateBirth, '1990-05-10');
     $this->assertEquals($player->Address, '123 somewhere street');
     $this->assertEquals($player->Status, 'Goalie');
 }
 public function build($request)
 {
     //Only build the classes do not populate the records
     $_REQUEST['dont_populate'] = 1;
     $renderer = DebugView::create();
     $renderer->writeHeader();
     $renderer->writeInfo("Orient Environment Builder: Do not run while logged in as a member", Director::absoluteBaseURL());
     echo "<div class=\"build\">";
     $da = DatabaseAdmin::create();
     return $da->handleRequest($request, $this->model);
     echo "</div>";
     $renderer->writeFooter();
 }
Exemplo n.º 5
0
 function setUp()
 {
     $className = get_class($this);
     $fixtureFile = eval("return {$className}::\$fixture_file;");
     if ($fixtureFile) {
         // Create a temporary database
         $dbConn = DB::getConn();
         $dbname = 'tmpdb' . rand(1000000, 9999999);
         while (!$dbname || $dbConn->databaseExists($dbname)) {
             $dbname = 'tmpdb' . rand(1000000, 9999999);
         }
         $dbConn->selectDatabase($dbname);
         // This code is a bit misplaced; we want some way of the whole session being reinitialised...
         Versioned::reading_stage(null);
         $dbConn->createDatabase();
         singleton('DataObject')->flushCache();
         $dbadmin = new DatabaseAdmin();
         $dbadmin->doBuild(true, false);
         // Load the fixture into the database
         $className = get_class($this);
         $this->loadFixture($fixtureFile);
     }
 }
Exemplo n.º 6
0
 public function fire()
 {
     // make sure we have a fresh manifest
     $this->call('clear:cache');
     /** @var DatabaseAdmin $da */
     $da = DatabaseAdmin::create();
     // hack untill we have something better...
     ob_start();
     $da->doBuild();
     $content = ob_get_contents();
     ob_get_clean();
     foreach (explode("\n", $content) as $line) {
         $this->displayBuildMessage($line);
     }
 }
 public function build($request)
 {
     if (Director::is_cli()) {
         $da = DatabaseAdmin::create();
         return $da->handleRequest($request, $this->model);
     } else {
         $renderer = DebugView::create();
         $renderer->writeHeader();
         $renderer->writeInfo("Environment Builder", Director::absoluteBaseURL());
         echo "<div class=\"build\">";
         $da = DatabaseAdmin::create();
         return $da->handleRequest($request, $this->model);
         echo "</div>";
         $renderer->writeFooter();
     }
 }
 /**
  * Remove all content from the temporary database.
  */
 static function empty_temp_db()
 {
     if (self::using_temp_db()) {
         $dbadmin = new DatabaseAdmin();
         $dbadmin->clearAllData();
         // Some DataObjectsDecorators keep a static cache of information that needs to
         // be reset whenever the database is cleaned out
         foreach (array_merge(ClassInfo::subclassesFor('DataObjectDecorator'), ClassInfo::subclassesFor('DataObject')) as $class) {
             $toCall = array($class, 'on_db_reset');
             if (is_callable($toCall)) {
                 call_user_func($toCall);
             }
         }
     }
 }
Exemplo n.º 9
0
	function build() {
		$renderer = new DebugView();
		$renderer->writeHeader();
		$renderer->writeInfo("Environment Builder (formerly db/build)", Director::absoluteBaseURL());
		echo "<div style=\"margin: 0 2em\">";

		$da = new DatabaseAdmin();
		$da->build();
		
		echo "</div>";
		$renderer->writeFooter();
	}
Exemplo n.º 10
0
 /**
  * Build the default data, calling requireDefaultRecords on all
  * DataObject classes
  * Should match the $url_handlers rule:
  *		'build/defaults' => 'buildDefaults',
  */
 function buildDefaults()
 {
     $da = DatabaseAdmin::create();
     if (!Director::is_cli()) {
         $renderer = DebugView::create();
         $renderer->writeHeader();
         $renderer->writeInfo("Defaults Builder", Director::absoluteBaseURL());
         echo "<div style=\"margin: 0 2em\">";
     }
     $da->buildDefaults();
     if (!Director::is_cli()) {
         echo "</div>";
         $renderer->writeFooter();
     }
 }
Exemplo n.º 11
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;
    }
 /**
  * Build the database with default records, see {@link DataObject->requireDefaultRecords()}.
  */
 public function requireDefaultRecords()
 {
     $dbAdmin = new DatabaseAdmin();
     Versioned::set_reading_mode('');
     $dbAdmin->doBuild(true, true);
 }
Exemplo n.º 13
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;
    }
Exemplo n.º 15
0
 /**
  * Rebuilds the database programmatically and keeps track of new tables and fields
  *
  * @return array
  */
 public static function rebuild_database()
 {
     SS_ClassLoader::instance()->getManifest()->regenerate();
     ob_start();
     $da = DatabaseAdmin::create();
     $da->handleRequest(new SS_HTTPRequest("POST", "build", array('flush' => 'all')), DataModel::inst());
     $output = ob_get_contents();
     ob_end_clean();
     $database_result = array();
     foreach (explode("\n", $output) as $line) {
         if (preg_match('/Table ([A-Za-z0-9_:]+) created/', $line, $matches)) {
             $table_name = str_replace(":", "", $matches[1]);
             if (substr($table_name, -9) == "_versions" || substr($table_name, -5) == "_Live") {
                 continue;
             }
             $database_result[$table_name] = array('created' => true, 'fields' => array());
         } elseif (preg_match('/Field (.*) created as ([A-Za-z0-9_\\(\\)\\"\',]+)/', $line, $matches)) {
             list($table_name, $field_name) = explode(".", $matches[1]);
             if (substr($table_name, -9) == "_versions" || substr($table_name, -5) == "_Live") {
                 continue;
             }
             $field_name = str_replace(":", "", $field_name);
             $field_type = $matches[2];
             if (!isset($database_result[$table_name])) {
                 $database_result[$table_name] = array('created' => false, 'fields' => array());
             }
             $database_result[$table_name]['fields'][] = "{$field_name} ({$field_type})";
         }
     }
     return $database_result;
 }
 private function cleanupdb()
 {
     $obj = new DatabaseAdmin();
     $obj->cleanup();
     DB::alteration_message("============= COMPLETED =================", "");
     echo "<a href=\"" . Director::absoluteURL("/dev/tasks/DataIntegrityTest/") . "\">back to main menu.</a>";
 }
Exemplo n.º 17
0
	static function create_temp_db() {
		// Create a temporary database
		$dbConn = DB::getConn();
		$dbname = 'tmpdb' . rand(1000000,9999999);
		while(!$dbname || $dbConn->databaseExists($dbname)) {
			$dbname = 'tmpdb' . rand(1000000,9999999);
		}
		
		$dbConn->selectDatabase($dbname);
		$dbConn->createDatabase();

		$dbadmin = new DatabaseAdmin();
		$dbadmin->doBuild(true, false, true);
		
		return $dbname;
	}
Exemplo n.º 18
0
 function doReset($data, $form, $request)
 {
     if (!isset($data['devResetRandNumber'])) {
         Director::redirectBack();
         return false;
     }
     // Avoid accidental database resets by checking the posted number to the one in session
     if (Session::get('devResetRandNumber') != $data['devResetRandNumber']) {
         Director::redirectBack();
         return false;
     }
     $da = new DatabaseAdmin();
     $da->clearAllData();
     // If _ss_environment.php has some constants set for default admin, set these up in the request
     $_REQUEST['username'] = defined('SS_DEFAULT_ADMIN_USERNAME') ? SS_DEFAULT_ADMIN_USERNAME : null;
     $_REQUEST['password'] = defined('SS_DEFAULT_ADMIN_PASSWORD') ? SS_DEFAULT_ADMIN_PASSWORD : null;
     $da->build();
     Session::clear('devResetRandNumber');
     Director::redirect(Director::absoluteBaseURL() . 'dev/reset?done=1');
 }
 public function run($request)
 {
     $dbAdmin = DatabaseAdmin::create();
     increase_time_limit_to(600);
     SS_ClassLoader::instance()->getManifest()->regenerate();
     $dbAdmin->clearAllData();
     $dbAdmin->doBuild(true);
     // Build again for good measure
     $dbAdmin->doBuild(true, false);
     //Move images to assets/Uploads/
     $assetsDir = Director::baseFolder() . '/assets/Uploads';
     $imagesDir = Director::baseFolder() . '/swipestripe-builder/images';
     foreach (new DirectoryIterator($assetsDir) as $fileInfo) {
         if (!$fileInfo->isDot()) {
             @unlink($fileInfo->getPathname());
         }
     }
     Filesystem::sync();
     foreach (new DirectoryIterator($imagesDir) as $fileInfo) {
         if ($fileInfo->isFile()) {
             copy($fileInfo->getPathname(), $assetsDir . '/' . $fileInfo->getFilename());
         }
     }
     //Build DB
     $fixture = Injector::inst()->create('YamlFixture', self::$fixture_file);
     $fixture->writeInto($this->getFixtureFactory());
     //Update the shop config
     $config = ShopConfig::current_shop_config();
     $config->BaseCurrency = 'NZD';
     $config->BaseCurrencySymbol = '$';
     $config->EmailSignature = '';
     $config->ReceiptSubject = 'Your order details from SwipeStripe demo site';
     $config->ReceiptBody = '';
     $config->ReceiptFrom = '*****@*****.**';
     $config->NotificationSubject = 'New order on SwipeStripe demo site';
     $config->NotificationBody = '';
     $config->NotificationTo = '*****@*****.**';
     $config->write();
     // Populate flat fee shipping rates
     $this->createShippingRates();
     // Populate tax rates
     $this->createTaxRates();
     // Populate exchange rates
     $this->createExchangeRates();
     // Populate coupon codes
     $this->createCouponCodes();
     // Product categories
     $this->createProductCategories();
     // Product images
     $this->createProductImages();
     // Clear product meta
     $products = Product::get();
     if ($products && $products->exists()) {
         foreach ($products as $product) {
             $product->ExtraMeta = '';
             $product->doPublish();
         }
     }
     // Create home page
     if (class_exists('HomePage')) {
         $page = Page::get()->where("\"URLSegment\" = 'home'")->first();
         $page->ClassName = 'HomePage';
         $page->doPublish();
     }
 }
 function runTests($classList, $coverage = false)
 {
     global $TESTING_CONFIG;
     $startTime = microtime(true);
     Config::inst()->update('Director', 'environment_type', 'dev');
     if (isset($TESTING_CONFIG['database']) && $TESTING_CONFIG['database'] != 'silverstripe_testing') {
         global $databaseConfig;
         $newConfig = $databaseConfig;
         $newConfig = array_merge($databaseConfig, $TESTING_CONFIG);
         $newConfig['memory'] = isset($TESTING_CONFIG['memory']) ? $TESTING_CONFIG['memory'] : true;
         $type = isset($newConfig['type']) ? $newConfig['type'] : 'MySQL';
         Debug::message("Connecting to new database {$type} as defined by testing config");
         DB::connect($newConfig);
         DB::getConn()->selectDatabase($TESTING_CONFIG['database']);
         $dbadmin = new DatabaseAdmin();
         $dbadmin->clearAllData();
         if (!(isset($_REQUEST['build']) && $_REQUEST['build'] == 0)) {
             $dbadmin->doBuild(true);
         }
     }
     // XDEBUG seem to cause problems with test execution :-(
     if (function_exists('xdebug_disable')) {
         xdebug_disable();
     }
     ini_set('max_execution_time', 0);
     $this->setUp();
     // Optionally skip certain tests
     $skipTests = array();
     if ($this->request->getVar('SkipTests')) {
         $skipTests = explode(',', $this->request->getVar('SkipTests'));
     }
     $classList = array_diff($classList, $skipTests);
     // run tests before outputting anything to the client
     $suite = new PHPUnit_Framework_TestSuite();
     natcasesort($classList);
     foreach ($classList as $className) {
         // Ensure that the autoloader pulls in the test class, as PHPUnit won't know how to do this.
         class_exists($className);
         $suite->addTest(new SapphireTestSuite($className));
     }
     // Remove the error handler so that PHPUnit can add its own
     restore_error_handler();
     // CUSTOMISATION
     if (Director::is_cli()) {
         if (isset($TESTING_CONFIG['reporter'])) {
             $clazz = $TESTING_CONFIG['reporter'];
         } else {
             $clazz = "CliTestReporter";
         }
     } else {
         $clazz = "SapphireTestReporter";
     }
     // END CUSTOMISATION
     $reporter = new $clazz();
     $default = self::$default_reporter;
     self::$default_reporter->writeHeader("Sapphire Test Runner");
     if (count($classList) > 1) {
         self::$default_reporter->writeInfo("All Tests", "Running test cases: " . implode(",", $classList));
     } else {
         self::$default_reporter->writeInfo($classList[0], "");
     }
     $results = new PHPUnit_Framework_TestResult();
     $results->addListener($reporter);
     if ($coverage === true) {
         $results->collectCodeCoverageInformation(true);
         $suite->run($results);
         if (!file_exists(ASSETS_PATH . '/coverage-report')) {
             mkdir(ASSETS_PATH . '/coverage-report');
         }
         PHPUnit_Util_Report::render($results, ASSETS_PATH . '/coverage-report/');
         $coverageApp = ASSETS_PATH . '/coverage-report/' . preg_replace('/[^A-Za-z0-9]/', '_', preg_replace('/(\\/$)|(^\\/)/', '', Director::baseFolder())) . '.html';
         $coverageTemplates = ASSETS_PATH . '/coverage-report/' . preg_replace('/[^A-Za-z0-9]/', '_', preg_replace('/(\\/$)|(^\\/)/', '', realpath(TEMP_FOLDER))) . '.html';
         echo "<p>Coverage reports available here:<ul>\n\t\t\t\t<li><a href=\"{$coverageApp}\">Coverage report of the application</a></li>\n\t\t\t\t<li><a href=\"{$coverageTemplates}\">Coverage report of the templates</a></li>\n\t\t\t</ul>";
     } else {
         $suite->run($results);
     }
     if (!Director::is_cli()) {
         echo '<div class="trace">';
     }
     // CUSTOMISATION
     $outputFile = null;
     if ($TESTING_CONFIG['logfile']) {
         $outputFile = BASE_PATH . '/' . $TESTING_CONFIG['logfile'];
     }
     $reporter->writeResults($outputFile);
     // END CUSTOMISATION
     $endTime = microtime(true);
     if (Director::is_cli()) {
         echo "\n\nTotal time: " . round($endTime - $startTime, 3) . " seconds\n";
     } else {
         echo "<p>Total time: " . round($endTime - $startTime, 3) . " seconds</p>\n";
     }
     if (!Director::is_cli()) {
         echo '</div>';
     }
     // Put the error handlers back
     Debug::loadErrorHandlers();
     if (!Director::is_cli()) {
         self::$default_reporter->writeFooter();
     }
     $this->tearDown();
     // Todo: we should figure out how to pass this data back through Director more cleanly
     if (Director::is_cli() && $results->failureCount() + $results->errorCount() > 0) {
         exit(2);
     }
 }
 /**
  * 
  * Somewhat messy and god-method, but this override exists because
  * 
  * a) we want to change the configuration of items from the user-set TESTING_CONFIG 
  * variable if it exists
  * 
  * b) PhpUnitWrapper is referenced with explicit class settings, rather than allowing us to 
  * override as we like (to change code coverage behaviour). 
  * 
  * @global type TESTING_CONFIG
  * @global type $TESTING_CONFIG
  * @global type $databaseConfig
  * @param type $classList
  * @param type $coverage
  * @throws Exception
  */
 function runTests($classList, $coverage = false)
 {
     global $TESTING_CONFIG;
     $startTime = microtime(true);
     Config::inst()->update('Director', 'environment_type', 'dev');
     if (isset($TESTING_CONFIG['database']) && $TESTING_CONFIG['database'] != 'silverstripe_testing') {
         if (class_exists("Multisites")) {
             Multisites::inst()->resetCurrentSite();
         }
         global $databaseConfig;
         $newConfig = $databaseConfig;
         $newConfig = array_merge($databaseConfig, $TESTING_CONFIG);
         $newConfig['memory'] = isset($TESTING_CONFIG['memory']) ? $TESTING_CONFIG['memory'] : true;
         $newDbName = $TESTING_CONFIG['database'];
         $type = isset($newConfig['type']) ? $newConfig['type'] : 'MySQL';
         Debug::message("Connecting to new {$type} database {$TESTING_CONFIG['database']} as defined by testing config");
         DB::connect($newConfig);
         if (!DB::getConn()->databaseExists($newDbName)) {
             DB::getConn()->createDatabase($newDbName);
         }
         if (!DB::getConn()->selectDatabase($newDbName)) {
             throw new Exception("Could not find database to use for testing");
         }
         if ($newConfig['memory']) {
             Debug::message("Using in memory database");
         }
         $dbadmin = new DatabaseAdmin();
         if (isset($_REQUEST['clear']) && $_REQUEST['clear'] == 0) {
         } else {
             $dbadmin->clearAllData();
         }
         if (!(isset($_REQUEST['build']) && $_REQUEST['build'] == 0)) {
             Debug::message("Executing dev/build as requested");
             $dbadmin->doBuild(true);
         }
     }
     // XDEBUG seem to cause problems with test execution :-(
     if (function_exists('xdebug_disable')) {
         xdebug_disable();
     }
     ini_set('max_execution_time', 0);
     $this->setUp();
     // Optionally skip certain tests
     $skipTests = array();
     if ($this->request->getVar('SkipTests')) {
         $skipTests = explode(',', $this->request->getVar('SkipTests'));
     }
     $abstractClasses = array();
     foreach ($classList as $className) {
         // Ensure that the autoloader pulls in the test class, as PHPUnit won't know how to do this.
         class_exists($className);
         $reflection = new ReflectionClass($className);
         if ($reflection->isAbstract()) {
             array_push($abstractClasses, $className);
         }
     }
     $classList = array_diff($classList, $skipTests);
     // run tests before outputting anything to the client
     $suite = new PHPUnit_Framework_TestSuite();
     natcasesort($classList);
     foreach ($classList as $className) {
         // Ensure that the autoloader pulls in the test class, as PHPUnit won't know how to do this.
         class_exists($className);
         $suite->addTest(new SapphireTestSuite($className));
     }
     // Remove the error handler so that PHPUnit can add its own
     restore_error_handler();
     // CUSTOMISATION
     if (Director::is_cli()) {
         if ($reporterClass = $this->request->requestVar('reporter')) {
             $clazz = $reporterClass;
         } else {
             if (isset($TESTING_CONFIG['reporter'])) {
                 $clazz = $TESTING_CONFIG['reporter'];
             } else {
                 $clazz = "CliTestReporter";
             }
         }
     } else {
         $clazz = "SapphireTestReporter";
     }
     // END CUSTOMISATION
     // CUSTOMISATION
     $outputFile = null;
     if ($TESTING_CONFIG['logfile']) {
         $outputFile = BASE_PATH . '/' . $TESTING_CONFIG['logfile'];
     }
     $reporter = new $clazz($outputFile);
     $default = self::$default_reporter;
     self::$default_reporter->writeHeader("Sapphire Test Runner");
     if (count($classList) > 1) {
         self::$default_reporter->writeInfo("All Tests", "Running test cases: " . implode(",", $classList));
     } else {
         self::$default_reporter->writeInfo($classList[0], "");
     }
     $results = new PHPUnit_Framework_TestResult();
     $results->addListener($reporter);
     if ($coverage === true) {
         $coverer = $this->getCodeCoverage();
         $results->setCodeCoverage($coverer);
         $suite->run($results);
         $writer = new PHP_CodeCoverage_Report_HTML();
         $writer->process($coverer, Director::baseFolder() . '/ssautesting/html/code-coverage-report');
     } else {
         $suite->run($results);
     }
     if (!Director::is_cli()) {
         echo '<div class="trace">';
     }
     if (method_exists($reporter, 'writeResults')) {
         $reporter->writeResults($outputFile);
     } else {
         $reporter->flush();
     }
     // END CUSTOMISATION
     $endTime = microtime(true);
     if (Director::is_cli()) {
         echo "\n\nTotal time: " . round($endTime - $startTime, 3) . " seconds\n";
     } else {
         echo "<p>Total time: " . round($endTime - $startTime, 3) . " seconds</p>\n";
     }
     if (!Director::is_cli()) {
         echo '</div>';
     }
     // Put the error handlers back
     Debug::loadErrorHandlers();
     if (!Director::is_cli()) {
         self::$default_reporter->writeFooter();
     }
     $this->tearDown();
     // Todo: we should figure out how to pass this data back through Director more cleanly
     if (Director::is_cli() && $results->failureCount() + $results->errorCount() > 0) {
         exit(2);
     }
 }
Exemplo n.º 22
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;
	}