PluginController   F
last analyzed

Complexity

Total Complexity 81

Size/Duplication

Total Lines 723
Duplicated Lines 7.19 %

Coupling/Cohesion

Components 2
Dependencies 12

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 81
lcom 2
cbo 12
dl 52
loc 723
ccs 0
cts 324
cp 0
rs 3.4285
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
D index() 0 105 14
B update() 0 57 7
A enable() 19 19 3
A disable() 19 19 3
A uninstall() 0 17 2
A handler() 0 15 2
A handler_up() 7 7 1
A handler_down() 7 7 1
B install() 0 56 7
D ownersInstall() 0 109 16
C upgrade() 0 89 10
B authenticationSetting() 0 40 3
B getRequestApi() 0 30 1
A getResponseErrorMessage() 0 14 2
D getUnregisteredPlugins() 0 36 9

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like PluginController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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

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

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 Eccube\Application;
28
use Eccube\Common\Constant;
29
use Eccube\Controller\AbstractController;
30
use Eccube\Exception\PluginException;
31
use Eccube\Util\Str;
32
use Monolog\Logger;
33
use Symfony\Component\Filesystem\Filesystem;
34
use Symfony\Component\Finder\Finder;
35
use Symfony\Component\HttpFoundation\Request;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
use Symfony\Component\Routing\Exception\RouteNotFoundException;
38
use Symfony\Component\Validator\Constraints as Assert;
39
40
class PluginController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
41
{
42
43
    /**
44
     * インストール済プラグイン画面
45
     *
46
     * @param Application $app
47
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
48
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
49
    public function index(Application $app, Request $request)
50
    {
51
52
        $pluginForms = array();
53
        $configPages = array();
54
55
        $Plugins = $app['eccube.repository.plugin']->findBy(array(), array('code' => 'ASC'));
56
57
        // ファイル設置プラグインの取得.
58
        $unregisterdPlugins = $this->getUnregisteredPlugins($Plugins, $app);
59
        $unregisterdPluginsConfigPages = array();
60
        foreach ($unregisterdPlugins as $unregisterdPlugin) {
61
            try {
62
                $code = $unregisterdPlugin['code'];
63
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
64
                $unregisterdPluginsConfigPages[$code] = $app->url('plugin_'.$code.'_config');
65
            } catch (RouteNotFoundException $e) {
66
                // プラグインで設定画面のルートが定義されていない場合は無視
67
            }
68
        }
69
70
        $officialPlugins = array();
71
        $unofficialPlugins = array();
72
73
        foreach ($Plugins as $Plugin) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
74
75
            $form = $app['form.factory']
76
                ->createNamedBuilder('form'.$Plugin->getId(), 'plugin_management', null, array(
77
                    'plugin_id' => $Plugin->getId(),
78
                ))
79
                ->getForm();
80
81
            $pluginForms[$Plugin->getId()] = $form->createView();
82
83
            try {
84
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
85
                $configPages[$Plugin->getCode()] = $app->url('plugin_'.$Plugin->getCode().'_config');
86
            } catch (\Exception $e) {
87
                // プラグインで設定画面のルートが定義されていない場合は無視
88
            }
89
90
            if ($Plugin->getSource() == 0) {
91
                // 商品IDが設定されていない場合、非公式プラグイン
92
                $unofficialPlugins[] = $Plugin;
93
            } else {
94
                $officialPlugins[] = $Plugin;
95
            }
96
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
97
        }
98
99
        // オーナーズストアからダウンロード可能プラグイン情報を取得
100
        $BaseInfo = $app['eccube.repository.base_info']->get();
101
102
        $authKey = $BaseInfo->getAuthenticationKey();
103
104
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
105
106
            // オーナーズストア通信
107
            $url = $app['config']['owners_store_url'].'?method=list';
108
            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...
109
110
            if ($json) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
111
112
                // 接続成功時
113
114
                $data = json_decode($json, true);
115
116
                if (isset($data['success'])) {
117
                    $success = $data['success'];
118
                    if ($success == '1') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
119
120
                        // 既にインストールされているかどうか確認
121
                        foreach ($data['item'] as $item) {
122
                            foreach ($officialPlugins as $plugin) {
123
                                if ($plugin->getSource() == $item['product_id']) {
124
                                    // 商品IDが同一の情報を設定
125
                                    $plugin->setNewVersion($item['version']);
126
                                    $plugin->setLastUpdateDate($item['last_update_date']);
127
                                    $plugin->setProductUrl($item['product_url']);
128
                                    $plugin->setEccubeVersion($item['eccube_version']);
129
130
                                    if ($plugin->getVersion() != $item['version']) {
131
                                        // バージョンが異なる
132
                                        $plugin->setUpdateStatus(3);
133
                                        break;
134
                                    }
135
                                }
136
                            }
137
                        }
138
                    }
139
                }
140
            }
141
        }
142
143
144
        return $app->render('Store/plugin.twig', array(
145
            'plugin_forms' => $pluginForms,
146
            'officialPlugins' => $officialPlugins,
147
            'unofficialPlugins' => $unofficialPlugins,
148
            'configPages' => $configPages,
149
            'unregisterdPlugins' => $unregisterdPlugins,
150
            'unregisterdPluginsConfigPages' => $unregisterdPluginsConfigPages,
151
        ));
152
153
    }
154
155
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
156
     * インストール済プラグインからのアップデート
157
     *
158
     * @param Application $app
159
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
160
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
161
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
162
    public function update(Application $app, Request $request, $id)
163
    {
164
165
        $Plugin = $app['eccube.repository.plugin']->find($id);
166
167
        $form = $app['form.factory']
168
            ->createNamedBuilder('form'.$id, 'plugin_management', null, array(
169
                'plugin_id' => null, // placeHolder
170
            ))
171
            ->getForm();
172
173
        $message = '';
174
175
        if ('POST' === $request->getMethod()) {
176
            $form->handleRequest($request);
177
178
            if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
179
180
                $tmpDir = null;
181
                try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
182
183
                    $formFile = $form['plugin_archive']->getData();
184
185
                    $tmpDir = $app['eccube.service.plugin']->createTempDir();
186
                    $tmpFile = sha1(Str::random(32)).'.'.$formFile->getClientOriginalExtension();
187
188
                    $formFile->move($tmpDir, $tmpFile);
189
                    $app['eccube.service.plugin']->update($Plugin, $tmpDir.'/'.$tmpFile);
190
191
                    $fs = new Filesystem();
192
                    $fs->remove($tmpDir);
193
194
                    $app->addSuccess('admin.plugin.update.complete', 'admin');
195
196
                    return $app->redirect($app->url('admin_store_plugin'));
197
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
198
                } catch (PluginException $e) {
199
                    if (!empty($tmpDir) && file_exists($tmpDir)) {
200
                        $fs = new Filesystem();
201
                        $fs->remove($tmpDir);
202
                    }
203
                    $message = $e->getMessage();
204
                }
205
            } else {
206
                $errors = $form->getErrors(true);
207
                foreach ($errors as $error) {
208
                    $message = $error->getMessage();
209
                }
210
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
211
            }
212
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
213
        }
214
215
        $app->addError($message, 'admin');
216
217
        return $app->redirect($app->url('admin_store_plugin'));
218
    }
219
220
221
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
222
     * 対象のプラグインを有効にします。
223
     *
224
     * @param Application $app
225
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
226
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
227 View Code Duplication
    public function enable(Application $app, $id)
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...
228
    {
229
        $this->isTokenValid($app);
230
231
        $Plugin = $app['eccube.repository.plugin']->find($id);
232
233
        if (!$Plugin) {
234
            throw new NotFoundHttpException();
235
        }
236
237
        if ($Plugin->getEnable() == Constant::ENABLED) {
238
            $app->addError('admin.plugin.already.enable', 'admin');
239
        } else {
240
            $app['eccube.service.plugin']->enable($Plugin);
241
            $app->addSuccess('admin.plugin.enable.complete', 'admin');
242
        }
243
244
        return $app->redirect($app->url('admin_store_plugin'));
245
    }
246
247
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
248
     * 対象のプラグインを無効にします。
249
     *
250
     * @param Application $app
251
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
252
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
253 View Code Duplication
    public function disable(Application $app, $id)
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...
254
    {
255
        $this->isTokenValid($app);
256
257
        $Plugin = $app['eccube.repository.plugin']->find($id);
258
259
        if (!$Plugin) {
260
            throw new NotFoundHttpException();
261
        }
262
263
        if ($Plugin->getEnable() == Constant::ENABLED) {
264
            $app['eccube.service.plugin']->disable($Plugin);
265
            $app->addSuccess('admin.plugin.disable.complete', 'admin');
266
        } else {
267
            $app->addError('admin.plugin.already.disable', 'admin');
268
        }
269
270
        return $app->redirect($app->url('admin_store_plugin'));
271
    }
272
273
274
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
275
     * 対象のプラグインを削除します。
276
     *
277
     * @param Application $app
278
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
279
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
280
    public function uninstall(Application $app, $id)
281
    {
282
        $this->isTokenValid($app);
283
284
        $Plugin = $app['eccube.repository.plugin']->find($id);
285
286
        if (!$Plugin) {
287
            $app->deleteMessage();
288
            return $app->redirect($app->url('admin_store_plugin'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
289
        }
290
291
        $app['eccube.service.plugin']->uninstall($Plugin);
292
293
        $app->addSuccess('admin.plugin.uninstall.complete', 'admin');
294
295
        return $app->redirect($app->url('admin_store_plugin'));
296
    }
297
298
    public function handler(Application $app)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
299
    {
300
        $handlers = $app['eccube.repository.plugin_event_handler']->getHandlers();
301
302
        // 一次元配列からイベント毎の二次元配列に変換する
303
        $HandlersPerEvent = array();
304
        foreach ($handlers as $handler) {
305
            $HandlersPerEvent[$handler->getEvent()][$handler->getHandlerType()][] = $handler;
306
        }
307
308
        return $app->render('Store/plugin_handler.twig', array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
309
            'handlersPerEvent' => $HandlersPerEvent
310
        ));
311
312
    }
313
314 View Code Duplication
    public function handler_up(Application $app, $handlerId)
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...
introduced by
Missing function doc comment
Loading history...
Coding Style introduced by
Method name "PluginController::handler_up" is not in camel caps format
Loading history...
315
    {
316
        $repo = $app['eccube.repository.plugin_event_handler'];
317
        $repo->upPriority($repo->find($handlerId));
318
319
        return $app->redirect($app->url('admin_store_plugin_handler'));
320
    }
321
322 View Code Duplication
    public function handler_down(Application $app, $handlerId)
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...
introduced by
Missing function doc comment
Loading history...
Coding Style introduced by
Method name "PluginController::handler_down" is not in camel caps format
Loading history...
323
    {
324
        $repo = $app['eccube.repository.plugin_event_handler'];
325
        $repo->upPriority($repo->find($handlerId), false);
326
327
        return $app->redirect($app->url('admin_store_plugin_handler'));
328
    }
329
330
    /**
331
     * プラグインファイルアップロード画面
332
     *
333
     * @param Application $app
334
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
335
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
336
    public function install(Application $app, Request $request)
337
    {
338
        $form = $app['form.factory']
339
            ->createBuilder('plugin_local_install')
340
            ->getForm();
341
342
        $errors = array();
343
344
        if ('POST' === $request->getMethod()) {
345
            $form->handleRequest($request);
346
347
            if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
348
349
                $tmpDir = null;
350
                try {
351
                    $service = $app['eccube.service.plugin'];
352
353
                    $formFile = $form['plugin_archive']->getData();
354
355
                    $tmpDir = $service->createTempDir();
356
                    $tmpFile = sha1(Str::random(32)).'.'.$formFile->getClientOriginalExtension(); // 拡張子を付けないとpharが動かないので付ける
357
358
                    $formFile->move($tmpDir, $tmpFile);
359
360
                    $service->install($tmpDir.'/'.$tmpFile);
361
362
                    $fs = new Filesystem();
363
                    $fs->remove($tmpDir);
364
365
                    $app->addSuccess('admin.plugin.install.complete', 'admin');
366
367
                    return $app->redirect($app->url('admin_store_plugin'));
368
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
369
                } catch (PluginException $e) {
370
                    if (!empty($tmpDir) && file_exists($tmpDir)) {
371
                        $fs = new Filesystem();
372
                        $fs->remove($tmpDir);
373
                    }
374
                    $app['monolog']->error("plugin install failed.", array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
375
                        'original-message' => $e->getMessage()
376
                    ));
377
                    $errors[] = $e;
378
                }
379
            } else {
380
                foreach ($form->getErrors(true) as $error) {
381
                    $errors[] = $error;
382
                }
383
            }
384
        }
385
386
        return $app->render('Store/plugin_install.twig', array(
387
            'form' => $form->createView(),
388
            'errors' => $errors,
389
        ));
390
391
    }
392
393
    /**
394
     * オーナーズストアプラグインインストール画面
395
     *
396
     * @param Application $app
397
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
398
     * @return \Symfony\Component\HttpFoundation\Response
399
     */
400
    public function ownersInstall(Application $app, Request $request)
401
    {
402
        // オーナーズストアからダウンロード可能プラグイン情報を取得
403
        $BaseInfo = $app['eccube.repository.base_info']->get();
404
405
        $authKey = $BaseInfo->getAuthenticationKey();
406
        $authResult = true;
407
        $success = 0;
408
        $items = array();
409
        $promotionItems = array();
410
        $message = '';
411
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
412
413
            // オーナーズストア通信
414
            $url = $app['config']['owners_store_url'].'?method=list';
415
            list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
416
417
            if ($json === false) {
418
                // 接続失敗時
419
                $success = 0;
420
421
                $message = $this->getResponseErrorMessage($info);
422
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
423
            } else {
424
                // 接続成功時
425
426
                $data = json_decode($json, true);
427
428
                if (isset($data['success'])) {
429
                    $success = $data['success'];
430
                    if ($success == '1') {
431
                        $items = array();
432
433
                        // 既にインストールされているかどうか確認
434
                        $Plugins = $app['eccube.repository.plugin']->findAll();
435
                        $status = false;
436
                        // update_status 1 : 未インストール、2 : インストール済、 3 : 更新あり、4 : 有料購入
437
                        foreach ($data['item'] as $item) {
438
                            foreach ($Plugins as $plugin) {
439
                                if ($plugin->getSource() == $item['product_id']) {
440
                                    if ($plugin->getVersion() == $item['version']) {
441
                                        // バージョンが同じ
442
                                        $item['update_status'] = 2;
443
                                    } else {
444
                                        // バージョンが異なる
445
                                        $item['update_status'] = 3;
446
                                    }
447
                                    $items[] = $item;
448
                                    $status = true;
449
                                    break;
450
                                }
451
                            }
452
                            if (!$status) {
453
                                // 未インストール
454
                                $item['update_status'] = 1;
455
                                $items[] = $item;
456
                            }
457
                            $status = false;
458
                        }
459
460
                        // EC-CUBEのバージョンチェック
461
                        // 参照渡しをして値を追加
462
                        foreach ($items as &$item) {
463
                            if (in_array(Constant::VERSION, $item['eccube_version'])) {
464
                                // 対象バージョン
465
                                $item['version_check'] = 1;
466
                            } else {
467
                                // 未対象バージョン
468
                                $item['version_check'] = 0;
469
                            }
470
                            if ($item['price'] != '0' && $item['purchased'] == '0') {
471
                                // 有料商品で未購入
472
                                $item['update_status'] = 4;
473
                            }
474
                        }
475
                        unset($item);
476
477
                        // promotionアイテム
478
                        $i = 0;
479
                        foreach ($items as $item) {
480
                            if ($item['promotion'] == 1) {
481
                                $promotionItems[] = $item;
482
                                unset($items[$i]);
483
                            }
484
                            $i++;
485
                        }
486
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
487
                    } else {
488
                        $message = $data['error_code'].' : '.$data['error_message'];
489
                    }
490
                } else {
491
                    $success = 0;
492
                    $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
493
                }
494
            }
495
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
496
        } else {
497
            $authResult = false;
498
        }
499
500
        return $app->render('Store/plugin_owners_install.twig', array(
501
            'authResult' => $authResult,
502
            'success' => $success,
503
            'items' => $items,
504
            'promotionItems' => $promotionItems,
505
            'message' => $message,
506
        ));
507
508
    }
