Passed
Push — 4.1.1 ( 01ed8a )
by Robbie
09:45
created

Installer   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 615
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 615
rs 5.82
c 0
b 0
f 0
wmc 55

13 Methods

Rating   Name   Duplication   Size   Complexity  
D install() 0 136 12
A installHeader() 0 11 2
A sendInstallStats() 0 20 3
B checkRewrite() 0 44 2
B writeIndexPHP() 0 32 1
C createHtaccess() 0 91 8
B writeConfigPHP() 0 24 3
A ymlString() 0 4 1
A statusMessage() 0 4 1
B writeConfigYaml() 0 30 3
B createWebConfig() 0 36 1
D writeConfigEnv() 0 60 13
B writeToFile() 0 14 5

How to fix   Complexity   

Complex Class

Complex classes like Installer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Installer, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SilverStripe\Dev\Install;
4
5
use Exception;
6
use SilverStripe\Control\Cookie;
7
use SilverStripe\Control\HTTPApplication;
8
use SilverStripe\Control\HTTPRequest;
9
use SilverStripe\Control\HTTPRequestBuilder;
10
use SilverStripe\Core\Convert;
11
use SilverStripe\Core\CoreKernel;
12
use SilverStripe\Core\EnvironmentLoader;
13
use SilverStripe\Core\Kernel;
14
use SilverStripe\Core\Startup\ParameterConfirmationToken;
15
use SilverStripe\ORM\DatabaseAdmin;
16
use SilverStripe\Security\DefaultAdminService;
17
use SilverStripe\Security\Security;
18
19
/**
20
 * This installer doesn't use any of the fancy SilverStripe stuff in case it's unsupported.
21
 */
