C:\temp\ec-cube-3.0.9\src\Eccube\Application.php C:\temp\eccube3.0.9_update_files\eccube-3.0.9\src\Eccube\Application.php
<?php <?php
/* /*
* This file is part of EC-CUBE * This file is part of EC-CUBE
* *
* Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved. * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
* *
* http://www.lockon.co.jp/ * http://www.lockon.co.jp/
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2 * as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. * of the License, or (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software * along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/  */ 
   
namespace Eccube; namespace Eccube;
   
use Eccube\Application\ApplicationTrait; use Eccube\Application\ApplicationTrait;
use Eccube\Common\Constant; use Eccube\Common\Constant;
use Monolog\Logger; use Monolog\Logger;
use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
   
class Application extends ApplicationTrait class Application extends ApplicationTrait
{ {
   protected static $instance;    protected static $instance;
   
   protected $initialized = false;    protected $initialized = false;
   protected $initializedPlugin = false;    protected $initializedPlugin = false;
   
   public static function getInstance(array $values = array())    public static function getInstance(array $values = array())
   {    {
       if (!is_object(self::$instance)) {        if (!is_object(self::$instance)) {
           self::$instance = new Application($values);            self::$instance = new Application($values);
       }        }
   
       return self::$instance;        return self::$instance;
   }    }
   
   public static function clearInstance()    public static function clearInstance()
   {    {
       self::$instance = null;        self::$instance = null;
   }    }
   
   final public function __clone()    final public function __clone()
   {    {
       throw new \Exception('Clone is not allowed against '.get_class($this));        throw new \Exception('Clone is not allowed against '.get_class($this));
   }    }
   
   public function __construct(array $values = array())    public function __construct(array $values = array())
   {    {
       parent::__construct($values);        parent::__construct($values);
   
       if (is_null(self::$instance)) {        if (is_null(self::$instance)) {
           self::$instance = $this;            self::$instance = $this;
       }        }
   
       // load config        // load config
       $this->initConfig();        $this->initConfig();
   
       // init monolog        // init monolog
       $this->initLogger();        $this->initLogger();
   }    }
   
   public function initConfig()    public function initConfig()
   {    {
       // load config        // load config
       $this['config'] = $this->share(function() {        $this['config'] = $this->share(function() {
           $ymlPath = __DIR__.'/../../app/config/eccube';            $ymlPath = __DIR__.'/../../app/config/eccube';
           $distPath = __DIR__.'/../../src/Eccube/Resource/config';            $distPath = __DIR__.'/../../src/Eccube/Resource/config';
   
           $config = array();            $config = array();
           $config_yml = $ymlPath.'/config.yml';            $config_yml = $ymlPath.'/config.yml';
           if (file_exists($config_yml)) {            if (file_exists($config_yml)) {
               $config = Yaml::parse(file_get_contents($config_yml));                $config = Yaml::parse(file_get_contents($config_yml));
           }            }
   
           $config_dist = array();            $config_dist = array();
           $config_yml_dist = $distPath.'/config.yml.dist';            $config_yml_dist = $distPath.'/config.yml.dist';
           if (file_exists($config_yml_dist)) {            if (file_exists($config_yml_dist)) {
               $config_dist = Yaml::parse(file_get_contents($config_yml_dist));                $config_dist = Yaml::parse(file_get_contents($config_yml_dist));
           }            }
   
           $config_path = array();            $config_path = array();
           $path_yml = $ymlPath.'/path.yml';            $path_yml = $ymlPath.'/path.yml';
           if (file_exists($path_yml)) {            if (file_exists($path_yml)) {
               $config_path = Yaml::parse(file_get_contents($path_yml));                $config_path = Yaml::parse(file_get_contents($path_yml));
           }            }
   
           $config_constant = array();            $config_constant = array();
           $constant_yml = $ymlPath.'/constant.yml';            $constant_yml = $ymlPath.'/constant.yml';
           if (file_exists($constant_yml)) {            if (file_exists($constant_yml)) {
               $config_constant = Yaml::parse(file_get_contents($constant_yml));                $config_constant = Yaml::parse(file_get_contents($constant_yml));
               $config_constant = empty($config_constant) ? array() : $config_constant;                $config_constant = empty($config_constant) ? array() : $config_constant;
           }            }
   
           $config_constant_dist = array();            $config_constant_dist = array();
           $constant_yml_dist = $distPath.'/constant.yml.dist';            $constant_yml_dist = $distPath.'/constant.yml.dist';
           if (file_exists($constant_yml_dist)) {            if (file_exists($constant_yml_dist)) {
               $config_constant_dist = Yaml::parse(file_get_contents($constant_yml_dist));                $config_constant_dist = Yaml::parse(file_get_contents($constant_yml_dist));
           }            }
   
           $configAll = array_replace_recursive($config_constant_dist, $config_dist, $config_constant, $config_path, $config);            $configAll = array_replace_recursive($config_constant_dist, $config_dist, $config_constant, $config_path, $config);
   
           $database = array();            $database = array();
           $yml = $ymlPath.'/database.yml';            $yml = $ymlPath.'/database.yml';
           if (file_exists($yml)) {            if (file_exists($yml)) {
               $database = Yaml::parse(file_get_contents($yml));                $database = Yaml::parse(file_get_contents($yml));
           }            }
   
           $mail = array();            $mail = array();
           $yml = $ymlPath.'/mail.yml';            $yml = $ymlPath.'/mail.yml';
           if (file_exists($yml)) {            if (file_exists($yml)) {
               $mail = Yaml::parse(file_get_contents($yml));                $mail = Yaml::parse(file_get_contents($yml));
           }            }
           $configAll = array_replace_recursive($configAll, $database, $mail);            $configAll = array_replace_recursive($configAll, $database, $mail);
   
           $config_log = array();            $config_log = array();
           $yml = $ymlPath.'/log.yml';            $yml = $ymlPath.'/log.yml';
           if (file_exists($yml)) {            if (file_exists($yml)) {
               $config_log = Yaml::parse(file_get_contents($yml));                $config_log = Yaml::parse(file_get_contents($yml));
           }            }
           $config_log_dist = array();            $config_log_dist = array();
           $log_yml_dist = $distPath.'/log.yml.dist';            $log_yml_dist = $distPath.'/log.yml.dist';
           if (file_exists($log_yml_dist)) {            if (file_exists($log_yml_dist)) {
               $config_log_dist = Yaml::parse(file_get_contents($log_yml_dist));                $config_log_dist = Yaml::parse(file_get_contents($log_yml_dist));
           }            }
   
           $configAll = array_replace_recursive($configAll, $config_log_dist, $config_log);            $configAll = array_replace_recursive($configAll, $config_log_dist, $config_log);
   
           $config_nav = array();            $config_nav = array();
           $yml = $ymlPath.'/nav.yml';            $yml = $ymlPath.'/nav.yml';
           if (file_exists($yml)) {            if (file_exists($yml)) {
               $config_nav = array('nav' => Yaml::parse(file_get_contents($yml)));                $config_nav = array('nav' => Yaml::parse(file_get_contents($yml)));
           }            }
           $config_nav_dist = array();            $config_nav_dist = array();
           $nav_yml_dist = $distPath.'/nav.yml.dist';            $nav_yml_dist = $distPath.'/nav.yml.dist';
           if (file_exists($nav_yml_dist)) {            if (file_exists($nav_yml_dist)) {
               $config_nav_dist = array('nav' => Yaml::parse(file_get_contents($nav_yml_dist)));                $config_nav_dist = array('nav' => Yaml::parse(file_get_contents($nav_yml_dist)));
           }            }
   
           $configAll = array_replace_recursive($configAll, $config_nav_dist, $config_nav);            $configAll = array_replace_recursive($configAll, $config_nav_dist, $config_nav);
   
           return $configAll;            return $configAll;
       });        });
   }    }
   
   public function initLogger()    public function initLogger()
   {    {
       $app = $this;        $app = $this;
       $this->register(new ServiceProvider\EccubeMonologServiceProvider($app));        $this->register(new ServiceProvider\EccubeMonologServiceProvider($app));
       $this['monolog.logfile'] = __DIR__.'/../../app/log/site.log';        $this['monolog.logfile'] = __DIR__.'/../../app/log/site.log';
       $this['monolog.name'] = 'eccube';        $this['monolog.name'] = 'eccube';
   }    }
   
   public function initialize()    public function initialize()
   {    {
       if ($this->initialized) {        if ($this->initialized) {
           return;            return;
       }        }
   
       // init locale        // init locale
       $this->initLocale();        $this->initLocale();
   
       // init session        // init session
       $this->initSession();        $this->initSession();
   
       // init twig        // init twig
       $this->initRendering();        $this->initRendering();
   
       // init provider        // init provider
       $this->register(new \Silex\Provider\HttpFragmentServiceProvider());        $this->register(new \Silex\Provider\HttpFragmentServiceProvider());
       $this->register(new \Silex\Provider\UrlGeneratorServiceProvider());        $this->register(new \Silex\Provider\UrlGeneratorServiceProvider());
       $this->register(new \Silex\Provider\FormServiceProvider());        $this->register(new \Silex\Provider\FormServiceProvider());
       $this->register(new \Silex\Provider\SerializerServiceProvider());        $this->register(new \Silex\Provider\SerializerServiceProvider());
       $this->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());        $this->register(new \Eccube\ServiceProvider\ValidatorServiceProvider());
   
       $app = $this;        $app = $this;
       $this->error(function(\Exception $e, $code) use ($app) {        $this->error(function(\Exception $e, $code) use ($app) {
           if ($app['debug']) {            if ($app['debug']) {
               return;                return;
           }            }
   
           switch ($code) {            switch ($code) {
               case 403:                case 403:
                   $title = 'アクセスできません。';                    $title = 'アクセスできません。';
                   $message = 'お探しのページはアクセスができない状況にあるか、移動もしくは削除された可能性があります。';                    $message = 'お探しのページはアクセスができない状況にあるか、移動もしくは削除された可能性があります。';
                   break;                    break;
               case 404:                case 404:
                   $title = 'ページがみつかりません。';                    $title = 'ページがみつかりません。';
                   $message = 'URLに間違いがないかご確認ください。';                    $message = 'URLに間違いがないかご確認ください。';
                   break;                    break;
               default:                default:
                   $title = 'システムエラーが発生しました。';                    $title = 'システムエラーが発生しました。';
                   $message = '大変お手数ですが、サイト管理者までご連絡ください。';                    $message = '大変お手数ですが、サイト管理者までご連絡ください。';
                   break;                    break;
           }            }
   
           return $app->render('error.twig', array(            return $app->render('error.twig', array(
               'error_title' => $title,                'error_title' => $title,
               'error_message' => $message,                'error_message' => $message,
           ));            ));
       });        });
   
       // init mailer        // init mailer
       $this->initMailer();        $this->initMailer();
   
       // init doctrine orm        // init doctrine orm
       $this->initDoctrine();        $this->initDoctrine();
   
       // Set up the DBAL connection now to check for a proper connection to the database.        // Set up the DBAL connection now to check for a proper connection to the database.
       $this->checkDatabaseConnection();        $this->checkDatabaseConnection();
   
       // init security        // init security
       $this->initSecurity();        $this->initSecurity();
   
       // init ec-cube service provider        // init ec-cube service provider
       $this->register(new ServiceProvider\EccubeServiceProvider());        $this->register(new ServiceProvider\EccubeServiceProvider());
   
       // mount controllers        // mount controllers
       $this->register(new \Silex\Provider\ServiceControllerServiceProvider());        $this->register(new \Silex\Provider\ServiceControllerServiceProvider());
       $this->mount('', new ControllerProvider\FrontControllerProvider());        $this->mount('', new ControllerProvider\FrontControllerProvider());
       $this->mount('/'.trim($this['config']['admin_route'], '/').'/', new ControllerProvider\AdminControllerProvider());        $this->mount('/'.trim($this['config']['admin_route'], '/').'/', new ControllerProvider\AdminControllerProvider());
       Request::enableHttpMethodParameterOverride(); // PUTやDELETEできるようにする        Request::enableHttpMethodParameterOverride(); // PUTやDELETEできるようにする
   
       $this->initialized = true;        $this->initialized = true;
   }    }
   
