Failed Conditions
Push — experimental/3.1 ( e41384...3768d9 )
by Ryo
103:48 queued 80:20
created

PluginController::uninstall()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 10
ccs 0
cts 2
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
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\Admin\Store;
26
27
use Doctrine\ORM\EntityManager;
28
use Eccube\Annotation\Inject;
29
use Eccube\Application;
30
use Eccube\Common\Constant;
31
use Eccube\Controller\AbstractController;
32
use Eccube\Entity\BaseInfo;
33
use Eccube\Entity\Plugin;
34
use Eccube\Entity\PluginEventHandler;
35
use Eccube\Exception\PluginException;
36
use Eccube\Form\Type\Admin\PluginLocalInstallType;
37
use Eccube\Form\Type\Admin\PluginManagementType;
38
use Eccube\Repository\PluginEventHandlerRepository;
39
use Eccube\Repository\PluginRepository;
40
use Eccube\Service\PluginService;
41
use Eccube\Util\Str;
42
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
43
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
44
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
45
use Symfony\Bridge\Monolog\Logger;
46
use Symfony\Component\Filesystem\Filesystem;
47
use Symfony\Component\Finder\Finder;
48
use Symfony\Component\Form\Extension\Core\Type\FormType;
49
use Symfony\Component\Form\Extension\Core\Type\TextType;
50
use Symfony\Component\Form\FormFactory;
51
use Symfony\Component\HttpFoundation\Request;
52
use Symfony\Component\Routing\Exception\RouteNotFoundException;
53
use Symfony\Component\Validator\Constraints as Assert;
54
55
/**
56
 * @Route(service=PluginController::class)
57
 */
