Failed Conditions
Push — master ( fc54b8...947180 )
by Yangsin
124:44 queued 119:37
created

PluginController::disable()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 11

Duplication

Lines 19
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 19
loc 19
ccs 0
cts 10
cp 0
rs 9.4285
cc 3
eloc 11
nc 3
nop 2
crap 12
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 Symfony\Component\Filesystem\Filesystem;
33
use Symfony\Component\Finder\Finder;
34
use Symfony\Component\HttpFoundation\Request;
35
use Symfony\Component\HttpFoundation\Response;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
use Symfony\Component\Routing\Exception\RouteNotFoundException;
38
use Symfony\Component\Validator\Constraints as Assert;
39
use Symfony\Component\Form\FormError;
40
use Monolog\Logger;
41
42
class PluginController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
43
{
44
45
    /**
46
     * インストール済プラグイン画面
47
     *
48
     * @param Application $app
49
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
50
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
51
    public function index(Application $app, Request $request)
52
    {
53
54
        $pluginForms = array();
55
        $configPages = array();
56
57
        $Plugins = $app['eccube.repository.plugin']->findBy(array(), array('name' => 'ASC'));
58
59
        // ファイル設置プラグインの取得.
60
        $unregisterdPlugins = $this->getUnregisteredPlugins($Plugins, $app);
61
        $unregisterdPluginsConfigPages = array();
62
        foreach ($unregisterdPlugins as $unregisterdPlugin) {
63
            try {
64
                $code = $unregisterdPlugin['code'];
65
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
66
                $unregisterdPluginsConfigPages[$code] = $app->url('plugin_'.$code.'_config');
67
            } catch (RouteNotFoundException $e) {
68
                // プラグインで設定画面のルートが定義されていない場合は無視
69
            }
70
        }
71
72
        $officialPlugins = array();
73
        $unofficialPlugins = array();
74
75
        foreach ($Plugins as $Plugin) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
76
77
            $form = $app['form.factory']
78
                ->createNamedBuilder('form'.$Plugin->getId(), 'plugin_management', null, array(
79
                    'plugin_id' => $Plugin->getId(),
80
                ))
81
                ->getForm();
82
83
            $pluginForms[$Plugin->getId()] = $form->createView();
84
85
            try {
86
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
87
                $configPages[$Plugin->getCode()] = $app->url('plugin_'.$Plugin->getCode().'_config');
88
            } catch (\Exception $e) {
89
                // プラグインで設定画面のルートが定義されていない場合は無視
90
            }
91
92
            if ($Plugin->getSource() == 0) {
93
                // 商品IDが設定されていない場合、非公式プラグイン
94
                $unofficialPlugins[] = $Plugin;
95
            } else {
96
                $officialPlugins[] = $Plugin;
97
            }
98
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
99
        }
100
101
        // オーナーズストアからダウンロード可能プラグイン情報を取得
102
        $BaseInfo = $app['eccube.repository.base_info']->get();
103
104
        $authKey = $BaseInfo->getAuthenticationKey();
105
106
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
107
108
            // オーナーズストア通信
109
            $url = $app['config']['owners_store_url'].'?method=list';
110
            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...
111
112
            if ($json) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
113
114
                // 接続成功時
115
116
                $data = json_decode($json, true);
117
118
                if (isset($data['success'])) {
119
                    $success = $data['success'];
120
                    if ($success == '1') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
121
122
                        // 既にインストールされているかどうか確認
123
                        foreach ($data['item'] as $item) {
124
                            foreach ($officialPlugins as $plugin) {
125
                                if ($plugin->getSource() == $item['product_id']) {
126
                                    // 商品IDが同一の情報を設定
127
                                    $plugin->setNewVersion($item['version']);
128
                                    $plugin->setLastUpdateDate($item['last_update_date']);
129
                                    $plugin->setProductUrl($item['product_url']);
130
                                    $plugin->setEccubeVersion($item['eccube_version']);
131
132
                                    if ($plugin->getVersion() != $item['version']) {
133
                                        // バージョンが異なる
134
                                        $plugin->setUpdateStatus(3);
135
                                        break;
136
                                    }
137
                                }
138
                            }
139
                        }
140
                    }
141
                }
142
            }
143
        }
144
145
146
        return $app->render('Store/plugin.twig', array(
147
            'plugin_forms' => $pluginForms,
148
            'officialPlugins' => $officialPlugins,
149
            'unofficialPlugins' => $unofficialPlugins,
150
            'configPages' => $configPages,
151
            'unregisterdPlugins' => $unregisterdPlugins,
152
            'unregisterdPluginsConfigPages' => $unregisterdPluginsConfigPages,
153
        ));
154
155
    }
156
157
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
158
     * インストール済プラグインからのアップデート
159
     *
160
     * @param Application $app
161
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
162
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
163
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
164
    public function update(Application $app, Request $request, $id)
165
    {
166
167
        $Plugin = $app['eccube.repository.plugin']->find($id);
168
169
        $form = $app['form.factory']
170
            ->createNamedBuilder('form'.$id, 'plugin_management', null, array(
171
                'plugin_id' => null, // placeHolder
172
            ))
173
            ->getForm();
174
175
        $message = '';
176
177
        if ('POST' === $request->getMethod()) {
178
            $form->handleRequest($request);
179
180
            if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
181
182
                $tmpDir = null;
183
                try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
184
185
                    $formFile = $form['plugin_archive']->getData();
186
187
                    $tmpDir = $app['eccube.service.plugin']->createTempDir();
188
                    $tmpFile = sha1(Str::random(32)).'.'.$formFile->getClientOriginalExtension();
189
190
                    $formFile->move($tmpDir, $tmpFile);
191
                    $app['eccube.service.plugin']->update($Plugin, $tmpDir.'/'.$tmpFile);
192
193
                    $fs = new Filesystem();
194
                    $fs->remove($tmpDir);
195
196
                    $app->addSuccess('admin.plugin.update.complete', 'admin');
197
198
                    return $app->redirect($app->url('admin_store_plugin'));
199
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
200
                } catch (PluginException $e) {
201
                    if (!empty($tmpDir) && file_exists($tmpDir)) {
202
                        $fs = new Filesystem();
203
                        $fs->remove($tmpDir);
204
                    }
205
                    $message = $e->getMessage();
206
                }
207
            } else {
208
                $errors = $form->getErrors(true);
209
                foreach ($errors as $error) {
210
                    $message = $error->getMessage();
211
                }
212
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
213
            }
214
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
215
        }
216
217
        $app->addError($message, 'admin');
218
219
        return $app->redirect($app->url('admin_store_plugin'));
220
    }
221
222
223
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
224
     * 対象のプラグインを有効にします。
225
     *
226
     * @param Application $app
227
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
228
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
229 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...
230
    {
231
        $this->isTokenValid($app);
232
233
        $Plugin = $app['eccube.repository.plugin']->find($id);
234
235
        if (!$Plugin) {
236
            throw new NotFoundHttpException();
237
        }
238
239
        if ($Plugin->getEnable() == Constant::ENABLED) {
240
            $app->addError('admin.plugin.already.enable', 'admin');
241
        } else {
242
            $app['eccube.service.plugin']->enable($Plugin);
243
            $app->addSuccess('admin.plugin.enable.complete', 'admin');
244
        }
245
246
        return $app->redirect($app->url('admin_store_plugin'));
247
    }
248
249
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
250
     * 対象のプラグインを無効にします。
251
     *
252
     * @param Application $app
253
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
254
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
255 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...
256
    {
257
        $this->isTokenValid($app);
258
259
        $Plugin = $app['eccube.repository.plugin']->find($id);
260
261
        if (!$Plugin) {
262
            throw new NotFoundHttpException();
263
        }
264
265
        if ($Plugin->getEnable() == Constant::ENABLED) {
266
            $app['eccube.service.plugin']->disable($Plugin);
267
            $app->addSuccess('admin.plugin.disable.complete', 'admin');
268
        } else {
269
            $app->addError('admin.plugin.already.disable', 'admin');
270
        }
271
272
        return $app->redirect($app->url('admin_store_plugin'));
273
    }
274
275
276
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
277
     * 対象のプラグインを削除します。
278
     *
279
     * @param Application $app
280
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
281
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
282
    public function uninstall(Application $app, $id)
283
    {
284
        $this->isTokenValid($app);
285
286
        $Plugin = $app['eccube.repository.plugin']->find($id);
287
288
        if (!$Plugin) {
289
            $app->deleteMessage();
290
            return $app->redirect($app->url('admin_store_plugin'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
291
        }
292
293
        $app['eccube.service.plugin']->uninstall($Plugin);
294
295
        $app->addSuccess('admin.plugin.uninstall.complete', 'admin');
296
297
        return $app->redirect($app->url('admin_store_plugin'));
298
    }
299
300
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
301
     * 対象プラグインの README を返却します。
302
     *
303
     * @param Application $app
304
     * @param unknown $code
0 ignored issues
show
Bug introduced by
There is no parameter named $code. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
introduced by
Doc comment for parameter $code does not match actual variable name $request
Loading history...
305
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
306
    public function readme(Application $app, Request $request, $id)
307
    {
308
        if ($request->isXmlHttpRequest()) {
309
            $Plugin = $app['eccube.repository.plugin']->find($id);
310 View Code Duplication
            if (!$Plugin) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
311
                $response = new Response(json_encode('NG'), 400);
312
                $response->headers->set('Content-Type', 'application/json');
313
                return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
314
            }
315
316
            $code = $Plugin->getCode();
317
            $readme = $app['config'][$code]['const']['readme'];
318
            $data = array(
319
                'code' => $code,
320
                'name' => $Plugin->getName(),
321
                'readme' => $readme,
322
            );
323
324
            $response = new Response(json_encode($data));
325
            $response->headers->set('Content-Type', 'application/json');
326
            return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
327
        }
328
329
        $response = new Response(json_encode('NG'), 400);
330
        $response->headers->set('Content-Type', 'application/json');
331
        return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
332
    }
333
334
    public function handler(Application $app)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
335
    {
336
        $handlers = $app['eccube.repository.plugin_event_handler']->getHandlers();
337
338
        // 一次元配列からイベント毎の二次元配列に変換する
339
        $HandlersPerEvent = array();
340
        foreach ($handlers as $handler) {
341
            $HandlersPerEvent[$handler->getEvent()][$handler->getHandlerType()][] = $handler;
342
        }
343
344
        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...
345
            'handlersPerEvent' => $HandlersPerEvent
346
        ));
347
348
    }
349
350 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...
351
    {
352
        $repo = $app['eccube.repository.plugin_event_handler'];
353
        $repo->upPriority($repo->find($handlerId));
354
355
        return $app->redirect($app->url('admin_store_plugin_handler'));
356
    }
357
358 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...
359
    {
360
        $repo = $app['eccube.repository.plugin_event_handler'];
361
        $repo->upPriority($repo->find($handlerId), false);
362
363
        return $app->redirect($app->url('admin_store_plugin_handler'));
364
    }
365
366
    /**
367
     * プラグインファイルアップロード画面
368
     *
369
     * @param Application $app
370
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
371
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
372
    public function install(Application $app, Request $request)
373
    {
374
        $form = $app['form.factory']
375
            ->createBuilder('plugin_local_install')
376
            ->getForm();
377
378
        $errors = array();
379
380
        if ('POST' === $request->getMethod()) {
381
            $form->handleRequest($request);
382
383
            if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
384
385
                $tmpDir = null;
386
                try {
387
                    $service = $app['eccube.service.plugin'];
388
389
                    $formFile = $form['plugin_archive']->getData();
390
391
                    $tmpDir = $service->createTempDir();
392
                    $tmpFile = sha1(Str::random(32)).'.'.$formFile->getClientOriginalExtension(); // 拡張子を付けないとpharが動かないので付ける
393
394
                    $formFile->move($tmpDir, $tmpFile);
395
396
                    $service->install($tmpDir.'/'.$tmpFile);
397
398
                    $fs = new Filesystem();
399
                    $fs->remove($tmpDir);
400
401
                    $app->addSuccess('admin.plugin.install.complete', 'admin');
402
403
                    return $app->redirect($app->url('admin_store_plugin'));
404
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
405
                } catch (PluginException $e) {
406
                    if (!empty($tmpDir) && file_exists($tmpDir)) {
407
                        $fs = new Filesystem();
408
                        $fs->remove($tmpDir);
409
                    }
410
                    $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...
411
                        'original-message' => $e->getMessage()
412
                    ));
413
                    $errors[] = $e;
414
                }
415
            } else {
416
                foreach ($form->getErrors(true) as $error) {
417
                    $errors[] = $error;
418
                }
419
            }
420
        }
421
422
        return $app->render('Store/plugin_install.twig', array(
423
            'form' => $form->createView(),
424
            'errors' => $errors,
425
        ));
426
427
    }
428
429
    /**
430
     * オーナーズストアプラグインインストール画面
431
     *
432
     * @param Application $app
433
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
434
     * @return \Symfony\Component\HttpFoundation\Response
435
     */
436
    public function ownersInstall(Application $app, Request $request)
437
    {
438
        // オーナーズストアからダウンロード可能プラグイン情報を取得
439
        $BaseInfo = $app['eccube.repository.base_info']->get();
440
441
        $authKey = $BaseInfo->getAuthenticationKey();
442
        $authResult = true;
443
        $success = 0;
444
        $items = array();
445
        $promotionItems = array();
446
        $message = '';
447
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
448
449
            // オーナーズストア通信
450
            $url = $app['config']['owners_store_url'].'?method=list';
451
            list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
452
453
            if ($json === false) {
454
                // 接続失敗時
455
                $success = 0;
456
457
                $message = $this->getResponseErrorMessage($info);
458
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
459
            } else {
460
                // 接続成功時
461
462
                $data = json_decode($json, true);
463
464
                if (isset($data['success'])) {
465
                    $success = $data['success'];
466
                    if ($success == '1') {
467
                        $items = array();
468
469
                        // 既にインストールされているかどうか確認
470
                        $Plugins = $app['eccube.repository.plugin']->findAll();
471
                        $status = false;
472
                        // update_status 1 : 未インストール、2 : インストール済、 3 : 更新あり、4 : 有料購入
473
                        foreach ($data['item'] as $item) {
474
                            foreach ($Plugins as $plugin) {
475
                                if ($plugin->getSource() == $item['product_id']) {
476
                                    if ($plugin->getVersion() == $item['version']) {
477
                                        // バージョンが同じ
478
                                        $item['update_status'] = 2;
479
                                    } else {
480
                                        // バージョンが異なる
481
                                        $item['update_status'] = 3;
482
                                    }
483
                                    $items[] = $item;
484
                                    $status = true;
485
                                    break;
486
                                }
487
                            }
488
                            if (!$status) {
489
                                // 未インストール
490
                                $item['update_status'] = 1;
491
                                $items[] = $item;
492
                            }
493
                            $status = false;
494
                        }
495
496
                        // EC-CUBEのバージョンチェック
497
                        // 参照渡しをして値を追加
498
                        foreach ($items as &$item) {
499
                            if (in_array(Constant::VERSION, $item['eccube_version'])) {
500
                                // 対象バージョン
501
                                $item['version_check'] = 1;
502
                            } else {
503
                                // 未対象バージョン
504
                                $item['version_check'] = 0;
505
                            }
506
                            if ($item['price'] != '0' && $item['purchased'] == '0') {
507
                                // 有料商品で未購入
508
                                $item['update_status'] = 4;
509
                            }
510
                        }
511
                        unset($item);
512
513
                        // promotionアイテム
514
                        $i = 0;
515
                        foreach ($items as $item) {
516
                            if ($item['promotion'] == 1) {
517
                                $promotionItems[] = $item;
518
                                unset($items[$i]);
519
                            }
520
                            $i++;
521
                        }
522
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
523
                    } else {
524
                        $message = $data['error_code'].' : '.$data['error_message'];
525
                    }
526
                } else {
527
                    $success = 0;
528
                    $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
529
                }
530
            }
531
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
532
        } else {
533
            $authResult = false;
534
        }
535
536
        return $app->render('Store/plugin_owners_install.twig', array(
537
            'authResult' => $authResult,
538
            'success' => $success,
539
            'items' => $items,
540
            'promotionItems' => $promotionItems,
541
            'message' => $message,
542
        ));
543
544
    }