   public function initLocale()    public function initLocale()
   {    {
   
       // timezone        // timezone
       if (!empty($this['config']['timezone'])) {        if (!empty($this['config']['timezone'])) {
           date_default_timezone_set($this['config']['timezone']);            date_default_timezone_set($this['config']['timezone']);
       }        }
   
       $this->register(new \Silex\Provider\TranslationServiceProvider(), array(        $this->register(new \Silex\Provider\TranslationServiceProvider(), array(
           'locale' => $this['config']['locale'],            'locale' => $this['config']['locale'],
       ));        ));
       $this['translator'] = $this->share($this->extend('translator', function($translator, \Silex\Application $app) {        $this['translator'] = $this->share($this->extend('translator', function($translator, \Silex\Application $app) {
           $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader());            $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader());
   
           $r = new \ReflectionClass('Symfony\Component\Validator\Validator');            $r = new \ReflectionClass('Symfony\Component\Validator\Validator');
           $file = dirname($r->getFilename()).'/Resources/translations/validators.'.$app['locale'].'.xlf';            $file = dirname($r->getFilename()).'/Resources/translations/validators.'.$app['locale'].'.xlf';
           if (file_exists($file)) {            if (file_exists($file)) {
               $translator->addResource('xliff', $file, $app['locale'], 'validators');                $translator->addResource('xliff', $file, $app['locale'], 'validators');
           }            }
   
           $file = __DIR__.'/Resource/locale/validator.'.$app['locale'].'.yml';            $file = __DIR__.'/Resource/locale/validator.'.$app['locale'].'.yml';
           if (file_exists($file)) {            if (file_exists($file)) {
               $translator->addResource('yaml', $file, $app['locale'], 'validators');                $translator->addResource('yaml', $file, $app['locale'], 'validators');
           }            }
   
           $file = __DIR__.'/Resource/locale/message.'.$app['locale'].'.yml';            $file = __DIR__.'/Resource/locale/message.'.$app['locale'].'.yml';
           if (file_exists($file)) {            if (file_exists($file)) {
               $translator->addResource('yaml', $file, $app['locale']);                $translator->addResource('yaml', $file, $app['locale']);
           }            }
   
           return $translator;            return $translator;
       }));        }));
   }    }
   
   public function initSession()    public function initSession()
   {    {
       $this->register(new \Silex\Provider\SessionServiceProvider(), array(        $this->register(new \Silex\Provider\SessionServiceProvider(), array(
           'session.storage.save_path' => $this['config']['root_dir'].'/app/cache/eccube/session',            'session.storage.save_path' => $this['config']['root_dir'].'/app/cache/eccube/session',
           'session.storage.options' => array(            'session.storage.options' => array(
               'name' => 'eccube',                'name' => 'eccube',
               'cookie_path' => $this['config']['root_urlpath'] ?: '/',                'cookie_path' => $this['config']['root_urlpath'] ?: '/',
               'cookie_secure' => $this['config']['force_ssl'],                'cookie_secure' => $this['config']['force_ssl'],
               'cookie_lifetime' => $this['config']['cookie_lifetime'],                'cookie_lifetime' => $this['config']['cookie_lifetime'],
               'cookie_httponly' => true,                'cookie_httponly' => true,
               // cookie_domainは指定しない                // cookie_domainは指定しない
               // http://blog.tokumaru.org/2011/10/cookiedomain.html                // http://blog.tokumaru.org/2011/10/cookiedomain.html
           ),            ),
       ));        ));
   }    }
   
   public function initRendering()    public function initRendering()
   {    {
       $this->register(new \Silex\Provider\TwigServiceProvider(), array(        $this->register(new \Silex\Provider\TwigServiceProvider(), array(
           'twig.form.templates' => array('Form/form_layout.twig'),            'twig.form.templates' => array('Form/form_layout.twig'),
       ));        ));
       $this['twig'] = $this->share($this->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {        $this['twig'] = $this->share($this->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {
           $twig->addExtension(new \Eccube\Twig\Extension\EccubeExtension($app));            $twig->addExtension(new \Eccube\Twig\Extension\EccubeExtension($app));
           $twig->addExtension(new \Twig_Extension_StringLoader());            $twig->addExtension(new \Twig_Extension_StringLoader());
   
           return $twig;            return $twig;
       }));        }));
   
       $this->before(function(Request $request, \Silex\Application $app) {        $this->before(function(Request $request, \Silex\Application $app) {
           // フロント or 管理画面ごとにtwigの探索パスを切り替える.            // フロント or 管理画面ごとにtwigの探索パスを切り替える.
           $app['twig'] = $app->share($app->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {            $app['twig'] = $app->share($app->extend('twig', function(\Twig_Environment $twig, \Silex\Application $app) {
               $paths = array();                $paths = array();
   
               // 互換性がないのでprofiler とproduction 時のcacheを分離する                // 互換性がないのでprofiler とproduction 時のcacheを分離する
   
               $app['admin'] = false;                $app['admin'] = false;
               $app['front'] = false;                $app['front'] = false;
   
               if (isset($app['profiler'])) {                if (isset($app['profiler'])) {
                   $cacheBaseDir = __DIR__.'/../../app/cache/twig/profiler/';                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/profiler/';
               } else {                } else {
                   $cacheBaseDir = __DIR__.'/../../app/cache/twig/production/';                    $cacheBaseDir = __DIR__.'/../../app/cache/twig/production/';
               }                }
.                if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {                $pathinfo = rawurldecode($app['request']->getPathInfo()); 
                 if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/')) === 0) {
                   if (file_exists(__DIR__.'/../../app/template/admin')) {                    if (file_exists(__DIR__.'/../../app/template/admin')) {
                       $paths[] = __DIR__.'/../../app/template/admin';                        $paths[] = __DIR__.'/../../app/template/admin';
                   }                    }
                   $paths[] = $app['config']['template_admin_realdir'];                    $paths[] = $app['config']['template_admin_realdir'];
                   $paths[] = __DIR__.'/../../app/Plugin';                    $paths[] = __DIR__.'/../../app/Plugin';
                   $cache = $cacheBaseDir.'admin';                    $cache = $cacheBaseDir.'admin';
                   $app['admin'] = true;                    $app['admin'] = true;
               } else {                } else {
                   if (file_exists($app['config']['template_realdir'])) {                    if (file_exists($app['config']['template_realdir'])) {
                       $paths[] = $app['config']['template_realdir'];                        $paths[] = $app['config']['template_realdir'];
                   }                    }
                   $paths[] = $app['config']['template_default_realdir'];                    $paths[] = $app['config']['template_default_realdir'];
                   $paths[] = __DIR__.'/../../app/Plugin';                    $paths[] = __DIR__.'/../../app/Plugin';
                   $cache = $cacheBaseDir.$app['config']['template_code'];                    $cache = $cacheBaseDir.$app['config']['template_code'];
                   $app['front'] = true;                    $app['front'] = true;
               }                }
               $twig->setCache($cache);                $twig->setCache($cache);
               $app['twig.loader']->addLoader(new \Twig_Loader_Filesystem($paths));                $app['twig.loader']->addLoader(new \Twig_Loader_Filesystem($paths));
   
               return $twig;                return $twig;
           }));            }));
   
           // 管理画面のIP制限チェック.            // 管理画面のIP制限チェック.
.            if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {            $pathinfo = rawurldecode($app['request']->getPathInfo()); 
             if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/')) === 0) {
               // IP制限チェック                // IP制限チェック
               $allowHost = $app['config']['admin_allow_host'];                $allowHost = $app['config']['admin_allow_host'];
               if (count($allowHost) > 0) {                if (count($allowHost) > 0) {
                   if (array_search($app['request']->getClientIp(), $allowHost) === false) {                    if (array_search($app['request']->getClientIp(), $allowHost) === false) {
                       throw new \Exception();                        throw new \Exception();
                   }                    }
               }                }
           }            }
       }, self::EARLY_EVENT);        }, self::EARLY_EVENT);
   
       // twigのグローバル変数を定義.        // twigのグローバル変数を定義.
       $app = $this;        $app = $this;
       $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {        $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {
           // ショップ基本情報            // ショップ基本情報
           $BaseInfo = $app['eccube.repository.base_info']->get();            $BaseInfo = $app['eccube.repository.base_info']->get();
           $app['twig']->addGlobal('BaseInfo', $BaseInfo);            $app['twig']->addGlobal('BaseInfo', $BaseInfo);
   
.            if (strpos($app['request']->getPathInfo(), '/'.trim($app['config']['admin_route'], '/')) === 0) {            $pathinfo = rawurldecode($app['request']->getPathInfo()); 
             if (strpos($pathinfo, '/'.trim($app['config']['admin_route'], '/')) === 0) {
               // 管理画面                // 管理画面
               // 管理画面メニュー                // 管理画面メニュー
               $menus = array('', '', '');                $menus = array('', '', '');
               $app['twig']->addGlobal('menus', $menus);                $app['twig']->addGlobal('menus', $menus);
   
               $Member = $app->user();                $Member = $app->user();
               if (is_object($Member)) {                if (is_object($Member)) {
                   // ログインしていれば管理者のロールを取得                    // ログインしていれば管理者のロールを取得
                   $AuthorityRoles = $app['eccube.repository.authority_role']->findBy(array('Authority' => $Member->getAuthority()));                    $AuthorityRoles = $app['eccube.repository.authority_role']->findBy(array('Authority' => $Member->getAuthority()));
   
                   $roles = array();                    $roles = array();
                   foreach ($AuthorityRoles as $AuthorityRole) {                    foreach ($AuthorityRoles as $AuthorityRole) {
                       // 管理画面でメニュー制御するため相対パス全てをセット                        // 管理画面でメニュー制御するため相対パス全てをセット
                       $roles[] = $app['request']->getBaseUrl().'/'.$app['config']['admin_route'].$AuthorityRole->getDenyUrl();                        $roles[] = $app['request']->getBaseUrl().'/'.$app['config']['admin_route'].$AuthorityRole->getDenyUrl();
                   }                    }
   
                   $app['twig']->addGlobal('AuthorityRoles', $roles);                    $app['twig']->addGlobal('AuthorityRoles', $roles);
               }                }
   
           } else {            } else {
               // フロント画面                // フロント画面
               $request = $event->getRequest();                $request = $event->getRequest();
               $route = $request->attributes->get('_route');                $route = $request->attributes->get('_route');
   
               // ユーザ作成画面                // ユーザ作成画面
               if ($route === trim($app['config']['user_data_route'])) {                if ($route === trim($app['config']['user_data_route'])) {
                   $params = $request->attributes->get('_route_params');                    $params = $request->attributes->get('_route_params');
                   $route = $params['route'];                    $route = $params['route'];
                   // プレビュー画面                    // プレビュー画面
               } elseif ($request->get('preview')) {                } elseif ($request->get('preview')) {
                   $route = 'preview';                    $route = 'preview';
               }                }
   
               try {                try {
                   $DeviceType = $app['eccube.repository.master.device_type']                    $DeviceType = $app['eccube.repository.master.device_type']
                       ->find(\Eccube\Entity\Master\DeviceType::DEVICE_TYPE_PC);                        ->find(\Eccube\Entity\Master\DeviceType::DEVICE_TYPE_PC);
                   $PageLayout = $app['eccube.repository.page_layout']->getByUrl($DeviceType, $route);                    $PageLayout = $app['eccube.repository.page_layout']->getByUrl($DeviceType, $route);
               } catch (\Doctrine\ORM\NoResultException $e) {                } catch (\Doctrine\ORM\NoResultException $e) {
                   $PageLayout = $app['eccube.repository.page_layout']->newPageLayout($DeviceType);                    $PageLayout = $app['eccube.repository.page_layout']->newPageLayout($DeviceType);
               }                }
   
               $app['twig']->addGlobal('PageLayout', $PageLayout);                $app['twig']->addGlobal('PageLayout', $PageLayout);
               $app['twig']->addGlobal('title', $PageLayout->getName());                $app['twig']->addGlobal('title', $PageLayout->getName());
           }            }
       });        });
   }    }
   
   public function initMailer()    public function initMailer()
   {    {
   
       // メール送信時の文字エンコード指定(デフォルトはUTF-8)        // メール送信時の文字エンコード指定(デフォルトはUTF-8)
       if (isset($this['config']['mail']['charset_iso_2022_jp']) && is_bool($this['config']['mail']['charset_iso_2022_jp'])) {        if (isset($this['config']['mail']['charset_iso_2022_jp']) && is_bool($this['config']['mail']['charset_iso_2022_jp'])) {
           if ($this['config']['mail']['charset_iso_2022_jp'] === true) {            if ($this['config']['mail']['charset_iso_2022_jp'] === true) {
               \Swift::init(function() {                \Swift::init(function() {
                   \Swift_DependencyContainer::getInstance()                    \Swift_DependencyContainer::getInstance()
                       ->register('mime.qpheaderencoder')                        ->register('mime.qpheaderencoder')
                       ->asAliasOf('mime.base64headerencoder');                        ->asAliasOf('mime.base64headerencoder');
                   \Swift_Preferences::getInstance()->setCharset('iso-2022-jp');                    \Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
               });                });
           }            }
       }        }
   
       $this->register(new \Silex\Provider\SwiftmailerServiceProvider());        $this->register(new \Silex\Provider\SwiftmailerServiceProvider());
       $this['swiftmailer.options'] = $this['config']['mail'];        $this['swiftmailer.options'] = $this['config']['mail'];
   
       if (isset($this['config']['mail']['spool']) && is_bool($this['config']['mail']['spool'])) {        if (isset($this['config']['mail']['spool']) && is_bool($this['config']['mail']['spool'])) {
           $this['swiftmailer.use_spool'] = $this['config']['mail']['spool'];            $this['swiftmailer.use_spool'] = $this['config']['mail']['spool'];
       }        }
       // デフォルトはsmtpを使用        // デフォルトはsmtpを使用
       $transport = $this['config']['mail']['transport'];        $transport = $this['config']['mail']['transport'];
       if ($transport == 'sendmail') {        if ($transport == 'sendmail') {
           $this['swiftmailer.transport'] = \Swift_SendmailTransport::newInstance();            $this['swiftmailer.transport'] = \Swift_SendmailTransport::newInstance();
       } elseif ($transport == 'mail') {        } elseif ($transport == 'mail') {
           $this['swiftmailer.transport'] = \Swift_MailTransport::newInstance();            $this['swiftmailer.transport'] = \Swift_MailTransport::newInstance();
       }        }
   }    }
   
   public function initDoctrine()    public function initDoctrine()
   {    {
       $this->register(new \Silex\Provider\DoctrineServiceProvider(), array(        $this->register(new \Silex\Provider\DoctrineServiceProvider(), array(
           'dbs.options' => array(            'dbs.options' => array(
               'default' => $this['config']['database']                'default' => $this['config']['database']
       )));        )));
       $this->register(new \Saxulum\DoctrineOrmManagerRegistry\Silex\Provider\DoctrineOrmManagerRegistryProvider());        $this->register(new \Saxulum\DoctrineOrmManagerRegistry\Silex\Provider\DoctrineOrmManagerRegistryProvider());
   
       // プラグインのmetadata定義を合わせて行う.        // プラグインのmetadata定義を合わせて行う.
       $pluginBasePath = __DIR__.'/../../app/Plugin';        $pluginBasePath = __DIR__.'/../../app/Plugin';
       $finder = Finder::create()        $finder = Finder::create()
           ->in($pluginBasePath)            ->in($pluginBasePath)
           ->directories()            ->directories()
           ->depth(0);            ->depth(0);
   
       $ormMappings = array();        $ormMappings = array();
       $ormMappings[] = array(        $ormMappings[] = array(
           'type' => 'yml',            'type' => 'yml',
           'namespace' => 'Eccube\Entity',            'namespace' => 'Eccube\Entity',
           'path' => array(            'path' => array(
               __DIR__.'/Resource/doctrine',                __DIR__.'/Resource/doctrine',
               __DIR__.'/Resource/doctrine/master',                __DIR__.'/Resource/doctrine/master',
           ),            ),
       );        );
   
       foreach ($finder as $dir) {        foreach ($finder as $dir) {
   
           $file = $dir->getRealPath().'/config.yml';            $file = $dir->getRealPath().'/config.yml';
   
           if (file_exists($file)) {            if (file_exists($file)) {
               $config = Yaml::parse(file_get_contents($file));                $config = Yaml::parse(file_get_contents($file));
           } else {            } else {
               $code = $dir->getBaseName();                $code = $dir->getBaseName();
               $this['monolog']->warning("skip {$code} orm.path loading. config.yml not found.", array('path' => $file));                $this['monolog']->warning("skip {$code} orm.path loading. config.yml not found.", array('path' => $file));
               continue;                continue;
           }            }
   
           // Doctrine Extend            // Doctrine Extend
           if (isset($config['orm.path']) && is_array($config['orm.path'])) {            if (isset($config['orm.path']) && is_array($config['orm.path'])) {
               $paths = array();                $paths = array();
               foreach ($config['orm.path'] as $path) {                foreach ($config['orm.path'] as $path) {
                   $paths[] = $pluginBasePath.'/'.$config['code'].$path;                    $paths[] = $pluginBasePath.'/'.$config['code'].$path;
               }                }
               $ormMappings[] = array(                $ormMappings[] = array(
                   'type' => 'yml',                    'type' => 'yml',
                   'namespace' => 'Plugin\\'.$config['code'].'\\Entity',                    'namespace' => 'Plugin\\'.$config['code'].'\\Entity',
                   'path' => $paths,                    'path' => $paths,
               );                );
           }            }
       }        }
   
       $this->register(new \Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(        $this->register(new \Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider(), array(
           'orm.proxies_dir' => __DIR__.'/../../app/cache/doctrine',            'orm.proxies_dir' => __DIR__.'/../../app/cache/doctrine',
           'orm.em.options' => array(            'orm.em.options' => array(
               'mappings' => $ormMappings,                'mappings' => $ormMappings,
           ),            ),
       ));        ));
   }    }
   
   public function initSecurity()    public function initSecurity()
   {    {
       $this->register(new \Silex\Provider\SecurityServiceProvider());        $this->register(new \Silex\Provider\SecurityServiceProvider());
       $this->register(new \Silex\Provider\RememberMeServiceProvider());        $this->register(new \Silex\Provider\RememberMeServiceProvider());
   
       $this['security.firewalls'] = array(        $this['security.firewalls'] = array(
           'admin' => array(            'admin' => array(
               'pattern' => "^/{$this['config']['admin_route']}",                'pattern' => "^/{$this['config']['admin_route']}",
               'form' => array(                'form' => array(
                   'login_path' => "/{$this['config']['admin_route']}/login",                    'login_path' => "/{$this['config']['admin_route']}/login",
                   'check_path' => "/{$this['config']['admin_route']}/login_check",                    'check_path' => "/{$this['config']['admin_route']}/login_check",
                   'username_parameter' => 'login_id',                    'username_parameter' => 'login_id',
                   'password_parameter' => 'password',                    'password_parameter' => 'password',
                   'with_csrf' => true,                    'with_csrf' => true,
                   'use_forward' => true,                    'use_forward' => true,
               ),                ),
               'logout' => array(                'logout' => array(
                   'logout_path' => "/{$this['config']['admin_route']}/logout",                    'logout_path' => "/{$this['config']['admin_route']}/logout",
                   'target_url' => "/{$this['config']['admin_route']}/",                    'target_url' => "/{$this['config']['admin_route']}/",
               ),                ),
               'users' => $this['orm.em']->getRepository('Eccube\Entity\Member'),                'users' => $this['orm.em']->getRepository('Eccube\Entity\Member'),
               'anonymous' => true,                'anonymous' => true,
           ),            ),
           'customer' => array(            'customer' => array(
               'pattern' => '^/',                'pattern' => '^/',
               'form' => array(                'form' => array(
                   'login_path' => '/mypage/login',                    'login_path' => '/mypage/login',
                   'check_path' => '/login_check',                    'check_path' => '/login_check',
                   'username_parameter' => 'login_email',                    'username_parameter' => 'login_email',
                   'password_parameter' => 'login_pass',                    'password_parameter' => 'login_pass',
                   'with_csrf' => true,                    'with_csrf' => true,
                   'use_forward' => true,                    'use_forward' => true,
               ),                ),
               'logout' => array(                'logout' => array(
                   'logout_path' => '/logout',                    'logout_path' => '/logout',
                   'target_url' => '/',                    'target_url' => '/',
               ),                ),
               'remember_me' => array(                'remember_me' => array(
                   'key' => sha1($this['config']['auth_magic']),                    'key' => sha1($this['config']['auth_magic']),
                   'name' => 'eccube_rememberme',                    'name' => 'eccube_rememberme',
                   // lifetimeはデフォルトの1年間にする                    // lifetimeはデフォルトの1年間にする
                   // 'lifetime' => $this['config']['cookie_lifetime'],                    // 'lifetime' => $this['config']['cookie_lifetime'],
                   'path' => $this['config']['root_urlpath'] ?: '/',                    'path' => $this['config']['root_urlpath'] ?: '/',
                   'secure' => $this['config']['force_ssl'],                    'secure' => $this['config']['force_ssl'],
                   'httponly' => true,                    'httponly' => true,
                   'always_remember_me' => false,                    'always_remember_me' => false,
                   'remember_me_parameter' => 'login_memory',                    'remember_me_parameter' => 'login_memory',
               ),                ),
               'users' => $this['orm.em']->getRepository('Eccube\Entity\Customer'),                'users' => $this['orm.em']->getRepository('Eccube\Entity\Customer'),
               'anonymous' => true,                'anonymous' => true,
           ),            ),
       );        );
   
       $this['security.access_rules'] = array(        $this['security.access_rules'] = array(
           array("^/{$this['config']['admin_route']}/login", 'IS_AUTHENTICATED_ANONYMOUSLY'),            array("^/{$this['config']['admin_route']}/login", 'IS_AUTHENTICATED_ANONYMOUSLY'),
           array("^/{$this['config']['admin_route']}", 'ROLE_ADMIN'),            array("^/{$this['config']['admin_route']}", 'ROLE_ADMIN'),
           array('^/mypage/login', 'IS_AUTHENTICATED_ANONYMOUSLY'),            array('^/mypage/login', 'IS_AUTHENTICATED_ANONYMOUSLY'),
           array('^/mypage/withdraw_complete', 'IS_AUTHENTICATED_ANONYMOUSLY'),            array('^/mypage/withdraw_complete', 'IS_AUTHENTICATED_ANONYMOUSLY'),
           array('^/mypage/change', 'IS_AUTHENTICATED_FULLY'),            array('^/mypage/change', 'IS_AUTHENTICATED_FULLY'),
           array('^/mypage', 'ROLE_USER'),            array('^/mypage', 'ROLE_USER'),
       );        );
   
       $this['eccube.password_encoder'] = $this->share(function($app) {        $this['eccube.password_encoder'] = $this->share(function($app) {
           return new \Eccube\Security\Core\Encoder\PasswordEncoder($app['config']);            return new \Eccube\Security\Core\Encoder\PasswordEncoder($app['config']);
       });        });
       $this['security.encoder_factory'] = $this->share(function($app) {        $this['security.encoder_factory'] = $this->share(function($app) {
           return new \Symfony\Component\Security\Core\Encoder\EncoderFactory(array(            return new \Symfony\Component\Security\Core\Encoder\EncoderFactory(array(
               'Eccube\Entity\Customer' => $app['eccube.password_encoder'],                'Eccube\Entity\Customer' => $app['eccube.password_encoder'],
               'Eccube\Entity\Member' => $app['eccube.password_encoder'],                'Eccube\Entity\Member' => $app['eccube.password_encoder'],
           ));            ));
       });        });
       $this['eccube.event_listner.security'] = $this->share(function($app) {        $this['eccube.event_listner.security'] = $this->share(function($app) {
           return new \Eccube\EventListener\SecurityEventListener($app['orm.em']);            return new \Eccube\EventListener\SecurityEventListener($app['orm.em']);
       });        });
       $this['user'] = function($app) {        $this['user'] = function($app) {
           $token = $app['security']->getToken();            $token = $app['security']->getToken();
   
           return ($token !== null) ? $token->getUser() : null;            return ($token !== null) ? $token->getUser() : null;
       };        };
   
       // ログイン時のイベントを設定.        // ログイン時のイベントを設定.
       $this['dispatcher']->addListener(\Symfony\Component\Security\Http\SecurityEvents::INTERACTIVE_LOGIN, array($this['eccube.event_listner.security'], 'onInteractiveLogin'));        $this['dispatcher']->addListener(\Symfony\Component\Security\Http\SecurityEvents::INTERACTIVE_LOGIN, array($this['eccube.event_listner.security'], 'onInteractiveLogin'));
   
       // Voterの設定        // Voterの設定
       $app = $this;        $app = $this;
       $this['authority_voter'] = $this->share(function($app) {        $this['authority_voter'] = $this->share(function($app) {
           return new \Eccube\Security\Voter\AuthorityVoter($app);            return new \Eccube\Security\Voter\AuthorityVoter($app);
       });        });
   
       $app['security.voters'] = $app->extend('security.voters', function($voters) use ($app) {        $app['security.voters'] = $app->extend('security.voters', function($voters) use ($app) {
           $voters[] = $app['authority_voter'];            $voters[] = $app['authority_voter'];
   
           return $voters;            return $voters;
       });        });
   
       $this['security.access_manager'] = $this->share(function($app) {        $this['security.access_manager'] = $this->share(function($app) {
           return new \Symfony\Component\Security\Core\Authorization\AccessDecisionManager($app['security.voters'], 'unanimous');            return new \Symfony\Component\Security\Core\Authorization\AccessDecisionManager($app['security.voters'], 'unanimous');
       });        });
   
   }    }
   
   public function initializePlugin()    public function initializePlugin()
   {    {
       if ($this->initializedPlugin) {        if ($this->initializedPlugin) {
           return;            return;
       }        }
   
       // setup event dispatcher        // setup event dispatcher
       $this->initPluginEventDispatcher();        $this->initPluginEventDispatcher();
   
       // load plugin        // load plugin
       $this->loadPlugin();        $this->loadPlugin();
   
       $this->initializedPlugin = true;        $this->initializedPlugin = true;
   }    }
   
   public function initPluginEventDispatcher()    public function initPluginEventDispatcher()
   {    {
       // EventDispatcher        // EventDispatcher
       $this['eccube.event.dispatcher'] = $this->share(function() {        $this['eccube.event.dispatcher'] = $this->share(function() {
           return new EventDispatcher();            return new EventDispatcher();
       });        });
   
       // hook point        // hook point
       $this->before(function(Request $request, \Silex\Application $app) {        $this->before(function(Request $request, \Silex\Application $app) {
           $app['eccube.event.dispatcher']->dispatch('eccube.event.app.before');            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.before');
       }, self::EARLY_EVENT);        }, self::EARLY_EVENT);
   
       $this->before(function(Request $request, \Silex\Application $app) {        $this->before(function(Request $request, \Silex\Application $app) {
           $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.before';            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.before';
           $app['eccube.event.dispatcher']->dispatch($event);            $app['eccube.event.dispatcher']->dispatch($event);
       });        });
   
       $this->after(function(Request $request, Response $response, \Silex\Application $app) {        $this->after(function(Request $request, Response $response, \Silex\Application $app) {
           $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.after';            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.after';
           $app['eccube.event.dispatcher']->dispatch($event);            $app['eccube.event.dispatcher']->dispatch($event);
       });        });
   
       $this->after(function(Request $request, Response $response, \Silex\Application $app) {        $this->after(function(Request $request, Response $response, \Silex\Application $app) {
           $app['eccube.event.dispatcher']->dispatch('eccube.event.app.after');            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.after');
       }, self::LATE_EVENT);        }, self::LATE_EVENT);
   
       $this->finish(function(Request $request, Response $response, \Silex\Application $app) {        $this->finish(function(Request $request, Response $response, \Silex\Application $app) {
           $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.finish';            $event = 'eccube.event.controller.'.$request->attributes->get('_route').'.finish';
           $app['eccube.event.dispatcher']->dispatch($event);            $app['eccube.event.dispatcher']->dispatch($event);
       });        });
   
       $app = $this;        $app = $this;
       $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function(\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function(\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
           $route = $event->getRequest()->attributes->get('_route');            $route = $event->getRequest()->attributes->get('_route');
           $app['eccube.event.dispatcher']->dispatch('eccube.event.render.'.$route.'.before', $event);            $app['eccube.event.dispatcher']->dispatch('eccube.event.render.'.$route.'.before', $event);
       });        });
   
       // Request Event        // Request Event
       $this->on(\Symfony\Component\HttpKernel\KernelEvents::REQUEST, function(\Symfony\Component\HttpKernel\Event\GetResponseEvent $event) use ($app) {        $this->on(\Symfony\Component\HttpKernel\KernelEvents::REQUEST, function(\Symfony\Component\HttpKernel\Event\GetResponseEvent $event) use ($app) {
   
           if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
               return;                return;
           }            }
   
           $route = $event->getRequest()->attributes->get('_route');            $route = $event->getRequest()->attributes->get('_route');
   
           if (is_null($route)) {            if (is_null($route)) {
               return;                return;
           }            }
   
           $app['monolog']->debug('KernelEvents::REQUEST '.$route);            $app['monolog']->debug('KernelEvents::REQUEST '.$route);
   
           // 全体            // 全体
           $app['eccube.event.dispatcher']->dispatch('eccube.event.app.request', $event);            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.request', $event);
   
           if (strpos('admin', $route) === 0) {            if (strpos('admin', $route) === 0) {
               // 管理画面                // 管理画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.request', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.request', $event);
           } else {            } else {
               // フロント画面                // フロント画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.front.request', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.request', $event);
           }            }
   
           // ルーティング単位            // ルーティング単位
           $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.request", $event);            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.request", $event);
   
       }, 30); // Routing(32)が解決しし, 認証判定(8)が実行される前のタイミング.        }, 30); // Routing(32)が解決しし, 認証判定(8)が実行される前のタイミング.
   
       // Controller Event        // Controller Event
       $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {        $this->on(\Symfony\Component\HttpKernel\KernelEvents::CONTROLLER, function(\Symfony\Component\HttpKernel\Event\FilterControllerEvent $event) use ($app) {
   
           if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
               return;                return;
           }            }
   
   
           $route = $event->getRequest()->attributes->get('_route');            $route = $event->getRequest()->attributes->get('_route');
   
           if (is_null($route)) {            if (is_null($route)) {
               return;                return;
           }            }
   
           $app['monolog']->debug('KernelEvents::CONTROLLER '.$route);            $app['monolog']->debug('KernelEvents::CONTROLLER '.$route);
   
           // 全体            // 全体
           $app['eccube.event.dispatcher']->dispatch('eccube.event.app.controller', $event);            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.controller', $event);
   
           if (strpos('admin', $route) === 0) {            if (strpos('admin', $route) === 0) {
               // 管理画面                // 管理画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.controller', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.controller', $event);
           } else {            } else {
               // フロント画面                // フロント画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.front.controller', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.controller', $event);
           }            }
   
           // ルーティング単位            // ルーティング単位
           $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.controller", $event);            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.controller", $event);
       });        });
   
       // Response Event        // Response Event
       $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function(\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {        $this->on(\Symfony\Component\HttpKernel\KernelEvents::RESPONSE, function(\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event) use ($app) {
   
           if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
               return;                return;
           }            }
   
           $route = $event->getRequest()->attributes->get('_route');            $route = $event->getRequest()->attributes->get('_route');
   
           if (is_null($route)) {            if (is_null($route)) {
               return;                return;
           }            }
   
           $app['monolog']->debug('KernelEvents::RESPONSE '.$route);            $app['monolog']->debug('KernelEvents::RESPONSE '.$route);
   
           // ルーティング単位            // ルーティング単位
           $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.response", $event);            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.response", $event);
   
           if (strpos('admin', $route) === 0) {            if (strpos('admin', $route) === 0) {
               // 管理画面                // 管理画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.response', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.response', $event);
           } else {            } else {
               // フロント画面                // フロント画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.front.response', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.response', $event);
           }            }
   
           // 全体            // 全体
           $app['eccube.event.dispatcher']->dispatch('eccube.event.app.response', $event);            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.response', $event);
       });        });
   
       // Exception Event        // Exception Event
       $this->on(\Symfony\Component\HttpKernel\KernelEvents::EXCEPTION, function(\Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event) use ($app) {        $this->on(\Symfony\Component\HttpKernel\KernelEvents::EXCEPTION, function(\Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event) use ($app) {
   
           if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {            if (\Symfony\Component\HttpKernel\HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
               return;                return;
           }            }
   
           $route = $event->getRequest()->attributes->get('_route');            $route = $event->getRequest()->attributes->get('_route');
   
           if (is_null($route)) {            if (is_null($route)) {
               return;                return;
           }            }
   
           $app['monolog']->debug('KernelEvents::EXCEPTION '.$route);            $app['monolog']->debug('KernelEvents::EXCEPTION '.$route);
   
           // ルーティング単位            // ルーティング単位
           $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.exception", $event);            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.exception", $event);
   
           if (strpos('admin', $route) === 0) {            if (strpos('admin', $route) === 0) {
               // 管理画面                // 管理画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.exception', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.exception', $event);
           } else {            } else {
               // フロント画面                // フロント画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.front.exception', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.exception', $event);
           }            }
   
           // 全体            // 全体
           $app['eccube.event.dispatcher']->dispatch('eccube.event.app.exception', $event);            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.exception', $event);
       });        });
   
       // Terminate Event        // Terminate Event
       $this->on(\Symfony\Component\HttpKernel\KernelEvents::TERMINATE, function(\Symfony\Component\HttpKernel\Event\PostResponseEvent $event) use ($app) {        $this->on(\Symfony\Component\HttpKernel\KernelEvents::TERMINATE, function(\Symfony\Component\HttpKernel\Event\PostResponseEvent $event) use ($app) {
   
           $route = $event->getRequest()->attributes->get('_route');            $route = $event->getRequest()->attributes->get('_route');
   
           if (is_null($route)) {            if (is_null($route)) {
               return;                return;
           }            }
   
           $app['monolog']->debug('KernelEvents::TERMINATE '.$route);            $app['monolog']->debug('KernelEvents::TERMINATE '.$route);
   
           // ルーティング単位            // ルーティング単位
           $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.terminate", $event);            $app['eccube.event.dispatcher']->dispatch("eccube.event.route.{$route}.terminate", $event);
   
           if (strpos('admin', $route) === 0) {            if (strpos('admin', $route) === 0) {
               // 管理画面                // 管理画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.terminate', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.admin.terminate', $event);
           } else {            } else {
               // フロント画面                // フロント画面
               $app['eccube.event.dispatcher']->dispatch('eccube.event.front.terminate', $event);                $app['eccube.event.dispatcher']->dispatch('eccube.event.front.terminate', $event);
           }            }
   
           // 全体            // 全体
           $app['eccube.event.dispatcher']->dispatch('eccube.event.app.terminate', $event);            $app['eccube.event.dispatcher']->dispatch('eccube.event.app.terminate', $event);
       });        });
   }    }
   
   public function loadPlugin()    public function loadPlugin()
   {    {
       // プラグインディレクトリを探索.        // プラグインディレクトリを探索.
       $basePath = __DIR__.'/../../app/Plugin';        $basePath = __DIR__.'/../../app/Plugin';
       $finder = Finder::create()        $finder = Finder::create()
           ->in($basePath)            ->in($basePath)
           ->directories()            ->directories()
           ->depth(0);            ->depth(0);
   
       $finder->sortByName();        $finder->sortByName();
   
       // ハンドラ優先順位をdbから持ってきてハッシュテーブルを作成        // ハンドラ優先順位をdbから持ってきてハッシュテーブルを作成
       $priorities = array();        $priorities = array();
       $handlers = $this['orm.em']        $handlers = $this['orm.em']
           ->getRepository('Eccube\Entity\PluginEventHandler')            ->getRepository('Eccube\Entity\PluginEventHandler')
           ->getHandlers();            ->getHandlers();
       foreach ($handlers as $handler) {        foreach ($handlers as $handler) {
           if ($handler->getPlugin()->getEnable() && !$handler->getPlugin()->getDelFlg()) {            if ($handler->getPlugin()->getEnable() && !$handler->getPlugin()->getDelFlg()) {
   
               $priority = $handler->getPriority();                $priority = $handler->getPriority();
           } else {            } else {
               // Pluginがdisable、削除済みの場合、EventHandlerのPriorityを全て0とみなす                // Pluginがdisable、削除済みの場合、EventHandlerのPriorityを全て0とみなす
               $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED;                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED;
           }            }
           $priorities[$handler->getPlugin()->getClassName()][$handler->getEvent()][$handler->getHandler()] = $priority;            $priorities[$handler->getPlugin()->getClassName()][$handler->getEvent()][$handler->getHandler()] = $priority;
       }        }
   
       // プラグインをロードする.        // プラグインをロードする.
       // config.yml/event.ymlの定義に沿ってインスタンスの生成を行い, イベント設定を行う.        // config.yml/event.ymlの定義に沿ってインスタンスの生成を行い, イベント設定を行う.
       foreach ($finder as $dir) {        foreach ($finder as $dir) {
           //config.ymlのないディレクトリは無視する            //config.ymlのないディレクトリは無視する
           $path = $dir->getRealPath();            $path = $dir->getRealPath();
           $code = $dir->getBaseName();            $code = $dir->getBaseName();
           try {            try {
               $this['eccube.service.plugin']->checkPluginArchiveContent($path);                $this['eccube.service.plugin']->checkPluginArchiveContent($path);
           } catch (\Eccube\Exception\PluginException $e) {            } catch (\Eccube\Exception\PluginException $e) {
               $this['monolog']->warning("skip {$code} config loading. config.yml not foud or invalid.", array(                $this['monolog']->warning("skip {$code} config loading. config.yml not foud or invalid.", array(
                   'path' =>  $path,                    'path' =>  $path,
                   'original-message' => $e->getMessage()                    'original-message' => $e->getMessage()
               ));                ));
               continue;                continue;
           }            }
           $config = $this['eccube.service.plugin']->readYml($dir->getRealPath().'/config.yml');            $config = $this['eccube.service.plugin']->readYml($dir->getRealPath().'/config.yml');
   
           $plugin = $this['orm.em']            $plugin = $this['orm.em']
               ->getRepository('Eccube\Entity\Plugin')                ->getRepository('Eccube\Entity\Plugin')
               ->findOneBy(array('code' => $config['code']));                ->findOneBy(array('code' => $config['code']));
   
           // const            // const
           if (isset($config['const'])) {            if (isset($config['const'])) {
               $this['config'] = $this->share($this->extend('config', function($eccubeConfig) use ($config) {                $this['config'] = $this->share($this->extend('config', function($eccubeConfig) use ($config) {
                   $eccubeConfig[$config['code']] = array(                    $eccubeConfig[$config['code']] = array(
                       'const' => $config['const'],                        'const' => $config['const'],
                   );                    );
   
                   return $eccubeConfig;                    return $eccubeConfig;
               }));                }));
           }            }
   
           if ($plugin && $plugin->getEnable() == Constant::DISABLED) {            if ($plugin && $plugin->getEnable() == Constant::DISABLED) {
               // プラグインが無効化されていれば読み込まない                // プラグインが無効化されていれば読み込まない
               continue;                continue;
           }            }
   
           // Type: Event            // Type: Event
           if (isset($config['event'])) {            if (isset($config['event'])) {
               $class = '\\Plugin\\'.$config['code'].'\\'.$config['event'];                $class = '\\Plugin\\'.$config['code'].'\\'.$config['event'];
               $eventExists = true;                $eventExists = true;
   
               if (!class_exists($class)) {                if (!class_exists($class)) {
                   $this['monolog']->warning("skip {$code} loading. event class not foud.", array(                    $this['monolog']->warning("skip {$code} loading. event class not foud.", array(
                       'class' =>  $class,                        'class' =>  $class,
                   ));                    ));
                   $eventExists = false;                    $eventExists = false;
               }                }
   
               if ($eventExists && file_exists($dir->getRealPath().'/event.yml')) {                if ($eventExists && file_exists($dir->getRealPath().'/event.yml')) {
   
                   $subscriber = new $class($this);                    $subscriber = new $class($this);
   
                   foreach (Yaml::parse(file_get_contents($dir->getRealPath().'/event.yml')) as $event => $handlers) {                    foreach (Yaml::parse(file_get_contents($dir->getRealPath().'/event.yml')) as $event => $handlers) {
                       foreach ($handlers as $handler) {                        foreach ($handlers as $handler) {
                           if (!isset($priorities[$config['event']][$event][$handler[0]])) { // ハンドラテーブルに登録されていない(ソースにしか記述されていない)ハンドラは一番後ろにする                            if (!isset($priorities[$config['event']][$event][$handler[0]])) { // ハンドラテーブルに登録されていない(ソースにしか記述されていない)ハンドラは一番後ろにする
                               $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_LATEST;                                $priority = \Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_LATEST;
                           } else {                            } else {
                               $priority = $priorities[$config['event']][$event][$handler[0]];                                $priority = $priorities[$config['event']][$event][$handler[0]];
                           }                            }
                           // 優先度が0のプラグインは登録しない                            // 優先度が0のプラグインは登録しない
                           if (\Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED != $priority) {                            if (\Eccube\Entity\PluginEventHandler::EVENT_PRIORITY_DISABLED != $priority) {
                               $this['eccube.event.dispatcher']->addListener($event, array($subscriber, $handler[0]), $priority);                                $this['eccube.event.dispatcher']->addListener($event, array($subscriber, $handler[0]), $priority);
                           }                            }
                       }                        }
                   }                    }
               }                }
           }            }
           // Type: ServiceProvider            // Type: ServiceProvider
           if (isset($config['service'])) {            if (isset($config['service'])) {
               foreach ($config['service'] as $service) {                foreach ($config['service'] as $service) {
                   $class = '\\Plugin\\'.$config['code'].'\\ServiceProvider\\'.$service;                    $class = '\\Plugin\\'.$config['code'].'\\ServiceProvider\\'.$service;
                   if (!class_exists($class)) {                    if (!class_exists($class)) {
                       $this['monolog']->warning("skip {$code} loading. service provider class not foud.", array(                        $this['monolog']->warning("skip {$code} loading. service provider class not foud.", array(
                           'class' =>  $class,                            'class' =>  $class,
                       ));                        ));
                       continue;                        continue;
                   }                    }
                   $this->register(new $class($this));                    $this->register(new $class($this));
               }                }
           }            }
       }        }
   }    }
   
   /**    /**
    *     *
    * データベースの接続を確認     * データベースの接続を確認
    * 成功 : trueを返却     * 成功 : trueを返却
    * 失敗 : \Doctrine\DBAL\DBALExceptionエラーが発生( 接続に失敗した場合 )、エラー画面を表示しdie()     * 失敗 : \Doctrine\DBAL\DBALExceptionエラーが発生( 接続に失敗した場合 )、エラー画面を表示しdie()
    * 備考 : app['debug']がtrueの際は処理を行わない     * 備考 : app['debug']がtrueの際は処理を行わない
    * @return boolean true     * @return boolean true
    *     *
    */      */ 
   protected function checkDatabaseConnection()    protected function checkDatabaseConnection()
   {    {
       if ($this['debug']) {        if ($this['debug']) {
           return;            return;
       }        }
       try {        try {
           $this['db']->connect();            $this['db']->connect();
       } catch (\Doctrine\DBAL\DBALException $e) {        } catch (\Doctrine\DBAL\DBALException $e) {
           $this['monolog']->error($e->getMessage());            $this['monolog']->error($e->getMessage());
           $this['twig.path'] = array(__DIR__.'/Resource/template/exception');            $this['twig.path'] = array(__DIR__.'/Resource/template/exception');
           $html = $this['twig']->render('error.twig', array(            $html = $this['twig']->render('error.twig', array(
               'error_title' => 'データーベース接続エラー',                'error_title' => 'データーベース接続エラー',
               'error_message' => 'データーベースを確認してください',                'error_message' => 'データーベースを確認してください',
           ));            ));
           $response = new Response();            $response = new Response();
           $response->setContent($html);            $response->setContent($html);
           $response->setStatusCode('500');            $response->setStatusCode('500');
           $response->headers->set('Content-Type', 'text/html');            $response->headers->set('Content-Type', 'text/html');
           $response->send();            $response->send();
           die();            die();
       }        }
       return true;        return true;
   }    }
} }