509
510
    /**
0 ignored issues
show
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...
511
     * オーナーズブラグインインストール、アップデート
512
     *
513
     * @param Application $app
514
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
515
     * @param $action
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
516
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
517
     * @param $version
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
518
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
519
    public function upgrade(Application $app, Request $request, $action, $id, $version)
520
    {
521
522
        $BaseInfo = $app['eccube.repository.base_info']->get();
523
524
        $authKey = $BaseInfo->getAuthenticationKey();
525
        $message = '';
526
527
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
528
529
            // オーナーズストア通信
530
            $url = $app['config']['owners_store_url'].'?method=download&product_id='.$id;
531
            list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
532
533
            if ($json === false) {
534
                // 接続失敗時
535
536
                $message = $this->getResponseErrorMessage($info);
537
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
538
            } else {
539
                // 接続成功時
540
541
                $data = json_decode($json, true);
542
543
                if (isset($data['success'])) {
544
                    $success = $data['success'];
545
                    if ($success == '1') {
546
                        $tmpDir = null;
547
                        try {
548
                            $service = $app['eccube.service.plugin'];
549
550
                            $item = $data['item'];
551
                            $file = base64_decode($item['data']);
552
                            $extension = pathinfo($item['file_name'], PATHINFO_EXTENSION);
553
554
                            $tmpDir = $service->createTempDir();
555
                            $tmpFile = sha1(Str::random(32)).'.'.$extension;
556
557
                            // ファイル作成
558
                            $fs = new Filesystem();
559
                            $fs->dumpFile($tmpDir.'/'.$tmpFile, $file);
560
561
                            if ($action == 'install') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
562
563
                                $service->install($tmpDir.'/'.$tmpFile, $id);
564
                                $app->addSuccess('admin.plugin.install.complete', 'admin');
565
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
566
                            } else if ($action == 'update') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
567
568
                                $Plugin = $app['eccube.repository.plugin']->findOneBy(array('source' => $id));
569
570
                                $service->update($Plugin, $tmpDir.'/'.$tmpFile);
571
                                $app->addSuccess('admin.plugin.update.complete', 'admin');
572
                            }
573
574
                            $fs = new Filesystem();
575
                            $fs->remove($tmpDir);
576
577
                            // ダウンロード完了通知処理(正常終了時)
578
                            $url = $app['config']['owners_store_url'].'?method=commit&product_id='.$id.'&status=1&version='.$version;
579
                            $this->getRequestApi($request, $authKey, $url, $app);
580
581
                            return $app->redirect($app->url('admin_store_plugin'));
582
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
583
                        } catch (PluginException $e) {
584
                            if (!empty($tmpDir) && file_exists($tmpDir)) {
585
                                $fs = new Filesystem();
586
                                $fs->remove($tmpDir);
587
                            }
588
                            $message = $e->getMessage();
589
                        }
590
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
591
                    } else {
592
                        $message = $data['error_code'].' : '.$data['error_message'];
593
                    }
594
                } else {
595
                    $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
596
                }
597
            }
598
        }
599
600
        // ダウンロード完了通知処理(エラー発生時)
601
        $url = $app['config']['owners_store_url'].'?method=commit&product_id='.$id.'&status=0&version='.$version.'&message='.urlencode($message);
602
        $this->getRequestApi($request, $authKey, $url, $app);
603
604
        $app->addError($message, 'admin');
605
606
        return $app->redirect($app->url('admin_store_plugin_owners_install'));
607
    }
608
609
    /**
610
     * 認証キー設定画面
611
     *
612
     * @param Application $app
613
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
614
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
615
    public function authenticationSetting(Application $app, Request $request)
616
    {
617
618
        $form = $app->form()->getForm();
619
620
        $BaseInfo = $app['eccube.repository.base_info']->get();
621
622
        // 認証キーの取得
623
        $form->add(
624
            'authentication_key', 'text', array(
625
            'label' => '認証キー',
626
            'constraints' => array(
627
                new Assert\Regex(array(
628
                    'pattern' => "/^[0-9a-zA-Z]+$/",
629
                )),
630
            ),
631
            'data' => $BaseInfo->getAuthenticationKey(),
632
        ));
633
634
        if ('POST' === $request->getMethod()) {
635
            $form->handleRequest($request);
636
637
            if ($form->isValid()) {
638
                $data = $form->getData();
639
640
                // 認証キーの登録
641
                $BaseInfo->setAuthenticationKey($data['authentication_key']);
642
                $app['orm.em']->flush($BaseInfo);
643
644
                $app->addSuccess('admin.plugin.authentication.setting.complete', 'admin');
645
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
646
            }
647
        }
648
649
650
        return $app->render('Store/authentication_setting.twig', array(
651
            'form' => $form->createView(),
652
        ));
653
654
    }
655
656
657
    /**
658
     * APIリクエスト処理
659
     *
660
     * @param Request $request
661
     * @param $authKey
662
     * @param string $url
663
     * @param Application $app
664
     * @return array
665
     */
