diff --git a/plugins/baser-core/src/Controller/Admin/BcAdminAppController.php b/plugins/baser-core/src/Controller/Admin/BcAdminAppController.php index e9aefeba3d..80aa39c9d0 100644 --- a/plugins/baser-core/src/Controller/Admin/BcAdminAppController.php +++ b/plugins/baser-core/src/Controller/Admin/BcAdminAppController.php @@ -12,7 +12,7 @@ namespace BaserCore\Controller\Admin; use Authentication\Controller\Component\AuthenticationComponent; -use BaserCore\Controller\BcAppController; +use BaserCore\Controller\AppController; use BaserCore\Service\Admin\BcAdminAppServiceInterface; use BaserCore\Service\SiteConfigsService; use BaserCore\Service\SiteConfigsServiceInterface; @@ -34,7 +34,7 @@ * Class BcAdminAppController * @property AuthenticationComponent $Authentication */ -class BcAdminAppController extends BcAppController +class BcAdminAppController extends AppController { /** diff --git a/plugins/baser-core/src/Controller/AppController.php b/plugins/baser-core/src/Controller/AppController.php index cec02db8f7..dde852c2af 100644 --- a/plugins/baser-core/src/Controller/AppController.php +++ b/plugins/baser-core/src/Controller/AppController.php @@ -20,6 +20,7 @@ use BaserCore\Annotation\Checked; use BaserCore\Annotation\Note; use BaserCore\Service\AppServiceInterface; +use BaserCore\Service\DblogsServiceInterface; use BaserCore\Service\PermissionsServiceInterface; use BaserCore\Utility\BcContainerTrait; use BaserCore\Utility\BcSiteConfig; @@ -37,6 +38,7 @@ use Cake\Http\ServerRequest; use Cake\Utility\Hash; use Cake\Utility\Inflector; +use Psr\Http\Message\ResponseInterface; /** * Class AppController @@ -54,22 +56,23 @@ class AppController extends BaseController use BcContainerTrait; /** - * BcAppController constructor. + * AppController constructor. * @param ServerRequest|null $request * @param Response|null $response * @param string|null $name * @param EventManagerInterface|null $eventManager * @param ComponentRegistry|null $components + * @return void|ResponseInterface * @checked * @noTodo * @unitTest */ public function __construct( - ?ServerRequest $request = null, - ?Response $response = null, - ?string $name = null, + ?ServerRequest $request = null, + ?Response $response = null, + ?string $name = null, ?EventManagerInterface $eventManager = null, - ?ComponentRegistry $components = null + ?ComponentRegistry $components = null ) { parent::__construct($request, $response, $name, $eventManager, $components); @@ -82,10 +85,10 @@ public function __construct( if (!($request? $request->is('install') : false)) { // app_local.php が存在しない場合は、CakePHPの Internal Server のエラー画面が出て、 // 原因がわからなくなるので強制的にコピーする - if($this->getName() === 'BcError' && !file_exists(CONFIG . 'app_local.php')) { + if ($this->getName() === 'BcError' && !file_exists(CONFIG . 'app_local.php')) { copy(CONFIG . 'app_local.example.php', CONFIG . 'app_local.php'); // app_local.php が存在しない場合、.env もない可能性があるので確認 - if(!file_exists(CONFIG . '.env')){ + if (!file_exists(CONFIG . '.env')) { copy(CONFIG . '.env.example', CONFIG . '.env'); } } @@ -105,7 +108,6 @@ public function __construct( } } } - } /** @@ -137,13 +139,13 @@ public function initialize(): void public function beforeFilter(EventInterface $event) { $response = parent::beforeFilter($event); - if($response) return $response; + if ($response) return $response; - // index.php をつけたURLの場合、base の値が正常でなくなり、 - // 内部リンクが影響を受けておかしくなってしまうため強制的に Not Found とする - if(preg_match('/\/index\.php\//', $this->getRequest()->getAttribute('base'))) { - $this->notFound(); - } + // index.php をつけたURLの場合、base の値が正常でなくなり、 + // 内部リンクが影響を受けておかしくなってしまうため強制的に Not Found とする + if (preg_match('/\/index\.php\//', $this->getRequest()->getAttribute('base'))) { + $this->notFound(); + } if (!$this->getRequest()->is('requestview')) return; @@ -160,13 +162,13 @@ public function beforeFilter(EventInterface $event) return; } - if(!$this->checkPermission()) { + if (!$this->checkPermission()) { $prefix = BcUtil::getRequestPrefix($this->getRequest()); if ($prefix === 'Api/Admin') { throw new ForbiddenException(__d('baser_core', '指定されたAPIエンドポイントへのアクセスは許可されていません。')); } else { if (BcUtil::loginUser()) { - if($this->getRequest()->getMethod() === 'GET') { + if ($this->getRequest()->getMethod() === 'GET') { $this->BcMessage->setError(__d('baser_core', '指定されたページへのアクセスは許可されていません。')); } else { $this->BcMessage->setError(__d('baser_core', '実行した操作は許可されていません。')); @@ -174,7 +176,7 @@ public function beforeFilter(EventInterface $event) } // リファラが存在する場合はリファラにリダイレクトする // $this->referer() で判定した場合、リファラがなくてもトップのURLが返却されるため ServerRequest で判定 - if($this->getRequest()->getEnv('HTTP_REFERER')) { + if ($this->getRequest()->getEnv('HTTP_REFERER')) { $url = $this->referer(); } else { $url = Configure::read("BcPrefixAuth.{$prefix}.loginRedirect"); @@ -200,7 +202,7 @@ public function beforeFilter(EventInterface $event) private function checkPermission() { $user = BcUtil::loginUser(); - if($user && $user->user_groups) { + if ($user && $user->user_groups) { $userGroupsIds = Hash::extract($user->toArray()['user_groups'], '{n}.id'); } else { $userGroupsIds = []; @@ -292,8 +294,8 @@ protected function _autoConvertEncodingByArray($data, $outenc = 'UTF-8'): array continue; } $inenc = mb_detect_encoding((string)$value); - if(!$inenc) continue; - if(!in_array($inenc, Configure::read('BcEncode.detectOrder'))) continue; + if (!$inenc) continue; + if (!in_array($inenc, Configure::read('BcEncode.detectOrder'))) continue; if ($inenc === $outenc) continue; // 半角カナは一旦全角に変換する $value = mb_convert_kana($value, 'KV', $inenc); @@ -533,4 +535,45 @@ public function notFound() throw new NotFoundException(__d('baser_core', '見つかりませんでした。')); } + /** + * データベースログを記録する + * + * @param string $message + * @return \Cake\Datasource\EntityInterface + * @checked + * @unitTest + * @noTodo + */ + protected function saveDblog($message) + { + $dblogsService = $this->getService(DblogsServiceInterface::class); + return $dblogsService->create(['message' => $message]); + } + + /** + * Ajax用のエラーを出力する + * + * @param int $errorNo エラーのステータスコード + * @param mixed $message エラーメッセージ + * @return void + * @deprecated since 5.0.5 このメソッドは非推奨です。 + * @checked + * @noTodo + */ + public function ajaxError(int $errorNo = 500, $message = '') + { + $this->response = $this->getResponse()->withStatus($errorNo); + if (!$message) return; + if (!is_array($message)) $message = [$message]; + $aryMessage = []; + foreach($message as $value) { + if (is_array($value)) { + $aryMessage[] = implode('
', $value); + } else { + $aryMessage[] = $value; + } + } + echo implode('
', $aryMessage); + } + } diff --git a/plugins/baser-core/src/Controller/BcAppController.php b/plugins/baser-core/src/Controller/BcAppController.php deleted file mode 100644 index 36159dc980..0000000000 --- a/plugins/baser-core/src/Controller/BcAppController.php +++ /dev/null @@ -1,252 +0,0 @@ - - * Copyright (c) NPO baser foundation - * - * @copyright Copyright (c) NPO baser foundation - * @link https://basercms.net baserCMS Project - * @since 5.0.0 - * @license https://basercms.net/license/index.html MIT License - */ - -namespace BaserCore\Controller; - -use BaserCore\Utility\BcContainerTrait; -use Cake\Event\EventInterface; -use BaserCore\Utility\BcUtil; -use BaserCore\Service\DblogsServiceInterface; -use Cake\Core\Configure; -use BaserCore\Annotation\UnitTest; -use BaserCore\Annotation\NoTodo; -use BaserCore\Annotation\Checked; -use BaserCore\Annotation\Note; - -/** - * Class BcAppController - */ -class BcAppController extends AppController -{ - - /** - * Trait - */ - use BcContainerTrait; - - /** - * サブディレクトリ - * - * @var string - * @access public - */ - public $subDir = null; - - /** - * コンテンツタイトル - * - * @var string - */ - public $contentsTitle = ''; - - /** - * プレビューフラグ - * - * @var bool - */ - public $preview = false; - - /** - * 管理画面テーマ - * - * @var string - */ - public $adminTheme = null; - - /** - * サイトデータ - * - * @var array - */ - public $site = []; - - /** - * コンテンツデータ - * - * @var array - */ - public $content = []; - - /** - * beforeFilter - * - * @checked - * @note(value="マイルストーン2が終わってから確認する") - * @todo ucmitz 未確認 - */ - public function beforeFilter(EventInterface $event) - { - return parent::beforeFilter($event); - - // 認証設定 - if (isset($this->BcAuthConfigure)) { - $authConfig = []; - if (!empty($this->request->getParam('prefix'))) { - $currentAuthPrefix = $this->request->getParam('prefix'); - } else { - $currentAuthPrefix = 'front'; - } - $authPrefixSettings = Configure::read('BcPrefixAuth'); - foreach($authPrefixSettings as $key => $authPrefixSetting) { - if (isset($authPrefixSetting['alias']) && $authPrefixSetting['alias'] == $currentAuthPrefix) { - $authConfig = $authPrefixSetting; - $authConfig['auth_prefix'] = $authPrefixSetting['alias']; - break; - } - if ($this->request->getParam('action') !== 'back_agent') { - if ($key == $currentAuthPrefix) { - $authConfig = $authPrefixSetting; - $authConfig['auth_prefix'] = $key; - break; - } - } - } - if ($authConfig) { - $this->BcAuthConfigure->setting($authConfig); - } else { - $this->BcAuth->setSessionKey('Auth.' . Configure::read('BcPrefixAuth.Admin.sessionKey')); - } - - // ================================================================= - // ユーザーの存在チェック - // ログイン中のユーザーを管理側で削除した場合、ログイン状態を削除する必要がある為 - // ================================================================= - $user = $this->BcAuth->user(); - if ($user && $authConfig && (empty($authConfig['type']) || $authConfig['type'] === 'Form')) { - $userModel = $authConfig['userModel']; - $User = ClassRegistry::init($userModel); - if (strpos($userModel, '.') !== false) { - [$plugin, $userModel] = explode('.', $userModel); - } - if ($userModel && !empty($this->{$userModel})) { - $nameField = 'name'; - if (!empty($authConfig['username'])) { - $nameField = $authConfig['username']; - } - $conditions = [ - $userModel . '.id' => $user['id'], - $userModel . '.' . $nameField => $user[$nameField] - ]; - if (isset($User->belongsTo['UserGroup'])) { - $UserGroup = ClassRegistry::init('UserGroup'); - $userGroups = $UserGroup->find('all', ['conditions' => ['UserGroup.auth_prefix LIKE' => '%' . $authConfig['auth_prefix'] . '%'], 'recursive' => -1]); - $userGroupIds = Hash::extract($userGroups, '{n}.UserGroup.id'); - $conditions[$userModel . '.user_group_id'] = $userGroupIds; - } - if (!$User->find('count', [ - 'conditions' => $conditions, - 'recursive' => -1])) { - $this->Session->delete(BcAuthComponent::$sessionKey); - } - } - } - } - - } - - /** - * beforeRender - * - * @return void - */ - public function beforeRender(EventInterface $event): void - { - parent::beforeRender($event); - // TODO ucmitz 未確認 - return; - $this->__loadDataToView(); - } - - /** - * View用のデータを読み込む。 - * beforeRenderで呼び出される - * - * @return void - */ - private function __loadDataToView() - { - $this->set('preview', $this->preview); - - if (!empty($this->request->getParam('prefix'))) { - $currentPrefix = $this->request->getParam('prefix'); - } else { - $currentPrefix = 'front'; - } - - $user = BcUtil::loginUser(); - $sessionKey = Configure::read('BcPrefixAuth.Admin.sessionKey'); - - $authPrefix = Configure::read('BcPrefixAuth.' . $currentPrefix); - if ($authPrefix) { - $currentPrefixUser = BcUtil::loginUser($currentPrefix); - if ($currentPrefixUser) { - $user = $currentPrefixUser; - $sessionKey = BcUtil::getLoginUserSessionKey(); - } - } - - /* ログインユーザー */ - if (BcUtil::isInstalled() && $user && $this->name !== 'Installations' && !Configure::read('BcRequest.isUpdater') && !Configure::read('BcRequest.isMaintenance') && $this->name !== 'CakeError') { - $this->set('user', $user); - } - - $currentUserAuthPrefixes = []; - if ($this->Session->check('Auth.' . $sessionKey . '.UserGroup.auth_prefix')) { - $currentUserAuthPrefixes = explode(',', $this->Session->read('Auth.' . $sessionKey . '.UserGroup.auth_prefix')); - } - $this->set('currentUserAuthPrefixes', $currentUserAuthPrefixes); - } - - /** - * Ajax用のエラーを出力する - * - * @param int $errorNo エラーのステータスコード - * @param mixed $message エラーメッセージ - * @return void - */ - public function ajaxError($errorNo = 500, $message = '') - { - $this->response = $this->response->withStatus($errorNo); - if (!$message) { - return; - } - - if (!is_array($message)) { - return; - } - - $aryMessage = []; - foreach($message as $value) { - if (is_array($value)) { - $aryMessage[] = implode('
', $value); - } else { - $aryMessage[] = $value; - } - } - echo implode('
', $aryMessage); - return; - } - - /** - * データベースログを記録する - * - * @param string $message - * @return \Cake\Datasource\EntityInterface - * @checked - * @unitTest - * @noTodo - */ - protected function saveDblog($message) - { - $DblogsService = $this->getService(DblogsServiceInterface::class); - return $DblogsService->create(['message' => $message]); - } -} diff --git a/plugins/baser-core/src/Controller/PagesController.php b/plugins/baser-core/src/Controller/PagesController.php index adf07b584e..2a24fa80a1 100644 --- a/plugins/baser-core/src/Controller/PagesController.php +++ b/plugins/baser-core/src/Controller/PagesController.php @@ -29,7 +29,6 @@ class PagesController extends BcFrontAppController /** * Trait - * NOTE: BcAppControllerにもあるので、移行時に取り除く */ use BcContainerTrait; diff --git a/plugins/baser-core/src/Model/Entity/User.php b/plugins/baser-core/src/Model/Entity/User.php index 5cab089453..58535591cd 100644 --- a/plugins/baser-core/src/Model/Entity/User.php +++ b/plugins/baser-core/src/Model/Entity/User.php @@ -201,4 +201,20 @@ public function getDisplayName() } } + /** + * 認証領域のプレフィックスを配列で取得する + * @return array + * @checked + * @noTodo + */ + public function getAuthPrefixes(): array + { + if(!$this->user_groups) return []; + $prefixes = []; + foreach($this->user_groups as $userGroup) { + $prefixes += explode(',', $userGroup->auth_prefix); + } + return $prefixes; + } + } diff --git a/plugins/baser-core/src/Service/AppService.php b/plugins/baser-core/src/Service/AppService.php index 93b76a650d..2201069f89 100644 --- a/plugins/baser-core/src/Service/AppService.php +++ b/plugins/baser-core/src/Service/AppService.php @@ -34,7 +34,7 @@ class AppService /** * アプリケーション全体で必要な変数を取得 - * + * * @return array * @checked * @noTodo @@ -42,17 +42,19 @@ class AppService */ public function getViewVarsForAll(): array { + $user = BcUtil::loginUser(); return [ 'currentSite' => $this->getCurrentSite(), 'otherSites' => $this->getOtherSiteList(), - 'loginUser' => BcUtil::loginUser(), - 'currentAdminTheme' => BcUtil::getCurrentAdminTheme() + 'loginUser' => $user, + 'currentAdminTheme' => BcUtil::getCurrentAdminTheme(), + 'currentUserAuthPrefixes' => $user ? $user->getAuthPrefixes() : [], ]; } /** * 現在の管理対象のサイトを取得する - * + * * @return EntityInterface * @checked * @noTodo @@ -72,7 +74,7 @@ public function getCurrentSite(): ?Site /** * 現在の管理対象のサイト以外のリストを取得する - * + * * @return array * @checked * @noTodo diff --git a/plugins/baser-core/tests/TestCase/Controller/AppControllerTest.php b/plugins/baser-core/tests/TestCase/Controller/AppControllerTest.php index 83c5d50b9f..d84c9e77bb 100644 --- a/plugins/baser-core/tests/TestCase/Controller/AppControllerTest.php +++ b/plugins/baser-core/tests/TestCase/Controller/AppControllerTest.php @@ -352,4 +352,43 @@ public function test_setViewConditions() $data = $session->read('BcApp.viewConditions.PagesView.index.data.Content'); $this->assertEquals(['title' => 'default'], $data); } + + + /** + * Test saveDblog + * + * @return void + * @dataProvider saveDblogDataProvider + */ + public function testSaveDblog(string $message, int $userId = null): void + { + $request =$this->getRequest('/baser/admin/baser-core/users/'); + if (isset($userId)) $this->loginAdmin($request, $userId); + + $this->execPrivateMethod($this->AppController, 'saveDblog', [$message]); + + $where = [ + 'message' => $message, + 'controller' => 'Users', + 'action' => 'index' + ]; + if (isset($userId)) { + $where['user_id'] = $userId; + } else { + $where['user_id IS'] = null; + } + + $dblogs = $this->getTableLocator()->get('Dblogs'); + $query = $dblogs->find()->where($where); + $this->assertSame(1, $query->count()); + } + + public function saveDblogDataProvider(): array + { + return [ + ['dblogs testSaveDblog message guest', null], + ['dblogs testSaveDblog message login', 1] + ]; + } + } diff --git a/plugins/baser-core/tests/TestCase/Controller/BcAppControllerTest.php b/plugins/baser-core/tests/TestCase/Controller/BcAppControllerTest.php deleted file mode 100644 index 0122e4e8d0..0000000000 --- a/plugins/baser-core/tests/TestCase/Controller/BcAppControllerTest.php +++ /dev/null @@ -1,106 +0,0 @@ - - * Copyright (c) NPO baser foundation - * - * @copyright Copyright (c) NPO baser foundation - * @link https://basercms.net baserCMS Project - * @since 5.0.0 - * @license https://basercms.net/license/index.html MIT License - */ - -namespace BaserCore\Test\TestCase\Controller; - -use Cake\TestSuite\IntegrationTestTrait; -use BaserCore\TestSuite\BcTestCase; -use BaserCore\Controller\BcAppController; -use Cake\Event\Event; - -/** - * BaserCore\Controller\BcAppController Test Case - */ -class BcAppControllerTest extends BcTestCase -{ - use IntegrationTestTrait; - - /** - * Fixtures - * - * @var array - */ - protected $fixtures = [ - 'plugin.BaserCore.Dblogs', - 'plugin.BaserCore.Users', - 'plugin.BaserCore.UsersUserGroups', - 'plugin.BaserCore.UserGroups', - 'plugin.BaserCore.Sites' - ]; - - /** - * set up - */ - public function setUp(): void - { - parent::setUp(); - $this->BcAppController = new BcAppController($this->getRequest()); - } - - /** - * Tear Down - * - * @return void - */ - public function tearDown(): void - { - parent::tearDown(); - unset($this->BcAppController); - } - - /** - * Test beforeFilter - * - * @return void - */ - public function testBeforeFilter(): void - { - $this->markTestIncomplete('このテストは、まだ実装されていません。'); - } - - /** - * Test saveDblog - * - * @return void - * @dataProvider saveDblogDataProvider - */ - public function testSaveDblog(string $message, int $userId = null): void - { - $request =$this->getRequest('/baser/admin/baser-core/users/'); - if (isset($userId)) $this->loginAdmin($request, $userId); - - $result = $this->execPrivateMethod($this->BcAppController, 'saveDblog', [$message]); - - $where = [ - 'message' => $message, - 'controller' => 'Users', - 'action' => 'index' - ]; - if (isset($userId)) { - $where['user_id'] = $userId; - } else { - $where['user_id IS'] = null; - } - - $dblogs = $this->getTableLocator()->get('Dblogs'); - $query = $dblogs->find()->where($where); - $this->assertSame(1, $query->count()); - } - - public function saveDblogDataProvider(): array - { - return [ - ['dblogs testSaveDblog message guest', null], - ['dblogs testSaveDblog message login', 1] - ]; - } - -} diff --git a/plugins/baser-core/tests/TestCase/Controller/Component/BcFrontContentsComponentTest.php b/plugins/baser-core/tests/TestCase/Controller/Component/BcFrontContentsComponentTest.php index 9d115b5dbd..3e0339961a 100644 --- a/plugins/baser-core/tests/TestCase/Controller/Component/BcFrontContentsComponentTest.php +++ b/plugins/baser-core/tests/TestCase/Controller/Component/BcFrontContentsComponentTest.php @@ -18,7 +18,7 @@ use BaserCore\TestSuite\BcTestCase; use BaserCore\Service\ContentsService; use Cake\Controller\ComponentRegistry; -use BaserCore\Controller\BcAppController; +use BaserCore\Controller\AppController; use BaserCore\Controller\PagesController; use BaserCore\Controller\Component\BcFrontContentsComponent; diff --git a/plugins/bc-custom-content/src/Controller/CustomContentFrontAppController.php b/plugins/bc-custom-content/src/Controller/CustomContentFrontAppController.php index a462bf794c..3929033cc2 100644 --- a/plugins/bc-custom-content/src/Controller/CustomContentFrontAppController.php +++ b/plugins/bc-custom-content/src/Controller/CustomContentFrontAppController.php @@ -11,7 +11,7 @@ namespace BcCustomContent\Controller; -use BaserCore\Controller\BcAppController; +use BaserCore\Controller\AppController; use Cake\Event\EventInterface; use BaserCore\Annotation\UnitTest; use BaserCore\Annotation\NoTodo; @@ -20,7 +20,7 @@ /** * CustomContentFrontAppController */ -class CustomContentFrontAppController extends BcAppController +class CustomContentFrontAppController extends AppController { /**