545
546
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$action" missing
Loading history...
introduced by
Doc comment for parameter "$version" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
547
     * オーナーズブラグインインストール、アップデート
548
     *
549
     * @param Application $app
550
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
551
     * @param $action
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
552
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
553
     * @param $version
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
554
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
555
    public function upgrade(Application $app, Request $request, $action, $id, $version)
556
    {
557
558
        $BaseInfo = $app['eccube.repository.base_info']->get();
559
560
        $authKey = $BaseInfo->getAuthenticationKey();
561
        $message = '';
562
563
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
564
565
            // オーナーズストア通信
566
            $url = $app['config']['owners_store_url'].'?method=download&product_id='.$id;
567
            list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
568
569
            if ($json === false) {
570
                // 接続失敗時
571
572
                $message = $this->getResponseErrorMessage($info);
573
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
574
            } else {
575
                // 接続成功時
576
577
                $data = json_decode($json, true);
578
579
                if (isset($data['success'])) {
580
                    $success = $data['success'];
581
                    if ($success == '1') {
582
                        $tmpDir = null;
583
                        try {
584
                            $service = $app['eccube.service.plugin'];
585
586
                            $item = $data['item'];
587
                            $file = base64_decode($item['data']);
588
                            $extension = pathinfo($item['file_name'], PATHINFO_EXTENSION);
589
590
                            $tmpDir = $service->createTempDir();
591
                            $tmpFile = sha1(Str::random(32)).'.'.$extension;
592
593
                            // ファイル作成
594
                            $fs = new Filesystem();
595
                            $fs->dumpFile($tmpDir.'/'.$tmpFile, $file);
596
597
                            if ($action == 'install') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
598
599
                                $service->install($tmpDir.'/'.$tmpFile, $id);
600
                                $app->addSuccess('admin.plugin.install.complete', 'admin');
601
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
602
                            } else if ($action == 'update') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
603
604
                                $Plugin = $app['eccube.repository.plugin']->findOneBy(array('source' => $id));
605
606
                                $service->update($Plugin, $tmpDir.'/'.$tmpFile);
607
                                $app->addSuccess('admin.plugin.update.complete', 'admin');
608
                            }
609
610
                            $fs = new Filesystem();
611
                            $fs->remove($tmpDir);
612
613
                            // ダウンロード完了通知処理(正常終了時)
614
                            $url = $app['config']['owners_store_url'].'?method=commit&product_id='.$id.'&status=1&version='.$version;
615
                            $this->getRequestApi($request, $authKey, $url, $app);
616
617
                            return $app->redirect($app->url('admin_store_plugin'));
618
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
619
                        } catch (PluginException $e) {
620
                            if (!empty($tmpDir) && file_exists($tmpDir)) {
621
                                $fs = new Filesystem();
622
                                $fs->remove($tmpDir);
623
                            }
624
                            $message = $e->getMessage();
625
                        }
626
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
627
                    } else {
628
                        $message = $data['error_code'].' : '.$data['error_message'];
629
                    }
630
                } else {
631
                    $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
632
                }
