Failed Conditions
Pull Request — master (#1543)
by Tsuyoshi
489:47 queued 481:38
created

InstallController::setup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1.0046

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 5
cts 6
cp 0.8333
rs 9.4285
cc 1
eloc 5
nc 1
nop 1
crap 1.0046
1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
25
namespace Eccube\Controller\Install;
26
27
use Doctrine\DBAL\Migrations\Configuration\Configuration;
28
use Doctrine\DBAL\Migrations\Migration;
29
use Doctrine\DBAL\Migrations\MigrationException;
30
use Doctrine\ORM\EntityManager;
31
use Doctrine\ORM\Tools\SchemaTool;
32
use Eccube\Application;
33
use Eccube\Common\Constant;
34
use Eccube\InstallApplication;
35
use Eccube\Util\Str;
36
use Symfony\Component\Filesystem\Filesystem;
37
use Symfony\Component\Finder\Finder;
38
use Symfony\Component\Form\Form;
39
use Symfony\Component\HttpFoundation\Request;
40
use Symfony\Component\Yaml\Yaml;
41
42
class InstallController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
43
{
44
    private $app;
45
46
    private $PDO;
47
    private $session_data;
48
49
    private $required_modules = array('pdo', 'phar', 'mbstring', 'zlib', 'ctype', 'session', 'JSON', 'xml', 'libxml', 'OpenSSL', 'zip', 'cURL', 'fileinfo');
50
    private $recommended_module = array('hash', 'mcrypt');
51
52
    // path
53
    private $config_path;
54
    private $dist_path;
55
    private $cache_path;
56
57
    const SESSION_KEY = 'eccube.session.install';
58
59 5
    public function setup(InstallApplication $app)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
60
    {
61 5
        $this->app = $app;
62
63 5
        $this->config_path = $this->app->rootDir . '/app/config/eccube';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
64 5
        $this->dist_path = __DIR__ . '/../../Resource/config';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
65 5
        $this->cache_path = $this->app->rootDir . '/app/cache';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
66
    }
67
68
    /**
69
     * 最初からやり直す場合、SESSION情報をクリア
70
     *
71
     * @param InstallApplication $app
72
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
73
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
74 1
    public function index(InstallApplication $app, Request $request)
75
    {
76
        $this->setup($app);
77
78
        $request->getSession()->remove(self::SESSION_KEY);
79
80
        return $app->redirect($app->url('install_step1'));
81 1
    }
82
83
    /**
84
     * ようこそ
85
     *
86
     * @param InstallApplication $app
87
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
88
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
89 1
    public function step1(InstallApplication $app, Request $request)
90
    {
91
        $this->setup($app);
92
93
        $form = $app['form.factory']
94
            ->createBuilder('install_step1')
95
            ->getForm();
96
        $sessionData = $this->getSessionData($request);
97
        $form->setData($sessionData);
98
99
        if ($this->isValid($request, $form)) {
100
            return $app->redirect($app->url('install_step2'));
101
        }
102
103
        $this->checkModules();
104
105 1
        return $app['twig']->render('step1.twig', array(
106 1
            'form' => $form->createView(),
107
        ));
108 1
    }
109
110
    /**
111
     * 権限チェック
112
     *
113
     * @param InstallApplication $app
114
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
115
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
116 1
    public function step2(InstallApplication $app, Request $request)
117
    {
118
        $this->setup($app);
119
120
        $this->getSessionData($request);
121
122
        $protectedDirs = $this->getProtectedDirs();
123
124
        // 権限がある場合, キャッシュディレクトリをクリア
125 1
        if (empty($protectedDirs)) {
126 1
            $finder = Finder::create()
127 1
                ->in($this->cache_path)
128 1
                ->directories()
129
                ->depth(0);
130
            $fs = new Filesystem();
131
            $fs->remove($finder);
132
        }
133
134 1
        return $app['twig']->render('step2.twig', array(
135
            'protectedDirs' => $protectedDirs,
136
        ));
137 1
    }
138
139
    /**
140
     * サイトの設定
141
     *
142
     * @param InstallApplication $app
143
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
144
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
145
    public function step3(InstallApplication $app, Request $request)
146
    {
147
        $this->setup($app);
148
149
        $form = $app['form.factory']
150
            ->createBuilder('install_step3')
151
            ->getForm();
152
        $sessionData = $this->getSessionData($request);
153
154
        if (empty($sessionData['shop_name'])) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
155
156
            $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
157
            $fs = new Filesystem();
158
159
            if ($fs->exists($config_file)) {
160
                // すでに登録されていた場合、登録データを表示
161
                $this->setPDO();
162
                $stmt = $this->PDO->query("SELECT shop_name, email01 FROM dtb_base_info WHERE id = 1;");
163
164
                foreach ($stmt as $row) {
165
                    $sessionData['shop_name'] = $row['shop_name'];
166
                    $sessionData['email'] = $row['email01'];
167
                }
168
169
                // セキュリティの設定
170
                $config_file = $this->config_path . '/path.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
171
                $config = Yaml::parse(file_get_contents($config_file));
172
                $sessionData['admin_dir'] = $config['admin_route'];
173
174
                $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
175
                $config = Yaml::parse(file_get_contents($config_file));
176
177
                $allowHost = $config['admin_allow_host'];
178
                if (count($allowHost) > 0) {
179
                    $sessionData['admin_allow_hosts'] = Str::convertLineFeed(implode("\n", $allowHost));
180
                }
181
                $sessionData['admin_force_ssl'] = (bool)$config['force_ssl'];
0 ignored issues
show
Coding Style introduced by
As per coding-style, a cast statement should be followed by a single space.
Loading history...
182
183
                // メール設定
184
                $config_file = $this->config_path . '/mail.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
185
                $config = Yaml::parse(file_get_contents($config_file));
186
                $mail = $config['mail'];
187
                $sessionData['mail_backend'] = $mail['transport'];
188
                $sessionData['smtp_host'] = $mail['host'];
189
                $sessionData['smtp_port'] = $mail['port'];
190
                $sessionData['smtp_username'] = $mail['username'];
191
                $sessionData['smtp_password'] = $mail['password'];
192
            } else {
193
                // 初期値にmailを設定
194
                $sessionData['mail_backend'] = 'mail';
195
            }
196
        }
197
198
        $form->setData($sessionData);
199
        if ($this->isValid($request, $form)) {
200
            $data = $form->getData();
0 ignored issues
show
Unused Code introduced by
$data is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
201
202
            return $app->redirect($app->url('install_step4'));
203
        }
204
205
        return $app['twig']->render('step3.twig', array(
206
            'form' => $form->createView(),
207
        ));
208
    }
209
210
    /**
211
     * データベースの設定
212
     *
213
     * @param InstallApplication $app
214
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
215
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
216
    public function step4(InstallApplication $app, Request $request)
217
    {
218
        $this->setup($app);
219
220
        $form = $app['form.factory']
221
            ->createBuilder('install_step4')
222
            ->getForm();
223
224
        $sessionData = $this->getSessionData($request);
225
226
        if (empty($sessionData['database'])) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
227
228
            $config_file = $this->config_path.'/database.yml';
229
            $fs = new Filesystem();
230
231
            if ($fs->exists($config_file)) {
232
                // すでに登録されていた場合、登録データを表示
233
234
                // データベース設定
235
                $config = Yaml::parse(file_get_contents($config_file));
236
                $database = $config['database'];
237
                $sessionData['database'] = $database['driver'];
238
                if ($database['driver'] != 'pdo_sqlite') {
239
                    $sessionData['database_host'] = $database['host'];
240
                    $sessionData['database_port'] = $database['port'];
241
                    $sessionData['database_name'] = $database['dbname'];
242
                    $sessionData['database_user'] = $database['user'];
243
                    $sessionData['database_password'] = $database['password'];
244
                }
245
            }
246
        }
247
248
        $form->setData($sessionData);
249
250
        if ($this->isValid($request, $form)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
251
252
            return $app->redirect($app->url('install_step5'));
253
        }
254
255
        return $app['twig']->render('step4.twig', array(
256
            'form' => $form->createView(),
257
        ));
258
    }
259
260
    /**
261
     * データベースの初期化
262
     *
263
     * @param InstallApplication $app
264
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
265
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
266 1
    public function step5(InstallApplication $app, Request $request)
267
    {
268
        $this->setup($app);
269
270
        set_time_limit(0);
271
        $form = $app['form.factory']
272
            ->createBuilder('install_step5')
273
            ->getForm();
274
        $sessionData = $this->getSessionData($request);
275
        $form->setData($sessionData);
276
277
        if ($this->isValid($request, $form)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
278
279
            $this
280
                ->createDatabaseYamlFile($sessionData)
281
                ->createMailYamlFile($sessionData)
282
                ->createPathYamlFile($sessionData, $request);
283
284
            if (!$form['no_update']->getData()) {
285
                set_time_limit(0);
286
                $this->createConfigYamlFile($sessionData);
287
288
                $this
289
                    ->setPDO()
290
                    ->dropTables()
291
                    ->createTables()
292
                    ->doMigrate()
293
                    ->insert();
294
            } else {
295
                // データベースを初期化しない場合、auth_magicは初期化しない
296
                $this->createConfigYamlFile($sessionData, false);
297
298
                $this
299
                    ->setPDO()
300
                    ->update();
301
            }
302
303
            if (isset($sessionData['agree']) && $sessionData['agree'] == '1') {
304
                $host = $request->getSchemeAndHttpHost();
305
                $basePath = $request->getBasePath();
306
                $params = array(
307
                    'http_url' => $host . $basePath,
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
308
                    'shop_name' => $sessionData['shop_name'],
309
                );
310
311
                $this->sendAppData($params);
312
            }
313
            $this->addInstallStatus();
314
315
            $request->getSession()->remove(self::SESSION_KEY);
316
317
            return $app->redirect($app->url('install_complete'));
318
        }
319
320 1
        return $app['twig']->render('step5.twig', array(
321 1
            'form' => $form->createView(),
322
        ));
323 1
    }
324
325
    /**
326
     * インストール完了
327
     *
328
     * @param InstallApplication $app
329
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
330
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
331 1
    public function complete(InstallApplication $app, Request $request)
332
    {
333
        $this->setup($app);
334
335 1
        $config_file = $this->config_path . '/path.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
336
        $config = Yaml::parse(file_get_contents($config_file));
337
338
        $host = $request->getSchemeAndHttpHost();
339
        $basePath = $request->getBasePath();
340
341 1
        $adminUrl = $host . $basePath . '/' . $config['admin_dir'];
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
342
343 1
        return $app['twig']->render('complete.twig', array(
344
            'admin_url' => $adminUrl,
345
        ));
346 1
    }
347
348
    /**
349
     * マイグレーション画面を表示する.
350
     *
351
     * @param InstallApplication $app
352
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
353
     *
354
     * @return \Symfony\Component\HttpFoundation\Response
355
     */
356
    public function migration(InstallApplication $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
357
    {
358
        return $app['twig']->render('migration.twig');
359
    }
360
361
    /**
362
     * インストール済プラグインの一覧を表示する.
363
     * プラグインがインストールされていない場合は, マイグレーション実行画面へリダイレクトする.
364
     *
365
     * @param InstallApplication $app
366
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
367
     *
368
     * @return \Symfony\Component\HttpFoundation\Response
369
     */
370
    public function migration_plugin(InstallApplication $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
Method name "InstallController::migration_plugin" is not in camel caps format
Loading history...
371
    {
372
        $eccube = \Eccube\Application::getInstance();
373
        $eccube->initialize();
374
        $eccube->boot();
375
376
        $pluginRepository = $eccube['orm.em']->getRepository('Eccube\Entity\Plugin');
377
        $Plugins = $pluginRepository->findBy(array('del_flg' => Constant::DISABLED));
378
379
        if (empty($Plugins)) {
380
            // インストール済プラグインがない場合はマイグレーション実行画面へリダイレクト.
381
            return $app->redirect($app->url('migration_end'));
382
        } else {
383
            return $app['twig']->render('migration_plugin.twig', array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
384
                'Plugins' => $Plugins,
385
                'version' => Constant::VERSION));
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 16.
Loading history...
386
        }
387
    }
388
389
    /**
390
     * マイグレーションを実行し, 完了画面を表示させる
391
     *
392
     * @param InstallApplication $app
393
     * @param Request $request
0 ignored issues
show
introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
394
     *
395
     * @return \Symfony\Component\HttpFoundation\Response
396
     */
397
    public function migration_end(InstallApplication $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
Method name "InstallController::migration_end" is not in camel caps format
Loading history...
398
    {
399
        $this->doMigrate();
400
401
        $config_app = new \Eccube\Application(); // install用のappだとconfigが取れないので
402
        $config_app->initialize();
403
        $config_app->boot();
404
        \Eccube\Util\Cache::clear($config_app, true);
0 ignored issues
show
Documentation introduced by
$config_app is of type object<Eccube\Application>, but the function expects a object<Eccube\Util\Application>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
405
406
        return $app['twig']->render('migration_end.twig');
407
    }
408
409 2
    private function isValid(Request $request, Form $form)
410
    {
411
        $session = $request->getSession();
412
        if ('POST' === $request->getMethod()) {
413
            $form->handleRequest($request);
414
            if ($form->isValid()) {
415
                $sessionData = $session->get(self::SESSION_KEY) ?: array();
416
                $formData = array_replace_recursive($sessionData, $form->getData());
417
                $session->set(self::SESSION_KEY, $formData);
418
419
                return true;
420
            }
421
        }
422
423 2
        return false;
424 2
    }
425
426 3
    private function getSessionData(Request $request)
427
    {
428
        $this->session_data = $request->getSession()->get(self::SESSION_KEY);
429
430 3
        return $this->session_data;
431 3
    }
432
433
    private function resetNatTimer()
434
    {
435
        // NATの無通信タイマ対策(仮)
436
        echo str_repeat(' ', 4 * 1024);
437
        ob_flush();
438
        flush();
439
    }
440
441
442 1
    private function checkModules()
0 ignored issues
show
Coding Style introduced by
checkModules uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
443
    {
444 1
        foreach ($this->required_modules as $module) {
445
            if (!extension_loaded($module)) {
446
                $this->app->addDanger('[必須] ' . $module . ' 拡張モジュールが有効になっていません。', 'install');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
447
            }
448
        }
449
450
        if (!extension_loaded('pdo_mysql') && !extension_loaded('pdo_pgsql')) {
451
            $this->app->addDanger('[必須] ' . 'pdo_pgsql又はpdo_mysql 拡張モジュールを有効にしてください。', 'install');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
452
        }
453
454 1
        foreach ($this->recommended_module as $module) {
455
            if (!extension_loaded($module)) {
456
                $this->app->addWarning('[推奨] ' . $module . ' 拡張モジュールが有効になっていません。', 'install');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
457
            }
458
        }
459
460 1
        if ('\\' === DIRECTORY_SEPARATOR) { // for Windows
461
            if (!extension_loaded('wincache')) {
462
                $this->app->addWarning('[推奨] WinCache 拡張モジュールが有効になっていません。', 'install');
463
            }
464
        } else {
465
            if (!extension_loaded('apc')) {
466
                $this->app->addWarning('[推奨] APC 拡張モジュールが有効になっていません。', 'install');
467
            }
468
        }
469
470 1
        if (isset($_SERVER['SERVER_SOFTWARE']) && strpos('Apache', $_SERVER['SERVER_SOFTWARE']) !== false) {
471
            if (!function_exists('apache_get_modules')) {
472
                $this->app->addWarning('mod_rewrite が有効になっているか不明です。', 'install');
473
            } elseif (!in_array('mod_rewrite', apache_get_modules())) {
474
                $this->app->addDanger('[必須] ' . 'mod_rewriteを有効にしてください。', 'install');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
475
            }
476 1
        } elseif (isset($_SERVER['SERVER_SOFTWARE']) && strpos('Microsoft-IIS', $_SERVER['SERVER_SOFTWARE']) !== false) {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
477
            // iis
478 1
        } elseif (isset($_SERVER['SERVER_SOFTWARE']) && strpos('nginx', $_SERVER['SERVER_SOFTWARE']) !== false) {
0 ignored issues
show
Unused Code introduced by
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
479
            // nginx
480
        }
481 1
    }
482
483
    private function setPDO()
484
    {
485
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
486
        $config = Yaml::parse(file_get_contents($config_file));
487
488
        try {
489
            $this->PDO = \Doctrine\DBAL\DriverManager::getConnection($config['database'], new \Doctrine\DBAL\Configuration());
490
            $this->PDO->connect();
491
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
492
        } catch (\Exception $e) {
493
            $this->PDO->close();
494
            throw $e;
495
        }
496
497
        return $this;
498
    }
499
500 View Code Duplication
    private function dropTables()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
501
    {
502
        $this->resetNatTimer();
503
504
        $em = $this->getEntityManager();
505
        $metadatas = $em->getMetadataFactory()->getAllMetadata();
506
        $schemaTool = new SchemaTool($em);
507
508
        $schemaTool->dropSchema($metadatas);
509
510
        $em->getConnection()->executeQuery('DROP TABLE IF EXISTS doctrine_migration_versions');
511
512
        return $this;
513
    }
514
515
    /**
516
     * @return EntityManager
517
     */
518
    private function getEntityManager()
519
    {
520
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
521
        $database = Yaml::parse(file_get_contents($config_file));
522
523
        $this->app->register(new \Silex\Provider\DoctrineServiceProvider(), array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
524
            'db.options' => $database['database']
525
        ));
526
527
        $this->app->register(new \Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
528
            'orm.proxies_dir' => $this->app->rootDir . '/app/cache/doctrine',
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
529
            'orm.em.options' => array(
530
                'mappings' => array(
531
                    array(
532
                        'type' => 'yml',
533
                        'namespace' => 'Eccube\Entity',
534
                        'path' => array(
535
                            __DIR__ . '/../../Resource/doctrine',
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
536
                            __DIR__ . '/../../Resource/doctrine/master',
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
537
                        ),
538
                    ),
539
540
                ),
541
            )
542
        ));
543
544
        return $em = $this->app['orm.em'];
0 ignored issues
show
Unused Code introduced by
$em is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
545
    }
546
547 View Code Duplication
    private function createTables()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
548
    {
549
        $this->resetNatTimer();
550
551
        $em = $this->getEntityManager();
552
        $metadatas = $em->getMetadataFactory()->getAllMetadata();
553
        $schemaTool = new SchemaTool($em);
554
555
        $schemaTool->createSchema($metadatas);
556
557
        return $this;
558
    }
559
560
    private function insert()
561
    {
562
        $this->resetNatTimer();
563
564
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
565
        $database = Yaml::parse(file_get_contents($config_file));
566
        $config['database'] = $database['database'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
567
568
        $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
569
        $baseConfig = Yaml::parse(file_get_contents($config_file));
570
        $config['config'] = $baseConfig;
571
572
        $this->PDO->beginTransaction();
573
574
        try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
575
576
            $config = array(
577
                'auth_type' => '',
578
                'auth_magic' => $config['config']['auth_magic'],
579
                'password_hash_algos' => 'sha256',
580
            );
581
            $passwordEncoder = new \Eccube\Security\Core\Encoder\PasswordEncoder($config);
582
            $salt = \Eccube\Util\Str::random(32);
583
584
            $encodedPassword = $passwordEncoder->encodePassword($this->session_data['login_pass'], $salt);
585
            $sth = $this->PDO->prepare('INSERT INTO dtb_base_info (
586
                id,
587
                shop_name,
588
                email01,
589
                email02,
590
                email03,
591
                email04,
592
                update_date,
593
                option_product_tax_rule
594
            ) VALUES (
595
                1,
596
                :shop_name,
597
                :admin_mail,
598
                :admin_mail,
599
                :admin_mail,
600
                :admin_mail,
601
                current_timestamp,
602
                0);');
603
            $sth->execute(array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
604
                ':shop_name' => $this->session_data['shop_name'],
605
                ':admin_mail' => $this->session_data['email']
606
            ));
607
608
            $sth = $this->PDO->prepare("INSERT INTO dtb_member (member_id, login_id, password, salt, work, del_flg, authority, creator_id, rank, update_date, create_date,name,department) VALUES (2, :login_id, :admin_pass , :salt , '1', '0', '0', '1', '1', current_timestamp, current_timestamp,'管理者','EC-CUBE SHOP');");
609
            $sth->execute(array(':login_id' => $this->session_data['login_id'], ':admin_pass' => $encodedPassword, ':salt' => $salt));
610
611
            $this->PDO->commit();
612
        } catch (\Exception $e) {
613
            $this->PDO->rollback();
614
            throw $e;
615
        }
616
617
        return $this;
618
    }
619
620
    private function update()
621
    {
622
        $this->resetNatTimer();
623
624
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
625
        $database = Yaml::parse(file_get_contents($config_file));
626
        $config['database'] = $database['database'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
627
628
        $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
629
        $baseConfig = Yaml::parse(file_get_contents($config_file));
630
        $config['config'] = $baseConfig;
631
632
        $this->PDO->beginTransaction();
633
634
        try {
635
            $config = array(
636
                'auth_type' => '',
637
                'auth_magic' => $config['config']['auth_magic'],
638
                'password_hash_algos' => 'sha256',
639
            );
640
            $passwordEncoder = new \Eccube\Security\Core\Encoder\PasswordEncoder($config);
641
            $salt = \Eccube\Util\Str::random(32);
642
643
            $stmt = $this->PDO->prepare("SELECT member_id FROM dtb_member WHERE login_id = :login_id;");
644
            $stmt->execute(array(':login_id' => $this->session_data['login_id']));
645
            $rs = $stmt->fetch();
646
647
            $encodedPassword = $passwordEncoder->encodePassword($this->session_data['login_pass'], $salt);
648
649
            if ($rs) {
650
                // 同一の管理者IDであればパスワードのみ更新
651
                $sth = $this->PDO->prepare("UPDATE dtb_member set password = :admin_pass, salt = :salt, update_date = current_timestamp WHERE login_id = :login_id;");
652
                $sth->execute(array(':admin_pass' => $encodedPassword, ':salt' => $salt, ':login_id' => $this->session_data['login_id']));
653
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
654
            } else {
655
                // 新しい管理者IDが入力されたらinsert
656
                $sth = $this->PDO->prepare("INSERT INTO dtb_member (login_id, password, salt, work, del_flg, authority, creator_id, rank, update_date, create_date,name,department) VALUES (:login_id, :admin_pass , :salt , '1', '0', '0', '1', '1', current_timestamp, current_timestamp,'管理者','EC-CUBE SHOP');");
657
                $sth->execute(array(':login_id' => $this->session_data['login_id'], ':admin_pass' => $encodedPassword, ':salt' => $salt));
658
            }
659
660
            $sth = $this->PDO->prepare('UPDATE dtb_base_info set
661
                shop_name = :shop_name,
662
                email01 = :admin_mail,
663
                email02 = :admin_mail,
664
                email03 = :admin_mail,
665
                email04 = :admin_mail,
666
                update_date = current_timestamp
667
            WHERE id = 1;');
668
            $sth->execute(array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
669
                ':shop_name' => $this->session_data['shop_name'],
670
                ':admin_mail' => $this->session_data['email']
671
            ));
672
673
            $this->PDO->commit();
674
        } catch (\Exception $e) {
675
            $this->PDO->rollback();
676
            throw $e;
677
        }
678
679
        return $this;
680
    }
681
682
683
    private function getMigration()
684
    {
685
        $eccube = \Eccube\Application::getInstance();
686
        $eccube->initialize();
687
        $eccube->boot();
688
689
        $config = new Configuration($eccube['db']);
690
        $config->setMigrationsNamespace('DoctrineMigrations');
691
692
        $migrationDir = __DIR__ . '/../../Resource/doctrine/migration';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
693
        $config->setMigrationsDirectory($migrationDir);
694
        $config->registerMigrationsFromDirectory($migrationDir);
695
696
        $migration = new Migration($config);
697
698
        return $migration;
699
    }
700
701
    private function doMigrate()
702
    {
703
        try {
704
            $migration = $this->getMigration();
705
706
            // DBとのコネクションを維持するためpingさせる
707
            if (is_null($this->PDO)) {
708
                $this->setPDO();
709
            }
710
            $this->PDO->ping();
711
712
            // nullを渡すと最新バージョンまでマイグレートする
713
            $migration->migrate(null, false);
714
        } catch (MigrationException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
715
        }
716
717
        return $this;
718
    }
719
720 1
    private function getProtectedDirs()
721
    {
722 1
        $protectedDirs = array();
723 1
        $base = $this->app->rootDir;
724
        $dirs = array(
725
            '/html',
726
            '/app',
727
            '/app/template',
728
            '/app/cache',
729
            '/app/config',
730
            '/app/config/eccube',
731
            '/app/log',
732
            '/app/Plugin',
733 1
        );
734
735
        foreach ($dirs as $dir) {
736
            if (!is_writable($base . $dir)) {
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
737
                $protectedDirs[] = $dir;
738
            }
739
        }
740
741 1
        return $protectedDirs;
742
    }
743
744
    private function createConfigYamlFile($data, $auth = true)
745
    {
746
        $fs = new Filesystem();
747
        $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
748
749
        if ($fs->exists($config_file)) {
750
            $config = Yaml::parse(file_get_contents($config_file));
751
            $fs->remove($config_file);
752
        }
753
754
        if ($auth) {
755
            $auth_magic = Str::random(32);
756
        } else {
757
            if (isset($config['auth_magic'])) {
758
                $auth_magic = $config['auth_magic'];
759
            } else {
760
                $auth_magic = Str::random(32);
761
            }
762
        }
763
764
        $allowHost = Str::convertLineFeed($data['admin_allow_hosts']);
765
        if (empty($allowHost)) {
766
            $adminAllowHosts = array();
767
        } else {
768
            $adminAllowHosts = explode("\n", $allowHost);
769
        }
770
771
        $target = array('${AUTH_MAGIC}', '${SHOP_NAME}', '${ECCUBE_INSTALL}', '${FORCE_SSL}');
772
        $replace = array($auth_magic, $data['shop_name'], '0', $data['admin_force_ssl']);
773
774
        $fs = new Filesystem();
775
        $content = str_replace(
776
            $target,
777
            $replace,
778
            file_get_contents($this->dist_path . '/config.yml.dist')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
779
        );
780
        $fs->dumpFile($config_file, $content);
781
782
        $config = Yaml::parse(file_get_contents($config_file));
783
        $config['admin_allow_host'] = $adminAllowHosts;
784
        $yml = Yaml::dump($config);
785
        file_put_contents($config_file, $yml);
786
787
        return $this;
788
    }
789
790
    private function addInstallStatus()
791
    {
792
        $config_file = $this->config_path . '/config.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
793
        $config = Yaml::parse(file_get_contents($config_file));
794
        $config['eccube_install'] = 1;
795
        $yml = Yaml::dump($config);
796
        file_put_contents($config_file, $yml);
797
798
        return $this;
799
    }
800
801
    private function createDatabaseYamlFile($data)
802
    {
803
        $fs = new Filesystem();
804
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
805
        if ($fs->exists($config_file)) {
806
            $fs->remove($config_file);
807
        }
808
809
        if ($data['database'] != 'pdo_sqlite') {
810
            switch ($data['database']) {
811
                case 'pdo_pgsql':
812
                    if (empty($data['db_port'])) {
813
                        $data['db_port'] = '5432';
814
                    }
815
                    $data['db_driver'] = 'pdo_pgsql';
816
                    break;
817
                case 'pdo_mysql':
818
                    if (empty($data['db_port'])) {
819
                        $data['db_port'] = '3306';
820
                    }
821
                    $data['db_driver'] = 'pdo_mysql';
822
                    break;
823
            }
824
            $target = array('${DBDRIVER}', '${DBSERVER}', '${DBNAME}', '${DBPORT}', '${DBUSER}', '${DBPASS}');
825
            $replace = array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
826
                $data['db_driver'],
827
                $data['database_host'],
828
                $data['database_name'],
829
                $data['database_port'],
830
                $data['database_user'],
831
                $data['database_password']
832
            );
833
834
            $fs = new Filesystem();
835
            $content = str_replace(
836
                $target,
837
                $replace,
838
                file_get_contents($this->dist_path . '/database.yml.dist')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
839
            );
840
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
841
        } else {
842
            $content = Yaml::dump(
843
                array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
844
                    'database' => array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
845
                        'driver' => 'pdo_sqlite',
846
                        'path' => realpath($this->config_path.'/eccube.db')
847
                    )
848
                )
849
            );
850
        }