58
class PluginController extends AbstractController
59
{
60
    /**
61
     * @Inject("orm.em")
62
     * @var EntityManager
63
     */
64
    protected $entityManager;
65
66
    /**
67
     * @Inject("monolog")
68
     * @var Logger
69
     */
70
    protected $logger;
71
72
    /**
73
     * @Inject(PluginEventHandlerRepository::class)
74
     * @var PluginEventHandlerRepository
75
     */
76
    protected $pluginEventHandlerRepository;
77
78
    /**
79
     * @Inject(PluginService::class)
80
     * @var PluginService
81
     */
82
    protected $pluginService;
83
84
    /**
85
     * @Inject("config")
86
     * @var array
87
     */
88
    protected $appConfig;
89
90
    /**
91
     * @Inject(BaseInfo::class)
92
     * @var BaseInfo
93
     */
94
    protected $BaseInfo;
95
96
    /**
97
     * @Inject("form.factory")
98
     * @var FormFactory
99
     */
100
    protected $formFactory;
101
102
    /**
103
     * @Inject(PluginRepository::class)
104
     * @var PluginRepository
105
     */
106
    protected $pluginRepository;
107
108
109
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
110
     * インストール済プラグイン画面
111
     *
112
     * @Route("/{_admin}/store/plugin", name="admin_store_plugin")
113
     * @Template("Store/plugin.twig")
114
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
115
    public function index(Application $app, Request $request)
116
    {
117
        $pluginForms = array();
118
        $configPages = array();
119
120
        $Plugins = $this->pluginRepository->findBy(array(), array('code' => 'ASC'));
121
122
        // ファイル設置プラグインの取得.
123
        $unregisterdPlugins = $this->getUnregisteredPlugins($Plugins, $app);
124
        $unregisterdPluginsConfigPages = array();
125
        foreach ($unregisterdPlugins as $unregisterdPlugin) {
126
            try {
127
                $code = $unregisterdPlugin['code'];
128
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
129
                $unregisterdPluginsConfigPages[$code] = $app->url('plugin_'.$code.'_config');
130
            } catch (RouteNotFoundException $e) {
131
                // プラグインで設定画面のルートが定義されていない場合は無視
132
            }
133
        }
134
135
        $officialPlugins = array();
136
        $unofficialPlugins = array();
137
138
        foreach ($Plugins as $Plugin) {
139
            $form = $this->formFactory
140
                ->createNamedBuilder(
141
                    'form'.$Plugin->getId(),
142
                    PluginManagementType::class,
143
                    null,
144
                    array(
145
                        'plugin_id' => $Plugin->getId(),
146
                    )
147
                )
148
                ->getForm();
149
            $pluginForms[$Plugin->getId()] = $form->createView();
150
151
            try {
152
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
153
                $configPages[$Plugin->getCode()] = $app->url('plugin_'.$Plugin->getCode().'_config');
154
            } catch (\Exception $e) {
155
                // プラグインで設定画面のルートが定義されていない場合は無視
156
            }
157
158
            if ($Plugin->getSource() == 0) {
159
                // 商品IDが設定されていない場合、非公式プラグイン
160
                $unofficialPlugins[] = $Plugin;
161
            } else {
162
                $officialPlugins[] = $Plugin;
163
            }
164
        }
165
166
        // Todo: Need new authentication mechanism
167
        // オーナーズストアからダウンロード可能プラグイン情報を取得
168
        $authKey = $this->BaseInfo->getAuthenticationKey();
169
//        if (!is_null($authKey)) {
170
171
        // オーナーズストア通信
172
        $url = $this->appConfig['owners_store_url'].'?method=list';
173
        list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
0 ignored issues
show
Unused Code introduced by
The assignment to $info is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
174
175
        $officialPluginsDetail = [];
176
        if ($json) {
177
            // 接続成功時
178
            $data = json_decode($json, true);
179
            if (isset($data['success'])) {
180
                $success = $data['success'];
181
                if ($success == '1') {
182
                    foreach ($data['item'] as $item) {
183
                        foreach ($officialPlugins as $key => $plugin) {
184
                            if ($plugin->getSource() == $item['product_id']) {
185
                                $officialPluginsDetail[$key] = $item;
186
                                $officialPluginsDetail[$key]['update_status'] = 0;
187
                                if ($plugin->getVersion() != $item['version']) {
188
                                    $officialPluginsDetail[$key]['update_status'] = 1;
189
                                }
190
                            }
191
                        }
192
                    }
193
                }
194
            }
195
        }
196
197
        return [
198
            'plugin_forms' => $pluginForms,
199
            'officialPlugins' => $officialPlugins,
200
            'unofficialPlugins' => $unofficialPlugins,
201
            'configPages' => $configPages,
202
            'unregisterdPlugins' => $unregisterdPlugins,
203
            'unregisterdPluginsConfigPages' => $unregisterdPluginsConfigPages,
204
            'officialPluginsDetail' => $officialPluginsDetail,
205
        ];
206
    }
207
208
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$Plugin" missing
Loading history...
209
     * インストール済プラグインからのアップデート
210
     *
211
     * @Method("POST")
212
     * @Route("/{_admin}/store/plugin/{id}/update", requirements={"id" = "\d+"}, name="admin_store_plugin_update")
213
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
214
    public function update(Application $app, Request $request, Plugin $Plugin)
215
    {
216
        $form = $this->formFactory
217
            ->createNamedBuilder(
218
                'form'.$Plugin->getId(),
219
                PluginManagementType::class,
220
                null,
221
                array(
222
                    'plugin_id' => null, // placeHolder
223
                )
224
            )
225
            ->getForm();
226
227
        $message = '';
228
229
        if ('POST' === $request->getMethod()) {
230
            $form->handleRequest($request);
231
232
            if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
233
234
                $tmpDir = null;
235
                try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
236
237
                    $formFile = $form['plugin_archive']->getData();
238
239
                    $tmpDir = $this->pluginService->createTempDir();
240
                    $tmpFile = sha1(Str::random(32)).'.'.$formFile->getClientOriginalExtension();
241
242
                    $formFile->move($tmpDir, $tmpFile);
243
                    $this->pluginService->update($Plugin, $tmpDir.'/'.$tmpFile);
244
245
                    $fs = new Filesystem();
246
                    $fs->remove($tmpDir);
247
248
                    $app->addSuccess('admin.plugin.update.complete', 'admin');
249
250
                    return $app->redirect($app->url('admin_store_plugin'));
251
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
252
                } catch (PluginException $e) {
253
                    if (!empty($tmpDir) && file_exists($tmpDir)) {
254
                        $fs = new Filesystem();
255
                        $fs->remove($tmpDir);
256
                    }
257
                    $message = $e->getMessage();
258
                }
259
            } else {
260
                $errors = $form->getErrors(true);
261
                foreach ($errors as $error) {
262
                    $message = $error->getMessage();
0 ignored issues
show
Bug introduced by
The method getMessage() does not seem to exist on object<Symfony\Component\Form\FormErrorIterator>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
263
                }
264
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
265
            }
266
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
267
        }