22
class Installer extends InstallRequirements
23
{
24
    /**
25
     * value='' attribute placeholder for password fields
26
     */
27
    const PASSWORD_PLACEHOLDER = '********';
28
29
    protected function installHeader()
30
    {
31
        $clientPath = PUBLIC_DIR
32
            ? 'resources/vendor/silverstripe/framework/src/Dev/Install/client'
33
            : 'resources/silverstripe/framework/src/Dev/Install/client';
34
        ?>
35
        <html>
36
        <head>
37
            <meta charset="utf-8"/>
38
            <title>Installing SilverStripe...</title>
39
            <link rel="stylesheet" type="text/css" href="<?=$clientPath; ?>/styles/install.css"/>
40
            <script src="//code.jquery.com/jquery-1.7.2.min.js"></script>
41
        </head>
42
        <body>
43
        <div class="install-header">
44
            <div class="inner">
45
                <div class="brand">
46
                    <span class="logo"></span>
47
48
                    <h1>SilverStripe</h1>
49
                </div>
50
            </div>
51
        </div>
52
53
        <div id="Navigation">&nbsp;</div>
54
        <div class="clear"><!-- --></div>
55
56
        <div class="main">
57
            <div class="inner">
58
                <h2>Installing SilverStripe...</h2>
59
60
                <p>I am now running through the installation steps (this should take about 30 seconds)</p>
61
62
                <p>If you receive a fatal error, refresh this page to continue the installation</p>
63
                <ul>
64
        <?php
65
    }
66
67
    public function install($config)
68
    {
69
        // Render header
70
        $this->installHeader();
71
72
        $isIIS = $this->isIIS();
73
        $isApache = $this->isApache();
74
75
        flush();
76
77
        // Send install stats
78
        if (!empty($config['stats'])) {
79
            $this->sendInstallStats($config);
80
        }
81
82
        // Cleanup _config.php
83
        if (file_exists('mysite/_config.php')) {
84
            // Truncate the contents of _config instead of deleting it - we can't re-create it because Windows handles permissions slightly
85
            // differently to UNIX based filesystems - it takes the permissions from the parent directory instead of retaining them
86
            $fh = fopen('mysite/_config.php', 'wb');
87
            fclose($fh);
0 ignored issues
show
Bug introduced by
It seems like $fh can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

87
            fclose(/** @scrutinizer ignore-type */ $fh);
Loading history...
88
        }
89
90
        // Write all files
91
        $this->writeIndexPHP();
92
        $this->writeConfigPHP($config);
93
        $this->writeConfigYaml($config);
94
        $this->writeConfigEnv($config);
95
96
        // Write other stuff
97
        if (!$this->checkModuleExists('cms')) {
98
            $this->writeToFile("mysite/code/RootURLController.php", <<<PHP
99
<?php
100
101
use SilverStripe\\Control\\Controller;
102
103
class RootURLController extends Controller {
104
105
    public function index() {
106
        echo "<html>Your site is now set up. Start adding controllers to mysite to get started.</html>";
107
    }
108
109
}
110
PHP
111
            );
112
        }
113
114
        // Write the appropriate web server configuration file for rewriting support
115
        if ($this->hasRewritingCapability()) {
116
            if ($isApache) {
117
                $this->createHtaccess();
118
            } elseif ($isIIS) {
119
                $this->createWebConfig();
120
            }
121
        }
122
123
        // Build request
124
        $request = HTTPRequestBuilder::createFromEnvironment();
125
126
        // Install kernel (fix to dev)
127
        $kernel = new CoreKernel(BASE_PATH);
128
        $kernel->setEnvironment(Kernel::DEV);
129
        $app = new HTTPApplication($kernel);
130
131
        // Build db within HTTPApplication
132
        $app->execute($request, function (HTTPRequest $request) use ($config) {
133
            // Suppress cookie errors on install
134
            Cookie::config()->set('report_errors', false);
135
136
            // Start session and execute
137
            $request->getSession()->init($request);
138
139
            // Output status
140
            $this->statusMessage("Building database schema...");
141
142
            // Setup DB
143
            $dbAdmin = new DatabaseAdmin();
144
            $dbAdmin->setRequest($request);
145
            $dbAdmin->pushCurrent();
146
            $dbAdmin->doInit();
147
            $dbAdmin->doBuild(true);
148
149
            // Create default administrator user and group in database
150
            // (not using Security::setDefaultAdmin())
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
151
            $username = $config['admin']['username'];
152
            $password = $config['admin']['password'];
153
            $adminMember = DefaultAdminService::singleton()
154
                ->findOrCreateAdmin(
155
                    $username,
156
                    _t('SilverStripe\\Security\\DefaultAdminService.DefaultAdminFirstname', 'Default Admin')
157
                );
158
            $adminMember->Email = $username;
159
            $adminMember->Password = $password;
160
            $adminMember->PasswordEncryption = Security::config()->get('encryption_algorithm');
161
162
            try {
163
                $this->statusMessage('Creating default CMS admin account...');
164
                $adminMember->write();
165
            } catch (Exception $e) {
166
                $this->statusMessage(
167
                    sprintf('Warning: Default CMS admin account could not be created (error: %s)', $e->getMessage())
168
                );
169
            }
170
171
            $request->getSession()->set('username', $username);
172
            $request->getSession()->set('password', $password);
173
            $request->getSession()->save($request);
174
        }, true);
175
176
        // Check result of install
177
        if (!$this->errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
178
            if (isset($_SERVER['HTTP_HOST']) && $this->hasRewritingCapability()) {
179
                $this->statusMessage("Checking that friendly URLs work...");
180
                $this->checkRewrite();
181
            } else {
182
                $token = new ParameterConfirmationToken('flush', $request);
183
                $params = http_build_query($token->params());
184
185
                $destinationURL = 'index.php/' .
186
                    ($this->checkModuleExists('cms') ? "home/successfullyinstalled?$params" : "?$params");
187
188
                echo <<<HTML
189
                <li>SilverStripe successfully installed; I am now redirecting you to your SilverStripe site...</li>
190
                <script>
191
                    setTimeout(function() {
192
                        window.location = "$destinationURL";
193
                    }, 2000);
194
                </script>
195
                <noscript>
196
                <li><a href="$destinationURL">Click here to access your site.</a></li>
197
                </noscript>
198
HTML;
199
            }
200
        }
201
202
        return $this->errors;
203
    }
204
205
    protected function writeIndexPHP()
206
    {
207
        $content = <<<'PHP'
208
<?php
209
210
use SilverStripe\Control\HTTPApplication;
211
use SilverStripe\Control\HTTPRequestBuilder;
212
use SilverStripe\Core\CoreKernel;
213
use SilverStripe\Core\Startup\ErrorControlChainMiddleware;
214
215
// Find autoload.php
216
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
217
    require __DIR__ . '/vendor/autoload.php';
218
} elseif (file_exists(__DIR__ . '/../vendor/autoload.php')) {
219
    require __DIR__ . '/../vendor/autoload.php';
220
} else {
221
    echo "autoload.php not found";
222
    die;
223
}
224
225
// Build request and detect flush
226
$request = HTTPRequestBuilder::createFromEnvironment();
227
228
// Default application
229
$kernel = new CoreKernel(BASE_PATH);
230
$app = new HTTPApplication($kernel);
231
$app->addMiddleware(new ErrorControlChainMiddleware($app));
232
$response = $app->handle($request);
233
$response->output();
234
PHP;
235
        $path = $this->getPublicDir() . 'index.php';
236
        $this->writeToFile($path, $content, true);
237
    }
