diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index f50b23dc..6eb23e77 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - php-versions: [ '8.1' ] + php-versions: [ '8.3' ] dependency-version: [ prefer-lowest, prefer-stable ] steps: - uses: actions/checkout@master @@ -50,13 +50,16 @@ jobs: composer validate --strict composer.json # Check that dependencies resolve. composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction + - name: Check that composer file is normalized + run: | + composer normalize --dry-run php-coding-standards: name: PHP coding standards runs-on: ubuntu-latest strategy: matrix: - php-versions: [ '8.1' ] + php-versions: [ '8.3' ] steps: - uses: actions/checkout@master - name: Setup PHP, with composer and extensions @@ -89,7 +92,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - php-versions: [ '8.1' ] + php-versions: [ '8.3' ] steps: - uses: actions/checkout@master - name: Setup PHP, with composer and extensions @@ -113,27 +116,13 @@ jobs: run: | ./scripts/code-analysis - markdownlint: + coding-standards-markdown: + name: Markdown coding standards runs-on: ubuntu-latest - name: markdownlint steps: - name: Checkout - uses: actions/checkout@v2 - - name: Get yarn cache directory path - id: yarn-cache-dir-path - run: echo "::set-output name=dir::$(yarn cache dir)" - - name: Cache yarn packages - uses: actions/cache@v2 - id: yarn-cache - with: - path: ${{ steps.yarn-cache-dir-path.outputs.dir }} - key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} - restore-keys: | - ${{ runner.os }}-yarn- - - name: Yarn install - uses: actions/setup-node@v2 - with: - node-version: '20' - - run: yarn install - - name: markdownlint - run: yarn coding-standards-check/markdownlint + uses: actions/checkout@master + + - name: Coding standards + run: | + docker run --rm --volume $PWD:/md peterdavehello/markdownlint markdownlint --ignore vendor --ignore LICENSE.md '**/*.md' diff --git a/.gitignore b/.gitignore index 1cc8643c..1a6c2523 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,3 @@ composer.lock vendor -node_modules/ -yarn.lock diff --git a/.markdownlint.jsonc b/.markdownlint.jsonc new file mode 100644 index 00000000..a28c5809 --- /dev/null +++ b/.markdownlint.jsonc @@ -0,0 +1,13 @@ +{ + "default": true, + // https://github.com/DavidAnson/markdownlint/blob/main/doc/md013.md + "line-length": { + "line_length": 120, + "code_blocks": false, + "tables": false + }, + // https://github.com/DavidAnson/markdownlint/blob/main/doc/md024.md + "no-duplicate-heading": { + "siblings_only": true + } +} diff --git a/.markdownlintrc b/.markdownlintrc deleted file mode 100644 index 75637156..00000000 --- a/.markdownlintrc +++ /dev/null @@ -1,18 +0,0 @@ -{ - // @see https://github.com/DavidAnson/markdownlint/blob/main/schema/.markdownlint.jsonc - // https://github.com/DavidAnson/markdownlint/blob/main/doc/md013.md - "MD013": { - // Exclude code blocks - "code_blocks": false - }, - - // Prevent complaining on duplicated headings in CHANGELOG.md - // https://github.com/DavidAnson/markdownlint/blob/main/doc/md024.md - "MD024": { - "siblings_only": true - } -} - -// Local Variables: -// mode: json -// End: diff --git a/CHANGELOG.md b/CHANGELOG.md index 274eb0cc..d6fbf37f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,13 @@ before starting to add changes. Use example [placed in the end of the page](#exa ## [Unreleased] +- [#101](https://github.com/OS2Forms/os2forms/pull/101) + - Added support for `os2web_key` in Digital post + - Switched from saving settings in key value store to config, i.e + the module needs to be reconfigured. + - Added support for `os2web_key` in Fasit handler. + - Switched from saving settings in key value store to config, i.e + the module needs to be reconfigured. - Removed modules ldap_auth, logging_alerts, maillog ## [3.21.2] 2025-01-07 diff --git a/README.md b/README.md index 12e4ad05..44eb8e47 100644 --- a/README.md +++ b/README.md @@ -122,29 +122,28 @@ run the checks locally. ```sh docker run --rm --volume ${PWD}:/app --workdir /app itkdev/php8.1-fpm composer install -docker run --rm --volume ${PWD}:/app --workdir /app itkdev/php8.1-fpm composer coding-standards-check - # Fix (some) coding standards issues. docker run --rm --volume ${PWD}:/app --workdir /app itkdev/php8.1-fpm composer coding-standards-apply +docker run --rm --volume ${PWD}:/app --workdir /app itkdev/php8.1-fpm composer coding-standards-check ``` ### Markdown ```sh -docker run --rm --volume ${PWD}:/app --workdir /app node:20 yarn install -docker run --rm --volume ${PWD}:/app --workdir /app node:20 yarn coding-standards-check/markdownlint - -# Fix (some) coding standards issues. -docker run --rm --volume ${PWD}:/app --workdir /app node:20 yarn coding-standards-apply/markdownlint +docker pull peterdavehello/markdownlint +docker run --rm --volume $PWD:/md peterdavehello/markdownlint markdownlint --ignore vendor --ignore LICENSE.md '**/*.md' --fix +docker run --rm --volume $PWD:/md peterdavehello/markdownlint markdownlint --ignore vendor --ignore LICENSE.md '**/*.md' ``` ## Code analysis We use [PHPStan](https://phpstan.org/) for static code analysis. -Running statis code analysis on a standalone Drupal module is a bit tricky, so -we use a helper script to run the analysis: +Running statis code analysis on a standalone Drupal module is a bit tricky, so we use a helper script to run the +analysis: -```sh -./scripts/code-analysis +```shell +docker run --rm --volume ${PWD}:/app --workdir /app itkdev/php8.1-fpm ./scripts/code-analysis ``` + +**Note**: Currently the code analysis is only run on the `os2forms_digital_post` sub-module (cf. [`phpstan.neon`](./phpstan.neon)). diff --git a/composer.json b/composer.json index 828bd6ca..7972ad98 100644 --- a/composer.json +++ b/composer.json @@ -1,20 +1,8 @@ { "name": "os2forms/os2forms", - "type": "drupal-module", "description": "Drupal 8 OS2Form module provides advanced webform functionality for Danish Municipalities", - "minimum-stability": "dev", - "prefer-stable": true, "license": "EUPL-1.2", - "repositories": { - "drupal": { - "type": "composer", - "url": "https://packages.drupal.org/8" - }, - "assets": { - "type": "composer", - "url": "https://asset-packagist.org" - } - }, + "type": "drupal-module", "require": { "php": "^8.1", "ext-dom": "*", @@ -23,7 +11,7 @@ "dompdf/dompdf": "^2.0", "drupal/admin_toolbar": "^3.0", "drupal/advancedqueue": "^1.0", - "drupal/cache_control_override": "^1.1|^2.0", + "drupal/cache_control_override": "^1.1 || ^2.0", "drupal/clientside_validation": "^4.0", "drupal/coc_forms_auto_export": "^2.0@alpha", "drupal/config_entity_revisions": "dev-2.0.x", @@ -43,7 +31,7 @@ "drupal/mailsystem": "^4.1", "drupal/masquerade": "^2.0@RC", "drupal/pathauto": "^1.5", - "drupal/permissions_by_term": "^3.1 || ^2.25", + "drupal/permissions_by_term": "^2.25 || ^3.1", "drupal/queue_mail": "^1.4", "drupal/r4032login": "^2.1", "drupal/redirect": "^1.4", @@ -69,8 +57,10 @@ "http-interop/http-factory-guzzle": "^1.0.0", "itk-dev/beskedfordeler-drupal": "^1.0", "itk-dev/serviceplatformen": "^1.5", + "mglaman/composer-drupal-lenient": "^1.0", "os2web/os2web_audit": "^0.1.6", "os2web/os2web_datalookup": "^2.0", + "os2web/os2web_key": "^1.0", "os2web/os2web_nemlogin": "^1.0", "os2web/os2web_simplesaml": "dev-master", "php-http/guzzle7-adapter": "^1.0", @@ -78,22 +68,58 @@ "symfony/options-resolver": "^5.4 || ^6.0", "webmozart/path-util": "^2.3", "wsdltophp/packagebase": "^5.0", - "zaporylie/composer-drupal-optimizations": "^1.2", - "mglaman/composer-drupal-lenient": "^1.0" + "zaporylie/composer-drupal-optimizations": "^1.2" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "^0.7.1", "drupal/coder": "^8.3", + "ergebnis/composer-normalize": "^2.42", "mglaman/phpstan-drupal": "^1.1", "phpstan/extension-installer": "^1.3", "phpstan/phpstan-deprecation-rules": "^1.1", "phpunit/phpunit": "^9.5", "wsdltophp/packagegenerator": "^4.0" }, - "extra" : { + "repositories": { + "drupal": { + "type": "composer", + "url": "https://packages.drupal.org/8" + }, + "assets": { + "type": "composer", + "url": "https://asset-packagist.org" + } + }, + "minimum-stability": "dev", + "prefer-stable": true, + "config": { + "allow-plugins": { + "cweagans/composer-patches": true, + "dealerdirect/phpcodesniffer-composer-installer": true, + "ergebnis/composer-normalize": true, + "mglaman/composer-drupal-lenient": true, + "phpstan/extension-installer": true, + "simplesamlphp/composer-module-installer": true, + "vaimo/composer-patches": true, + "zaporylie/composer-drupal-optimizations": true + }, + "sort-packages": true + }, + "extra": { "composer-exit-on-patch-failure": false, - "enable-patching" : true, + "drupal-lenient": { + "allowed-list": [ + "drupal/coc_forms_auto_export", + "drupal/webform_node_element" + ] + }, + "enable-patching": true, "patches": { + "drupal/coc_forms_auto_export": { + "3240592 - Problem with phpseclib requirement in 2.x (https://www.drupal.org/project/coc_forms_auto_export/issues/3240592)": "https://www.drupal.org/files/issues/2021-10-04/requirement-namespace-3240592-1.patch", + "3286562 - Automated Drupal 10 compatibility fixes": "https://www.drupal.org/files/issues/2022-06-15/coc_forms_auto_export.2.0.x-dev.rector.patch", + "3259009 - PHP Warnings/Notices on Download Page": "https://git.drupalcode.org/project/coc_forms_auto_export/-/merge_requests/1.diff" + }, "drupal/entity_print": { "2733781 - Add Export to Word Support": "https://www.drupal.org/files/issues/2019-11-22/2733781-47.patch" }, @@ -101,58 +127,34 @@ "Unlock possibility of using Entity print module export to Word": "https://www.drupal.org/files/issues/2020-02-29/3096552-6.patch", "Webform computed element post save alter": "https://www.drupal.org/files/issues/2024-06-25/webform_computed_post_save_field_alter.patch", "Add custom hook (hook_webform_post_load_data) for audit logging": "https://gist.githubusercontent.com/cableman/d26898fc8f65ee0a31001bf391583b59/raw/6189dc4c2ceaabb19d25cc4b98b0b3028a6b0e1e/gistfile1.txt" - - }, - "drupal/coc_forms_auto_export": { - "3240592 - Problem with phpseclib requirement in 2.x (https://www.drupal.org/project/coc_forms_auto_export/issues/3240592)": "https://www.drupal.org/files/issues/2021-10-04/requirement-namespace-3240592-1.patch", - "3286562 - Automated Drupal 10 compatibility fixes" : "https://www.drupal.org/files/issues/2022-06-15/coc_forms_auto_export.2.0.x-dev.rector.patch", - "3259009 - PHP Warnings/Notices on Download Page" : "https://git.drupalcode.org/project/coc_forms_auto_export/-/merge_requests/1.diff" - }, - "drupal/webform_node_element": { - "3290637 - Automated Drupal 10 compatibility fixes": "https://www.drupal.org/files/issues/2023-05-12/webform_node_element_d10-3290637-11.patch" }, "drupal/webform_encrypt": { "Ensure data is base64 encoded (https://www.drupal.org/project/webform_encrypt/issues/3399414)": "https://git.drupalcode.org/project/webform_encrypt/-/merge_requests/4.patch", "PHP Warning if unserialize fails (https://www.drupal.org/project/webform_encrypt/issues/3292305)": "https://www.drupal.org/files/issues/2022-06-23/unserialize-php-notice.patch" + }, + "drupal/webform_node_element": { + "3290637 - Automated Drupal 10 compatibility fixes": "https://www.drupal.org/files/issues/2023-05-12/webform_node_element_d10-3290637-11.patch" } - }, - "drupal-lenient": { - "allowed-list": [ - "drupal/coc_forms_auto_export", - "drupal/webform_node_element" - ] } }, "scripts": { - "code-analysis/phpstan": [ - "phpstan analyse" - ], "code-analysis": [ "@code-analysis/phpstan" ], - "coding-standards-check/phpcs": [ - "phpcs --standard=phpcs.xml.dist" + "code-analysis/phpstan": [ + "phpstan analyse" ], - "coding-standards-check": [ - "@coding-standards-check/phpcs" + "coding-standards-apply": [ + "@coding-standards-apply/phpcs" ], "coding-standards-apply/phpcs": [ "phpcbf --standard=phpcs.xml.dist" ], - "coding-standards-apply": [ - "@coding-standards-apply/phpcs" + "coding-standards-check": [ + "@coding-standards-check/phpcs" + ], + "coding-standards-check/phpcs": [ + "phpcs --standard=phpcs.xml.dist" ] - }, - "config": { - "sort-packages": true, - "allow-plugins": { - "cweagans/composer-patches": true, - "dealerdirect/phpcodesniffer-composer-installer": true, - "phpstan/extension-installer": true, - "simplesamlphp/composer-module-installer": true, - "vaimo/composer-patches": true, - "zaporylie/composer-drupal-optimizations": true, - "mglaman/composer-drupal-lenient": true - } } } diff --git a/modules/os2forms_attachment/README.md b/modules/os2forms_attachment/README.md index f732ad2f..5b1c7501 100644 --- a/modules/os2forms_attachment/README.md +++ b/modules/os2forms_attachment/README.md @@ -1,20 +1,22 @@ # OS2Forms Attachment Drupal module -# Module purpose +## Module purpose The aim of this module is to provide an OS2forms attachment element for adding PDF/HTML attachment. It also supports creation of reusable headers/footers components which are used when rendering the attachments. -# How does it work +## How does it work -To add custom headers/footer ```admin/structure/webform/config/os2forms_attachment_component``` +To add custom headers/footer `admin/structure/webform/config/os2forms_attachment_component` -To specify headers/footers that will override the default ones on a global level (**Third party settings** -> **Entity print** section): ```admin/structure/webform/config``` +To specify headers/footers that will override the default ones on a global level (**Third party settings** -> **Entity +print** section): `admin/structure/webform/config` -To specify headers/footers that will override the default ones on a form level (**Third party settings** -> **Entity print** section): ```/admin/structure/webform/manage/[webform]/settings``` +To specify headers/footers that will override the default ones on a form level (**Third party settings** -> **Entity +print** section): ```/admin/structure/webform/manage/[webform]/settings``` -# Overwriting templates +## Overwriting templates With some setups it might be necessary to overwrite templates in order to access stylesheets or images. diff --git a/modules/os2forms_autocomplete/README.md b/modules/os2forms_autocomplete/README.md index d5902385..2294d45e 100644 --- a/modules/os2forms_autocomplete/README.md +++ b/modules/os2forms_autocomplete/README.md @@ -1,15 +1,16 @@ # OS2Forms Autocomplete Drupal module -# Module purpose +## Module purpose -The aim of this module is to provide a genetic OS2Forms Autocomplete element which can return options from an external webservice. +The aim of this module is to provide a genetic OS2Forms Autocomplete element which can return options from an external +webservice. -# How does it work +## How does it work Module exposes OS2Forms Autocomplete component that are available in the webform build process. Build page: -``` +```url admin/structure/webform/manage/[webform] ``` diff --git a/modules/os2forms_dawa/README.md b/modules/os2forms_dawa/README.md index 53876ba3..ae242ade 100644 --- a/modules/os2forms_dawa/README.md +++ b/modules/os2forms_dawa/README.md @@ -1,10 +1,11 @@ # OS2Forms DAWA Drupal module -# Module purpose +## Module purpose -The aim of this module is to provide integration with Danish Addresses Web API (DAWA https://dawa.aws.dk) and provider address autocomplete fields. +The aim of this module is to provide integration with Danish Addresses Web API (DAWA ) and provider +address autocomplete fields. -# How does it work +## How does it work Module exposes couple of new Autocomplete components that are available in the webform build process. diff --git a/modules/os2forms_dawa/src/Plugin/os2web/DataLookup/DatafordelerDataLookup.php b/modules/os2forms_dawa/src/Plugin/os2web/DataLookup/DatafordelerDataLookup.php index ba699519..0e50ffaf 100644 --- a/modules/os2forms_dawa/src/Plugin/os2web/DataLookup/DatafordelerDataLookup.php +++ b/modules/os2forms_dawa/src/Plugin/os2web/DataLookup/DatafordelerDataLookup.php @@ -3,8 +3,10 @@ namespace Drupal\os2forms_dawa\Plugin\os2web\DataLookup; use Drupal\Component\Utility\NestedArray; +use Drupal\Core\File\FileSystem; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; +use Drupal\key\KeyRepositoryInterface; use Drupal\os2forms_dawa\Entity\DatafordelerMatrikula; use Drupal\os2web_audit\Service\Logger; use Drupal\os2web_datalookup\Plugin\os2web\DataLookup\DataLookupBase; @@ -21,13 +23,6 @@ */ class DatafordelerDataLookup extends DataLookupBase implements DatafordelerDataLookupInterface, ContainerFactoryPluginInterface { - /** - * The HTTP client to fetch the feed data with. - * - * @var \GuzzleHttp\ClientInterface - */ - protected $httpClient; - /** * {@inheritdoc} */ @@ -35,23 +30,33 @@ public function __construct( array $configuration, $plugin_id, $plugin_definition, - ClientInterface $httpClient, + protected ClientInterface $httpClient, Logger $auditLogger, + KeyRepositoryInterface $keyRepository, + FileSystem $fileSystem, ) { - $this->httpClient = $httpClient; - parent::__construct($configuration, $plugin_id, $plugin_definition, $auditLogger); + parent::__construct($configuration, $plugin_id, $plugin_definition, $auditLogger, $keyRepository, $fileSystem); } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + /** @var \Drupal\os2web_audit\Service\Logger $auditLogger */ + $auditLogger = $container->get('os2web_audit.logger'); + /** @var \Drupal\key\KeyRepositoryInterface $keyRepository */ + $keyRepository = $container->get('key.repository'); + /** @var \Drupal\Core\File\FileSystem $fileSystem */ + $fileSystem = $container->get('file_system'); + return new static( $configuration, $plugin_id, $plugin_definition, $container->get('http_client'), - $container->get('os2web_audit.logger'), + $auditLogger, + $keyRepository, + $fileSystem, ); } diff --git a/modules/os2forms_digital_post/README.md b/modules/os2forms_digital_post/README.md index a487b13e..999d87c7 100644 --- a/modules/os2forms_digital_post/README.md +++ b/modules/os2forms_digital_post/README.md @@ -31,6 +31,11 @@ examples](modules/os2forms_digital_post_examples/README.md). Go to `/admin/os2forms_digital_post/settings` to set up global settings for digital post. +### Key + +We use [os2web_key](https://github.com/OS2web/os2web_key) to provide the certificate for sending digital post, and the +key must be of type "[Certificate](https://github.com/os2web/os2web_key?tab=readme-ov-file#certificate)". + ### Queue The actual sending of digital post is handled by jobs in an [Advanced diff --git a/modules/os2forms_digital_post/drush.services.yml b/modules/os2forms_digital_post/drush.services.yml deleted file mode 100644 index ac0d5f8e..00000000 --- a/modules/os2forms_digital_post/drush.services.yml +++ /dev/null @@ -1,9 +0,0 @@ -services: - Drupal\os2forms_digital_post\Drush\Commands\DigitalPostTestCommands: - arguments: - - '@Drupal\os2forms_digital_post\Helper\DigitalPostHelper' - - '@token' - - '@plugin.manager.entity_print.print_engine' - - '@Drupal\os2forms_digital_post\Helper\Settings' - tags: - - { name: drush.command } diff --git a/modules/os2forms_digital_post/os2forms_digital_post.info.yml b/modules/os2forms_digital_post/os2forms_digital_post.info.yml index 71a17688..0e1408cc 100644 --- a/modules/os2forms_digital_post/os2forms_digital_post.info.yml +++ b/modules/os2forms_digital_post/os2forms_digital_post.info.yml @@ -7,6 +7,7 @@ dependencies: - 'beskedfordeler:beskedfordeler' - 'drupal:advancedqueue' - 'os2web_datalookup:os2web_datalookup' + - 'os2web_key:os2web_key' - 'webform:webform' - 'webform:webform_submission_log' - 'os2web:os2web_audit' diff --git a/modules/os2forms_digital_post/os2forms_digital_post.install b/modules/os2forms_digital_post/os2forms_digital_post.install index 760743cb..f8140579 100644 --- a/modules/os2forms_digital_post/os2forms_digital_post.install +++ b/modules/os2forms_digital_post/os2forms_digital_post.install @@ -17,3 +17,12 @@ use Drupal\os2forms_digital_post\Helper\BeskedfordelerHelper; function os2forms_digital_post_schema() { return Drupal::service(BeskedfordelerHelper::class)->schema(); } + +/** + * Implements hook_update_N(). + */ +function os2forms_digital_post_update_9001(): void { + \Drupal::service('module_installer')->install([ + 'os2web_key', + ], TRUE); +} diff --git a/modules/os2forms_digital_post/os2forms_digital_post.services.yml b/modules/os2forms_digital_post/os2forms_digital_post.services.yml index c13fb96f..1b554d91 100644 --- a/modules/os2forms_digital_post/os2forms_digital_post.services.yml +++ b/modules/os2forms_digital_post/os2forms_digital_post.services.yml @@ -8,62 +8,29 @@ services: arguments: [ 'webform_submission' ] Drupal\os2forms_digital_post\Helper\Settings: - arguments: - - "@keyvalue" + autowire: true Drupal\os2forms_digital_post\Helper\CertificateLocatorHelper: - arguments: - - "@Drupal\\os2forms_digital_post\\Helper\\Settings" + autowire: true Drupal\os2forms_digital_post\Helper\MeMoHelper: - arguments: - - "@Drupal\\os2forms_digital_post\\Helper\\Settings" - - "@plugin.manager.element_info" - - "@webform.token_manager" + autowire: true Drupal\os2forms_digital_post\Helper\ForsendelseHelper: - arguments: - - "@Drupal\\os2forms_digital_post\\Helper\\Settings" - - "@plugin.manager.element_info" - - "@webform.token_manager" + autowire: true Drupal\os2forms_digital_post\Helper\DigitalPostHelper: - arguments: - - "@Drupal\\os2forms_digital_post\\Helper\\Settings" - - "@Drupal\\os2forms_digital_post\\Helper\\CertificateLocatorHelper" - - "@plugin.manager.os2web_datalookup" - - "@Drupal\\os2forms_digital_post\\Helper\\MeMoHelper" - - "@Drupal\\os2forms_digital_post\\Helper\\ForsendelseHelper" - - "@Drupal\\os2forms_digital_post\\Helper\\BeskedfordelerHelper" - - "@logger.channel.os2forms_digital_post" - - "@logger.channel.os2forms_digital_post_submission" - - "@os2web_audit.logger" + autowire: true Drupal\os2forms_digital_post\Helper\WebformHelperSF1601: - arguments: - - "@Drupal\\os2forms_digital_post\\Helper\\Settings" - - "@entity_type.manager" - - "@plugin.manager.os2web_datalookup" - - "@Drupal\\os2forms_digital_post\\Helper\\MeMoHelper" - - "@Drupal\\os2forms_digital_post\\Helper\\ForsendelseHelper" - - "@Drupal\\os2forms_digital_post\\Helper\\BeskedfordelerHelper" - - "@logger.channel.os2forms_digital_post" - - "@logger.channel.os2forms_digital_post_submission" - - "@Drupal\\os2forms_digital_post\\Helper\\DigitalPostHelper" + autowire: true Drupal\os2forms_digital_post\Helper\SF1461Helper: Drupal\os2forms_digital_post\EventSubscriber\BeskedfordelerEventSubscriber: - arguments: - - '@Drupal\os2forms_digital_post\Helper\BeskedfordelerHelper' - - '@Drupal\beskedfordeler\Helper\MessageHelper' - - '@Drupal\os2forms_digital_post\Helper\WebformHelperSF1601' - - '@logger.channel.os2forms_digital_post' + autowire: true tags: - { name: 'event_subscriber' } Drupal\os2forms_digital_post\Helper\BeskedfordelerHelper: - arguments: - - '@database' - - '@Drupal\os2forms_digital_post\Helper\MeMoHelper' - - '@logger.channel.os2forms_digital_post' + autowire: true diff --git a/modules/os2forms_digital_post/src/Drush/Commands/DigitalPostTestCommands.php b/modules/os2forms_digital_post/src/Drush/Commands/DigitalPostTestCommands.php index 248452a3..6b23d874 100644 --- a/modules/os2forms_digital_post/src/Drush/Commands/DigitalPostTestCommands.php +++ b/modules/os2forms_digital_post/src/Drush/Commands/DigitalPostTestCommands.php @@ -3,6 +3,7 @@ namespace Drupal\os2forms_digital_post\Drush\Commands; use Drupal\Component\Serialization\Yaml; +use Drupal\Core\DependencyInjection\AutowireTrait; use Drupal\Core\Utility\Token; use Drupal\entity_print\Plugin\EntityPrintPluginManagerInterface; use Drupal\os2forms_digital_post\Helper\DigitalPostHelper; @@ -12,12 +13,14 @@ use ItkDev\Serviceplatformen\Service\SF1601\SF1601; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; /** * Test commands for digital post. */ -class DigitalPostTestCommands extends DrushCommands { +final class DigitalPostTestCommands extends DrushCommands { + use AutowireTrait; /** * Constructor. @@ -25,6 +28,7 @@ class DigitalPostTestCommands extends DrushCommands { public function __construct( private readonly DigitalPostHelper $digitalPostHelper, private readonly Token $token, + #[Autowire(service: 'plugin.manager.entity_print.print_engine')] private readonly EntityPrintPluginManagerInterface $entityPrintPluginManager, private readonly Settings $digitalPostSettings, ) { @@ -145,7 +149,9 @@ private function dumpDigitalPostSettings(SymfonyStyle $io): void { Yaml::encode([ 'testMode' => $this->digitalPostSettings->getTestMode(), 'sender' => $this->digitalPostSettings->getSender(), - 'certificate' => $this->digitalPostSettings->getCertificate(), + 'certificate' => [ + 'key' => $this->digitalPostSettings->getKey(), + ], 'processing' => $this->digitalPostSettings->getProcessing(), ]), '', diff --git a/modules/os2forms_digital_post/src/EventSubscriber/BeskedfordelerEventSubscriber.php b/modules/os2forms_digital_post/src/EventSubscriber/BeskedfordelerEventSubscriber.php index cbef5ad4..446dc8f3 100644 --- a/modules/os2forms_digital_post/src/EventSubscriber/BeskedfordelerEventSubscriber.php +++ b/modules/os2forms_digital_post/src/EventSubscriber/BeskedfordelerEventSubscriber.php @@ -8,6 +8,7 @@ use Drupal\os2forms_digital_post\Helper\BeskedfordelerHelper; use Drupal\os2forms_digital_post\Helper\WebformHelperSF1601; use Psr\Log\LoggerInterface; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Event subscriber for PostStatusBeskedModtagEvent. @@ -23,6 +24,7 @@ public function __construct( private readonly BeskedfordelerHelper $beskedfordelerHelper, private readonly MessageHelper $messageHelper, private readonly WebformHelperSF1601 $webformHelper, + #[Autowire(service: 'logger.channel.os2forms_digital_post')] LoggerInterface $logger, ) { parent::__construct($logger); diff --git a/modules/os2forms_digital_post/src/Exception/InvalidSettingException.php b/modules/os2forms_digital_post/src/Exception/InvalidSettingException.php deleted file mode 100644 index c3d34af6..00000000 --- a/modules/os2forms_digital_post/src/Exception/InvalidSettingException.php +++ /dev/null @@ -1,10 +0,0 @@ -queueStorage = $entityTypeManager->getStorage('advancedqueue_queue'); } @@ -44,12 +47,23 @@ public function __construct( */ public static function create(ContainerInterface $container) { return new static( + $container->get('config.factory'), + $container->get('entity_type.manager'), $container->get(Settings::class), - $container->get(CertificateLocatorHelper::class), - $container->get('entity_type.manager') ); } + /** + * {@inheritdoc} + * + * @phpstan-return string[] + */ + protected function getEditableConfigNames() { + return [ + Settings::CONFIG_NAME, + ]; + } + /** * {@inheritdoc} */ @@ -63,15 +77,26 @@ public function getFormId() { * @phpstan-param array $form * @phpstan-return array */ - public function buildForm(array $form, FormStateInterface $form_state) { - $form['test_mode'] = [ + public function buildForm(array $form, FormStateInterface $form_state): array { + $form = parent::buildForm($form, $form_state); + + $form['message'] = [ + '#theme' => 'status_messages', + '#message_list' => [ + 'status' => [ + $this->t('Use drush os2forms-digital-post:test:send to test sending digital post.'), + ], + ], + ]; + + $form[Settings::TEST_MODE] = [ '#type' => 'checkbox', '#title' => $this->t('Test mode'), - '#default_value' => $this->settings->getTestMode(), + '#default_value' => $this->settings->getEditableValue(Settings::TEST_MODE), + '#description' => $this->createDescription(Settings::TEST_MODE), ]; - $sender = $this->settings->getSender(); - $form['sender'] = [ + $form[Settings::SENDER] = [ '#type' => 'fieldset', '#title' => $this->t('Sender'), '#tree' => TRUE, @@ -82,126 +107,184 @@ public function buildForm(array $form, FormStateInterface $form_state) { '#options' => [ 'CVR' => $this->t('CVR'), ], - '#default_value' => $sender[Settings::SENDER_IDENTIFIER_TYPE] ?? 'CVR', + '#default_value' => $this->settings->getEditableValue([Settings::SENDER, Settings::SENDER_IDENTIFIER_TYPE]) ?? 'CVR', '#required' => TRUE, + '#description' => $this->createDescription([Settings::SENDER, Settings::SENDER_IDENTIFIER_TYPE]), ], Settings::SENDER_IDENTIFIER => [ '#type' => 'textfield', '#title' => $this->t('Identifier'), - '#default_value' => $sender[Settings::SENDER_IDENTIFIER] ?? NULL, + '#default_value' => $this->settings->getEditableValue([Settings::SENDER, Settings::SENDER_IDENTIFIER]), '#required' => TRUE, + '#description' => $this->createDescription([Settings::SENDER, Settings::SENDER_IDENTIFIER]), ], Settings::FORSENDELSES_TYPE_IDENTIFIKATOR => [ '#type' => 'textfield', '#title' => $this->t('Forsendelsestypeidentifikator'), - '#default_value' => $sender[Settings::FORSENDELSES_TYPE_IDENTIFIKATOR] ?? NULL, + '#default_value' => $this->settings->getEditableValue([ + Settings::SENDER, Settings::FORSENDELSES_TYPE_IDENTIFIKATOR, + ]), '#required' => TRUE, + '#description' => $this->createDescription([Settings::SENDER, Settings::FORSENDELSES_TYPE_IDENTIFIKATOR]), ], ]; - $certificate = $this->settings->getCertificate(); - $form['certificate'] = [ + $form[Settings::CERTIFICATE] = [ '#type' => 'fieldset', '#title' => $this->t('Certificate'), '#tree' => TRUE, + ]; - 'locator_type' => [ - '#type' => 'select', - '#title' => $this->t('Certificate locator type'), - '#options' => [ - 'azure_key_vault' => $this->t('Azure key vault'), - 'file_system' => $this->t('File system'), - ], - '#default_value' => $certificate['locator_type'] ?? NULL, + $form[Settings::CERTIFICATE][Settings::CERTIFICATE_PROVIDER] = [ + '#type' => 'select', + '#title' => $this->t('Provider'), + '#options' => [ + Settings::PROVIDER_TYPE_FORM => $this->t('Form'), + Settings::PROVIDER_TYPE_KEY => $this->t('Key'), ], + '#default_value' => $this->settings->getEditableValue([Settings::CERTIFICATE, Settings::CERTIFICATE_PROVIDER]) ?? Settings::PROVIDER_TYPE_FORM, + '#description' => $this->t('Specifies which provider to use'), ]; - $form['certificate'][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT] = [ + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE] = [ + '#type' => 'select', + '#title' => $this->t('Certificate locator type'), + '#options' => [ + CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT => $this->t('Azure key vault'), + CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM => $this->t('File system'), + ], + '#default_value' => $this->settings->getEditableValue([ + Settings::CERTIFICATE, + CertificateLocatorHelper::LOCATOR_TYPE, + ]) ?? NULL, + '#states' => [ + 'visible' => [':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM]], + ], + '#description' => $this->t('Specifies which locator to use'), + ]; + + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT] = [ '#type' => 'fieldset', '#title' => $this->t('Azure key vault'), '#states' => [ - 'visible' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT]], + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT], + ], ], ]; $settings = [ - 'tenant_id' => ['title' => $this->t('Tenant id')], - 'application_id' => ['title' => $this->t('Application id')], - 'client_secret' => ['title' => $this->t('Client secret')], - 'name' => ['title' => $this->t('Name')], - 'secret' => ['title' => $this->t('Secret')], - 'version' => ['title' => $this->t('Version')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_TENANT_ID => ['title' => $this->t('Tenant id')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_APPLICATION_ID => ['title' => $this->t('Application id')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_CLIENT_SECRET => ['title' => $this->t('Client secret')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_NAME => ['title' => $this->t('Name')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_SECRET => ['title' => $this->t('Secret')], + CertificateLocatorHelper::LOCATOR_AZURE_KEY_VAULT_VERSION => ['title' => $this->t('Version')], ]; foreach ($settings as $key => $info) { - $form['certificate'][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] = [ + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] = [ '#type' => 'textfield', '#title' => $info['title'], - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] ?? NULL, + '#default_value' => $this->settings->getEditableValue([ + Settings::CERTIFICATE, + CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT, + $key, + ]) ?? NULL, '#states' => [ - 'required' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT]], + 'required' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT], + ], ], ]; } - $form['certificate'][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM] = [ + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM] = [ '#type' => 'fieldset', '#title' => $this->t('File system'), '#states' => [ - 'visible' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]], + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM], + ], ], - 'path' => [ + CertificateLocatorHelper::LOCATOR_FILE_SYSTEM_PATH => [ '#type' => 'textfield', '#title' => $this->t('Path'), - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL, + '#default_value' => $this->settings->getEditableValue([ + Settings::CERTIFICATE, + CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM, + CertificateLocatorHelper::LOCATOR_FILE_SYSTEM_PATH, + ]) ?? NULL, '#states' => [ - 'required' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]], + 'required' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM], + ], ], ], ]; - $form['certificate']['passphrase'] = [ + $form[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_PASSPHRASE] = [ '#type' => 'textfield', '#title' => $this->t('Passphrase'), - '#default_value' => $certificate['passphrase'] ?? NULL, + '#default_value' => $this->settings->getEditableValue([ + Settings::CERTIFICATE, + CertificateLocatorHelper::LOCATOR_PASSPHRASE, + ]) ?? '', + '#states' => [ + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_FORM], + ], + ], ]; - $processing = $this->settings->getProcessing(); - $form['processing'] = [ + $form[Settings::CERTIFICATE][Settings::PROVIDER_TYPE_KEY] = [ + '#type' => 'key_select', + '#key_filters' => [ + 'type' => 'os2web_key_certificate', + ], + '#key_description' => FALSE, + '#title' => $this->t('Key'), + '#default_value' => $this->settings->getEditableValue([Settings::CERTIFICATE, Settings::PROVIDER_TYPE_KEY]), + '#description' => $this->createDescription([Settings::CERTIFICATE, Settings::PROVIDER_TYPE_KEY]), + '#states' => [ + 'visible' => [':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_KEY]], + 'required' => [':input[name="certificate[certificate_provider]"]' => ['value' => Settings::PROVIDER_TYPE_KEY]], + ], + ]; + + $form[Settings::PROCESSING] = [ '#type' => 'fieldset', '#title' => $this->t('Processing'), '#tree' => TRUE, ]; - $defaultValue = $processing['queue'] ?? 'os2forms_digital_post'; - $form['processing']['queue'] = [ + $queue = $this->settings->getEditableValue([Settings::PROCESSING, Settings::QUEUE]); + $form[Settings::PROCESSING][Settings::QUEUE] = [ '#type' => 'select', '#title' => $this->t('Queue'), '#options' => array_map( static fn(EntityInterface $queue) => $queue->label(), $this->queueStorage->loadMultiple() ), - '#default_value' => $defaultValue, - '#description' => $this->t("Queue for digital post jobs. The queue must be run via Drupal's cron or via drush advancedqueue:queue:process @queue(in a cron job).", [ - '@queue' => $defaultValue, - ':queue_url' => '/admin/config/system/queues/jobs/' . urlencode($defaultValue), - ]), - ]; - - $form['actions']['#type'] = 'actions'; - - $form['actions']['submit'] = [ - '#type' => 'submit', - '#value' => $this->t('Save settings'), - ]; - - $form['actions']['testCertificate'] = [ - '#type' => 'submit', - '#name' => 'testCertificate', - '#value' => $this->t('Test certificate'), + '#required' => TRUE, + '#default_value' => $queue, + '#description' => $this->createDescription([Settings::PROCESSING, Settings::QUEUE], + $queue + ? $this->t("Queue for digital post jobs. The queue must be run via Drupal's cron or via drush advancedqueue:queue:process @queue (in a cron job).", [ + '@queue' => $queue, + ':queue_url' => Url::fromRoute('view.advancedqueue_jobs.page_1', [ + 'arg_0' => $queue, + ])->toString(TRUE)->getGeneratedUrl(), + ]) + : $this->t("Queue for digital post jobs. The queue must be processed via Drupal's cron or drush advancedqueue:queue:process (in a cron job)."), + ), ]; return $form; @@ -212,19 +295,19 @@ public function buildForm(array $form, FormStateInterface $form_state) { * * @phpstan-param array $form */ - public function validateForm(array &$form, FormStateInterface $formState): void { - $triggeringElement = $formState->getTriggeringElement(); - if ('testCertificate' === ($triggeringElement['#name'] ?? NULL)) { - return; - } - - $values = $formState->getValues(); - if (CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM === $values['certificate']['locator_type']) { - $path = $values['certificate'][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL; - if (!file_exists($path)) { - $formState->setErrorByName('certificate][file_system][path', $this->t('Invalid certificate path: %path', ['%path' => $path])); + public function validateForm(array &$form, FormStateInterface $form_state): void { + $values = $form_state->getValues(); + + if (Settings::PROVIDER_TYPE_FORM === $values[Settings::CERTIFICATE][Settings::CERTIFICATE_PROVIDER]) { + if (CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM === $values[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE]) { + $path = $values[Settings::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM][CertificateLocatorHelper::LOCATOR_FILE_SYSTEM_PATH] ?? NULL; + if (!file_exists($path)) { + $form_state->setErrorByName('certificate][file_system][path', $this->t('Invalid certificate path: %path', ['%path' => $path])); + } } } + + parent::validateForm($form, $form_state); } /** @@ -232,39 +315,43 @@ public function validateForm(array &$form, FormStateInterface $formState): void * * @phpstan-param array $form */ - public function submitForm(array &$form, FormStateInterface $formState): void { - $triggeringElement = $formState->getTriggeringElement(); - if ('testCertificate' === ($triggeringElement['#name'] ?? NULL)) { - $this->testCertificate(); - return; + public function submitForm(array &$form, FormStateInterface $form_state): void { + $config = $this->config(Settings::CONFIG_NAME); + foreach ([ + Settings::TEST_MODE, + Settings::SENDER, + Settings::CERTIFICATE, + Settings::PROCESSING, + ] as $key) { + $config->set($key, $form_state->getValue($key)); } + $config->save(); - try { - $settings['test_mode'] = (bool) $formState->getValue('test_mode'); - $settings['sender'] = $formState->getValue('sender'); - $settings['certificate'] = $formState->getValue('certificate'); - $settings['processing'] = $formState->getValue('processing'); - $this->settings->setSettings($settings); - $this->messenger()->addStatus($this->t('Settings saved')); - } - catch (OptionsResolverException $exception) { - $this->messenger()->addError($this->t('Settings not saved (@message)', ['@message' => $exception->getMessage()])); - } + parent::submitForm($form, $form_state); } /** - * Test certificate. + * Create form field description with information on any runtime override. + * + * @param string|array $key + * The key. + * @param \Drupal\Core\StringTranslation\TranslatableMarkup|null $description + * The actual field description. + * + * @return string + * The full description. + * + * @phpstan-param string|string[] $key */ - private function testCertificate(): void { - try { - $certificateLocator = $this->certificateLocatorHelper->getCertificateLocator(); - $certificateLocator->getCertificates(); - $this->messenger()->addStatus($this->t('Certificate succesfully tested')); - } - catch (\Throwable $throwable) { - $message = $this->t('Error testing certificate: %message', ['%message' => $throwable->getMessage()]); - $this->messenger()->addError($message); + private function createDescription(string|array $key, ?TranslatableMarkup $description = NULL): string { + if ($value = $this->settings->getOverride($key)) { + if (!empty($description)) { + $description .= '
'; + } + $description .= $this->t('Note: overridden on runtime with the value @value.', ['@value' => var_export($value['runtime'], TRUE)]); } + + return (string) $description; } } diff --git a/modules/os2forms_digital_post/src/Helper/AbstractMessageHelper.php b/modules/os2forms_digital_post/src/Helper/AbstractMessageHelper.php index d9fb96a3..c2f2b990 100644 --- a/modules/os2forms_digital_post/src/Helper/AbstractMessageHelper.php +++ b/modules/os2forms_digital_post/src/Helper/AbstractMessageHelper.php @@ -12,6 +12,7 @@ use Drupal\webform_attachment\Element\WebformAttachmentBase; use ItkDev\Serviceplatformen\Service\SF1601\Serializer; use Oio\Fjernprint\ForsendelseI; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Abstract message helper. @@ -23,7 +24,9 @@ abstract class AbstractMessageHelper { */ public function __construct( readonly protected Settings $settings, + #[Autowire(service: 'plugin.manager.element_info')] readonly protected ElementInfoManager $elementInfoManager, + #[Autowire(service: 'webform.token_manager')] readonly protected WebformTokenManagerInterface $webformTokenManager, ) { } diff --git a/modules/os2forms_digital_post/src/Helper/BeskedfordelerHelper.php b/modules/os2forms_digital_post/src/Helper/BeskedfordelerHelper.php index 5b93da5e..c256dc17 100644 --- a/modules/os2forms_digital_post/src/Helper/BeskedfordelerHelper.php +++ b/modules/os2forms_digital_post/src/Helper/BeskedfordelerHelper.php @@ -9,6 +9,7 @@ use Drupal\webform\WebformSubmissionInterface; use Psr\Log\LoggerAwareTrait; use Psr\Log\LoggerInterface; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Beskedfordeler helper. @@ -24,6 +25,7 @@ class BeskedfordelerHelper { public function __construct( private readonly Connection $database, private readonly MeMoHelper $meMoHelper, + #[Autowire(service: 'logger.channel.os2forms_digital_post')] LoggerInterface $logger, ) { $this->setLogger($logger); diff --git a/modules/os2forms_digital_post/src/Helper/CertificateLocatorHelper.php b/modules/os2forms_digital_post/src/Helper/CertificateLocatorHelper.php index 10e6ac57..01fde400 100644 --- a/modules/os2forms_digital_post/src/Helper/CertificateLocatorHelper.php +++ b/modules/os2forms_digital_post/src/Helper/CertificateLocatorHelper.php @@ -16,8 +16,17 @@ * Certificate locator helper. */ class CertificateLocatorHelper { + public const LOCATOR_TYPE = 'locator_type'; public const LOCATOR_TYPE_AZURE_KEY_VAULT = 'azure_key_vault'; public const LOCATOR_TYPE_FILE_SYSTEM = 'file_system'; + public const LOCATOR_PASSPHRASE = 'passphrase'; + public const LOCATOR_AZURE_KEY_VAULT_TENANT_ID = 'tenant_id'; + public const LOCATOR_AZURE_KEY_VAULT_APPLICATION_ID = 'application_id'; + public const LOCATOR_AZURE_KEY_VAULT_CLIENT_SECRET = 'client_secret'; + public const LOCATOR_AZURE_KEY_VAULT_NAME = 'name'; + public const LOCATOR_AZURE_KEY_VAULT_SECRET = 'secret'; + public const LOCATOR_AZURE_KEY_VAULT_VERSION = 'version'; + public const LOCATOR_FILE_SYSTEM_PATH = 'path'; /** * {@inheritdoc} @@ -31,12 +40,12 @@ public function __construct( * Get certificate locator. */ public function getCertificateLocator(): CertificateLocatorInterface { - $certificateSettings = $this->settings->getCertificate(); + $certificateSettings = $this->settings->getEditableValue(Settings::CERTIFICATE); $locatorType = $certificateSettings['locator_type']; $options = $certificateSettings[$locatorType]; $options += [ - 'passphrase' => $certificateSettings['passphrase'] ?: '', + 'passphrase' => $certificateSettings['passphrase'], ]; if (self::LOCATOR_TYPE_AZURE_KEY_VAULT === $locatorType) { diff --git a/modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php b/modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php index 8681cf35..44198074 100644 --- a/modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php +++ b/modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php @@ -11,12 +11,14 @@ use Drupal\os2web_datalookup\Plugin\DataLookupManager; use Drupal\os2web_datalookup\Plugin\os2web\DataLookup\DataLookupCompanyInterface; use Drupal\os2web_datalookup\Plugin\os2web\DataLookup\DataLookupCprInterface; +use Drupal\os2web_key\KeyHelper; use Drupal\webform\WebformSubmissionInterface; use ItkDev\Serviceplatformen\Service\SF1601\SF1601; use ItkDev\Serviceplatformen\Service\SF1601\Serializer; use Oio\Fjernprint\ForsendelseI; use Psr\Log\LoggerInterface; use Psr\Log\LoggerTrait; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Webform helper. @@ -29,13 +31,18 @@ final class DigitalPostHelper implements LoggerInterface { */ public function __construct( private readonly Settings $settings, - private readonly CertificateLocatorHelper $certificateLocatorHelper, + private readonly KeyHelper $keyHelper, + #[Autowire(service: 'plugin.manager.os2web_datalookup')] private readonly DataLookupManager $dataLookupManager, private readonly MeMoHelper $meMoHelper, private readonly ForsendelseHelper $forsendelseHelper, private readonly BeskedfordelerHelper $beskedfordelerHelper, + private readonly CertificateLocatorHelper $certificateLocatorHelper, + #[Autowire(service: 'logger.channel.os2forms_digital_post')] private readonly LoggerChannelInterface $logger, + #[Autowire(service: 'logger.channel.os2forms_digital_post_submission')] private readonly LoggerChannelInterface $submissionLogger, + #[Autowire(service: 'os2web_audit.logger')] private readonly Logger $auditLogger, ) { } @@ -59,11 +66,23 @@ public function __construct( */ public function sendDigitalPost(string $type, Message $message, ?ForsendelseI $forsendelse, ?WebformSubmissionInterface $submission = NULL): array { $senderSettings = $this->settings->getSender(); + + if (Settings::PROVIDER_TYPE_FORM === $this->settings->getCertificateProvider()) { + $certificateLocator = $this->certificateLocatorHelper->getCertificateLocator(); + } + else { + $certificateLocator = new KeyCertificateLocator( + $this->settings->getCertificateKey(), + $this->keyHelper + ); + } + $options = [ 'test_mode' => (bool) $this->settings->getTestMode(), 'authority_cvr' => $senderSettings[Settings::SENDER_IDENTIFIER], - 'certificate_locator' => $this->certificateLocatorHelper->getCertificateLocator(), + 'certificate_locator' => $certificateLocator, ]; + $service = new SF1601($options); $transactionId = Serializer::createUuid(); diff --git a/modules/os2forms_digital_post/src/Helper/KeyCertificateLocator.php b/modules/os2forms_digital_post/src/Helper/KeyCertificateLocator.php new file mode 100644 index 00000000..8d8f0a41 --- /dev/null +++ b/modules/os2forms_digital_post/src/Helper/KeyCertificateLocator.php @@ -0,0 +1,59 @@ + + */ + private array $certificates; + + /** + * Constructor. + */ + public function __construct( + private readonly KeyInterface $key, + private readonly KeyHelper $keyHelper, + ) { + parent::__construct(); + } + + /** + * {@inheritdoc} + * + * @phpstan-return array + */ + public function getCertificates(): array { + if (!isset($this->certificates)) { + $this->certificates = $this->keyHelper->getCertificates($this->key); + } + + return $this->certificates; + } + + /** + * {@inheritdoc} + */ + public function getCertificate(): string { + return $this->key->getKeyValue(); + } + + /** + * {@inheritdoc} + */ + public function getAbsolutePathToCertificate(): string { + throw new CertificateLocatorException(__METHOD__ . ' should not be used.'); + } + +} diff --git a/modules/os2forms_digital_post/src/Helper/Settings.php b/modules/os2forms_digital_post/src/Helper/Settings.php index e64be738..fc7ab385 100644 --- a/modules/os2forms_digital_post/src/Helper/Settings.php +++ b/modules/os2forms_digital_post/src/Helper/Settings.php @@ -2,45 +2,66 @@ namespace Drupal\os2forms_digital_post\Helper; -use Drupal\Core\KeyValueStore\KeyValueFactoryInterface; -use Drupal\Core\KeyValueStore\KeyValueStoreInterface; -use Drupal\os2forms_digital_post\Exception\InvalidSettingException; -use Symfony\Component\OptionsResolver\OptionsResolver; +use Drupal\Core\Config\Config; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Config\ImmutableConfig; +use Drupal\key\KeyInterface; +use Drupal\key\KeyRepositoryInterface; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * General settings for os2forms_digital_post. */ final class Settings { + public const CONFIG_NAME = 'os2forms_digital_post.settings'; + + public const TEST_MODE = 'test_mode'; + + public const SENDER = 'sender'; public const SENDER_IDENTIFIER_TYPE = 'sender_identifier_type'; public const SENDER_IDENTIFIER = 'sender_identifier'; public const FORSENDELSES_TYPE_IDENTIFIKATOR = 'forsendelses_type_identifikator'; + public const CERTIFICATE = 'certificate'; + public const KEY = 'key'; + public const CERTIFICATE_PROVIDER = 'certificate_provider'; + public const PROVIDER_TYPE_FORM = 'form'; + public const PROVIDER_TYPE_KEY = 'key'; + + public const PROCESSING = 'processing'; + public const QUEUE = 'queue'; + /** - * The store. + * The runtime (immutable) config. * - * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface + * @var \Drupal\Core\Config\ImmutableConfig */ - private KeyValueStoreInterface $store; + private ImmutableConfig $runtimeConfig; /** - * The key prefix. + * The (mutable) config. * - * @var string + * @var \Drupal\Core\Config\Config */ - private $collection = 'os2forms_digital_post.'; + private Config $editableConfig; /** - * Constructor. + * The constructor. */ - public function __construct(KeyValueFactoryInterface $keyValueFactory) { - $this->store = $keyValueFactory->get($this->collection); + public function __construct( + ConfigFactoryInterface $configFactory, + #[Autowire(service: 'key.repository')] + private readonly KeyRepositoryInterface $keyRepository, + ) { + $this->runtimeConfig = $configFactory->get(self::CONFIG_NAME); + $this->editableConfig = $configFactory->getEditable(self::CONFIG_NAME); } /** * Get test mode. */ public function getTestMode(): bool { - return (bool) $this->get('test_mode', TRUE); + return (bool) $this->get(self::TEST_MODE, TRUE); } /** @@ -49,18 +70,32 @@ public function getTestMode(): bool { * @phpstan-return array */ public function getSender(): array { - $value = $this->get('sender'); + $value = $this->get(self::SENDER); + return is_array($value) ? $value : []; } + /** + * Get certificate provider. + */ + public function getCertificateProvider(): ?string { + return $this->get([self::CERTIFICATE, self::CERTIFICATE_PROVIDER]); + } + + /** + * Get key. + */ + public function getKey(): ?string { + return $this->get([self::CERTIFICATE, self::KEY]); + } + /** * Get certificate. - * - * @phpstan-return array */ - public function getCertificate(): array { - $value = $this->get('certificate'); - return is_array($value) ? $value : []; + public function getCertificateKey(): ?KeyInterface { + return $this->keyRepository->getKey( + $this->getKey(), + ); } /** @@ -69,57 +104,82 @@ public function getCertificate(): array { * @phpstan-return array */ public function getProcessing(): array { - $value = $this->get('processing'); + $value = $this->get(self::PROCESSING); + return is_array($value) ? $value : []; } /** - * Get a setting value. + * Get editable value. * - * @param string $key + * @param string|array $key * The key. - * @param mixed|null $default - * The default value. * * @return mixed - * The setting value. + * The editable value. */ - private function get(string $key, $default = NULL) { - $resolver = $this->getSettingsResolver(); - if (!$resolver->isDefined($key)) { - throw new InvalidSettingException(sprintf('Setting %s is not defined', $key)); + public function getEditableValue(string|array $key): mixed { + if (is_array($key)) { + $key = implode('.', $key); } - - return $this->store->get($key, $default); + return $this->editableConfig->get($key); } /** - * Set settings. + * Get runtime value override if any. * - * @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface + * @param string|array $key + * The key. * - * @phpstan-param array $settings + * @return array|null + * - 'runtime': the runtime value + * - 'editable': the editable (raw) value */ - public function setSettings(array $settings): self { - $settings = $this->getSettingsResolver()->resolve($settings); - foreach ($settings as $key => $value) { - $this->store->set($key, $value); + public function getOverride(string|array $key): ?array { + $runtimeValue = $this->getRuntimeValue($key); + $editableValue = $this->getEditableValue($key); + + // Note: We deliberately use "Equal" (==) rather than "Identical" (===) + // to compare values (cf. https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison). + if ($runtimeValue == $editableValue) { + return NULL; } - return $this; + return [ + 'runtime' => $runtimeValue, + 'editable' => $editableValue, + ]; } /** - * Get settings resolver. + * Get a setting value. + * + * @param string|array $key + * The key. + * @param mixed $default + * The default value. + * + * @return mixed + * The setting value. */ - private function getSettingsResolver(): OptionsResolver { - return (new OptionsResolver()) - ->setDefaults([ - 'test_mode' => TRUE, - 'sender' => [], - 'certificate' => [], - 'processing' => [], - ]); + private function get(string|array $key, mixed $default = NULL) { + return $this->getRuntimeValue($key) ?? $default; + } + + /** + * Get runtime value with any overrides applied. + * + * @param string|array $key + * The key. + * + * @return mixed + * The runtime value. + */ + public function getRuntimeValue(string|array $key): mixed { + if (is_array($key)) { + $key = implode('.', $key); + } + return $this->runtimeConfig->get($key); } } diff --git a/modules/os2forms_digital_post/src/Helper/WebformHelperSF1601.php b/modules/os2forms_digital_post/src/Helper/WebformHelperSF1601.php index 3c2c724e..60fae6a2 100644 --- a/modules/os2forms_digital_post/src/Helper/WebformHelperSF1601.php +++ b/modules/os2forms_digital_post/src/Helper/WebformHelperSF1601.php @@ -21,6 +21,7 @@ use ItkDev\Serviceplatformen\Service\SF1601\SF1601; use Psr\Log\LoggerInterface; use Psr\Log\LoggerTrait; +use Symfony\Component\DependencyInjection\Attribute\Autowire; /** * Webform helper. @@ -51,11 +52,14 @@ final class WebformHelperSF1601 implements LoggerInterface { public function __construct( private readonly Settings $settings, EntityTypeManagerInterface $entityTypeManager, + #[Autowire(service: 'plugin.manager.os2web_datalookup')] private readonly DataLookupManager $dataLookupManager, private readonly MeMoHelper $meMoHelper, private readonly ForsendelseHelper $forsendelseHelper, private readonly BeskedfordelerHelper $beskedfordelerHelper, + #[Autowire(service: 'logger.channel.os2forms_digital_post')] private readonly LoggerChannelInterface $logger, + #[Autowire(service: 'logger.channel.os2forms_digital_post_submission')] private readonly LoggerChannelInterface $submissionLogger, private readonly DigitalPostHelper $digitalPostHelper, ) { diff --git a/modules/os2forms_fasit/README.md b/modules/os2forms_fasit/README.md index 6a697c2a..e7faac00 100644 --- a/modules/os2forms_fasit/README.md +++ b/modules/os2forms_fasit/README.md @@ -1,36 +1,32 @@ # OS2Forms Fasit -Adds [Fasit Schultz](https://schultz.dk/loesninger/schultz-fasit/) -handler for archiving purposes. +Adds [Fasit Schultz](https://schultz.dk/loesninger/schultz-fasit/) handler for archiving purposes. For usage in danish, see [BENYTTELSE](docs/BENYTTELSE.md). ## Installation -```sh +```shell drush pm:enable os2forms_fasit ``` ## Settings -Configure Fasit API `base url` and a way of getting -certificate on `/admin/os2forms_fasit/settings`. +Go to `/admin/os2forms_fasit/settings` and configure the module. ### Certificate -The certificate must be in `pem` or `cer` format and -must be whitelisted by Fasit Schultz. -For this the certificate thumbprint, -in lowercase and without colons, is needed. +The certificate must be in `pem` or `cer` format and must be whitelisted by Fasit Schultz. For this the certificate +thumbprint, in lowercase and without colons, is needed. To get the thumbprint in the correct format from the command line run -```sh +```shell openssl x509 -in SOME_CERTIFICATE.pem -noout -fingerprint | cut -d= -f2 | sed 's/://g' | tr '[:upper:]' '[:lower:]' ``` -Example output +Example output: -```sh +```shell 6acb261f393172d87fa3997cec86569759a8528a ``` @@ -42,13 +38,13 @@ called `fasit_queue`. The queue should be processed with `drush`: -```sh +```shell drush advancedqueue:queue:process fasit_queue ``` List the queue (and all other queues) with -```sh +```shell drush advancedqueue:queue:list ``` diff --git a/modules/os2forms_fasit/docs/BENYTTELSE.md b/modules/os2forms_fasit/docs/BENYTTELSE.md index 63cc361d..cb8c958a 100644 --- a/modules/os2forms_fasit/docs/BENYTTELSE.md +++ b/modules/os2forms_fasit/docs/BENYTTELSE.md @@ -10,7 +10,7 @@ aftale hvilke certifikater der anvendes. Disse certifikater skal være OCES-3, f.eks. FOCES-3, og skal bruges i pem- eller cer-format. Dernæst oplyses det anvendte certifikats thumbprint eller public-key til Fasit, -som derefter aktiverer snitfladen. Se evt. +som derefter aktiverer snitfladen. Se evt. [README#certificate](../README.md#certificate) for hvordan et certifikats thumbprint kan findes gennem kommandolinjen. @@ -22,7 +22,7 @@ Her skal følgende sættes op: * Fasit API base url * Basis url’en til Fasit. Denne specificeres af Fasit. - * Eksempel: https://webservices.fasit.dk/ + * Eksempel: * Fasit API tenant * Fasit tenant. Denne specificeres af Fasit. * Eksempel: aarhus @@ -30,14 +30,14 @@ Her skal følgende sættes op: * Hvilken version af af API’et der skal bruges. Her er mulighederne ’v1’ eller ’v2’. Der bør altid bruges ’v2’. * Eksempel: v2 * Certificate - * Her kan angives detaljer til et azure key vault hvori certifikatet ligges (Azure key vault) eller en sti direkte til certifikatet (Filsystem) + * Her kan angives detaljer til et azure key vault hvori certifikatet ligges (Azure key vault) eller en sti direkte til + certifikatet (Filsystem) * Passphrase * Passphrase til certifikatet, hvis sådan et eksisterer. - Se evt. Fasit Scultz dokumentationen for flere detaljer på opbygningen af endpoint url’er. -Det er desuden muligt at teste om os2forms kan få fat i certifikatet på samme konfigurations-side. +Det er desuden muligt at teste om os2forms kan få fat i certifikatet på samme konfigurations-side. ## Handler diff --git a/modules/os2forms_fasit/os2forms_fasit.info.yml b/modules/os2forms_fasit/os2forms_fasit.info.yml index 43309b4d..d151bcde 100644 --- a/modules/os2forms_fasit/os2forms_fasit.info.yml +++ b/modules/os2forms_fasit/os2forms_fasit.info.yml @@ -8,4 +8,5 @@ dependencies: - drupal:advancedqueue - os2forms:os2forms_attachment - os2web:os2web_audit + - os2web_key:os2web_key configure: os2forms_fasit.admin.settings diff --git a/modules/os2forms_fasit/os2forms_fasit.install b/modules/os2forms_fasit/os2forms_fasit.install new file mode 100644 index 00000000..b671b660 --- /dev/null +++ b/modules/os2forms_fasit/os2forms_fasit.install @@ -0,0 +1,15 @@ +install([ + 'key', + ], TRUE); +} diff --git a/modules/os2forms_fasit/os2forms_fasit.services.yml b/modules/os2forms_fasit/os2forms_fasit.services.yml index 4397c83f..e70008fb 100644 --- a/modules/os2forms_fasit/os2forms_fasit.services.yml +++ b/modules/os2forms_fasit/os2forms_fasit.services.yml @@ -1,16 +1,13 @@ services: Drupal\os2forms_fasit\Helper\Settings: + autowire: true arguments: - - "@keyvalue" + $keyRepository: "@key.repository" Drupal\os2forms_fasit\Helper\CertificateLocatorHelper: - arguments: - - "@Drupal\\os2forms_fasit\\Helper\\Settings" + autowire: true Drupal\os2forms_fasit\Helper\FasitHelper: + autowire: true arguments: - - '@http_client' - - '@entity_type.manager' - - "@Drupal\\os2forms_fasit\\Helper\\Settings" - - "@Drupal\\os2forms_fasit\\Helper\\CertificateLocatorHelper" - - "@os2web_audit.logger" + $auditLogger: "@os2web_audit.logger" diff --git a/modules/os2forms_fasit/src/Drush/Commands/FasitTestCommand.php b/modules/os2forms_fasit/src/Drush/Commands/FasitTestCommand.php new file mode 100644 index 00000000..9d1fb281 --- /dev/null +++ b/modules/os2forms_fasit/src/Drush/Commands/FasitTestCommand.php @@ -0,0 +1,41 @@ +helper->pingApi(); + $this->io()->success('Successfully connected to Fasit API'); + } + catch (\Throwable $t) { + $this->io()->error($t->getMessage()); + } + + } + +} diff --git a/modules/os2forms_fasit/src/Form/SettingsForm.php b/modules/os2forms_fasit/src/Form/SettingsForm.php index d0fe119e..9e05b95b 100644 --- a/modules/os2forms_fasit/src/Form/SettingsForm.php +++ b/modules/os2forms_fasit/src/Form/SettingsForm.php @@ -2,41 +2,65 @@ namespace Drupal\os2forms_fasit\Form; -use Drupal\Core\Form\FormBase; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; use Drupal\os2forms_fasit\Helper\CertificateLocatorHelper; -use Drupal\os2forms_fasit\Helper\Settings; +use Drupal\os2forms_fasit\Helper\FasitHelper; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\OptionsResolver\Exception\ExceptionInterface as OptionsResolverException; /** - * Organisation settings form. + * Fasit settings form. */ -final class SettingsForm extends FormBase { +final class SettingsForm extends ConfigFormBase { use StringTranslationTrait; + public const CONFIG_NAME = 'os2forms_fasit.settings'; public const FASIT_API_BASE_URL = 'fasit_api_base_url'; public const FASIT_API_TENANT = 'fasit_api_tenant'; public const FASIT_API_VERSION = 'fasit_api_version'; public const CERTIFICATE = 'certificate'; + public const KEY = 'key'; + public const CERTIFICATE_PROVIDER = 'certificate_provider'; + public const PROVIDER_TYPE_FORM = 'form'; + public const PROVIDER_TYPE_KEY = 'key'; + + public const ACTION_PING_API = 'action_ping_api'; /** - * Constructor. + * {@inheritdoc} */ - public function __construct(private readonly Settings $settings, private readonly CertificateLocatorHelper $certificateLocatorHelper) { + public function __construct( + ConfigFactoryInterface $config_factory, + private readonly FasitHelper $helper, + ) { + parent::__construct($config_factory); } /** * {@inheritdoc} + * + * @phpstan-return self */ - public static function create(ContainerInterface $container): SettingsForm { + public static function create(ContainerInterface $container): self { return new static( - $container->get(Settings::class), - $container->get(CertificateLocatorHelper::class) + $container->get('config.factory'), + $container->get(FasitHelper::class) ); } + /** + * {@inheritdoc} + * + * @phpstan-return array + */ + protected function getEditableConfigNames() { + return [ + self::CONFIG_NAME, + ]; + } + /** * {@inheritdoc} */ @@ -51,57 +75,74 @@ public function getFormId() { * @phpstan-return array */ public function buildForm(array $form, FormStateInterface $form_state): array { + $form = parent::buildForm($form, $form_state); + $config = $this->config(self::CONFIG_NAME); - $fasitApiBaseUrl = $this->settings->getFasitApiBaseUrl(); $form[self::FASIT_API_BASE_URL] = [ '#type' => 'textfield', '#title' => $this->t('Fasit API base url'), '#required' => TRUE, - '#default_value' => !empty($fasitApiBaseUrl) ? $fasitApiBaseUrl : NULL, + '#default_value' => $config->get(self::FASIT_API_BASE_URL), '#description' => $this->t('Specifies which base url to use. This is disclosed by Schultz'), ]; - $fasitApiTenant = $this->settings->getFasitApiTenant(); $form[self::FASIT_API_TENANT] = [ '#type' => 'textfield', '#title' => $this->t('Fasit API tenant'), '#required' => TRUE, - '#default_value' => !empty($fasitApiTenant) ? $fasitApiTenant : NULL, + '#default_value' => $config->get(self::FASIT_API_TENANT), '#description' => $this->t('Specifies which tenant to use. This is disclosed by Schultz'), ]; - $fasitApiVersion = $this->settings->getFasitApiVersion(); $form[self::FASIT_API_VERSION] = [ '#type' => 'textfield', '#title' => $this->t('Fasit API version'), '#required' => TRUE, - '#default_value' => !empty($fasitApiVersion) ? $fasitApiVersion : NULL, + '#default_value' => $config->get(self::FASIT_API_VERSION), '#description' => $this->t('Specifies which api version to use. Should probably be v2'), ]; - $certificate = $this->settings->getCertificate(); + $certificateConfig = $config->get(self::CERTIFICATE) ?? []; $form[self::CERTIFICATE] = [ '#type' => 'fieldset', '#title' => $this->t('Certificate'), '#tree' => TRUE, - CertificateLocatorHelper::LOCATOR_TYPE => [ + self::CERTIFICATE_PROVIDER => [ '#type' => 'select', - '#title' => $this->t('Certificate locator type'), + '#title' => $this->t('Provider'), '#options' => [ - CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT => $this->t('Azure key vault'), - CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM => $this->t('File system'), + self::PROVIDER_TYPE_FORM => $this->t('Form'), + self::PROVIDER_TYPE_KEY => $this->t('Key'), ], - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE] ?? NULL, + '#default_value' => $certificateConfig[self::CERTIFICATE_PROVIDER] ?? self::PROVIDER_TYPE_FORM, + '#description' => $this->t('Specifies which provider to use'), ], ]; + $form[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE] = [ + '#type' => 'select', + '#title' => $this->t('Certificate locator type'), + '#options' => [ + CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT => $this->t('Azure key vault'), + CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM => $this->t('File system'), + ], + '#default_value' => $certificateConfig[CertificateLocatorHelper::LOCATOR_TYPE] ?? NULL, + '#states' => [ + 'visible' => [':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM]], + ], + '#description' => $this->t('Specifies which locator to use'), + ]; + $form[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT] = [ '#type' => 'fieldset', '#title' => $this->t('Azure key vault'), '#states' => [ - 'visible' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT]], + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT], + ], ], ]; @@ -118,9 +159,12 @@ public function buildForm(array $form, FormStateInterface $form_state): array { $form[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] = [ '#type' => 'textfield', '#title' => $info['title'], - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] ?? NULL, + '#default_value' => $certificateConfig[CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT][$key] ?? NULL, '#states' => [ - 'required' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT]], + 'required' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_AZURE_KEY_VAULT], + ], ], ]; } @@ -129,15 +173,21 @@ public function buildForm(array $form, FormStateInterface $form_state): array { '#type' => 'fieldset', '#title' => $this->t('File system'), '#states' => [ - 'visible' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]], + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM], + ], ], 'path' => [ '#type' => 'textfield', '#title' => $this->t('Path'), - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL, + '#default_value' => $certificateConfig[CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL, '#states' => [ - 'required' => [':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]], + 'required' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ':input[name="certificate[locator_type]"]' => ['value' => CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM], + ], ], ], ]; @@ -145,20 +195,39 @@ public function buildForm(array $form, FormStateInterface $form_state): array { $form[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_PASSPHRASE] = [ '#type' => 'textfield', '#title' => $this->t('Passphrase'), - '#default_value' => $certificate[CertificateLocatorHelper::LOCATOR_PASSPHRASE] ?? NULL, + '#default_value' => $certificateConfig[CertificateLocatorHelper::LOCATOR_PASSPHRASE] ?? NULL, + '#states' => [ + 'visible' => [ + ':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_FORM], + ], + ], ]; - $form['actions']['#type'] = 'actions'; - - $form['actions']['submit'] = [ - '#type' => 'submit', - '#value' => $this->t('Save settings'), + $form[self::CERTIFICATE][self::PROVIDER_TYPE_KEY] = [ + '#type' => 'key_select', + '#key_filters' => [ + 'type' => 'os2web_key_certificate', + ], + '#title' => $this->t('Key'), + '#default_value' => $certificateConfig[self::PROVIDER_TYPE_KEY] ?? NULL, + '#states' => [ + 'visible' => [':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_KEY]], + 'required' => [':input[name="certificate[certificate_provider]"]' => ['value' => self::PROVIDER_TYPE_KEY]], + ], ]; - $form['actions']['testCertificate'] = [ - '#type' => 'submit', - '#name' => 'testCertificate', - '#value' => $this->t('Test certificate'), + $form['actions']['ping_api'] = [ + '#type' => 'container', + + self::ACTION_PING_API => [ + '#type' => 'submit', + '#name' => self::ACTION_PING_API, + '#value' => $this->t('Ping API'), + ], + + 'message' => [ + '#markup' => $this->t('Note: Pinging the API will use saved config.'), + ], ]; return $form; @@ -169,20 +238,23 @@ public function buildForm(array $form, FormStateInterface $form_state): array { * * @phpstan-param array $form */ - public function validateForm(array &$form, FormStateInterface $formState): void { - $triggeringElement = $formState->getTriggeringElement(); - if ('testCertificate' === ($triggeringElement['#name'] ?? NULL)) { + public function validateForm(array &$form, FormStateInterface $form_state): void { + if (self::ACTION_PING_API === ($form_state->getTriggeringElement()['#name'] ?? NULL)) { return; } - $values = $formState->getValues(); + $values = $form_state->getValues(); - if (CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM === $values[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE]) { - $path = $values[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL; - if (!file_exists($path)) { - $formState->setErrorByName('certificate][file_system][path', $this->t('Invalid certificate path: %path', ['%path' => $path])); + if (self::PROVIDER_TYPE_FORM === $values[self::CERTIFICATE][self::CERTIFICATE_PROVIDER]) { + if (CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM === $values[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE]) { + $path = $values[self::CERTIFICATE][CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM]['path'] ?? NULL; + if (!file_exists($path)) { + $form_state->setErrorByName('certificate][file_system][path', $this->t('Invalid certificate path: %path', ['%path' => $path])); + } } } + + parent::validateForm($form, $form_state); } /** @@ -190,44 +262,30 @@ public function validateForm(array &$form, FormStateInterface $formState): void * * @phpstan-param array $form */ - public function submitForm(array &$form, FormStateInterface $formState): void { - $triggeringElement = $formState->getTriggeringElement(); - if ('testCertificate' === ($triggeringElement['#name'] ?? NULL)) { - $this->testCertificate(); + public function submitForm(array &$form, FormStateInterface $form_state): void { + if (self::ACTION_PING_API === ($form_state->getTriggeringElement()['#name'] ?? NULL)) { + try { + $this->helper->pingApi(); + $this->messenger()->addStatus($this->t('Pinged API successfully.')); + } + catch (\Throwable $t) { + $this->messenger()->addError($this->t('Pinging API failed: @message', ['@message' => $t->getMessage()])); + } return; } - try { - $settings[self::CERTIFICATE] = $formState->getValue(self::CERTIFICATE); - $settings[self::FASIT_API_BASE_URL] = $formState->getValue(self::FASIT_API_BASE_URL); - $settings[self::FASIT_API_TENANT] = $formState->getValue(self::FASIT_API_TENANT); - $settings[self::FASIT_API_VERSION] = $formState->getValue(self::FASIT_API_VERSION); - - $this->settings->setSettings($settings); - $this->messenger()->addStatus($this->t('Settings saved')); + $config = $this->config(self::CONFIG_NAME); + foreach ([ + self::FASIT_API_BASE_URL, + self::FASIT_API_TENANT, + self::FASIT_API_VERSION, + self::CERTIFICATE, + ] as $key) { + $config->set($key, $form_state->getValue($key)); } - catch (OptionsResolverException $exception) { - $this->messenger()->addError($this->t('Settings not saved (@message)', ['@message' => $exception->getMessage()])); - - return; - } - - $this->messenger()->addStatus($this->t('Settings saved')); - } + $config->save(); - /** - * Test certificate. - */ - private function testCertificate(): void { - try { - $certificateLocator = $this->certificateLocatorHelper->getCertificateLocator(); - $certificateLocator->getCertificates(); - $this->messenger()->addStatus($this->t('Certificate successfully tested')); - } - catch (\Throwable $throwable) { - $message = $this->t('Error testing certificate: %message', ['%message' => $throwable->getMessage()]); - $this->messenger()->addError($message); - } + parent::submitForm($form, $form_state); } } diff --git a/modules/os2forms_fasit/src/Helper/CertificateLocatorHelper.php b/modules/os2forms_fasit/src/Helper/CertificateLocatorHelper.php index 3f244d1a..4d56a580 100644 --- a/modules/os2forms_fasit/src/Helper/CertificateLocatorHelper.php +++ b/modules/os2forms_fasit/src/Helper/CertificateLocatorHelper.php @@ -38,12 +38,12 @@ public function __construct(private readonly Settings $settings) { * Get certificate locator. */ public function getCertificateLocator(): CertificateLocatorInterface { - $certificateSettings = $this->settings->getCertificate(); + $config = $this->settings->getFasitCertificateConfig(); - $locatorType = $certificateSettings[self::LOCATOR_TYPE]; - $options = $certificateSettings[$locatorType]; + $locatorType = $config[self::LOCATOR_TYPE]; + $options = $config[$locatorType]; $options += [ - self::LOCATOR_PASSPHRASE => $certificateSettings[self::LOCATOR_PASSPHRASE] ?: '', + self::LOCATOR_PASSPHRASE => $config[self::LOCATOR_PASSPHRASE] ?: '', ]; if (self::LOCATOR_TYPE_AZURE_KEY_VAULT === $locatorType) { diff --git a/modules/os2forms_fasit/src/Helper/FasitHelper.php b/modules/os2forms_fasit/src/Helper/FasitHelper.php index 2bd84d65..12a5c51f 100644 --- a/modules/os2forms_fasit/src/Helper/FasitHelper.php +++ b/modules/os2forms_fasit/src/Helper/FasitHelper.php @@ -4,18 +4,21 @@ use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; +use Drupal\Core\File\FileSystemInterface; use Drupal\os2forms_attachment\Element\AttachmentElement; use Drupal\os2forms_fasit\Exception\FasitResponseException; use Drupal\os2forms_fasit\Exception\FasitXMLGenerationException; use Drupal\os2forms_fasit\Exception\FileTypeException; use Drupal\os2forms_fasit\Exception\InvalidSettingException; use Drupal\os2forms_fasit\Exception\InvalidSubmissionException; +use Drupal\os2forms_fasit\Form\SettingsForm; use Drupal\os2forms_fasit\Plugin\WebformHandler\FasitWebformHandler; use Drupal\os2web_audit\Service\Logger; use Drupal\webform\Entity\WebformSubmission; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Psr7\Utils; +use Psr\Http\Message\ResponseInterface; use Symfony\Component\HttpFoundation\Response; /** @@ -38,6 +41,7 @@ public function __construct( private readonly ClientInterface $client, private readonly EntityTypeManagerInterface $entityTypeManager, private readonly Settings $settings, + private readonly FileSystemInterface $fileSystem, private readonly CertificateLocatorHelper $certificateLocator, private readonly Logger $auditLogger, ) { @@ -206,8 +210,6 @@ private function uploadDocument(array $uploads, string $submissionId, array $han } } - [$certificateOptions, $tempCertFilename] = $this->getCertificateOptionsAndTempCertFilename(); - $body = $doc->saveXML(); if (!$body) { @@ -219,20 +221,14 @@ private function uploadDocument(array $uploads, string $submissionId, array $han 'Content-Type' => 'application/xml', ], 'body' => $body, - 'cert' => $certificateOptions, ]; // Attempt upload. try { - $response = $this->client->request('POST', $endpoint, $options); + $response = $this->post($endpoint, $options); } catch (GuzzleException $e) { throw new FasitResponseException($e->getMessage(), $e->getCode()); - } finally { - // Remove the certificate from disk. - if (file_exists($tempCertFilename)) { - unlink($tempCertFilename); - } } if (Response::HTTP_OK !== $response->getStatusCode()) { @@ -262,26 +258,6 @@ private function checkHandlerConfiguration(array $handlerConfiguration, string $ } } - /** - * Gets certificate options and temp certificate filename. - * - * @throws \Drupal\os2forms_fasit\Exception\CertificateLocatorException - * Certificate locator exception. - * - * @phpstan-return array - */ - private function getCertificateOptionsAndTempCertFilename(): array { - $certificateLocator = $this->certificateLocator->getCertificateLocator(); - $localCertFilename = tempnam(sys_get_temp_dir(), 'cert'); - file_put_contents($localCertFilename, $certificateLocator->getCertificate()); - $certificateOptions = - $certificateLocator->hasPassphrase() ? - [$localCertFilename, $certificateLocator->getPassphrase()] - : $localCertFilename; - - return [$certificateOptions, $localCertFilename]; - } - /** * Uploads attachment to Fasit. * @@ -345,8 +321,6 @@ private function uploadFile(string $originalFilename, string $tempFilename, stri self::FASIT_API_METHOD_UPLOAD ); - [$certificateOptions, $tempCertFilename] = $this->getCertificateOptionsAndTempCertFilename(); - // Attempt upload. try { $options = [ @@ -356,18 +330,13 @@ private function uploadFile(string $originalFilename, string $tempFilename, stri 'X-Title' => pathinfo($originalFilename, PATHINFO_FILENAME), ], 'body' => Utils::tryFopen($tempFilename, 'r'), - 'cert' => $certificateOptions, ]; - $response = $this->client->request('POST', $endpoint, $options); + $response = $this->post($endpoint, $options); } catch (GuzzleException $e) { throw new FasitResponseException($e->getMessage(), $e->getCode()); } finally { - // Remove the certificate from disk. - if (file_exists($tempCertFilename)) { - unlink($tempCertFilename); - } // Remove the attachment from disk. if (file_exists($tempFilename)) { unlink($tempFilename); @@ -510,4 +479,96 @@ private function getSubmission(string $submissionId): EntityInterface { return $storage->load($submissionId); } + /** + * Send POST request to Fasit API. + * + * @param string $endpoint + * The API endpoint. + * @param array $options + * The request options. + * + * @return \Psr\Http\Message\ResponseInterface + * The response. + * + * @throws \GuzzleHttp\Exception\GuzzleException + * A Guzzle exception. + */ + private function post(string $endpoint, array $options): ResponseInterface { + try { + $config = $this->settings->getFasitCertificateConfig(); + + // Key => string + // Azure => file without passphrase + // Filesystem => file with potential passphrase. + $provider = $config['certificate_provider']; + + if (SettingsForm::PROVIDER_TYPE_KEY === $provider) { + $certificate = $this->settings->getKeyValue(); + $certPath = $this->fileSystem->tempnam($this->fileSystem->getTempDirectory(), 'os2forms_fasit_cert'); + // `tempnam` has created a file, so we must replace when saving. + $this->fileSystem->saveData($certificate, $certPath, FileSystemInterface::EXISTS_REPLACE); + $options['cert'] = $certPath; + } + elseif (SettingsForm::PROVIDER_TYPE_FORM === $provider) { + [$certificateOptions] = $this->getCertificateOptionsAndTempCertFilename(); + $options['cert'] = $certificateOptions; + } + else { + throw new InvalidSettingException('Invalid certificate configuration'); + } + + return $this->client->request('POST', $endpoint, $options); + } finally { + // Remove the certificate from disk. + if (isset($certPath) && file_exists($certPath)) { + unlink($certPath); + } + } + } + + /** + * Ping the Fasit API and expect a 400 Bad Request response. + * + * @throws \Throwable + */ + public function pingApi(): void { + $endpoint = sprintf('%s/%s/%s/documents/%s', + $this->settings->getFasitApiBaseUrl(), + $this->settings->getFasitApiTenant(), + $this->settings->getFasitApiVersion(), + self::FASIT_API_METHOD_UPLOAD + ); + + try { + $this->post($endpoint, []); + } + catch (\Throwable $t) { + // Throw if it's not a 400 Bad Request exception. + if (!($t instanceof GuzzleException) + || Response::HTTP_BAD_REQUEST !== $t->getCode()) { + throw $t; + } + } + } + + /** + * Gets certificate options and temp certificate filename. + * + * @throws \Drupal\os2forms_fasit\Exception\CertificateLocatorException + * Certificate locator exception. + * + * @phpstan-return array + */ + private function getCertificateOptionsAndTempCertFilename(): array { + $certificateLocator = $this->certificateLocator->getCertificateLocator(); + $localCertFilename = tempnam(sys_get_temp_dir(), 'cert'); + file_put_contents($localCertFilename, $certificateLocator->getCertificate()); + $certificateOptions = + $certificateLocator->hasPassphrase() ? + [$localCertFilename, $certificateLocator->getPassphrase()] + : $localCertFilename; + + return [$certificateOptions, $localCertFilename]; + } + } diff --git a/modules/os2forms_fasit/src/Helper/Settings.php b/modules/os2forms_fasit/src/Helper/Settings.php index de065fc6..09410299 100644 --- a/modules/os2forms_fasit/src/Helper/Settings.php +++ b/modules/os2forms_fasit/src/Helper/Settings.php @@ -2,115 +2,111 @@ namespace Drupal\os2forms_fasit\Helper; -use Drupal\Core\KeyValueStore\KeyValueFactoryInterface; -use Drupal\Core\KeyValueStore\KeyValueStoreInterface; -use Drupal\os2forms_fasit\Exception\InvalidSettingException; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Config\ImmutableConfig; +use Drupal\key\KeyRepositoryInterface; use Drupal\os2forms_fasit\Form\SettingsForm; -use Symfony\Component\OptionsResolver\OptionsResolver; /** * General settings for os2forms_fasit. */ final class Settings { /** - * The store. + * The config. * - * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface + * @var \Drupal\Core\Config\ImmutableConfig */ - private KeyValueStoreInterface $store; + private ImmutableConfig $config; /** - * The key value collection name. - * - * @var string + * The constructor. */ - private $collection = 'os2forms_fasit'; + public function __construct( + ConfigFactoryInterface $configFactory, + private readonly KeyRepositoryInterface $keyRepository, + ) { + $this->config = $configFactory->get(SettingsForm::CONFIG_NAME); + } /** - * The constructor. + * Get fasit api base url. */ - public function __construct(KeyValueFactoryInterface $keyValueFactory) { - $this->store = $keyValueFactory->get($this->collection); + public function getFasitApiBaseUrl(): ?string { + return $this->get(SettingsForm::FASIT_API_BASE_URL); } /** - * Get fasit api base url. + * Get fasit api tenant. */ - public function getFasitApiBaseUrl(): string { - return $this->get(SettingsForm::FASIT_API_BASE_URL, ''); + public function getFasitApiTenant(): ?string { + return $this->get(SettingsForm::FASIT_API_TENANT); } /** - * Get fasit api base url. + * Get fasit api version. */ - public function getFasitApiTenant(): string { - return $this->get(SettingsForm::FASIT_API_TENANT, ''); + public function getFasitApiVersion(): ?string { + return $this->get(SettingsForm::FASIT_API_VERSION); } /** - * Get fasit api base url. + * Get Fasit configuration selector. */ - public function getFasitApiVersion(): string { - return $this->get(SettingsForm::FASIT_API_VERSION, ''); + public function getFasitCertificateConfig(): ?array { + return $this->get(SettingsForm::CERTIFICATE); } /** - * Get certificate. - * - * @phpstan-return array + * Get Fasit certificate provider. */ - public function getCertificate(): array { - $value = $this->get(SettingsForm::CERTIFICATE); - return is_array($value) ? $value : []; + public function getFasitCertificateProvider(): string { + $config = $this->getFasitCertificateConfig(); + + return $config[SettingsForm::CERTIFICATE_PROVIDER] ?? SettingsForm::PROVIDER_TYPE_FORM; } /** - * Get a setting value. - * - * @param string $key - * The key. - * @param mixed|null $default - * The default value. - * - * @return mixed - * The setting value. + * Get Fasit certificate locator. */ - private function get(string $key, $default = NULL) { - $resolver = $this->getSettingsResolver(); - if (!$resolver->isDefined($key)) { - throw new InvalidSettingException(sprintf('Setting %s is not defined', $key)); - } + public function getFasitCertificateLocator(): string { + $config = $this->getFasitCertificateConfig(); - return $this->store->get($key, $default); + return $config[CertificateLocatorHelper::LOCATOR_TYPE] ?? CertificateLocatorHelper::LOCATOR_TYPE_FILE_SYSTEM; } /** - * Set settings. - * - * @throws \Symfony\Component\OptionsResolver\Exception\ExceptionInterface - * - * @phpstan-param array $settings + * Get Fasit key certificate configuration. + */ + public function getFasitCertificateKey(): ?string { + $config = $this->getFasitCertificateConfig(); + + return $config[SettingsForm::PROVIDER_TYPE_KEY] ?? NULL; + } + + /** + * Get certificate. */ - public function setSettings(array $settings): self { - $settings = $this->getSettingsResolver()->resolve($settings); - foreach ($settings as $key => $value) { - $this->store->set($key, $value); - } + public function getKeyValue(): ?string { + $key = $this->keyRepository->getKey( + $this->getFasitCertificateKey(), + ); - return $this; + return $key?->getKeyValue(); } /** - * Get settings resolver. + * Get a setting value. + * + * @param string $key + * The key. + * @param mixed|null $default + * The default value. + * + * @return mixed + * The setting value. */ - private function getSettingsResolver(): OptionsResolver { - return (new OptionsResolver()) - ->setDefaults([ - SettingsForm::FASIT_API_BASE_URL => '', - SettingsForm::FASIT_API_TENANT => '', - SettingsForm::FASIT_API_VERSION => '', - SettingsForm::CERTIFICATE => [], - ]); + private function get(string $key, $default = NULL): mixed { + return $this->config->get($key) ?? $default; } } diff --git a/modules/os2forms_forloeb/CHANGELOG.md b/modules/os2forms_forloeb/CHANGELOG.md index 3338d105..6d569821 100644 --- a/modules/os2forms_forloeb/CHANGELOG.md +++ b/modules/os2forms_forloeb/CHANGELOG.md @@ -1,4 +1,5 @@ # OS2Forms Forløb Change Log + All notable changes to this project should be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) @@ -17,9 +18,11 @@ before starting to add changes. ## 2.5.2 - 27.03.2023 ### Updated + - Bumped drupal/ultimate_cron version fixing [Deprecated function: Implicit conversion from float-string](https://www.drupal.org/project/ultimate_cron/issues/3256142). ## 2.5.1 - 10.03.2023 + - Added github action for checking changelog changes when creating pull requests - Added os2forms/os2forms dependency - Changed composer patching configuration @@ -30,18 +33,20 @@ before starting to add changes. ## 2.5.0 - 11.10.2022 ### Added + - retry task controller action - Added support for inheriting values without creating a submission ## 2.4.0 ### Added + - Github CI action for checking Drupal Coding standards with PHP Code Sniffer - Fixed coding standards issues - ## Example of change log record -``` + +```markdown ## [x.x.x] Release name ### Added - Description on added functionality. diff --git a/modules/os2forms_forloeb/README.md b/modules/os2forms_forloeb/README.md index 7cf06186..11d1b07b 100644 --- a/modules/os2forms_forloeb/README.md +++ b/modules/os2forms_forloeb/README.md @@ -4,11 +4,13 @@ Adds a Maestro workflow engine and advanced workflow functionality to OS2forms. ## Installing OS2forms 2.1 med Forløb -This module requires the codebase from the [OS2forms core project](https://github.com/OS2Forms/os2forms8) installed per the documentation and by selecting the os2forms_forloeb_profile at installation. After succesful installation you should have the OS2forms med Forløb Module available for install via gui. +This module requires the codebase from the [OS2forms core project](https://github.com/OS2Forms/os2forms8) installed per +the documentation and by selecting the os2forms_forloeb_profile at installation. After succesful installation you should +have the OS2forms med Forløb Module available for install via gui. You can also install the module by using Drush: -``` +```shell ./vendor/bin/drush pm:enable os2forms_forloeb ``` @@ -32,20 +34,18 @@ Settings for OS2Forms forløb are defined on `/admin/config/system/os2forms_forl #### Known anonymous roles -In order to make the notifications work, Maestro workflow tasks must be assigned -to a *known anonymous role* and these roles are defined under *Known anonymous -roles*. +In order to make the notifications work, Maestro workflow tasks must be assigned to a *known anonymous role* and these +roles are defined under *Known anonymous roles*. #### Processing -A notification is not sent to a user immediately, but added to a queue which -must be processed asynchronously. Specify the queue handling notification jobs. +A notification is not sent to a user immediately, but added to a queue which must be processed asynchronously. Specify +the queue handling notification jobs. #### Templates Define templates for emails and digital post (PDF). - To reference assets, e.g. stylesheet or images, in your templates, you can use the `base_url` Twig variable to get the base URL: diff --git a/modules/os2forms_nemid/README.md b/modules/os2forms_nemid/README.md index 98ec5532..ec7c7932 100644 --- a/modules/os2forms_nemid/README.md +++ b/modules/os2forms_nemid/README.md @@ -1,10 +1,10 @@ # OS2Forms Nemid Drupal module -# Module purpose +## Module purpose The aim of this module is to provide custom NemId field and integration with OS2Web Nemlogin module. -# How does it work +## How does it work Module exposes dozen of new NemID components that are available in the webform build process. @@ -17,4 +17,3 @@ Besides this module adds a special settings to the Third Party Webform settings: - Hide form if under address protection Settings: admin/structure/webform/manage/[webform]/settings - diff --git a/modules/os2forms_permissions_by_term/README.md b/modules/os2forms_permissions_by_term/README.md index 2c572931..33ac9367 100644 --- a/modules/os2forms_permissions_by_term/README.md +++ b/modules/os2forms_permissions_by_term/README.md @@ -1,10 +1,13 @@ # OS2Forms permission by term module + This module implements permission by term access restrictions on several lists and entity displays related to webform and maestro. ## Setup configuration + Add to your settings.php or local.settings.php -``` + +```php $config['permissions_by_term.settings'] = [ 'permissions_mode' => FALSE, 'require_all_terms_granted' => FALSE, @@ -12,6 +15,7 @@ $config['permissions_by_term.settings'] = [ 'target_bundles' => ['user_affiliation'] ] ``` + Alternative change your site configuration on admin/permissions-by-term/settings to match the above. !note This is the recommended configuration of the permissions_by_term module. Using different values for @@ -19,6 +23,7 @@ Alternative change your site configuration on admin/permissions-by-term/settings be thoroughly tested. ## Usage + - The user affiliation taxonomy is added to webform config form and Maestro workflow forms. - The Permissions by Term module adds a form element to the user form. - When a user visits an entity of the above mentioned this module checks for match between the entity and the users diff --git a/modules/os2forms_sbsys/README.md b/modules/os2forms_sbsys/README.md index b554eebc..8e1129f0 100644 --- a/modules/os2forms_sbsys/README.md +++ b/modules/os2forms_sbsys/README.md @@ -1,6 +1,7 @@ # OS2forms SBSYS integration Drupal module ## Module purpose + The aim of this module is to provide integration with SBSYS ESDH provider. ## How does it work diff --git a/modules/os2forms_webform_maps/README.md b/modules/os2forms_webform_maps/README.md index e6d08748..c36b901e 100644 --- a/modules/os2forms_webform_maps/README.md +++ b/modules/os2forms_webform_maps/README.md @@ -1,13 +1,16 @@ # OS2Forms Webform Maps module for Drupal 9 ## Module description + Provides integration with Leaflet maps and provides map element for webform. ## How does it work + The module provides a new element type for webform. The element type is called "OS2Forms Kort". The element type is based on the Leaflet library. The element type provides a map with a marker that can be moved around on the map. The element type also provides ways of changing layers on the map. The data can be exported to PDF. ## Installation + The module can be installed using the standard Drupal installation procedure. diff --git a/package.json b/package.json deleted file mode 100644 index 52fcd34c..00000000 --- a/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "license": "UNLICENSED", - "private": true, - "devDependencies": { - "markdownlint-cli": "^0.32.2" - }, - "scripts": { - "coding-standards-check/markdownlint": "yarn markdownlint --ignore LICENSE.md --ignore vendor --ignore node_modules '*.md' 'modules/os2forms_digital_post/**/*.md'", - "coding-standards-check": "yarn coding-standards-check/markdownlint", - "coding-standards-apply/markdownlint": "yarn markdownlint --ignore LICENSE.md --ignore vendor --ignore node_modules '*.md' 'modules/os2forms_digital_post/**/*.md' --fix", - "coding-standards-apply": "yarn coding-standards-apply/markdownlint" - } -} diff --git a/scripts/code-analysis b/scripts/code-analysis index 9fec0f46..ace9e282 100755 --- a/scripts/code-analysis +++ b/scripts/code-analysis @@ -16,9 +16,21 @@ if [ ! -f "$drupal_dir/composer.json" ]; then composer --no-interaction create-project drupal/recommended-project:^10 "$drupal_dir" fi # Copy our code into the modules folder -mkdir -p "$drupal_dir/$module_path" + +# Clean up +rm -fr "${drupal_dir:?}/$module_path" + # https://stackoverflow.com/a/15373763 -rsync --archive --compress . --filter=':- .gitignore' --exclude "$drupal_dir" --exclude .git "$drupal_dir/$module_path" +# rsync --archive --compress . --filter=':- .gitignore' --exclude "$drupal_dir" --exclude .git "$drupal_dir/$module_path" + +# The rsync command in not available in itkdev/php8.1-fpm + +git config --global --add safe.directory /app +# Copy module files into module path +for f in $(git ls-files); do + mkdir -p "$drupal_dir/$module_path/$(dirname "$f")" + cp "$f" "$drupal_dir/$module_path/$f" +done drupal_composer config minimum-stability dev @@ -37,4 +49,4 @@ drupal_composer config extra.merge-plugin.include "$module_path/composer.json" drupal_composer require --dev symfony/phpunit-bridge # Run PHPStan -(cd "$drupal_dir" && vendor/bin/phpstan --configuration="$module_path/phpstan.neon") +(cd "$drupal_dir/$module_path" && ../../../../vendor/bin/phpstan)