268
269
        $app->addError($message, 'admin');
270
271
        return $app->redirect($app->url('admin_store_plugin'));
272
    }
273
274
275
    /**
276
     * 対象のプラグインを有効にします。
277
     *
278
     * @Method("PUT")
279
     * @Route("/{_admin}/store/plugin/{id}/enable", requirements={"id" = "\d+"}, name="admin_store_plugin_enable")
280
     * @param Application $app
281
     * @param Plugin      $Plugin
282
     * @return RedirectResponse
283
     */
284
    public function enable(Application $app, Plugin $Plugin)
285
    {
286
        $this->isTokenValid($app);
287
288
        if ($Plugin->getEnable() == Constant::ENABLED) {
289
            $app->addError('admin.plugin.already.enable', 'admin');
290
        } else {
291
            $requires = $this->pluginService->findRequirePluginNeedEnable($Plugin->getCode());
292
            if (!empty($requires)) {
293
                $DependPlugin = $this->pluginRepository->findOneBy(['code' => $requires[0]]);
294
                $dependName = $requires[0];
295
                if ($DependPlugin) {
296
                    $dependName = $DependPlugin->getName();
297
                }
298
                $app->addError($Plugin->getName().'を有効化するためには、先に'.$dependName.'を有効化してください。', 'admin');
299
300
                return $app->redirect($app->url('admin_store_plugin'));
301
            }
302
            $this->pluginService->enable($Plugin);
303
            $app->addSuccess('admin.plugin.enable.complete', 'admin');
304
        }
305
306
        return $app->redirect($app->url('admin_store_plugin'));
307
    }
308
309
    /**
310
     * 対象のプラグインを無効にします。
311
     *
312
     * @Method("PUT")
313
     * @Route("/{_admin}/store/plugin/{id}/disable", requirements={"id" = "\d+"}, name="admin_store_plugin_disable")
314
     * @param Application $app
315
     * @param Plugin      $Plugin
316
     * @return RedirectResponse
317
     */
318
    public function disable(Application $app, Plugin $Plugin)
319
    {
320
        $this->isTokenValid($app);
321
322
        if ($Plugin->getEnable() == Constant::ENABLED) {
323
            $requires = $this->pluginService->findDependentPluginNeedDisable($Plugin->getCode());
324
            if (!empty($requires)) {
325
                $dependName = $requires[0];
326
                $app->addError($Plugin->getName().'を無効化するためには、先に'.$dependName.'を無効化してください。', 'admin');
327
328
                return $app->redirect($app->url('admin_store_plugin'));
329
            }
330
331
            $this->pluginService->disable($Plugin);
332
            $app->addSuccess('admin.plugin.disable.complete', 'admin');
333
        } else {
334
            $app->addError('admin.plugin.already.disable', 'admin');
335
        }
336
337
        return $app->redirect($app->url('admin_store_plugin'));
338
    }
339
340
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$Plugin" missing
Loading history...
341
     * 対象のプラグインを削除します。
342
     *
343
     * @Method("DELETE")
344
     * @Route("/{_admin}/store/plugin/{id}/uninstall", requirements={"id" = "\d+"}, name="admin_store_plugin_uninstall")
345
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
346
    public function uninstall(Application $app, Plugin $Plugin)
347
    {
348
        $this->isTokenValid($app);
349
350
        $this->pluginService->uninstall($Plugin);
351
352
        $app->addSuccess('admin.plugin.uninstall.complete', 'admin');
353
354
        return $app->redirect($app->url('admin_store_plugin'));
355
    }
356
357
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
358
     * @Route("/{_admin}/store/plugin/handler", name="admin_store_plugin_handler")