633
            }
634
        }
635
636
        // ダウンロード完了通知処理(エラー発生時)
637
        $url = $app['config']['owners_store_url'].'?method=commit&product_id='.$id.'&status=0&version='.$version.'&message='.urlencode($message);
638
        $this->getRequestApi($request, $authKey, $url, $app);
639
640
        $app->addError($message, 'admin');
641
642
        return $app->redirect($app->url('admin_store_plugin_owners_install'));
643
    }
644
645
    /**
646
     * 認証キー設定画面
647
     *
648
     * @param Application $app
649
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
650
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
651
    public function authenticationSetting(Application $app, Request $request)
652
    {
653
654
        $form = $app->form()->getForm();
655
656
        $BaseInfo = $app['eccube.repository.base_info']->get();
657
658
        // 認証キーの取得
659
        $form->add(
660
            'authentication_key', 'text', array(
661
            'label' => '認証キー',
662
            'constraints' => array(
663
                new Assert\Regex(array(
664
                    'pattern' => "/^[0-9a-zA-Z]+$/",
665
                )),
666
            ),
667
            'data' => $BaseInfo->getAuthenticationKey(),
668
        ));
669
670
        if ('POST' === $request->getMethod()) {
671
            $form->handleRequest($request);
672
673
            if ($form->isValid()) {
674
                $data = $form->getData();
675
676
                // 認証キーの登録
677
                $BaseInfo->setAuthenticationKey($data['authentication_key']);
678
                $app['orm.em']->flush($BaseInfo);
679
680
                $app->addSuccess('admin.plugin.authentication.setting.complete', 'admin');
681
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
682
            }
683
        }
684
685
686
        return $app->render('Store/authentication_setting.twig', array(
687
            'form' => $form->createView(),
688
        ));
689
690
    }
691
692
693
    /**
694
     * APIリクエスト処理
695
     *
696
     * @param Request $request
697
     * @param $authKey
698
     * @param string $url
699
     * @param Application $app
700
     * @return array
701
     */