238
239
    /**
240
     * Write all .env files
241
     *
242
     * @param $config
243
     */
244
    protected function writeConfigEnv($config)
245
    {
246
        if (!$config['usingEnv']) {
247
            return;
248
        }
249
250
        $path = $this->getBaseDir() . '.env';
251
        $vars = [];
252
253
        // Retain existing vars
254
        $env = new EnvironmentLoader();
255
        if (file_exists($path)) {
256
            $vars = $env->loadFile($path) ?: [];
257
        }
258
259
        // Set base URL
260
        if (!isset($vars['SS_BASE_URL']) && isset($_SERVER['HTTP_HOST'])) {
261
            $vars['SS_BASE_URL'] = 'http://' . $_SERVER['HTTP_HOST'] . BASE_URL;
262
        }
263
264
        // Set DB env
265
        if (empty($config['db']['database'])) {
266
            $vars['SS_DATABASE_CHOOSE_NAME'] = true;
267
        } else {
268
            $vars['SS_DATABASE_NAME'] = $config['db']['database'];
269
        }
270
        $vars['SS_DATABASE_CLASS'] = $config['db']['type'];
271
        if (isset($config['db']['server'])) {
272
            $vars['SS_DATABASE_SERVER'] = $config['db']['server'];
273
        }
274
        if (isset($config['db']['username'])) {
275
            $vars['SS_DATABASE_USERNAME'] = $config['db']['username'];
276
        }
277
        if (isset($config['db']['password'])) {
278
            $vars['SS_DATABASE_PASSWORD'] = $config['db']['password'];
279
        }
280
        if (isset($config['db']['path'])) {
281
            $vars['SS_DATABASE_PATH'] = $config['db']['path'];
282
            // sqlite compat
283
            $vars['SS_SQLITE_DATABASE_PATH'] = $config['db']['path'];
284
        }
285
        if (isset($config['db']['key'])) {
286
            $vars['SS_DATABASE_KEY'] = $config['db']['key'];
287
            // sqlite compat
288
            $vars['SS_SQLITE_DATABASE_KEY'] = $config['db']['key'];
289
        }
290
291
        // Write all env vars
292
        $lines = [
293
            '# Generated by SilverStripe Installer'
294
        ];
295
        ksort($vars);
296
        foreach ($vars as $key => $value) {
297
            $lines[] = $key . '="' . addcslashes($value, '"') . '"';
298
        }
299
300
        $this->writeToFile('.env', implode("\n", $lines));
301
302
        // Re-load env vars for installer access
303
        $env->loadFile($path);
304
    }
305
306
    /**
307
     * Write all *.php files
308
     *
309
     * @param array $config
310
     */
311
    protected function writeConfigPHP($config)