359
     * @Template("Store/plugin_handler.twig")
360
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
361
    public function handler(Application $app)
0 ignored issues
show
Unused Code introduced by
The parameter $app 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...
362
    {
363
        $handlers = $this->pluginEventHandlerRepository->getHandlers();
364
365
        // 一次元配列からイベント毎の二次元配列に変換する
366
        $HandlersPerEvent = array();
367
        foreach ($handlers as $handler) {
368
            $HandlersPerEvent[$handler->getEvent()][$handler->getHandlerType()][] = $handler;
369
        }
370
371
        return [
372
            'handlersPerEvent' => $HandlersPerEvent,
373
        ];
374
    }
375
376
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$Handler" missing
Loading history...
377
     * @Route("/{_admin}/store/plugin/handler_up/{id}", requirements={"id" = "\d+"}, name="admin_store_plugin_handler_up")
378
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
379 View Code Duplication
    public function handler_up(Application $app, PluginEventHandler $Handler)
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...
Coding Style introduced by
Method name "PluginController::handler_up" is not in camel caps format
Loading history...
380
    {
381
        $repo = $this->pluginEventHandlerRepository;
382
        $repo->upPriority($repo->find($Handler->getId()));
383
384
        return $app->redirect($app->url('admin_store_plugin_handler'));
385
    }
386
387
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$Handler" missing
Loading history...
388
     * @Route("/{_admin}/store/plugin/handler_down/{id}", requirements={"id" = "\d+"}, name="admin_store_plugin_handler_down")
389
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
390 View Code Duplication
    public function handler_down(Application $app, PluginEventHandler $Handler)
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...
Coding Style introduced by
Method name "PluginController::handler_down" is not in camel caps format
Loading history...
391
    {
392
        $repo = $this->pluginEventHandlerRepository;
393
        $repo->upPriority($Handler, false);
394
395
        return $app->redirect($app->url('admin_store_plugin_handler'));
396
    }
397
398
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
399
     * プラグインファイルアップロード画面
400
     *
401
     * @Route("/{_admin}/store/plugin/install", name="admin_store_plugin_install")
402
     * @Template("Store/plugin_install.twig")
403
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
404
    public function install(Application $app, Request $request)
405
    {
406
        $form = $this->formFactory
407
            ->createBuilder(PluginLocalInstallType::class)
408
            ->getForm();
409
410
        $errors = array();
411
412
        if ('POST' === $request->getMethod()) {
413
            $form->handleRequest($request);
414
415
            if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
416
417
                $tmpDir = null;
418
                try {
419
                    $service = $this->pluginService;
420
421
                    $formFile = $form['plugin_archive']->getData();
422
423
                    $tmpDir = $service->createTempDir();
424
                    $tmpFile = sha1(Str::random(32))
425
                        .'.'
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
426
                        .$formFile->getClientOriginalExtension(); // 拡張子を付けないとpharが動かないので付ける
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
427
428
                    $formFile->move($tmpDir, $tmpFile);
429
430
                    $service->install($tmpDir.'/'.$tmpFile);
431
432
                    $fs = new Filesystem();
433
                    $fs->remove($tmpDir);
434
435
                    $app->addSuccess('admin.plugin.install.complete', 'admin');
436
437
                    return $app->redirect($app->url('admin_store_plugin'));
438
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
439
                } catch (PluginException $e) {
440
                    if (!empty($tmpDir) && file_exists($tmpDir)) {
441
                        $fs = new Filesystem();
442
                        $fs->remove($tmpDir);
443
                    }
444
                    $this->logger->error(
445
                        "plugin install failed.",
446
                        array(
447
                            'original-message' => $e->getMessage(),
448
                        )
449
                    );
450
                    $errors[] = $e;
451
                }
452
            } else {
453
                foreach ($form->getErrors(true) as $error) {
454
                    $errors[] = $error;
455
                }
456
            }
457
        }
458
459
        return [
460
            'form' => $form->createView(),
461
            'errors' => $errors,
462
        ];
463
    }
464
465
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
466
     * オーナーズストアプラグインインストール画面
467
     *
468
     * @Route("/{_admin}/store/plugin/owners_install", name="admin_store_plugin_owners_install")
