Failed Conditions
Push — 4.0 ( 31bfc5...86a776 )
by Kiyotaka
06:13
created

PluginController::authenticationCaptcha()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
nc 4
nop 1
dl 0
loc 23
ccs 0
cts 9
cp 0
crap 56
rs 8.6186
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller\Admin\Store;
15
16
use Eccube\Common\Constant;
17
use Eccube\Controller\AbstractController;
18
use Eccube\Entity\BaseInfo;
19
use Eccube\Entity\Plugin;
20
use Eccube\Entity\PluginEventHandler;
21
use Eccube\Exception\PluginException;
22
use Eccube\Form\Type\Admin\CaptchaType;
23
use Eccube\Form\Type\Admin\AuthenticationType;
24
use Eccube\Form\Type\Admin\PluginLocalInstallType;
25
use Eccube\Form\Type\Admin\PluginManagementType;
26
use Eccube\Repository\BaseInfoRepository;
27
use Eccube\Repository\PluginEventHandlerRepository;
28
use Eccube\Repository\PluginRepository;
29
use Eccube\Service\PluginApiService;
30
use Eccube\Service\PluginService;
31
use Eccube\Util\CacheUtil;
32
use Eccube\Util\StringUtil;
33
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
34
use Symfony\Component\DependencyInjection\Container;
35
use Symfony\Component\Filesystem\Filesystem;
36
use Symfony\Component\Finder\Finder;
37
use Symfony\Component\Form\Extension\Core\Type\FormType;
38
use Symfony\Component\Form\Extension\Core\Type\TextType;
39
use Symfony\Component\HttpFoundation\File\UploadedFile;
40
use Symfony\Component\HttpFoundation\RedirectResponse;
41
use Symfony\Component\HttpFoundation\Request;
42
use Symfony\Component\Routing\Annotation\Route;
43
use Symfony\Component\Routing\Exception\RouteNotFoundException;
44
use Symfony\Component\Validator\Constraints as Assert;
45
46
class PluginController extends AbstractController
47
{
48
    /**
49
     * @var PluginEventHandlerRepository
50
     */
51
    protected $pluginEventHandlerRepository;
52
53
    /**
54
     * @var PluginService
55
     */
56
    protected $pluginService;
57
58
    /**
59
     * @var BaseInfo
60
     */
61
    protected $BaseInfo;
62
63
    /**
64
     * @var PluginRepository
65
     */
66
    protected $pluginRepository;
67
68
    /**
69
     * @var PluginApiService
70
     */
71
    protected $pluginApiService;
72
73
    /**
74
     * PluginController constructor.
75
     *
76
     * @param PluginRepository $pluginRepository
77
     * @param PluginService $pluginService
78
     * @param PluginEventHandlerRepository $eventHandlerRepository
79
     * @param BaseInfoRepository $baseInfoRepository
80
     * @param PluginApiService $pluginApiService
81
     * @throws \Doctrine\ORM\NoResultException
82
     * @throws \Doctrine\ORM\NonUniqueResultException
83
     */
84
    public function __construct(PluginRepository $pluginRepository, PluginService $pluginService, PluginEventHandlerRepository $eventHandlerRepository, BaseInfoRepository $baseInfoRepository, PluginApiService $pluginApiService)
85
    {
86
        $this->pluginRepository = $pluginRepository;
87
        $this->pluginService = $pluginService;
88
        $this->pluginEventHandlerRepository = $eventHandlerRepository;
89
        $this->BaseInfo = $baseInfoRepository->get();
90
        $this->pluginApiService = $pluginApiService;
91
    }
92
93
    /**
94
     * インストール済プラグイン画面
95
     *
96
     * @Route("/%eccube_admin_route%/store/plugin", name="admin_store_plugin")
97
     * @Template("@admin/Store/plugin.twig")
98
     */
99
    public function index(Request $request)
100
    {
101
        $pluginForms = [];
102
        $configPages = [];
103
        $Plugins = $this->pluginRepository->findBy([], ['code' => 'ASC']);
104
105
        // ファイル設置プラグインの取得.
106
        $unregisterdPlugins = $this->getUnregisteredPlugins($Plugins);
107
        $unregisterdPluginsConfigPages = [];
108
        foreach ($unregisterdPlugins as $unregisterdPlugin) {
109
            try {
110
                $code = $unregisterdPlugin['code'];
111
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
112
                $unregisterdPluginsConfigPages[$code] = $this->generateUrl('plugin_'.$code.'_config');
113
            } catch (RouteNotFoundException $e) {
114
                // プラグインで設定画面のルートが定義されていない場合は無視
115
            }
116
        }
117
118
        $officialPlugins = [];
119
        $unofficialPlugins = [];
120
121
        foreach ($Plugins as $Plugin) {
122
            $form = $this->formFactory
123
                ->createNamedBuilder(
124
                    'form'.$Plugin->getId(),
125
                    PluginManagementType::class,
126
                    null,
127
                    [
128
                        'plugin_id' => $Plugin->getId(),
129
                    ]
130
                )
131
                ->getForm();
132
            $pluginForms[$Plugin->getId()] = $form->createView();
133
134
            try {
135
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
136
                $configPages[$Plugin->getCode()] = $this->generateUrl(Container::underscore($Plugin->getCode()).'_admin_config');
137
            } catch (\Exception $e) {
138
                // プラグインで設定画面のルートが定義されていない場合は無視
139
            }
140
            if ($Plugin->getSource() == 0) {
141
                // 商品IDが設定されていない場合、非公式プラグイン
142
                $unofficialPlugins[] = $Plugin;
143
            } else {
144
                $officialPlugins[$Plugin->getSource()] = $Plugin;
145
            }
146
        }
147
148
        // Todo: Need new authentication mechanism
149
        // オーナーズストアからダウンロード可能プラグイン情報を取得
150
        $authKey = $this->BaseInfo->getAuthenticationKey();
151
        // オーナーズストア通信
152
        // TODO: get url from api service instead of direct from controller
153
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/plugins/purchased';
154
        list($json, $info) = $this->getRequestApi($request, $authKey, $url);
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...
Deprecated Code introduced by
The method Eccube\Controller\Admin\...roller::getRequestApi() has been deprecated with message: since release, please refer PluginApiService

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
155
        $officialPluginsDetail = [];
156
        if ($json) {
157
            // 接続成功時
158
            $data = json_decode($json, true);
159
            foreach ($data as $item) {
160
                if (isset($officialPlugins[$item['id']])) {
161
                    $Plugin = $officialPlugins[$item['id']];
162
                    $officialPluginsDetail[$item['id']] = $item;
163
                    $officialPluginsDetail[$item['id']]['update_status'] = 0;
164 View Code Duplication
                    if ($this->pluginService->isUpdate($Plugin->getVersion(), $item['version'])) {
165
                        $officialPluginsDetail[$item['id']]['update_status'] = 1;
166
                    }
167
                } else {
168
                    $Plugin = new Plugin();
169
                    $Plugin->setName($item['name']);
170
                    $Plugin->setCode($item['code']);
171
                    $Plugin->setVersion($item['version']);
172
                    $Plugin->setSource($item['id']);
173
                    $Plugin->setEnabled(false);
174
                    $officialPlugins[$item['id']] = $Plugin;
175
                    $officialPluginsDetail[$item['id']] = $item;
176
                    $officialPluginsDetail[$item['id']]['update_status'] = 0;
177 View Code Duplication
                    if ($this->pluginService->isUpdate($Plugin->getVersion(), $item['version'])) {
178
                        $officialPluginsDetail[$item['id']]['update_status'] = 1;
179
                    }
180
                }
181
            }
182
        }
183
184
        return [
185
            'plugin_forms' => $pluginForms,
186
            'officialPlugins' => $officialPlugins,
187
            'unofficialPlugins' => $unofficialPlugins,
188
            'configPages' => $configPages,
189
            'unregisterdPlugins' => $unregisterdPlugins,
190
            'unregisterdPluginsConfigPages' => $unregisterdPluginsConfigPages,
191
            'officialPluginsDetail' => $officialPluginsDetail,
192
        ];
193
    }
194
195
    /**
196
     * インストール済プラグインからのアップデート
197
     *
198
     * @Route("/%eccube_admin_route%/store/plugin/{id}/update", requirements={"id" = "\d+"}, name="admin_store_plugin_update", methods={"POST"})
199
     *
200
     * @param Request $request
201
     * @param Plugin $Plugin
202
     *
203
     * @return RedirectResponse
204
     */
205
    public function update(Request $request, Plugin $Plugin)
206
    {
207
        $form = $this->formFactory
208
            ->createNamedBuilder(
209
                'form'.$Plugin->getId(),
210
                PluginManagementType::class,
211
                null,
212
                [
213
                    'plugin_id' => null, // placeHolder
214
                ]
215
            )
216
            ->getForm();
217
218
        $message = '';
219
        $form->handleRequest($request);
220
        if ($form->isSubmitted() && $form->isValid()) {
221
            $tmpDir = null;
222
            try {
223
                $formFile = $form['plugin_archive']->getData();
224
                $tmpDir = $this->pluginService->createTempDir();
225
                $tmpFile = sha1(StringUtil::random(32)).'.'.$formFile->getClientOriginalExtension();
226
                $formFile->move($tmpDir, $tmpFile);
227
                $this->pluginService->update($Plugin, $tmpDir.'/'.$tmpFile);
228
                $fs = new Filesystem();
229
                $fs->remove($tmpDir);
230
                $this->addSuccess('admin.plugin.update.complete', 'admin');
231
232
                return $this->redirectToRoute('admin_store_plugin');
233
            } catch (PluginException $e) {
234
                if (!empty($tmpDir) && file_exists($tmpDir)) {
235
                    $fs = new Filesystem();
236
                    $fs->remove($tmpDir);
237
                }
238
                $message = $e->getMessage();
239
            } catch (\Exception $er) {
240
                // Catch composer install error | Other error
241
                if (!empty($tmpDir) && file_exists($tmpDir)) {
242
                    $fs = new Filesystem();
243
                    $fs->remove($tmpDir);
244
                }
245
                log_error('plugin install failed.', ['original-message' => $er->getMessage()]);
246
                $message = 'admin.plugin.install.fail';
247
            }
248
        } else {
249
            $errors = $form->getErrors(true);
250
            foreach ($errors as $error) {
251
                $message = $error->getMessage();
0 ignored issues
show
Bug introduced by
The method getMessage does only exist in Symfony\Component\Form\FormError, but not in Symfony\Component\Form\FormErrorIterator.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
252
            }
253
        }
254
255
        $this->addError($message, 'admin');
256
257
        return $this->redirectToRoute('admin_store_plugin');
258
    }
259
260
    /**
261
     * 対象のプラグインを有効にします。
262
     *
263
     * @Route("/%eccube_admin_route%/store/plugin/{id}/enable", requirements={"id" = "\d+"}, name="admin_store_plugin_enable", methods={"PUT"})
264
     *
265
     * @param Plugin $Plugin
266
     *
267
     * @return RedirectResponse
268
     */
269 View Code Duplication
    public function enable(Plugin $Plugin, CacheUtil $cacheUtil)
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...
270
    {
271
        $this->isTokenValid();
272
273
        if ($Plugin->isEnabled()) {
274
            $this->addError('admin.plugin.already.enable', 'admin');
275
        } else {
276
            $requires = $this->pluginService->findRequirePluginNeedEnable($Plugin->getCode());
277
            if (!empty($requires)) {
278
                $DependPlugin = $this->pluginRepository->findOneBy(['code' => $requires[0]]);
279
                $dependName = $requires[0];
280
                if ($DependPlugin) {
281
                    $dependName = $DependPlugin->getName();
282
                }
283
                $message = trans('admin.plugin.enable.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
284
                $this->addError($message, 'admin');
285
286
                return $this->redirectToRoute('admin_store_plugin');
287
            }
288
            $this->pluginService->enable($Plugin);
289
            $this->addSuccess('admin.plugin.enable.complete', 'admin');
290
        }
291
292
        // キャッシュを削除してリダイレクト
293
        // リダイレクトにredirectToRoute関数を使用していないのは、削除したキャッシュが再生成されてしまうため。
294
        $url = $this->generateUrl('admin_store_plugin');
295
        $cacheUtil->clearCache();
296
297
        return $this->redirect($url);
298
    }
299
300
    /**
301
     * 対象のプラグインを無効にします。
302
     *
303
     * @Route("/%eccube_admin_route%/store/plugin/{id}/disable", requirements={"id" = "\d+"}, name="admin_store_plugin_disable", methods={"PUT"})
304
     *
305
     * @param Plugin $Plugin
306
     *
307
     * @return RedirectResponse
308
     */
309 View Code Duplication
    public function disable(Plugin $Plugin, CacheUtil $cacheUtil)
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...
310
    {
311
        $this->isTokenValid();
312
313
        if ($Plugin->isEnabled()) {
314
            $dependents = $this->pluginService->findDependentPluginNeedDisable($Plugin->getCode());
315
            if (!empty($dependents)) {
316
                $dependName = $dependents[0];
317
                $DependPlugin = $this->pluginRepository->findOneBy(['code' => $dependents[0]]);
318
                if ($DependPlugin) {
319
                    $dependName = $DependPlugin->getName();
320
                }
321
                $message = trans('admin.plugin.disable.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
322
                $this->addError($message, 'admin');
323
324
                return $this->redirectToRoute('admin_store_plugin');
325
            }
326
327
            $this->pluginService->disable($Plugin);
328
            $this->addSuccess('admin.plugin.disable.complete', 'admin');
329
        } else {
330
            $this->addError('admin.plugin.already.disable', 'admin');
331
332
            return $this->redirectToRoute('admin_store_plugin');
333
        }
334
335
        // キャッシュを削除してリダイレクト
336
        // リダイレクトにredirectToRoute関数を使用していないのは、削除したキャッシュが再生成されてしまうため。
337
        $url = $this->generateUrl('admin_store_plugin');
338
        $cacheUtil->clearCache();
339
340
        return $this->redirect($url);
341
    }
342
343
    /**
344
     * 対象のプラグインを削除します。
345
     *
346
     * @Route("/%eccube_admin_route%/store/plugin/{id}/uninstall", requirements={"id" = "\d+"}, name="admin_store_plugin_uninstall", methods={"DELETE"})
347
     *
348
     * @param Plugin $Plugin
349
     *
350
     * @return RedirectResponse
351
     */
352 View Code Duplication
    public function uninstall(Plugin $Plugin)
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...
353
    {
354
        $this->isTokenValid();
355
356
        if ($Plugin->isEnabled()) {
357
            $this->addError('admin.plugin.uninstall.error.not_disable', 'admin');
358
359
            return $this->redirectToRoute('admin_store_plugin');
360
        }
361
362
        // Check other plugin depend on it
363
        $pluginCode = $Plugin->getCode();
364
        $otherDepend = $this->pluginService->findDependentPlugin($pluginCode);
365
        if (!empty($otherDepend)) {
366
            $DependPlugin = $this->pluginRepository->findOneBy(['code' => $otherDepend[0]]);
367
            $dependName = $otherDepend[0];
368
            if ($DependPlugin) {
369
                $dependName = $DependPlugin->getName();
370
            }
371
            $message = trans('admin.plugin.uninstall.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
372
            $this->addError($message, 'admin');
373
374
            return $this->redirectToRoute('admin_store_plugin');
375
        }
376
377
        $this->pluginService->uninstall($Plugin);
378
        $this->addSuccess('admin.plugin.uninstall.complete', 'admin');
379
380
        return $this->redirectToRoute('admin_store_plugin');
381
    }
382
383
    /**
384
     * @Route("/%eccube_admin_route%/store/plugin/handler", name="admin_store_plugin_handler")
385
     * @Template("@admin/Store/plugin_handler.twig")
386
     */
387
    public function handler()
388
    {
389
        $handlers = $this->pluginEventHandlerRepository->getHandlers();
390
391
        // 一次元配列からイベント毎の二次元配列に変換する
392
        $HandlersPerEvent = [];
393
        foreach ($handlers as $handler) {
394
            $HandlersPerEvent[$handler->getEvent()][$handler->getHandlerType()][] = $handler;
395
        }
396
397
        return [
398
            'handlersPerEvent' => $HandlersPerEvent,
399
        ];
400
    }
401
402
    /**
403
     * @Route("/%eccube_admin_route%/store/plugin/handler_up/{id}", requirements={"id" = "\d+"}, name="admin_store_plugin_handler_up")
404
     */
405
    public function handler_up(PluginEventHandler $Handler)
406
    {
407
        $repo = $this->pluginEventHandlerRepository;
408
        $repo->upPriority($repo->find($Handler->getId()));
409
410
        return $this->redirectToRoute('admin_store_plugin_handler');
411
    }
412
413
    /**
414
     * @Route("/%eccube_admin_route%/store/plugin/handler_down/{id}", requirements={"id" = "\d+"}, name="admin_store_plugin_handler_down")
415
     */
416
    public function handler_down(PluginEventHandler $Handler)
417
    {
418
        $repo = $this->pluginEventHandlerRepository;
419
        $repo->upPriority($Handler, false);
420
421
        return $this->redirectToRoute('admin_store_plugin_handler');
422
    }
423
424
    /**
425
     * プラグインファイルアップロード画面
426
     *
427
     * @Route("/%eccube_admin_route%/store/plugin/install", name="admin_store_plugin_install")
428
     * @Template("@admin/Store/plugin_install.twig")
429
     *
430
     * @param Request $request
431
     *
432
     * @return array|RedirectResponse
433
     */
434
    public function install(Request $request)
435
    {
436
        $form = $this->formFactory
437
            ->createBuilder(PluginLocalInstallType::class)
438
            ->getForm();
439
        $errors = [];
440
        $form->handleRequest($request);
441
        if ($form->isSubmitted() && $form->isValid()) {
442
            $tmpDir = null;
443
            try {
444
                $service = $this->pluginService;
445
                /** @var UploadedFile $formFile */
446
                $formFile = $form['plugin_archive']->getData();
447
                $tmpDir = $service->createTempDir();
448
                // 拡張子を付けないとpharが動かないので付ける
449
                $tmpFile = sha1(StringUtil::random(32)).'.'.$formFile->getClientOriginalExtension();
450
                $formFile->move($tmpDir, $tmpFile);
451
                $tmpPath = $tmpDir.'/'.$tmpFile;
452
                $service->install($tmpPath);
453
                // Remove tmp file
454
                $fs = new Filesystem();
455
                $fs->remove($tmpDir);
456
                $this->addSuccess('admin.plugin.install.complete', 'admin');
457
458
                return $this->redirectToRoute('admin_store_plugin');
459
            } catch (PluginException $e) {
460
                if (!empty($tmpDir) && file_exists($tmpDir)) {
461
                    $fs = new Filesystem();
462
                    $fs->remove($tmpDir);
463
                }
464
                log_error('plugin install failed.', ['original-message' => $e->getMessage()]);
465
                $errors[] = $e;
466
            } catch (\Exception $er) {
467
                // Catch composer install error | Other error
468
                if (!empty($tmpDir) && file_exists($tmpDir)) {
469
                    $fs = new Filesystem();
470
                    $fs->remove($tmpDir);
471
                }
472
                log_error('plugin install failed.', ['original-message' => $er->getMessage()]);
473
                $this->addError('admin.plugin.install.fail', 'admin');
474
            }
475
        } else {
476
            foreach ($form->getErrors(true) as $error) {
477
                $errors[] = $error;
478
            }
479
        }
480
481
        return [
482
            'form' => $form->createView(),
483
            'errors' => $errors,
484
        ];
485
    }
486
487
    /**
488
     * 認証キー設定画面
489
     *
490
     * @Route("/%eccube_admin_route%/store/plugin/authentication_setting", name="admin_store_authentication_setting")
491
     * @Template("@admin/Store/authentication_setting.twig")
492
     */
493
    public function authenticationSetting(Request $request)
494
    {
495
        $builder = $this->formFactory
496
            ->createBuilder(AuthenticationType::class, $this->BaseInfo);
497
498
        $form = $builder->getForm();
499
        $form->handleRequest($request);
500
501
        if ($form->isSubmitted() && $form->isValid()) {
502
            // 認証キーの登録 and PHP path
503
            $this->BaseInfo = $form->getData();
504
            $this->entityManager->persist($this->BaseInfo);
505
            $this->entityManager->flush();
506
507
            $this->addSuccess('admin.flash.register_completed', 'admin');
508
        }
509
510
        $builderCaptcha = $this->formFactory->createBuilder(CaptchaType::class);
511
512
        // get captcha image, save it to temp folder
513
        list($captcha, $info) = $this->pluginApiService->getCaptcha();
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...
514
        $tmpFolder = $this->eccubeConfig->get('eccube_temp_image_dir');
515
        file_put_contents($tmpFolder.'/captcha.png', $captcha);
516
517
        return [
518
            'form' => $form->createView(),
519
            'captchaForm' => $builderCaptcha->getForm()->createView(),
520
        ];
521
    }
522
523
    /**
524
     * Captcha
525
     * Todo: check fail (implement after the api defined)
526
     *
527
     * @param Request $request
528
     * @return RedirectResponse
529
     *
530
     * @Route("/%eccube_admin_route%/store/plugin/auth/captcha", name="admin_store_auth_captcha")
531
     */
532
    public function authenticationCaptcha(Request $request)
533
    {
534
        $builder = $this->formFactory->createBuilder(CaptchaType::class);
535
        $form = $builder->getForm();
536
        $form->handleRequest($request);
537
        if ($form->isSubmitted() && $form->isValid()) {
538
            $param['captcha'] = $form['captcha']->getData();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$param was never initialized. Although not strictly required by PHP, it is generally a good practice to add $param = 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...
539
            list($ret, $info) = $this->pluginApiService->postApiKey($param);
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...
540
            if ($ret && $data = json_decode($ret, true)) {
541
                if (isset($data['api_key']) && !empty($data['api_key'])) {
542
                    $this->BaseInfo->setAuthenticationKey($data['api_key']);
543
                    $this->entityManager->persist($this->BaseInfo);
544
                    $this->entityManager->flush($this->BaseInfo);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $this->BaseInfo.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
545
                    $this->addSuccess('admin.flash.register_completed', 'admin');
546
547
                    return $this->redirectToRoute('admin_store_authentication_setting');
548
                }
549
            }
550
        }
551
        $this->addError('admin.flash.register_failed', 'admin');
552
553
        return $this->redirectToRoute('admin_store_authentication_setting');
554
    }
555
556
    /**
557
     * APIリクエスト処理
558
     *
559
     * @param Request $request
560
     * @param string|null $authKey
561
     * @param string $url
562
     * @deprecated since release, please refer PluginApiService
563
     * @return array
564
     */
565
    private function getRequestApi(Request $request, $authKey, $url)
566
    {
567
        $curl = curl_init($url);
568
569
        $options = [// オプション配列
570
            //HEADER
571
            CURLOPT_HTTPHEADER => [
572
                'Authorization: '.base64_encode($authKey),
573
                'x-eccube-store-url: '.base64_encode($request->getSchemeAndHttpHost().$request->getBasePath()),
574
                'x-eccube-store-version: '.base64_encode(Constant::VERSION),
575
            ],
576
            CURLOPT_HTTPGET => true,
577
            CURLOPT_SSL_VERIFYPEER => true,
578
            CURLOPT_RETURNTRANSFER => true,
579
            CURLOPT_FAILONERROR => true,
580
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
581
        ];
582
583
        curl_setopt_array($curl, $options); /// オプション値を設定
584
        $result = curl_exec($curl);
585
        $info = curl_getinfo($curl);
586
587
        $message = curl_error($curl);
588
        $info['message'] = $message;
589
        curl_close($curl);
590
591
        log_info('http get_info', $info);
592
593
        return [$result, $info];
594
    }
595
596
    /**
597
     * レスポンスのチェック
598
     *
599
     * @param $info
600
     *
601
     * @return string
602
     * @deprecated since release, please refer PluginApiService
603
     */
604 View Code Duplication
    private function getResponseErrorMessage($info)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
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...
605
    {
606
        if (!empty($info)) {
607
            $statusCode = $info['http_code'];
608
            $message = $info['message'];
609
610
            $message = $statusCode.' : '.$message;
611
        } else {
612
            $message = trans('plugin.text.error.timeout_or_invalid_url');
613
        }
614
615
        return $message;
616
    }
617
618
    /**
619
     * フォルダ設置のみのプラグインを取得する.
620
     *
621
     * @param array $plugins
622
     *
623
     * @return array
624
     */
625
    protected function getUnregisteredPlugins(array $plugins)
626
    {
627
        $finder = new Finder();
628
        $pluginCodes = [];
629
630
        // DB登録済みプラグインコードのみ取得
631
        foreach ($plugins as $key => $plugin) {
632
            $pluginCodes[] = $plugin->getCode();
633
        }
634
        // DB登録済みプラグインコードPluginディレクトリから排他
635
        $dirs = $finder->in($this->eccubeConfig['plugin_realdir'])->depth(0)->directories();
636
637
        // プラグイン基本チェック
638
        $unregisteredPlugins = [];
639
        foreach ($dirs as $dir) {
640
            $pluginCode = $dir->getBasename();
641
            if (in_array($pluginCode, $pluginCodes, true)) {
642
                continue;
643
            }
644
            try {
645
                $this->pluginService->checkPluginArchiveContent($dir->getRealPath());
646
            } catch (\Eccube\Exception\PluginException $e) {
647
                //config.yamlに不備があった際は全てスキップ
648
                log_warning($e->getMessage());
649
                continue;
650
            }
651
            $config = $this->pluginService->readYml($dir->getRealPath().'/config.yml');
652
            $unregisteredPlugins[$pluginCode]['name'] = isset($config['name']) ? $config['name'] : null;
653
            $unregisteredPlugins[$pluginCode]['event'] = isset($config['event']) ? $config['event'] : null;
654
            $unregisteredPlugins[$pluginCode]['version'] = isset($config['version']) ? $config['version'] : null;
655
            $unregisteredPlugins[$pluginCode]['enabled'] = Constant::DISABLED;
656
            $unregisteredPlugins[$pluginCode]['code'] = isset($config['code']) ? $config['code'] : null;
657
        }
658
659
        return $unregisteredPlugins;
660
    }
661
}
662