Completed
Pull Request — master (#1910)
by chihiro
60:18 queued 54:32
created

PluginController::readme()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 19

Duplication

Lines 5
Ratio 18.52 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 19
nc 3
nop 3
dl 5
loc 27
ccs 0
cts 18
cp 0
crap 12
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
25
namespace Eccube\Controller\Admin\Store;
26
27
use 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
     * @var string 証明書ファイル
47
     */
48
    private $certFileName = 'cacert.pem';
49
50
    /**
51
     * インストール済プラグイン画面
52
     *
53
     * @param Application $app
54
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
55
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
56
    public function index(Application $app, Request $request)
57
    {
58
59
        $pluginForms = array();
60
        $configPages = array();
61
62
        $Plugins = $app['eccube.repository.plugin']->findBy(array(), array('name' => 'ASC'));
63
64
        // ファイル設置プラグインの取得.
65
        $unregisterdPlugins = $this->getUnregisteredPlugins($Plugins, $app);
66
        $unregisterdPluginsConfigPages = array();
67
        foreach ($unregisterdPlugins as $unregisterdPlugin) {
68
            try {
69
                $code = $unregisterdPlugin['code'];
70
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
71
                $unregisterdPluginsConfigPages[$code] = $app->url('plugin_'.$code.'_config');
72
            } catch (RouteNotFoundException $e) {
73
                // プラグインで設定画面のルートが定義されていない場合は無視
74
            }
75
        }
76
77
        $officialPlugins = array();
78
        $unofficialPlugins = array();
79
80
        foreach ($Plugins as $Plugin) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
81
82
            $form = $app['form.factory']
83
                ->createNamedBuilder('form'.$Plugin->getId(), 'plugin_management', null, array(
84
                    'plugin_id' => $Plugin->getId(),
85
                ))
86
                ->getForm();
87
88
            $pluginForms[$Plugin->getId()] = $form->createView();
89
90
            try {
91
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
92
                $configPages[$Plugin->getCode()] = $app->url('plugin_'.$Plugin->getCode().'_config');
93
            } catch (\Exception $e) {
94
                // プラグインで設定画面のルートが定義されていない場合は無視
95
            }
96
97
            if ($Plugin->getSource() == 0) {
98
                // 商品IDが設定されていない場合、非公式プラグイン
99
                $unofficialPlugins[] = $Plugin;
100
            } else {
101
                $officialPlugins[] = $Plugin;
102
            }
103
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
104
        }
105
106
        // オーナーズストアからダウンロード可能プラグイン情報を取得
107
        $BaseInfo = $app['eccube.repository.base_info']->get();
108
109
        $authKey = $BaseInfo->getAuthenticationKey();
110
111
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
112
113
            // オーナーズストア通信
114
            $url = $app['config']['owners_store_url'].'?method=list';
115
            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...
116
117
            if ($json) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
118
119
                // 接続成功時
120
121
                $data = json_decode($json, true);
122
123
                if (isset($data['success'])) {
124
                    $success = $data['success'];
125
                    if ($success == '1') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
126
127
                        // 既にインストールされているかどうか確認
128
                        foreach ($data['item'] as $item) {
129
                            foreach ($officialPlugins as $plugin) {
130
                                if ($plugin->getSource() == $item['product_id']) {
131
                                    // 商品IDが同一の情報を設定
132
                                    $plugin->setNewVersion($item['version']);
133
                                    $plugin->setLastUpdateDate($item['last_update_date']);
134
                                    $plugin->setProductUrl($item['product_url']);
135
                                    $plugin->setEccubeVersion($item['eccube_version']);
136
137
                                    if ($plugin->getVersion() != $item['version']) {
138
                                        // バージョンが異なる
139
                                        $plugin->setUpdateStatus(3);
140
                                        break;
141
                                    }
142
                                }
143
                            }
144
                        }
145
                    }
146
                }
147
            }
148
        }
149
150
151
        return $app->render('Store/plugin.twig', array(
152
            'plugin_forms' => $pluginForms,
153
            'officialPlugins' => $officialPlugins,
154
            'unofficialPlugins' => $unofficialPlugins,
155
            'configPages' => $configPages,
156
            'unregisterdPlugins' => $unregisterdPlugins,
157
            'unregisterdPluginsConfigPages' => $unregisterdPluginsConfigPages,
158
        ));
159
160
    }
161
162
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
163
     * インストール済プラグインからのアップデート
164
     *
165
     * @param Application $app
166
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
167
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
168
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
169
    public function update(Application $app, Request $request, $id)
170
    {
171
172
        $Plugin = $app['eccube.repository.plugin']->find($id);
173
174
        $form = $app['form.factory']
175
            ->createNamedBuilder('form'.$id, 'plugin_management', null, array(
176
                'plugin_id' => null, // placeHolder
177
            ))
178
            ->getForm();
179
180
        $message = '';
181
182
        if ('POST' === $request->getMethod()) {
183
            $form->handleRequest($request);
184
185
            if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
186
187
                $tmpDir = null;
188
                try {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
189
190
                    $formFile = $form['plugin_archive']->getData();
191
192
                    $tmpDir = $app['eccube.service.plugin']->createTempDir();
193
                    $tmpFile = sha1(Str::random(32)).'.'.$formFile->getClientOriginalExtension();
194
195
                    $formFile->move($tmpDir, $tmpFile);
196
                    $app['eccube.service.plugin']->update($Plugin, $tmpDir.'/'.$tmpFile);
197
198
                    $fs = new Filesystem();
199
                    $fs->remove($tmpDir);
200
201
                    $app->addSuccess('admin.plugin.update.complete', 'admin');
202
203
                    return $app->redirect($app->url('admin_store_plugin'));
204
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
205
                } catch (PluginException $e) {
206
                    if (!empty($tmpDir) && file_exists($tmpDir)) {
207
                        $fs = new Filesystem();
208
                        $fs->remove($tmpDir);
209
                    }
210
                    $message = $e->getMessage();
211
                }
212
            } else {
213
                $errors = $form->getErrors(true);
214
                foreach ($errors as $error) {
215
                    $message = $error->getMessage();
216
                }
217
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
218
            }
219
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
220
        }
221
222
        $app->addError($message, 'admin');
223
224
        return $app->redirect($app->url('admin_store_plugin'));
225
    }
226
227
228
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
229
     * 対象のプラグインを有効にします。
230
     *
231
     * @param Application $app
232
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
233
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
234 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...
235
    {
236
        $this->isTokenValid($app);
237
238
        $Plugin = $app['eccube.repository.plugin']->find($id);
239
240
        if (!$Plugin) {
241
            throw new NotFoundHttpException();
242
        }
243
244
        if ($Plugin->getEnable() == Constant::ENABLED) {
245
            $app->addError('admin.plugin.already.enable', 'admin');
246
        } else {
247
            $app['eccube.service.plugin']->enable($Plugin);
248
            $app->addSuccess('admin.plugin.enable.complete', 'admin');
249
        }
250
251
        return $app->redirect($app->url('admin_store_plugin'));
252
    }
253
254
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
255
     * 対象のプラグインを無効にします。
256
     *
257
     * @param Application $app
258
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
259
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
260 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...
261
    {
262
        $this->isTokenValid($app);
263
264
        $Plugin = $app['eccube.repository.plugin']->find($id);
265
266
        if (!$Plugin) {
267
            throw new NotFoundHttpException();
268
        }
269
270
        if ($Plugin->getEnable() == Constant::ENABLED) {
271
            $app['eccube.service.plugin']->disable($Plugin);
272
            $app->addSuccess('admin.plugin.disable.complete', 'admin');
273
        } else {
274
            $app->addError('admin.plugin.already.disable', 'admin');
275
        }
276
277
        return $app->redirect($app->url('admin_store_plugin'));
278
    }
279
280
281
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
282
     * 対象のプラグインを削除します。
283
     *
284
     * @param Application $app
285
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
286
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
287
    public function uninstall(Application $app, $id)
288
    {
289
        $this->isTokenValid($app);
290
291
        $Plugin = $app['eccube.repository.plugin']->find($id);
292
293
        if (!$Plugin) {
294
            $app->deleteMessage();
295
            return $app->redirect($app->url('admin_store_plugin'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
296
        }
297
298
        $app['eccube.service.plugin']->uninstall($Plugin);
299
300
        $app->addSuccess('admin.plugin.uninstall.complete', 'admin');
301
302
        return $app->redirect($app->url('admin_store_plugin'));
303
    }
304
305
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
introduced by
Doc comment for parameter "$id" missing
Loading history...
306
     * 対象プラグインの README を返却します。
307
     *
308
     * @param Application $app
309
     * @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...
310
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
311
    public function readme(Application $app, Request $request, $id)
312
    {
313
        if ($request->isXmlHttpRequest()) {
314
            $Plugin = $app['eccube.repository.plugin']->find($id);
315 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...
316
                $response = new Response(json_encode('NG'), 400);
317
                $response->headers->set('Content-Type', 'application/json');
318
                return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
319
            }
320
321
            $code = $Plugin->getCode();
322
            $readme = $app['config'][$code]['const']['readme'];
323
            $data = array(
324
                'code' => $code,
325
                'name' => $Plugin->getName(),
326
                'readme' => $readme,
327
            );
328
329
            $response = new Response(json_encode($data));
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
        $response = new Response(json_encode('NG'), 400);
335
        $response->headers->set('Content-Type', 'application/json');
336
        return $response;
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
337
    }
338
339
    public function handler(Application $app)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
340
    {
341
        $handlers = $app['eccube.repository.plugin_event_handler']->getHandlers();
342
343
        // 一次元配列からイベント毎の二次元配列に変換する
344
        $HandlersPerEvent = array();
345
        foreach ($handlers as $handler) {
346
            $HandlersPerEvent[$handler->getEvent()][$handler->getHandlerType()][] = $handler;
347
        }
348
349
        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...
350
            'handlersPerEvent' => $HandlersPerEvent
351
        ));
352
353
    }
354
355 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...
356
    {
357
        $repo = $app['eccube.repository.plugin_event_handler'];
358
        $repo->upPriority($repo->find($handlerId));
359
360
        return $app->redirect($app->url('admin_store_plugin_handler'));
361
    }
362
363 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...
364
    {
365
        $repo = $app['eccube.repository.plugin_event_handler'];
366
        $repo->upPriority($repo->find($handlerId), false);
367
368
        return $app->redirect($app->url('admin_store_plugin_handler'));
369
    }
370
371
    /**
372
     * プラグインファイルアップロード画面
373
     *
374
     * @param Application $app
375
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
376
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
377
    public function install(Application $app, Request $request)
378
    {
379
        $form = $app['form.factory']
380
            ->createBuilder('plugin_local_install')
381
            ->getForm();
382
383
        $errors = array();
384
385
        if ('POST' === $request->getMethod()) {
386
            $form->handleRequest($request);
387
388
            if ($form->isValid()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
389
390
                $tmpDir = null;
391
                try {
392
                    $service = $app['eccube.service.plugin'];
393
394
                    $formFile = $form['plugin_archive']->getData();
395
396
                    $tmpDir = $service->createTempDir();
397
                    $tmpFile = sha1(Str::random(32)).'.'.$formFile->getClientOriginalExtension(); // 拡張子を付けないとpharが動かないので付ける
398
399
                    $formFile->move($tmpDir, $tmpFile);
400
401
                    $service->install($tmpDir.'/'.$tmpFile);
402
403
                    $fs = new Filesystem();
404
                    $fs->remove($tmpDir);
405
406
                    $app->addSuccess('admin.plugin.install.complete', 'admin');
407
408
                    return $app->redirect($app->url('admin_store_plugin'));
409
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
410
                } catch (PluginException $e) {
411
                    if (!empty($tmpDir) && file_exists($tmpDir)) {
412
                        $fs = new Filesystem();
413
                        $fs->remove($tmpDir);
414
                    }
415
                    $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...
416
                        'original-message' => $e->getMessage()
417
                    ));
418
                    $errors[] = $e;
419
                }
420
            } else {
421
                foreach ($form->getErrors(true) as $error) {
422
                    $errors[] = $error;
423
                }
424
            }
425
        }
426
427
        return $app->render('Store/plugin_install.twig', array(
428
            'form' => $form->createView(),
429
            'errors' => $errors,
430
        ));
431
432
    }
433
434
    /**
435
     * オーナーズストアプラグインインストール画面
436
     *
437
     * @param Application $app
438
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
439
     * @return \Symfony\Component\HttpFoundation\Response
440
     */
441
    public function ownersInstall(Application $app, Request $request)
442
    {
443
        // オーナーズストアからダウンロード可能プラグイン情報を取得
444
        $BaseInfo = $app['eccube.repository.base_info']->get();
445
446
        $authKey = $BaseInfo->getAuthenticationKey();
447
        $authResult = true;
448
        $success = 0;
449
        $items = array();
450
        $promotionItems = array();
451
        $message = '';
452
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
453
454
            // オーナーズストア通信
455
            $url = $app['config']['owners_store_url'].'?method=list';
456
            list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
457
458
            if ($json === false) {
459
                // 接続失敗時
460
                $success = 0;
461
462
                $message = $this->getResponseErrorMessage($info);
463
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
464
            } else {
465
                // 接続成功時
466
467
                $data = json_decode($json, true);
468
469
                if (isset($data['success'])) {
470
                    $success = $data['success'];
471
                    if ($success == '1') {
472
                        $items = array();
473
474
                        // 既にインストールされているかどうか確認
475
                        $Plugins = $app['eccube.repository.plugin']->findAll();
476
                        $status = false;
477
                        // update_status 1 : 未インストール、2 : インストール済、 3 : 更新あり、4 : 有料購入
478
                        foreach ($data['item'] as $item) {
479
                            foreach ($Plugins as $plugin) {
480
                                if ($plugin->getSource() == $item['product_id']) {
481
                                    if ($plugin->getVersion() == $item['version']) {
482
                                        // バージョンが同じ
483
                                        $item['update_status'] = 2;
484
                                    } else {
485
                                        // バージョンが異なる
486
                                        $item['update_status'] = 3;
487
                                    }
488
                                    $items[] = $item;
489
                                    $status = true;
490
                                    break;
491
                                }
492
                            }
493
                            if (!$status) {
494
                                // 未インストール
495
                                $item['update_status'] = 1;
496
                                $items[] = $item;
497
                            }
498
                            $status = false;
499
                        }
500
501
                        // EC-CUBEのバージョンチェック
502
                        // 参照渡しをして値を追加
503
                        foreach ($items as &$item) {
504
                            if (in_array(Constant::VERSION, $item['eccube_version'])) {
505
                                // 対象バージョン
506
                                $item['version_check'] = 1;
507
                            } else {
508
                                // 未対象バージョン
509
                                $item['version_check'] = 0;
510
                            }
511
                            if ($item['price'] != '0' && $item['purchased'] == '0') {
512
                                // 有料商品で未購入
513
                                $item['update_status'] = 4;
514
                            }
515
                        }
516
                        unset($item);
517
518
                        // promotionアイテム
519
                        $i = 0;
520
                        foreach ($items as $item) {
521
                            if ($item['promotion'] == 1) {
522
                                $promotionItems[] = $item;
523
                                unset($items[$i]);
524
                            }
525
                            $i++;
526
                        }
527
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
528
                    } else {
529
                        $message = $data['error_code'].' : '.$data['error_message'];
530
                    }
531
                } else {
532
                    $success = 0;
533
                    $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
534
                }
535
            }
536
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
537
        } else {
538
            $authResult = false;
539
        }
540
541
        return $app->render('Store/plugin_owners_install.twig', array(
542
            'authResult' => $authResult,
543
            'success' => $success,
544
            'items' => $items,
545
            'promotionItems' => $promotionItems,
546
            'message' => $message,
547
        ));
548
549
    }