469
     * @Template("Store/plugin_owners_install.twig")
470
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
471
    public function ownersInstall(Application $app, Request $request)
472
    {
473
        // オーナーズストアからダウンロード可能プラグイン情報を取得
474
        $authKey = $this->BaseInfo->getAuthenticationKey();
475
        $authResult = true;
476
        $success = 0;
477
        $items = array();
478
        $promotionItems = array();
479
        $message = '';
480
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
481
482
            // オーナーズストア通信
483
            $url = $this->appConfig['owners_store_url'].'?method=list';
484
            list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
485
486
            if ($json === false) {
487
                // 接続失敗時
488
                $success = 0;
489
490
                $message = $this->getResponseErrorMessage($info);
491
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
492
            } else {
493
                // 接続成功時
494
495
                $data = json_decode($json, true);
496
497
                if (isset($data['success'])) {
498
                    $success = $data['success'];
499
                    if ($success == '1') {
500
                        $items = array();
501
502
                        // 既にインストールされているかどうか確認
503
                        $Plugins = $this->pluginRepository->findAll();
504
                        $status = false;
505
                        // update_status 1 : 未インストール、2 : インストール済、 3 : 更新あり、4 : 有料購入
506
                        foreach ($data['item'] as $item) {
507
                            foreach ($Plugins as $plugin) {
508
                                if ($plugin->getSource() == $item['product_id']) {
509
                                    if ($plugin->getVersion() == $item['version']) {
510
                                        // バージョンが同じ
511
                                        $item['update_status'] = 2;
512
                                    } else {
513
                                        // バージョンが異なる
514
                                        $item['update_status'] = 3;
515
                                    }
516
                                    $items[] = $item;
517
                                    $status = true;
518
                                    break;
519
                                }
520
                            }
521
                            if (!$status) {
522
                                // 未インストール
523
                                $item['update_status'] = 1;
524
                                $items[] = $item;
525
                            }
526
                            $status = false;
527
                        }
528
529
                        // EC-CUBEのバージョンチェック
530
                        // 参照渡しをして値を追加
531
                        foreach ($items as &$item) {
532
                            if (in_array(Constant::VERSION, $item['eccube_version'])) {
533
                                // 対象バージョン
534
                                $item['version_check'] = 1;
535
                            } else {
536
                                // 未対象バージョン
537
                                $item['version_check'] = 0;
538
                            }
539
                            if ($item['price'] != '0' && $item['purchased'] == '0') {
540
                                // 有料商品で未購入
541
                                $item['update_status'] = 4;
542
                            }
543
                        }
544
                        unset($item);
545
546
                        // promotionアイテム
547
                        $i = 0;
548 View Code Duplication
                        foreach ($items as $item) {
549
                            if ($item['promotion'] == 1) {
550
                                $promotionItems[] = $item;
551
                                unset($items[$i]);
552
                            }
553
                            $i++;
554
                        }
555
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
556
                    } else {
557
                        $message = $data['error_code'].' : '.$data['error_message'];
558
                    }
559
                } else {
560
                    $success = 0;
561
                    $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
562
                }
563
            }
564
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
565
        } else {
566
            $authResult = false;
567
        }
568
569
        return [
570
            'authResult' => $authResult,
571
            'success' => $success,
572
            'items' => $items,
573
            'promotionItems' => $promotionItems,
574
            'message' => $message,
575
        ];
576
    }
577
578
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$action" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
introduced by
Doc comment for parameter "$version" missing
Loading history...
579
     * オーナーズブラグインインストール、アップデート
580
     *
581
     * @Route("/{_admin}/store/plugin/upgrade/{action}/{id}/{version}", requirements={"id" = "\d+"}, name="admin_store_plugin_upgrade")
582
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
583
    public function upgrade(Application $app, Request $request, $action, $id, $version)