666
    private function getRequestApi(Request $request, $authKey, $url, $app)
667
    {
668
        $curl = curl_init($url);
669
670
        $options = array(           // オプション配列
671
            //HEADER
672
            CURLOPT_HTTPHEADER => array(
673
                'Authorization: '.base64_encode($authKey),
674
                'x-eccube-store-url: '.base64_encode($request->getSchemeAndHttpHost().$request->getBasePath()),
675
                'x-eccube-store-version: '.base64_encode(Constant::VERSION),
676
            ),
677
            CURLOPT_HTTPGET => true,
678
            CURLOPT_SSL_VERIFYPEER => true,
679
            CURLOPT_RETURNTRANSFER => true,
680
            CURLOPT_FAILONERROR => true,
681
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
682
        );
683
684
        curl_setopt_array($curl, $options); /// オプション値を設定
685
        $result = curl_exec($curl);
686
        $info = curl_getinfo($curl);
687
688
        $message = curl_error($curl);
689
        $info['message'] = $message;
690
        curl_close($curl);
691
692
        $app->log('http get_info', $info);
693
694
        return array($result, $info);
695
    }
696
697
    /**
698
     * レスポンスのチェック
699
     *
700
     * @param $info
701
     * @return string
702
     */
703
    private function getResponseErrorMessage($info)