312
    {
313
        if ($config['usingEnv']) {
314
            $this->writeToFile("mysite/_config.php", "<?php\n ");
315
            return;
316
        }
317
318
        // Create databaseConfig
319
        $lines = [];
320
        foreach ($config['db'] as $key => $value) {
321
            $lines[] = sprintf(
322
                "    '%s' => '%s'",
323
                addslashes($key),
324
                addslashes($value)
325
            );
326
        }
327
        $databaseConfigContent = implode(",\n", $lines);
328
        $this->writeToFile("mysite/_config.php", <<<PHP
329
<?php
330
331
use SilverStripe\\ORM\\DB;
332
333
DB::setConfig([
334
{$databaseConfigContent}
335
]);
336
337
PHP
338
        );
339
    }
340
341
    /**
342
     * Write yml files
343
     *
344
     * @param array $config
345
     */
346
    protected function writeConfigYaml($config)
347
    {
348
        // Escape user input for safe insertion into PHP file
349
        $locale = $this->ymlString($config['locale']);
350
351
        // Set either specified, or no theme
352
        if ($config['theme'] && $config['theme'] !== 'tutorial') {
353
            $theme = $this->ymlString($config['theme']);
354
            $themeYML = <<<YML
355
    - '\$public'
356
    - '$theme'
357
    - '\$default'
358
YML;
359
        } else {
360
            $themeYML = <<<YML
361
    - '\$public'
362
    - '\$default'
363
YML;
364
        }
365
366
        // Write theme.yml
367
        $this->writeToFile("mysite/_config/theme.yml", <<<YML
368
---
369
Name: mytheme
370
---
371
SilverStripe\\View\\SSViewer:
372
  themes:
373
$themeYML
374
SilverStripe\\i18n\\i18n:
375
  default_locale: '$locale'
376
YML
377
        );
378
    }
379
380
    /**
381
     * Escape yml string
382
     *
383
     * @param string $string
384
     * @return mixed
385
     */
386
    protected function ymlString($string)
387
    {
388
        // just escape single quotes using ''
389
        return str_replace("'", "''", $string);
390
    }
391
392
    /**
393
     * Write file to given location
394
     *
395
     * @param string $filename
396
     * @param string $content
397
     * @param bool $absolute If $filename is absolute path set to true
398
     * @return bool
399
     */
400
    public function writeToFile($filename, $content, $absolute = false)