584
    {
585
        $authKey = $this->BaseInfo->getAuthenticationKey();
586
        $message = '';
587
588
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
589
590
            // オーナーズストア通信
591
            $url = $this->appConfig['owners_store_url'].'?method=download&product_id='.$id;
592
            list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
593
594
            if ($json === false) {
595
                // 接続失敗時
596
597
                $message = $this->getResponseErrorMessage($info);
598
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
599
            } else {
600
                // 接続成功時
601
602
                $data = json_decode($json, true);
603
604
                if (isset($data['success'])) {
605
                    $success = $data['success'];
606
                    if ($success == '1') {
607
                        $tmpDir = null;
608
                        try {
609
                            $service = $this->pluginService;
610
611
                            $item = $data['item'];
612
                            $file = base64_decode($item['data']);
613
                            $extension = pathinfo($item['file_name'], PATHINFO_EXTENSION);
614
615
                            $tmpDir = $service->createTempDir();
616
                            $tmpFile = sha1(Str::random(32)).'.'.$extension;
617
618
                            // ファイル作成
619
                            $fs = new Filesystem();
620
                            $fs->dumpFile($tmpDir.'/'.$tmpFile, $file);
621
622
                            if ($action == 'install') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
623
624
                                $service->install($tmpDir.'/'.$tmpFile, $id);
625
                                $app->addSuccess('admin.plugin.install.complete', 'admin');
626
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
627
                            } else {
628
                                if ($action == 'update') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
629
630
                                    $Plugin = $this->pluginRepository->findOneBy(array('source' => $id));
631
632
                                    $service->update($Plugin, $tmpDir.'/'.$tmpFile);
0 ignored issues
show
Documentation introduced by
$Plugin is of type object|null, but the function expects a object<Eccube\Entity\Plugin>.

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...
633
                                    $app->addSuccess('admin.plugin.update.complete', 'admin');
634
                                }
635
                            }
636
637
                            $fs = new Filesystem();
638
                            $fs->remove($tmpDir);
639
640
                            // ダウンロード完了通知処理(正常終了時)
641
                            $url = $this->appConfig['owners_store_url'].'?method=commit&product_id='.$id.'&status=1&version='.$version;
642
                            $this->getRequestApi($request, $authKey, $url, $app);
643
644
                            return $app->redirect($app->url('admin_store_plugin'));
645
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
646
                        } catch (PluginException $e) {
647
                            if (!empty($tmpDir) && file_exists($tmpDir)) {
648
                                $fs = new Filesystem();
649
                                $fs->remove($tmpDir);
650
                            }
651
                            $message = $e->getMessage();
652
                        }
653
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
654
                    } else {
655
                        $message = $data['error_code'].' : '.$data['error_message'];
656
                    }
657
                } else {
658
                    $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
659
                }
660
            }
661
        }
662
663
        // ダウンロード完了通知処理(エラー発生時)
664
        $url = $this->appConfig['owners_store_url']
665
            .'?method=commit&product_id='.$id
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
666
            .'&status=0&version='.$version
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
667
            .'&message='.urlencode($message);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
668
669
        $this->getRequestApi($request, $authKey, $url, $app);
670
671
        $app->addError($message, 'admin');
672
673
        return $app->redirect($app->url('admin_store_plugin_owners_install'));
674
    }
675
676
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$request" missing
Loading history...
677
     * 認証キー設定画面
678
     *
679
     * @Route("/{_admin}/store/plugin/authentication_setting", name="admin_store_authentication_setting")
680
     * @Template("Store/authentication_setting.twig")
681
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
682
    public function authenticationSetting(Application $app, Request $request)
683
    {
684
        $builder = $this->formFactory
685
            ->createBuilder(FormType::class, $this->BaseInfo);
686
        $builder->add(
687
            'authentication_key',
688
            TextType::class,
689
            [
690
                'label' => '認証キー',
691
                'constraints' => [
692
                    new Assert\Regex(['pattern' => "/^[0-9a-zA-Z]+$/",]),
0 ignored issues
show
introduced by
Add a single space after each comma delimiter
Loading history...
693
                ],
694
            ]
695
        );
696
697
        $form = $builder->getForm();
698
        $form->handleRequest($request);
699
700
        if ($form->isSubmitted() && $form->isValid()) {
701
            // 認証キーの登録
702
            $BaseInfo = $form->getData();
703
            $this->entityManager->flush($BaseInfo);
704
705
            $app->addSuccess('admin.plugin.authentication.setting.complete', 'admin');
706
        }
707
708
        return [
709
            'form' => $form->createView(),
710
        ];
711
    }