851
        $fs->dumpFile($config_file, $content);
852
853
        return $this;
854
    }
855
856
    private function createMailYamlFile($data)
857
    {
858
        $fs = new Filesystem();
859
        $config_file = $this->config_path . '/mail.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
860
        if ($fs->exists($config_file)) {
861
            $fs->remove($config_file);
862
        }
863
        $target = array('${MAIL_BACKEND}', '${MAIL_HOST}', '${MAIL_PORT}', '${MAIL_USER}', '${MAIL_PASS}');
864
        $replace = array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
865
            $data['mail_backend'],
866
            $data['smtp_host'],
867
            $data['smtp_port'],
868
            $data['smtp_username'],
869
            $data['smtp_password']
870
        );
871
872
        $fs = new Filesystem();
873
        $content = str_replace(
874
            $target,
875
            $replace,
876
            file_get_contents($this->dist_path . '/mail.yml.dist')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
877
        );
878
        $fs->dumpFile($config_file, $content);
879
880
        return $this;
881
    }
882
883
    private function createPathYamlFile($data, Request $request)
884
    {
885
        $fs = new Filesystem();
886
        $config_file = $this->config_path . '/path.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
887
        if ($fs->exists($config_file)) {
888
            $fs->remove($config_file);
889
        }
890
891
        $ADMIN_ROUTE = $data['admin_dir'];
892
        $TEMPLATE_CODE = 'default';
893
        $USER_DATA_ROUTE = 'user_data';
894
        $ROOT_DIR = realpath($this->app->rootDir);
895
        $ROOT_URLPATH = $request->getBasePath();
896
897
        $target = array('${ADMIN_ROUTE}', '${TEMPLATE_CODE}', '${USER_DATA_ROUTE}', '${ROOT_DIR}', '${ROOT_URLPATH}');
898
        $replace = array($ADMIN_ROUTE, $TEMPLATE_CODE, $USER_DATA_ROUTE, $ROOT_DIR, $ROOT_URLPATH);
899
900
        $fs = new Filesystem();
901
        $content = str_replace(
902
            $target,
903
            $replace,
904
            file_get_contents($this->dist_path . '/path.yml.dist')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
905
        );
906
        $fs->dumpFile($config_file, $content);
907
908
        return $this;
909
    }