704
    {
705
        if (!empty($info)) {
706
            $statusCode = $info['http_code'];
707
            $message = $info['message'];
708
709
            $message = $statusCode.' : '.$message;
710
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
711
        } else {
712
            $message = "タイムアウトエラーまたはURLの指定に誤りがあります。";
713
        }
714
715
        return $message;
716
    }
717
718
719
    /**
720
     * フォルダ設置のみのプラグインを取得する.
721
     *
722
     * @param array $plugins
723
     * @param Application $app
724
     * @return array
725
     */
726
    protected function getUnregisteredPlugins(array $plugins, \Eccube\Application $app)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
727
    {
728
        $finder = new Finder();
729
        $pluginCodes = array();
730
731
        // DB登録済みプラグインコードのみ取得
732
        foreach ($plugins as $key => $plugin) {
733
            $pluginCodes[] = $plugin->getCode();
734
        }
735
        // DB登録済みプラグインコードPluginディレクトリから排他
736
        $dirs = $finder->in($app['config']['plugin_realdir'])->depth(0)->directories();
737
738
        // プラグイン基本チェック
739
        $unregisteredPlugins = array();
740
        foreach ($dirs as $dir) {
741
            $pluginCode = $dir->getBasename();
742
            if (in_array($pluginCode, $pluginCodes, true)) {
743
                continue;
744
            }
745
            try {
746
                $app['eccube.service.plugin']->checkPluginArchiveContent($dir->getRealPath());
747
            } catch (\Eccube\Exception\PluginException $e) {
748
                //config.yamlに不備があった際は全てスキップ
749
                $app['monolog']->warning($e->getMessage());
750
                continue;
751
            }
752
            $config = $app['eccube.service.plugin']->readYml($dir->getRealPath().'/config.yml');
753
            $unregisteredPlugins[$pluginCode]['name'] = isset($config['name']) ? $config['name'] : null;
754
            $unregisteredPlugins[$pluginCode]['event'] = isset($config['event']) ? $config['event'] : null;
755
            $unregisteredPlugins[$pluginCode]['version'] = isset($config['version']) ? $config['version'] : null;
756
            $unregisteredPlugins[$pluginCode]['enable'] = Constant::DISABLED;
757
            $unregisteredPlugins[$pluginCode]['code'] = isset($config['code']) ? $config['code'] : null;
758
        }
759
760
        return $unregisteredPlugins;
761
    }
762
}
763