550
551
    /**
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...
552
     * オーナーズブラグインインストール、アップデート
553
     *
554
     * @param Application $app
555
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
556
     * @param $action
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
557
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
558
     * @param $version
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
559
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
560
    public function upgrade(Application $app, Request $request, $action, $id, $version)
561
    {
562
563
        $BaseInfo = $app['eccube.repository.base_info']->get();
564
565
        $authKey = $BaseInfo->getAuthenticationKey();
566
        $message = '';
567
568
        if (!is_null($authKey)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
569
570
            // オーナーズストア通信
571
            $url = $app['config']['owners_store_url'].'?method=download&product_id='.$id;
572
            list($json, $info) = $this->getRequestApi($request, $authKey, $url, $app);
573
574
            if ($json === false) {
575
                // 接続失敗時
576
577
                $message = $this->getResponseErrorMessage($info);
578
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
579
            } else {
580
                // 接続成功時
581
582
                $data = json_decode($json, true);
583
584
                if (isset($data['success'])) {
585
                    $success = $data['success'];
586
                    if ($success == '1') {
587
                        $tmpDir = null;
588
                        try {
589
                            $service = $app['eccube.service.plugin'];
590
591
                            $item = $data['item'];
592
                            $file = base64_decode($item['data']);
593
                            $extension = pathinfo($item['file_name'], PATHINFO_EXTENSION);
594
595
                            $tmpDir = $service->createTempDir();
596
                            $tmpFile = sha1(Str::random(32)).'.'.$extension;
597
598
                            // ファイル作成
599
                            $fs = new Filesystem();
600
                            $fs->dumpFile($tmpDir.'/'.$tmpFile, $file);
601
602
                            if ($action == 'install') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
603
604
                                $service->install($tmpDir.'/'.$tmpFile, $id);
605
                                $app->addSuccess('admin.plugin.install.complete', 'admin');
606
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
607
                            } else if ($action == 'update') {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
608
609
                                $Plugin = $app['eccube.repository.plugin']->findOneBy(array('source' => $id));
610
611
                                $service->update($Plugin, $tmpDir.'/'.$tmpFile);
612
                                $app->addSuccess('admin.plugin.update.complete', 'admin');
613
                            }
614
615
                            $fs = new Filesystem();
616
                            $fs->remove($tmpDir);
617
618
                            // ダウンロード完了通知処理(正常終了時)
619
                            $url = $app['config']['owners_store_url'].'?method=commit&product_id='.$id.'&status=1&version='.$version;
620
                            $this->getRequestApi($request, $authKey, $url, $app);
621
622
                            return $app->redirect($app->url('admin_store_plugin'));
623
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
624
                        } catch (PluginException $e) {
625
                            if (!empty($tmpDir) && file_exists($tmpDir)) {
626
                                $fs = new Filesystem();
627
                                $fs->remove($tmpDir);
628
                            }
629
                            $message = $e->getMessage();
630
                        }
631
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
632
                    } else {
633
                        $message = $data['error_code'].' : '.$data['error_message'];
634
                    }
635
                } else {
636
                    $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
637
                }
638
            }
639
        }
640
641
        // ダウンロード完了通知処理(エラー発生時)
642
        $url = $app['config']['owners_store_url'].'?method=commit&product_id='.$id.'&status=0&version='.$version.'&message='.urlencode($message);
643
        $this->getRequestApi($request, $authKey, $url, $app);
644
645
        $app->addError($message, 'admin');
646
647
        return $app->redirect($app->url('admin_store_plugin_owners_install'));
648
    }
649
650
    /**
651
     * 認証キー設定画面
652
     *
653
     * @param Application $app
654
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
655
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
656
    public function authenticationSetting(Application $app, Request $request)
657
    {
658
659
        $form = $app->form()->getForm();
660
661
        $BaseInfo = $app['eccube.repository.base_info']->get();
662
663
        // 認証キーの取得
664
        $form->add(
665
            'authentication_key', 'text', array(
666
            'label' => '認証キー',
667
            'constraints' => array(
668
                new Assert\Regex(array(
669
                    'pattern' => "/^[0-9a-zA-Z]+$/",
670
                )),
671
            ),
672
            'data' => $BaseInfo->getAuthenticationKey(),
673
        ));
674
675
        if ('POST' === $request->getMethod()) {
676
            $form->handleRequest($request);
677
678
            if ($form->isValid()) {
679
                $data = $form->getData();
680
681
                // 認証キーの登録
682
                $BaseInfo->setAuthenticationKey($data['authentication_key']);
683
                $app['orm.em']->flush($BaseInfo);
684
685
                $app->addSuccess('admin.plugin.authentication.setting.complete', 'admin');
686
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
687
            }
688
        }
689
690
691
        return $app->render('Store/authentication_setting.twig', array(
692
            'form' => $form->createView(),
693
        ));
694
695
    }
696
697
698
    /**
699
     * 認証キーダウンロード
700
     *
701
     * @param Application $app
702
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
703
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
704
     */