702
    private function getRequestApi(Request $request, $authKey, $url, $app)
703
    {
704
        $curl = curl_init($url);
705
706
        $options = array(           // オプション配列
707
            //HEADER
708
            CURLOPT_HTTPHEADER => array(
709
                'Authorization: '.base64_encode($authKey),
710
                'x-eccube-store-url: '.base64_encode($request->getSchemeAndHttpHost().$request->getBasePath()),
711
                'x-eccube-store-version: '.base64_encode(Constant::VERSION),
712
            ),
713
            CURLOPT_HTTPGET => true,
714
            CURLOPT_SSL_VERIFYPEER => true,
715
            CURLOPT_RETURNTRANSFER => true,
716
            CURLOPT_FAILONERROR => true,
717
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
718
        );
719
720
        curl_setopt_array($curl, $options); /// オプション値を設定
721
        $result = curl_exec($curl);
722
        $info = curl_getinfo($curl);
723
724
        $message = curl_error($curl);
725
        $info['message'] = $message;
726
        curl_close($curl);
727
728
        $app->log('http get_info', $info);
729
730
        return array($result, $info);
731
    }
732
733
    /**
734
     * レスポンスのチェック
735
     *
736
     * @param $info
737
     * @return string
738
     */
739
    private function getResponseErrorMessage($info)