712
713
714
    /**
715
     * APIリクエスト処理
716
     *
717
     * @param Request $request
718
     * @param $authKey
719
     * @param string $url
720
     * @param Application $app
721
     * @return array
722
     */
723
    private function getRequestApi(Request $request, $authKey, $url, $app)
724
    {
725
        $curl = curl_init($url);
726
727
        $options = array(           // オプション配列
728
            //HEADER
729
            CURLOPT_HTTPHEADER => array(
730
                'Authorization: '.base64_encode($authKey),
731
                'x-eccube-store-url: '.base64_encode($request->getSchemeAndHttpHost().$request->getBasePath()),
732
                'x-eccube-store-version: '.base64_encode(Constant::VERSION),
733
            ),
734
            CURLOPT_HTTPGET => true,
735
            CURLOPT_SSL_VERIFYPEER => true,
736
            CURLOPT_RETURNTRANSFER => true,
737
            CURLOPT_FAILONERROR => true,
738
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
739
        );
740
741
        curl_setopt_array($curl, $options); /// オプション値を設定
742
        $result = curl_exec($curl);
743
        $info = curl_getinfo($curl);
744
745
        $message = curl_error($curl);
746
        $info['message'] = $message;
747
        curl_close($curl);
748
749
        $app->log('http get_info', $info);
750
751
        return array($result, $info);
752
    }
753
754
    /**
755
     * レスポンスのチェック
756
     *
757
     * @param $info
758
     * @return string
759
     */
760 View Code Duplication
    private function getResponseErrorMessage($info)
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...
761
    {
762
        if (!empty($info)) {
763
            $statusCode = $info['http_code'];
764
            $message = $info['message'];
765
766
            $message = $statusCode.' : '.$message;
767
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
768
        } else {
769
            $message = "タイムアウトエラーまたはURLの指定に誤りがあります。";
770
        }
771
772
        return $message;
773
    }
774
775
776
    /**
777
     * フォルダ設置のみのプラグインを取得する.
778
     *
779
     * @param array $plugins
780
     * @param Application $app
781
     * @return array
782
     */
783
    protected function getUnregisteredPlugins(array $plugins, \Eccube\Application $app)
0 ignored issues
show
Unused Code introduced by
The parameter $app 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...
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
784
    {
785
        $finder = new Finder();
786
        $pluginCodes = array();
787
788
        // DB登録済みプラグインコードのみ取得
789
        foreach ($plugins as $key => $plugin) {
790
            $pluginCodes[] = $plugin->getCode();
791
        }
792
        // DB登録済みプラグインコードPluginディレクトリから排他
793
        $dirs = $finder->in($this->appConfig['plugin_realdir'])->depth(0)->directories();
794
795
        // プラグイン基本チェック
796
        $unregisteredPlugins = array();
797
        foreach ($dirs as $dir) {
798
            $pluginCode = $dir->getBasename();
799
            if (in_array($pluginCode, $pluginCodes, true)) {
800
                continue;
801
            }
802
            try {
803
                $this->pluginService->checkPluginArchiveContent($dir->getRealPath());
804
            } catch (\Eccube\Exception\PluginException $e) {
805
                //config.yamlに不備があった際は全てスキップ
806
                $this->logger->warning($e->getMessage());
807
                continue;
808
            }
809
            $config = $this->pluginService->readYml($dir->getRealPath().'/config.yml');
810
            $unregisteredPlugins[$pluginCode]['name'] = isset($config['name']) ? $config['name'] : null;
811
            $unregisteredPlugins[$pluginCode]['event'] = isset($config['event']) ? $config['event'] : null;
812
            $unregisteredPlugins[$pluginCode]['version'] = isset($config['version']) ? $config['version'] : null;
813
            $unregisteredPlugins[$pluginCode]['enable'] = Constant::DISABLED;
814
            $unregisteredPlugins[$pluginCode]['code'] = isset($config['code']) ? $config['code'] : null;
815
        }
816
817
        return $unregisteredPlugins;
818
    }
819
}
820