910
911
    private function sendAppData($params)
912
    {
913
        $config_file = $this->config_path . '/database.yml';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
914
        $db_config = Yaml::parse(file_get_contents($config_file));
915
916
        $this->setPDO();
917
        $stmt = $this->PDO->query('select version() as v');
918
919
        $version = '';
920
        foreach ($stmt as $row) {
921
            $version = $row['v'];
922
        }
923
924
        if ($db_config['database']['driver'] === 'pdo_mysql') {
925
            $db_ver = 'MySQL:' . $version;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
926
        } else {
927
            $db_ver = $version;
928
        }
929
930
        $data = http_build_query(
931
            array(
932
                'site_url' => $params['http_url'],
933
                'shop_name' => $params['shop_name'],
934
                'cube_ver' => Constant::VERSION,
935
                'php_ver' => phpversion(),
936
                'db_ver' => $db_ver,
937
                'os_type' => php_uname(),
938
            )
939
        );
940
941
        $header = array(
942
            'Content-Type: application/x-www-form-urlencoded',
943
            'Content-Length: ' . strlen($data),
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
944
        );
945
        $context = stream_context_create(
946
            array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
947
                'http' => array(
948
                    'method' => 'POST',
949
                    'header' => $header,
950
                    'content' => $data,
951
                )
952
            )
953
        );
954
        file_get_contents('http://www.ec-cube.net/mall/use_site.php', false, $context);
955
956
        return $this;
957
    }
958
}
959