740
    {
741
        if (!empty($info)) {
742
            $statusCode = $info['http_code'];
743
            $message = $info['message'];
744
745
            $message = $statusCode.' : '.$message;
746
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
747
        } else {
748
            $message = "タイムアウトエラーまたはURLの指定に誤りがあります。";
749
        }
750
751
        return $message;
752
    }
753
754
755
    /**
756
     * フォルダ設置のみのプラグインを取得する.
757
     *
758
     * @param array $plugins
759
     * @param Application $app
760
     * @return array
761
     */
762
    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...
763
    {
764
        $finder = new Finder();
765
        $pluginCodes = array();
766
767
        // DB登録済みプラグインコードのみ取得
768
        foreach ($plugins as $key => $plugin) {
769
            $pluginCodes[] = $plugin->getCode();
770
        }
771
        // DB登録済みプラグインコードPluginディレクトリから排他
772
        $dirs = $finder->in($app['config']['plugin_realdir'])->depth(0)->directories();
773
774
        // プラグイン基本チェック
775
        $unregisteredPlugins = array();
776
        foreach ($dirs as $dir) {
777
            $pluginCode = $dir->getBasename();
778
            if (in_array($pluginCode, $pluginCodes, true)) {
779
                continue;
780
            }
781
            try {
782
                $app['eccube.service.plugin']->checkPluginArchiveContent($dir->getRealPath());
783
            } catch (\Eccube\Exception\PluginException $e) {
784
                //config.yamlに不備があった際は全てスキップ
785
                $app['monolog']->warning($e->getMessage());
786
                continue;
787
            }
788
            $config = $app['eccube.service.plugin']->readYml($dir->getRealPath().'/config.yml');
789
            $unregisteredPlugins[$pluginCode]['name'] = isset($config['name']) ? $config['name'] : null;
790
            $unregisteredPlugins[$pluginCode]['event'] = isset($config['event']) ? $config['event'] : null;
791
            $unregisteredPlugins[$pluginCode]['version'] = isset($config['version']) ? $config['version'] : null;
792
            $unregisteredPlugins[$pluginCode]['enable'] = Constant::DISABLED;
793
            $unregisteredPlugins[$pluginCode]['code'] = isset($config['code']) ? $config['code'] : null;
794
        }
795
796
        return $unregisteredPlugins;
797
    }
798
}
799