705
    public function download(Application $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
706
    {
707
708
        $this->isTokenValid($app);
709
710
        $url = $app['config']['cacert_pem_url'];
711
712
        $curl = curl_init($url);
713
        $fileName = $app['config']['root_dir'].'/app/config/eccube/'.$this->certFileName;
714
        $fp = fopen($fileName, 'w');
715
        if ($fp === false) {
716
            $app->addError('admin.plugin.download.pem.error', 'admin');
717
            $app->log('Cannot fopen to '.$fileName, array(), Logger::ERROR);
718
            return $app->redirect($app->url('admin_store_authentication_setting'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
719
        }
720
721
        curl_setopt($curl, CURLOPT_FILE, $fp);
722
        curl_setopt($curl, CURLOPT_HEADER, 0);
723
724
        $results = curl_exec($curl);
725
        $error = curl_error($curl);
726
        curl_close($curl);
727
728
        // curl で取得できない場合は file_get_contents で取得を試みる
729
        if ($results === false) {
730
            $file = file_get_contents($url);
731
            if ($file !== false) {
732
                fwrite($fp, $file);
733
            }
734
        }
735
        fclose($fp);
736
737
        $f = new Filesystem();
738
        if ($f->exists($fileName) && filesize($fileName) > 0) {
739
            $app->addSuccess('admin.plugin.download.pem.complete', 'admin');
740
        } else {
741
            $app->addError('admin.plugin.download.pem.error', 'admin');
742
            $app->log('curl_error: '.$error, array(), Logger::ERROR);
743
        }
744
745
        return $app->redirect($app->url('admin_store_authentication_setting'));
746
747
    }
748
749
750
    /**
751
     * APIリクエスト処理
752
     *
753
     * @param Request $request
754
     * @param $authKey
755
     * @param string $url
756
     * @param Application $app
757
     * @return array
758
     */
759
    private function getRequestApi(Request $request, $authKey, $url, $app)
760
    {
761
        $curl = curl_init($url);
762
763
        $options = array(           // オプション配列
764
            //HEADER
765
            CURLOPT_HTTPHEADER => array(
766
                'Authorization: '.base64_encode($authKey),
767
                'x-eccube-store-url: '.base64_encode($request->getSchemeAndHttpHost().$request->getBasePath()),
768
                'x-eccube-store-version: '.base64_encode(Constant::VERSION),
769
            ),
770
            CURLOPT_HTTPGET => true,
771
            CURLOPT_SSL_VERIFYPEER => true,
772
            CURLOPT_RETURNTRANSFER => true,
773
            CURLOPT_FAILONERROR => true,
774
        );
775
776
        curl_setopt_array($curl, $options); /// オプション値を設定
777
778
        $certFile = $app['config']['root_dir'].'/app/config/eccube/'.$this->certFileName;
779
        if (file_exists($certFile)) {
780
            // php5.6でサーバ上に適切な証明書がなければhttps通信エラーが発生するため、
781
            // http://curl.haxx.se/ca/cacert.pem を利用して通信する
782
            curl_setopt($curl, CURLOPT_CAINFO, $certFile);
783
        }
784
785
        $result = curl_exec($curl);
786
        $info = curl_getinfo($curl);
787
788
        $message = curl_error($curl);
789
        $info['message'] = $message;
790
        curl_close($curl);
791
792
        $app->log('http get_info', $info);
793
794
        return array($result, $info);
795
    }
796
797
    /**
798
     * レスポンスのチェック
799
     *
800
     * @param $info
801
     * @return string
802
     */
803
    private function getResponseErrorMessage($info)
804
    {
805
        if (!empty($info)) {
806
            $statusCode = $info['http_code'];
807
            $message = $info['message'];
808
809
            $message = $statusCode.' : '.$message;
810
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
811
        } else {
812
            $message = "タイムアウトエラーまたはURLの指定に誤りがあります。";
813
        }
814
815
        return $message;
816
    }
817
818
819
    /**
820
     * フォルダ設置のみのプラグインを取得する.
821
     *
822
     * @param array $plugins
823
     * @param Application $app
824
     * @return array
825
     */
826
    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...
827
    {
828
        $finder = new Finder();
829
        $pluginCodes = array();
830
831
        // DB登録済みプラグインコードのみ取得
832
        foreach ($plugins as $key => $plugin) {
833
            $pluginCodes[] = $plugin->getCode();
834
        }
835
        // DB登録済みプラグインコードPluginディレクトリから排他
836
        $dirs = $finder->in($app['config']['plugin_realdir'])->depth(0)->directories();
837
838
        // プラグイン基本チェック
839
        $unregisteredPlugins = array();
840
        foreach ($dirs as $dir) {
841
            $pluginCode = $dir->getBasename();
842
            if (in_array($pluginCode, $pluginCodes, true)) {
843
                continue;
844
            }
845
            try {
846
                $app['eccube.service.plugin']->checkPluginArchiveContent($dir->getRealPath());
847
            } catch (\Eccube\Exception\PluginException $e) {
848
                //config.yamlに不備があった際は全てスキップ
849
                $app['monolog']->warning($e->getMessage());
850
                continue;
851
            }
852
            $config = $app['eccube.service.plugin']->readYml($dir->getRealPath().'/config.yml');
853
            $unregisteredPlugins[$pluginCode]['name'] = isset($config['name']) ? $config['name'] : null;
854
            $unregisteredPlugins[$pluginCode]['event'] = isset($config['event']) ? $config['event'] : null;
855
            $unregisteredPlugins[$pluginCode]['version'] = isset($config['version']) ? $config['version'] : null;
856
            $unregisteredPlugins[$pluginCode]['enable'] = Constant::DISABLED;
857
            $unregisteredPlugins[$pluginCode]['code'] = isset($config['code']) ? $config['code'] : null;
858
        }
859
860
        return $unregisteredPlugins;
861
    }
862
}
863