401
    {
402
        $path = $absolute
403
            ? $filename
404
            : $this->getBaseDir() . $filename;
405
        $this->statusMessage("Setting up $path");
406
407
        if ((@$fh = fopen($path, 'wb')) && fwrite($fh, $content) && fclose($fh)) {
0 ignored issues
show
Bug introduced by
It seems like $fh can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

407
        if ((@$fh = fopen($path, 'wb')) && fwrite(/** @scrutinizer ignore-type */ $fh, $content) && fclose($fh)) {
Loading history...
Bug introduced by
It seems like $fh can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

407
        if ((@$fh = fopen($path, 'wb')) && fwrite($fh, $content) && fclose(/** @scrutinizer ignore-type */ $fh)) {
Loading history...
408
            // Set permissions to writable
409
            @chmod($path, 0775);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

409
            /** @scrutinizer ignore-unhandled */ @chmod($path, 0775);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
410
            return true;
411
        }
412
        $this->error("Couldn't write to file $path");
413
        return false;
414
    }
415
416
    /**
417
     * Ensure root .htaccess is setup
418
     */
419
    public function createHtaccess()
420
    {
421
        $start = "### SILVERSTRIPE START ###\n";
422
        $end = "\n### SILVERSTRIPE END ###";
423
424
        $base = dirname($_SERVER['SCRIPT_NAME']);
425
        $base = Convert::slashes($base, '/');
426
427
        if ($base != '.') {
428
            $baseClause = "RewriteBase '$base'\n";
429
        } else {
430
            $baseClause = "";
431
        }
432
        if (strpos(strtolower(php_sapi_name()), "cgi") !== false) {
433
            $cgiClause = "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n";
434
        } else {
435
            $cgiClause = "";
436
        }
437
        $rewrite = <<<TEXT
438
# Deny access to templates (but allow from localhost)
439
<Files *.ss>
440
    Order deny,allow
441
    Deny from all
442
    Allow from 127.0.0.1
443
</Files>
444
445
# Deny access to IIS configuration
446
<Files web.config>
447
    Order deny,allow
448
    Deny from all
449
</Files>
450
451
# Deny access to YAML configuration files which might include sensitive information
452
<Files ~ "\.ya?ml$">
453
    Order allow,deny
454
    Deny from all
455
</Files>
456
457
# Route errors to static pages automatically generated by SilverStripe
458
ErrorDocument 404 /assets/error-404.html
459
ErrorDocument 500 /assets/error-500.html
460
461
<IfModule mod_rewrite.c>
462
463
    # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4
464
    <IfModule mod_dir.c>
465
        DirectoryIndex disabled
466
        DirectorySlash On
467
    </IfModule>
468
469
    SetEnv HTTP_MOD_REWRITE On
470
    RewriteEngine On
471
    $baseClause
472
    $cgiClause
473
474
    # Deny access to potentially sensitive files and folders
475
    RewriteRule ^vendor(/|$) - [F,L,NC]
476
    RewriteRule ^\.env - [F,L,NC]
477
    RewriteRule silverstripe-cache(/|$) - [F,L,NC]
478
    RewriteRule composer\.(json|lock) - [F,L,NC]
479
    RewriteRule (error|silverstripe|debug)\.log - [F,L,NC]
480
481
    # Process through SilverStripe if no file with the requested name exists.
482
    # Pass through the original path as a query parameter, and retain the existing parameters.
483
    # Try finding framework in the vendor folder first
484
    RewriteCond %{REQUEST_URI} ^(.*)$
485
    RewriteCond %{REQUEST_FILENAME} !-f
486
    RewriteRule .* index.php
487
</IfModule>
488
TEXT;
489
490
        $htaccessPath = $this->getPublicDir() . '.htaccess';
491
        if (file_exists($htaccessPath)) {
492
            $htaccess = file_get_contents($htaccessPath);
493
494
            if (strpos($htaccess, '### SILVERSTRIPE START ###') === false
495
                && strpos($htaccess, '### SILVERSTRIPE END ###') === false
496
            ) {
497
                $htaccess .= "\n### SILVERSTRIPE START ###\n### SILVERSTRIPE END ###\n";
498
            }
499
500
            if (strpos($htaccess, '### SILVERSTRIPE START ###') !== false
501
                && strpos($htaccess, '### SILVERSTRIPE END ###') !== false
502
            ) {
503
                $start = substr($htaccess, 0, strpos($htaccess, '### SILVERSTRIPE START ###'))
504
                    . "### SILVERSTRIPE START ###\n";
505
                $end = "\n" . substr($htaccess, strpos($htaccess, '### SILVERSTRIPE END ###'));
506
            }
507
        }
508
509
        $this->writeToFile($htaccessPath, $start . $rewrite . $end, true);
510
    }
511
512
    /**
513
     * Writes basic configuration to the web.config for IIS
514
     * so that rewriting capability can be use.
515
     */
516
    public function createWebConfig()
517
    {
518
        $content = <<<TEXT
519
<?xml version="1.0" encoding="utf-8"?>
520
<configuration>
521
    <system.webServer>
522
        <security>
523
            <requestFiltering>
524
                <hiddenSegments applyToWebDAV="false">
525
                    <add segment="silverstripe-cache" />
526
                    <add segment="composer.json" />
527
                    <add segment="composer.lock" />
528
                </hiddenSegments>
529
                <fileExtensions allowUnlisted="true" >
530
                    <add fileExtension=".ss" allowed="false"/>
531
                    <add fileExtension=".yml" allowed="false"/>
532
                </fileExtensions>
533
            </requestFiltering>
534
        </security>
535
        <rewrite>
536
            <rules>
537
                <rule name="SilverStripe Clean URLs" stopProcessing="true">
538
                    <match url="^(.*)$" />
539
                    <conditions>
540
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
541
                    </conditions>
542
                    <action type="Rewrite" url="index.php" appendQueryString="true" />
543
                </rule>
544
            </rules>
545
        </rewrite>
546
    </system.webServer>
547
</configuration>
548
TEXT;
549
550
        $path = $this->getPublicDir() . 'web.config';
551
        $this->writeToFile($path, $content, true);
552
    }
553
554
    public function checkRewrite()
555
    {
556
        $token = new ParameterConfirmationToken('flush', new HTTPRequest('GET', '/'));
557
        $params = http_build_query($token->params());
558
559
        $destinationURL = BASE_URL . '/' . (
560
            $this->checkModuleExists('cms')
561
                ? "home/successfullyinstalled?$params"
562
                : "?$params"
563
        );
564
565
        echo <<<HTML
566
<li id="ModRewriteResult">Testing...</li>
567
<script>
568
    if (typeof $ == 'undefined') {
569
        document.getElemenyById('ModeRewriteResult').innerHTML = "I can't run jQuery ajax to set rewriting; I will redirect you to the homepage to see if everything is working.";
570
        setTimeout(function() {
571
            window.location = "$destinationURL";
572
        }, 10000);
573
    } else {
574
        $.ajax({
575
            method: 'get',
576
            url: 'InstallerTest/testrewrite',
577
            complete: function(response) {
578
                var r = response.responseText.replace(/[^A-Z]?/g,"");
579
                if (r === "OK") {
580
                    $('#ModRewriteResult').html("Friendly URLs set up successfully; I am now redirecting you to your SilverStripe site...")
581
                    setTimeout(function() {
582
                        window.location = "$destinationURL";
583
                    }, 2000);
584
                } else {
585
                    $('#ModRewriteResult').html("Friendly URLs are not working. This is most likely because a rewrite module isn't configured "
586
                        + "correctly on your site. You may need to get your web host or server administrator to do this for you: "
587
                        + "<ul>"
588
                        + "<li><strong>mod_rewrite</strong> or other rewrite module is enabled on your web server</li>"
589
                        + "<li><strong>AllowOverride All</strong> is set for the directory where SilverStripe is installed</li>"
590
                        + "</ul>");
591
                }
592
            }
593
        });
594
    }
595
</script>
596
<noscript>
597
    <li><a href="$destinationURL">Click here</a> to check friendly URLs are working. If you get a 404 then something is wrong.</li>
598
</noscript>
599
HTML;
600
    }
601
602
    /**
603
     * Show an installation status message.
604
     * The output differs depending on whether this is CLI or web based
605
     *
606
     * @param string $msg
607
     */
608
    public function statusMessage($msg)
609
    {
610
        echo "<li>$msg</li>\n";
611
        flush();
612
    }
613
614
    /**
615
     * @param $config
616
     */
617
    protected function sendInstallStats($config)
618
    {
619
        // Try to determine the database version from the helper
620
        $dbType = $config['db']['type'];
621
        $helper = $this->getDatabaseConfigurationHelper($dbType);
622
        if ($helper) {
0 ignored issues
show
introduced by
$helper is of type SilverStripe\Dev\Install...baseConfigurationHelper, thus it always evaluated to true.
Loading history...
623
            $databaseVersion = $dbType . ': ' . $helper->getDatabaseVersion($config['db']);
624
        } else {
625
            $databaseVersion = $dbType;
626
        }
627
628
        $args = http_build_query(array_filter([
629
            'SilverStripe' => $config['version'],
630
            'PHP' => phpversion(),
631
            'Database' => $databaseVersion,
632
            'WebServer' => $this->findWebserver(),
633
            'ID' => empty($_SESSION['StatsID']) ? null : $_SESSION['StatsID']
634
        ]));
635
        $url = "http://ss2stat.silverstripe.com/Installation/add?{$args}";
636
        @$_SESSION['StatsID'] = file_get_contents($url);
637
    }
638
}
639