diff --git a/sites/all/modules/contrib/admin/admin_toolbar/CHANGELOG.txt b/sites/all/modules/contrib/admin/admin_toolbar/CHANGELOG.txt index 12f4450ae..a3a0d75b4 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/CHANGELOG.txt +++ b/sites/all/modules/contrib/admin/admin_toolbar/CHANGELOG.txt @@ -1,6 +1,33 @@ -Admin Toolbar 8.1.23, 2018-02-06 --------------------------------- -Changes since 8.1.22: +Admin Toolbar 8.x-1.24, 2018-05-28 +---------------------------------- +Changes since 8.x-1.23: + +- #2973131 by adriancid: Don't refer to Drupal in the help page. +- #2975170 by adriancid: Add composer.json file to submodules. +- #2975165 by Gamewalker, adriancid: datetime.time services is not found in + ToolbarController. +- #2971466 by recrit, adriancid, acbramley: Add media links incorrectly set to + "node.add.". +- #2972553 by dww, adriancid: Add static cache to speed up + admin_toolbar_links_access_filter_user_has_admin_role(). +- #2971435 by adriancid: Module help page for Admin Toolbar Extra Tools module + doesn't show the links. +- #2971398 by adriancid: Add the docblock to the ToolbarController constructor. +- #2969686 by adriancid, Vidushi Mehta: Add a menu link to clean the twig cache. +- #2969325 by adriancid: Fix the module version in the CHANGELOG.txt. +- #2961450 by adriancid: Convert the AdminToolbarAlterTest test class to + PHPUnit. +- #2961445 by adriancid: Convert the AdminToolbarToolsAlterTest test class to + PHPUnit. +- #2959684 by adriancid: Remove recommended modules section from README.txt. +- #2959647 by adriancid: Use interfaces instead of classes to inject + dependencies. +- #2952643 by romainj, if-jds, adriancid: Add Item for Files under Content Menu. +- #2944463 by adriancid: Update the composer.json file. + +Admin Toolbar 8.x-1.23, 2018-02-06 +---------------------------------- +Changes since 8.x-1.22: - #2924266 by sunlix, romainj, adriancid, samerali: Add a menu link for the media module. @@ -19,9 +46,9 @@ Changes since 8.1.22: core/drupal library. - #2931503 by K3vin_nl: Admin toolbar generates invalid class names. -Admin Toolbar 8.1.22, 2018-01-02 --------------------------------- -Changes since 8.1.21: +Admin Toolbar 8.x-1.22, 2018-01-02 +---------------------------------- +Changes since 8.x-1.21: - #2929053 by kkuhnen, eme, adriancid: admin_toolbar.js should use Drupal behaviors. @@ -42,9 +69,9 @@ Changes since 8.1.21: - #2925128 by adriancid: Create the module help page for the Admin Toolbar Links Access Filter submodule. -Admin Toolbar 8.1.21, 2017-11-20 --------------------------------- -Changes since 8.1.20: +Admin Toolbar 8.x-1.21, 2017-11-20 +---------------------------------- +Changes since 8.x-1.20: - #2923580 by sylus, adriancid: Unsupported operand types in ToolbarHandler::lazyBuilder(). @@ -87,9 +114,9 @@ Changes since 8.1.20: - #2909003 by eme: fix z-index for CKEditor. - #2504449 by robin.ingelbrecht, rwam, eme: Un-hover delay. -Admin Toolbar 8.1.20, 2017-09-07 --------------------------------- -Changes since 8.1.19: +Admin Toolbar 8.x-1.20, 2017-09-07 +---------------------------------- +Changes since 8.x-1.19: - #2887439 by romainj: Fix test. - #2759135 by Johnny vd Laar, miiimooo, chegor, romainj: Content type, @@ -106,9 +133,9 @@ Changes since 8.1.19: - #2870404 by romainj: Add a link to the Webprofiler settings page. - #2706643 by esod, romainj, Keenegan, DamienMcKenna: Use short array syntax. -Admin Toolbar 8.1.19, 2017-04-06 --------------------------------- -Changes since 8.1.18: +Admin Toolbar 8.x-1.19, 2017-04-06 +---------------------------------- +Changes since 8.x-1.18: - #2706643 by esod, romainj, Keenegan, DamienMcKenna: Use short array syntax. - #2781745 by minakshiPh, eelkeblok, romainj, akhilavnair_zyxware: Drupal coding @@ -117,9 +144,9 @@ Changes since 8.1.18: - #2841512 by Chi, romainj: User error: Redirects to external URLs are not allowed by default. -Admin Toolbar 8.1.18, 2016-12-01 --------------------------------- -Changes since 8.1.17: +Admin Toolbar 8.x-1.18, 2016-12-01 +---------------------------------- +Changes since 8.x-1.17: - #2830677 by vaplas, romainj: z-index for sub menu. - by romainj: Get rid of the Hello popup. @@ -130,9 +157,9 @@ Changes since 8.1.17: - #2518202 by james.williams, chegor, eme, romainj, DuneBL: Change default link to taxonomy. -Admin Toolbar 8.1.17, 2016-08-19 --------------------------------- -Changes since 8.1.16: +Admin Toolbar 8.x-1.17, 2016-08-19 +---------------------------------- +Changes since 8.x-1.16: - #2779251 by romainj, DuneBL: Wrong integration of field_collection delete form. @@ -150,9 +177,9 @@ Changes since 8.1.16: - #2707747 by Balu Ertl, nevergone, eme, esod: D8 logo not rendered with smooth antialiasing. -Admin Toolbar 8.1.16, 2016-07-28 --------------------------------- -Changes since 8.1.15: +Admin Toolbar 8.x-1.16, 2016-07-28 +---------------------------------- +Changes since 8.x-1.15: - #2723209 by andrewmacpherson, colan, mattshoaf: Enabling admin_toolbar_tools causes Devel Settings to disappear from the main configuration page. @@ -185,9 +212,9 @@ Changes since 8.1.15: - by romainj: Fixes issue #2731663 by canceling the move of the Logout menu link. -Admin Toolbar 8.1.15, 2016-05-23 --------------------------------- -Changes since 8.1.14: +Admin Toolbar 8.x-1.15, 2016-05-23 +---------------------------------- +Changes since 8.x-1.14: - by matio89: add RTL in admin.toolbar.css. - by romainj: Changes Devel menu item titles. @@ -208,9 +235,9 @@ Changes since 8.1.14: - by eme: fix issue #2658896 and refactor and fix chevron-right.svg. - by eme: fix Issue #2493037. -Admin Toolbar 8.1.14, 2016-02-08 --------------------------------- -Changes since 8.1.13: +Admin Toolbar 8.x-1.14, 2016-02-08 +---------------------------------- +Changes since 8.x-1.13: - by matio89: Correction differents bugs(problem white page when installing a new module). @@ -218,17 +245,17 @@ Changes since 8.1.13: - by matio89: resolving the dependecies problem(dependencies of others modules). - by matio89: Correction route of entities. -Admin Toolbar 8.1.13, 2016-02-02 --------------------------------- -Changes since 8.1.12: +Admin Toolbar 8.x-1.13, 2016-02-02 +---------------------------------- +Changes since 8.x-1.12: - by matio89: Admin toolbar is compatible with 8.0.2. - by matio89: Commmit dev version compatible with drupal 8.0.2. - by matio89: New version of admin toolbar compatible with 8.0.2. -Admin Toolbar 8.1.12, 2016-01-15 --------------------------------- -Changes since 8.1.11: +Admin Toolbar 8.x-1.12, 2016-01-15 +---------------------------------- +Changes since 8.x-1.11: - by matio89: Correction AdminToolbaToolsAlterTest. - #2493037 by mimran: Empty elements in #toolbar-bar. @@ -236,9 +263,9 @@ Changes since 8.1.11: - #2635154 by Lukas von Blarer: Too general CSS selectors. - by eme: Fix chevron right in local state. -Admin Toolbar 8.1.11, 2015-12-11 --------------------------------- -Changes since 8.1.10: +Admin Toolbar 8.x-1.11, 2015-12-11 +---------------------------------- +Changes since 8.x-1.10: - #2620430 by Vagelis, NarendraR: Typo. - #2632888 by JamesK: Add dependency on node module. @@ -255,46 +282,46 @@ Changes since 8.1.10: login link. - by matio89: Correction the login link on the site when in a logged-out state. -Admin Toolbar 8.1.10, 2015-08-07 --------------------------------- -Changes since 8.1.9: +Admin Toolbar 8.x-1.10, 2015-08-07 +---------------------------------- +Changes since 8.x-1.9: - #2546939 by jonhattan: Add dependency on toolbar module. -Admin Toolbar 8.1.9, 2015-07-22 -------------------------------- -Changes since 8.1.8: +Admin Toolbar 8.x-1.9, 2015-07-22 +--------------------------------- +Changes since 8.x-1.8: - #2537016 by matio89: Removing dependance for user & system. - #2533420 by Dave Reid, twistor: Chase HEAD changes in toolbar. - #2537016 by twistor: Rewrite admin_toolbar_tools.module - by matio89: Correction all bugs and add new security features. -Admin Toolbar 8.1.8, 2015-06-22 -------------------------------- -Changes since 8.1.7: +Admin Toolbar 8.x-1.8, 2015-06-22 +--------------------------------- +Changes since 8.x-1.7: - correction not found route. - #2493037 by bobrov1989: Empty elements in #toolbar-bar. - by fethi: icones. -Admin Toolbar 8.1.7, 2015-06-22 -------------------------------- -Changes since 8.1.6: +Admin Toolbar 8.x-1.7, 2015-06-22 +--------------------------------- +Changes since 8.x-1.6: - correction not found route. - #2493037 by bobrov1989: Empty elements in #toolbar-bar. - by fethi: icones. -Admin Toolbar 8.1.6, 2015-06-03 -------------------------------- -Changes since 8.1.5: +Admin Toolbar 8.x-1.6, 2015-06-03 +--------------------------------- +Changes since 8.x-1.5: - by matio89: correction admin_toolbar. -Admin Toolbar 8.1.5, 2015-06-03 -------------------------------- -Changes since 8.1.4: +Admin Toolbar 8.x-1.5, 2015-06-03 +--------------------------------- +Changes since 8.x-1.4: - by matio89: test if module update exist or no to display install and update module. @@ -302,36 +329,36 @@ Changes since 8.1.4: - by matio89: compatibility with Drupal 8 béta 11. - by fethi: Change the colors used to match the Seven styleguide. -Admin Toolbar 8.1.4, 2015-05-20 -------------------------------- -Changes since 8.1.3: +Admin Toolbar 8.x-1.4, 2015-05-20 +--------------------------------- +Changes since 8.x-1.3: - by matio89: correction add/node. -Admin Toolbar 8.1.3, 2015-05-19 -------------------------------- -Changes since 8.1.2: +Admin Toolbar 8.x-1.3, 2015-05-19 +--------------------------------- +Changes since 8.x-1.2: - by matio89: add new functionalities. - by matio89: add administration devel link. - by matio89: correction reload page. - by matio89: correction redirect to the same page. -Admin Toolbar 8.1.2, 2015-05-19 -------------------------------- -Changes since 8.1.1: +Admin Toolbar 8.x-1.2, 2015-05-19 +--------------------------------- +Changes since 8.x-1.1: - by matio89: add new functionalities. - by matio89: add administration devel link. - by matio89: correction reload page. - by matio89: correction redirect to the same page. -Admin Toolbar 8.1.1, 2015-05-19 -------------------------------- -Changes since 8.1.0: +Admin Toolbar 8.x-1.1, 2015-05-19 +--------------------------------- +Changes since 8.x-1.0: - by matio89: add new functionalities. -Admin Toolbar 8.1.0, 2015-05-07 -------------------------------- +Admin Toolbar 8.x-1.0, 2015-05-07 +--------------------------------- - Initial release. diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar.info.yml b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar.info.yml index 900077c7b..a8b87bf02 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar.info.yml +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar.info.yml @@ -1,5 +1,5 @@ name: Admin Toolbar -description: Provides a drop-down menu interface to the core Drupal Toolbar. +description: Provides a drop-down menu interface to the site Toolbar. package: Administration type: module @@ -8,8 +8,8 @@ type: module dependencies: - drupal:toolbar -# Information added by Drupal.org packaging script on 2018-02-06 -version: '8.x-1.23' +# Information added by Drupal.org packaging script on 2018-05-28 +version: '8.x-1.24' core: '8.x' project: 'admin_toolbar' -datestamp: 1517936588 +datestamp: 1527522484 diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar.module b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar.module index a9199e91a..c8ee104da 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar.module +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar.module @@ -27,14 +27,13 @@ function admin_toolbar_help($route_name, RouteMatchInterface $route_match) { $variables = [ ':toolbar' => Url::fromRoute('help.page', ['name' => 'toolbar'])->toString(), ':automated_cron' => (\Drupal::moduleHandler()->moduleExists('automated_cron')) ? Url::fromRoute('help.page', ['name' => 'automated_cron'])->toString() : '#', - ':admin_toolbar_documentation' => 'https://www.drupal.org/node/2713693', ]; $output = ''; $output .= '

' . t('About') . '

'; - $output .= '

' . t('The Admin Toolbar module enhances the Toolbar module by providing fast access to all the administrative links at the top of your site. Admin Toolbar remains a very "lightweight" module by closely integrating with all Toolbar functionality. It can be used in conjunction with all the sub or complimentary modules, listed on Admin Toolbar, for quick access to system commands such as Flush all caches, Run cron, Run Updates, etc... For more information, see the online documentation for the Admin Toolbar module.', $variables) . '

'; + $output .= '

' . t('The Admin Toolbar module enhances the Toolbar module by providing fast access to all the administrative links at the top of your site. Admin Toolbar remains a very "lightweight" module by closely integrating with all Toolbar functionality. It can be used in conjunction with all the sub modules included on Admin Toolbar, for quick access to system commands such as Flush all caches, Run cron, Run Updates, etc.', $variables) . '

'; $output .= '

' . t('Uses') . '

'; - $output .= '

' . t('The Admin Toolbar greatly improves the user experience for those who regularly interact with the Drupal Toolbar by providing fast, full access to all links in the Drupal Toolbar without having to click to get there.') . '

'; + $output .= '

' . t('The Admin Toolbar greatly improves the user experience for those who regularly interact with the site Toolbar by providing fast, full access to all links in the site Toolbar without having to click to get there.') . '

'; return $output; } diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/README.txt b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/README.txt index 60598b871..37670cf49 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/README.txt +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/README.txt @@ -3,7 +3,6 @@ CONTENTS OF THIS FILE * Introduction * Requirements - * Recommended modules * Installation * Configuration * Maintainers @@ -32,15 +31,6 @@ This module requires the following modules: * Admin Toolbar (https://www.drupal.org/project/admin_toolbar) -RECOMMENDED MODULES -------------------- - - * Admin Toolbar (https://www.drupal.org/project/admin_toolbar): - Improve the default Drupal Toolbar (the administration menu at the top of - your site) to transform it into a drop-down menu, providing a fast access to - all administration pages. - - INSTALLATION ------------ diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.info.yml b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.info.yml index 355a40cac..46edfd8a4 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.info.yml +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.info.yml @@ -8,8 +8,8 @@ type: module dependencies: - admin_toolbar:admin_toolbar -# Information added by Drupal.org packaging script on 2018-02-06 -version: '8.x-1.23' +# Information added by Drupal.org packaging script on 2018-05-28 +version: '8.x-1.24' core: '8.x' project: 'admin_toolbar' -datestamp: 1517936588 +datestamp: 1527522484 diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.module b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.module index 7b4476897..d9930e07b 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.module +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/admin_toolbar_links_access_filter.module @@ -20,7 +20,7 @@ function admin_toolbar_links_access_filter_help($route_name, RouteMatchInterface case 'help.page.admin_toolbar_links_access_filter': $output = ''; $output .= '

' . t('About') . '

'; - $output .= '

' . t("The Admin Toolbar Links Access Filter module Provides a workaround for the common problem that users with Use the administration pages and help permission see menu links they don't have access permission for. Once the issue Hide empty admin categories be solved, this module will be deprecated.", ['@url' => Url::fromUri('https://www.drupal.org/node/296693')->toString()]) . '

'; + $output .= '

' . t('The Admin Toolbar Links Access Filter module provides a workaround for the common problem that users with Use the administration pages and help permission see menu links they done not have access permission for.') . '

'; return $output; } @@ -184,10 +184,17 @@ function admin_toolbar_links_access_filter_is_overview_page($route_name) { * assigned, FALSE otherwise. */ function admin_toolbar_links_access_filter_user_has_admin_role(AccountInterface $account) { - foreach ($account->getRoles() as $role_id) { - if (Role::load($role_id)->isAdmin()) { - return TRUE; + static $user_has_admin_role = []; + $uid = $account->id(); + if (!isset($user_has_admin_role[$uid])) { + $roles = Role::loadMultiple($account->getRoles()); + foreach ($roles as $role) { + if ($role->isAdmin()) { + $user_has_admin_role[$uid] = TRUE; + break; + } + $user_has_admin_role[$uid] = FALSE; } } - return FALSE; + return $user_has_admin_role[$uid]; } diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/composer.json b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/composer.json new file mode 100644 index 000000000..d75f3b0c6 --- /dev/null +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_links_access_filter/composer.json @@ -0,0 +1,38 @@ +{ + "name": "drupal/admin_toolbar_links_access_filter", + "description": "Provides a workaround for the common problem that users with 'Use the administration pages and help' permission see menu links they don't have access permission for. Once the issue https://www.drupal.org/node/296693 be solved, this module will be deprecated.", + "type": "drupal-module", + "keywords": ["Drupal", "Toolbar"], + "homepage": "http://drupal.org/project/admin_toolbar", + "license": "GPL-2.0+", + "authors": [ + { + "name": "Wilfrid Roze (eme)", + "homepage": "https://www.drupal.org/u/eme", + "role": "Maintainer" + }, + { + "name": "Romain Jarraud (romainj)", + "homepage": "https://www.drupal.org/u/romainj", + "role": "Maintainer" + }, + { + "name": "Adrian Cid Almaguer (adriancid)", + "email": "adriancid@gmail.com", + "homepage": "https://www.drupal.org/u/adriancid", + "role": "Maintainer" + }, + { + "name": "Mohamed Anis Taktak (matio89)", + "homepage": "https://www.drupal.org/u/matio89", + "role": "Maintainer" + } + ], + "support": { + "issues": "https://www.drupal.org/project/issues/admin_toolbar", + "source": "http://cgit.drupalcode.org/admin_toolbar" + }, + "require": { + "drupal/admin_toolbar": "^1" + } +} diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/README.txt b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/README.txt index 4e40e8730..263cde93c 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/README.txt +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/README.txt @@ -33,15 +33,6 @@ This module requires the following modules: * Admin Toolbar (https://www.drupal.org/project/admin_toolbar) -RECOMMENDED MODULES -------------------- - - * Admin Toolbar (https://www.drupal.org/project/admin_toolbar): - Improve the default Drupal Toolbar (the administration menu at the top of - your site) to transform it into a drop-down menu, providing a fast access to - all administration pages. - - INSTALLATION ------------ diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.info.yml b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.info.yml index 8166fe66e..a42c0ccbe 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.info.yml +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.info.yml @@ -7,9 +7,10 @@ type: module dependencies: - admin_toolbar:admin_toolbar + - drupal:system (>=8.3) -# Information added by Drupal.org packaging script on 2018-02-06 -version: '8.x-1.23' +# Information added by Drupal.org packaging script on 2018-05-28 +version: '8.x-1.24' core: '8.x' project: 'admin_toolbar' -datestamp: 1517936588 +datestamp: 1527522484 diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.links.menu.yml b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.links.menu.yml index cb8cc2587..fc7df7f1c 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.links.menu.yml +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.links.menu.yml @@ -63,6 +63,12 @@ admin_toolbar_tools.flush_menu: parent: admin_toolbar_tools.flush menu_name: admin +admin_toolbar_tools.flush_twig: + title: 'Flush twig cache' + route_name: admin_toolbar_tools.flush_twig + parent: admin_toolbar_tools.flush + menu_name: admin + admin_toolbar_tools.flush_rendercache: title: 'Flush render cache' route_name: admin_toolbar_tools.flush_rendercache diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.module b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.module index d08141db4..1db436a1d 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.module +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.module @@ -5,7 +5,6 @@ * Provides extra menu links for the core drupal toolbar. */ -use Drupal\Core\Link; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\Core\Url; @@ -34,21 +33,12 @@ function admin_toolbar_tools_toolbar() { function admin_toolbar_tools_help($route_name, RouteMatchInterface $route_match) { switch ($route_name) { case 'help.page.admin_toolbar_tools': - $url = Url::fromUri('https://www.drupal.org/project/admin_toolbar'); - $external_link = Link::fromTextAndUrl(t('Admin Toolbar'), $url); - $external_link2 = Link::fromTextAndUrl(t('Toolbar'), $url); - $url = Url::fromUri('https://www.drupal.org/node/2713693'); - $external_link3 = Link::fromTextAndUrl(t('online documentation for Admin Toolbar'), $url); $output = ''; $output .= '

'; - $output .= t('The Admin Toolbar Extra Tools module comes packaged with the :link module and adds functionality to it. The additional functionality is accessed thru extra links on the main administration :link2. Some links to Admin Toolbar Extra Tools administration pages are located at the bottom of this page. For more information, see the :link3', [ - ':link' => $external_link, - ':link2' => $external_link2, - ':link3' => $external_link3, - ]); + $output .= t('The Admin Toolbar Extra Tools module comes packaged with the Admin Toolbar module and adds functionality to it. The additional functionality is accessed thru extra links on the main administration Toolbar. Some links to Admin Toolbar Extra Tools administration pages are located at the bottom of this page.', [':admin-toolbar' => Url::fromRoute('help.page', ['name' => 'admin_toolbar'])->toString()]); $output .= '

'; $output .= '

' . t('Uses') . '

'; - $output .= '

' . t('To use Admin Toolbar Extra Tools just install it like any other module. There is no other configuration required. The Admin Toolbar functionality can be further extended by installing complimentary modules. See :link for a complete listing of these complimentary modules.', [':link' => $external_link]) . '

'; + $output .= '

' . t('To use Admin Toolbar Extra Tools just install it like any other module. There is no other configuration required.') . '

'; return $output; } @@ -85,6 +75,15 @@ function admin_toolbar_tools_menu_links_discovered_alter(&$links) { 'menu_name' => 'admin', 'parent' => 'admin_toolbar_tools.flush', ]; + // Adding a menu link to Files. + if ($moduleHandler->moduleExists('file') && in_array('view.files.page_1', $routes)) { + $links['admin_toolbar_tools.view.files'] = [ + 'title' => t('Files'), + 'route_name' => 'view.files.page_1', + 'menu_name' => 'admin', + 'parent' => 'system.admin_content', + ]; + } } // Adds common links to entities. @@ -568,7 +567,7 @@ function admin_toolbar_tools_menu_links_discovered_alter(&$links) { ]; // Add node links for each media type. foreach (\Drupal::entityTypeManager()->getStorage('media_type')->loadMultiple() as $type) { - $links['node.add.' . $type->id()] = [ + $links['media.add.' . $type->id()] = [ 'title' => t($type->label()), 'route_name' => 'entity.media.add_form', 'parent' => 'admin_toolbar_tools.add_media', diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.routing.yml b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.routing.yml index 277808c8e..dc081c860 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.routing.yml +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.routing.yml @@ -61,6 +61,15 @@ admin_toolbar_tools.flush_views: _permission: 'administer site configuration' _csrf_token: 'TRUE' +admin_toolbar_tools.flush_twig: + path: '/admin/flush/twig' + defaults: + _controller: '\Drupal\admin_toolbar_tools\Controller\ToolbarController::flushTwig' + _title: 'Twig' + requirements: + _permission: 'administer site configuration' + _csrf_token: 'TRUE' + admin_toolbar.run.cron: path: '/run-cron' defaults: diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/composer.json b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/composer.json new file mode 100644 index 000000000..49414fc2b --- /dev/null +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/composer.json @@ -0,0 +1,39 @@ +{ + "name": "drupal/admin_toolbar_tools", + "description": "Adds menu links to the Admin Toolbar.", + "type": "drupal-module", + "keywords": ["Drupal", "Toolbar"], + "homepage": "http://drupal.org/project/admin_toolbar", + "license": "GPL-2.0+", + "authors": [ + { + "name": "Wilfrid Roze (eme)", + "homepage": "https://www.drupal.org/u/eme", + "role": "Maintainer" + }, + { + "name": "Romain Jarraud (romainj)", + "homepage": "https://www.drupal.org/u/romainj", + "role": "Maintainer" + }, + { + "name": "Adrian Cid Almaguer (adriancid)", + "email": "adriancid@gmail.com", + "homepage": "https://www.drupal.org/u/adriancid", + "role": "Maintainer" + }, + { + "name": "Mohamed Anis Taktak (matio89)", + "homepage": "https://www.drupal.org/u/matio89", + "role": "Maintainer" + } + ], + "support": { + "issues": "https://www.drupal.org/project/issues/admin_toolbar", + "source": "http://cgit.drupalcode.org/admin_toolbar" + }, + "require": { + "drupal/admin_toolbar": "^1", + "drupal/core": "~8.3" + } +} diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/src/Controller/ToolbarController.php b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/src/Controller/ToolbarController.php index b1f275a79..8b74436c8 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/src/Controller/ToolbarController.php +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/src/Controller/ToolbarController.php @@ -2,18 +2,19 @@ namespace Drupal\admin_toolbar_tools\Controller; -use Drupal\Component\Datetime\Time; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Controller\ControllerBase; use Drupal\Core\CronInterface; -use Drupal\Core\Menu\ContextualLinkManager; -use Drupal\Core\Menu\LocalActionManager; -use Drupal\Core\Menu\LocalTaskManager; -use Drupal\Core\Menu\MenuLinkManager; +use Drupal\Core\Menu\ContextualLinkManagerInterface; +use Drupal\Core\Menu\LocalActionManagerInterface; +use Drupal\Core\Menu\LocalTaskManagerInterface; +use Drupal\Core\Menu\MenuLinkManagerInterface; use Drupal\Core\Plugin\CachedDiscoveryClearerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RequestStack; +use Drupal\Core\PhpStorage\PhpStorageFactory; /** * Class ToolbarController. @@ -32,28 +33,28 @@ class ToolbarController extends ControllerBase { /** * A menu link manager instance. * - * @var \Drupal\Core\Menu\MenuLinkManager + * @var \Drupal\Core\Menu\MenuLinkManagerInterface */ protected $menuLinkManager; /** * A context link manager instance. * - * @var \Drupal\Core\Menu\ContextualLinkManager + * @var \Drupal\Core\Menu\ContextualLinkManagerInterface */ protected $contextualLinkManager; /** * A local task manager instance. * - * @var \Drupal\Core\Menu\LocalTaskManager + * @var \Drupal\Core\Menu\LocalTaskManagerInterface */ protected $localTaskLinkManager; /** * A local action manager instance. * - * @var \Drupal\Core\Menu\LocalActionManager + * @var \Drupal\Core\Menu\LocalActionManagerInterface */ protected $localActionLinkManager; @@ -67,7 +68,7 @@ class ToolbarController extends ControllerBase { /** * A date time instance. * - * @var \Drupal\Component\Datetime\Time + * @var \Drupal\Component\Datetime\TimeInterface */ protected $time; @@ -86,15 +87,34 @@ class ToolbarController extends ControllerBase { protected $pluginCacheClearer; /** - * {@inheritdoc} + * Constructs a ToolbarController object. + * + * @param \Drupal\Core\CronInterface $cron + * A cron instance. + * @param \Drupal\Core\Menu\MenuLinkManagerInterface $menuLinkManager + * A menu link manager instance. + * @param \Drupal\Core\Menu\ContextualLinkManagerInterface $contextualLinkManager + * A context link manager instance. + * @param \Drupal\Core\Menu\LocalTaskManagerInterface $localTaskLinkManager + * A local task manager instance. + * @param \Drupal\Core\Menu\LocalActionManagerInterface $localActionLinkManager + * A local action manager instance. + * @param \Drupal\Core\Cache\CacheBackendInterface $cacheRender + * A cache backend interface instance. + * @param \Drupal\Component\Datetime\TimeInterface $time + * A date time instance. + * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack + * A request stack symfony instance. + * @param \Drupal\Core\Plugin\CachedDiscoveryClearerInterface $plugin_cache_clearer + * A plugin cache clear instance. */ public function __construct(CronInterface $cron, - MenuLinkManager $menuLinkManager, - ContextualLinkManager $contextualLinkManager, - LocalTaskManager $localTaskLinkManager, - LocalActionManager $localActionLinkManager, + MenuLinkManagerInterface $menuLinkManager, + ContextualLinkManagerInterface $contextualLinkManager, + LocalTaskManagerInterface $localTaskLinkManager, + LocalActionManagerInterface $localActionLinkManager, CacheBackendInterface $cacheRender, - Time $time, + TimeInterface $time, RequestStack $request_stack, CachedDiscoveryClearerInterface $plugin_cache_clearer) { $this->cron = $cron; @@ -197,6 +217,17 @@ class ToolbarController extends ControllerBase { return new RedirectResponse($this->reloadPage()); } + /** + * Clears the twig cache. + */ + public function flushTwig() { + // @todo Update once Drupal 8.6 will be released. + // @see https://www.drupal.org/node/2908461 + PhpStorageFactory::get('twig')->deleteAll(); + drupal_set_message($this->t('Twig cache cleared.')); + return new RedirectResponse($this->reloadPage()); + } + /** * Run the cron. */ diff --git a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/src/Tests/AdminToolbarToolsAlterTest.php b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/tests/src/Functional/AdminToolbarToolsAlterTest.php similarity index 78% rename from sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/src/Tests/AdminToolbarToolsAlterTest.php rename to sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/tests/src/Functional/AdminToolbarToolsAlterTest.php index 73035efb1..f61329c63 100644 --- a/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/src/Tests/AdminToolbarToolsAlterTest.php +++ b/sites/all/modules/contrib/admin/admin_toolbar/admin_toolbar_tools/tests/src/Functional/AdminToolbarToolsAlterTest.php @@ -1,22 +1,26 @@ + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/sites/all/modules/contrib/admin/matomo/README.txt b/sites/all/modules/contrib/admin/matomo/README.txt new file mode 100644 index 000000000..dec0ab4b8 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/README.txt @@ -0,0 +1,109 @@ + +Module: Matomo Analytics +Author: Alexander Hass + + +Description +=========== +Adds the Matomo tracking system to your website. + +Requirements +============ + +* Matomo installation +* Matomo website ID + + +Installation +============ +* Copy the 'matomo' module directory in to your Drupal 'modules' +directory as usual. + + +Usage +===== +In the settings page enter your Matomo website ID. + +All pages will now have the required JavaScript added to the +HTML footer can confirm this by viewing the page source from +your browser. + +Page specific tracking +==================================================== +The default is set to "Add to every page except the listed pages". By +default the following pages are listed for exclusion: + +/admin +/admin/* +/batch +/node/add* +/node/*/* +/user/*/* + +These defaults are changeable by the website administrator or any other +user with 'Administer Matomo' permission. + +Like the blocks visibility settings in Drupal core, there is a choice for +"Add if the following PHP code returns TRUE." Sample PHP snippets that can be +used in this textarea can be found on the handbook page "Overview-approach to +block visibility" at http://drupal.org/node/64135. + +Custom variables +================= +One example for custom variables tracking is the "User roles" tracking. Enter +the below configuration data into the custom variables settings form under +admin/config/system/matomo. + +Slot: 1 +Name: User roles +Value: [current-user:matomo-role-names] +Scope: Visitor + +Slot: 1 +Name: User ids +Value: [current-user:matomo-role-ids] +Scope: Visitor + +More details about custom variables can be found in the Matomo API documentation +at http://matomo.org/docs/javascript-tracking/#toc-custom-variables. + + +Advanced Settings +================= +You can include additional JavaScript snippets in the custom javascript +code textarea. These can be found on various blog posts, or on the +official Matomo pages. Support is not provided for any customisations +you include. + +To speed up page loading you may also cache the Matomo "piwik.js" +file locally. + +Known issues +============ +Drupal requirements (http://drupal.org/requirements) tell you to configure +PHP with "session.save_handler = user", but your Matomo installation may +not work with this configuration and gives you a server error 500. + +1. You are able to workaround with the PHP default in your php.ini: + + [Session] + session.save_handler = files + +2. With Apache you may overwrite the PHP setting for the Matomo directory only. + If Matomo is installed in /matomo you are able to create a .htaccess file in + this directory with the below code: + + # PHP 4, Apache 1. + + php_value session.save_handler files + + + # PHP 4, Apache 2. + + php_value session.save_handler files + + + # PHP 5, Apache 1 and 2. + + php_value session.save_handler files + diff --git a/sites/all/modules/contrib/admin/matomo/composer.json b/sites/all/modules/contrib/admin/matomo/composer.json new file mode 100644 index 000000000..c946a4fb7 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/composer.json @@ -0,0 +1,22 @@ +{ + "name": "drupal/matomo", + "description": "Adds Matomo javascript tracking code to all your site's pages", + "type": "drupal-module", + "homepage": "https://www.drupal.org/project/matomo", + "authors": [ + { + "name": "hass", + "homepage": "https://www.drupal.org/u/hass" + }, + { + "name": "See other contributors", + "homepage":"https://www.drupal.org/node/247808/committers" + } + ], + "support": { + "issues": "https://www.drupal.org/project/issues/matomo", + "source": "http://git.drupal.org/project/matomo.git" + }, + "license": "GPL-2.0+", + "require": {} +} diff --git a/sites/all/modules/contrib/admin/matomo/config/install/matomo.settings.yml b/sites/all/modules/contrib/admin/matomo/config/install/matomo.settings.yml new file mode 100644 index 000000000..bb7df96fd --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/config/install/matomo.settings.yml @@ -0,0 +1,29 @@ +site_id: '' +url_http: '' +url_https: '' +domain_mode: 0 +visibility: + request_path_mode: 0 + request_path_pages: "/admin\n/admin/*\n/batch\n/node/add*\n/node/*/*\n/user/*/*" + user_role_mode: 0 + user_role_roles: { } + user_account_mode: 1 +track: + mailto: true + files: true + files_extensions: '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip' + colorbox: true + userid: false + messages: { } + site_search: false +privacy: + donottrack: true +custom: + variable: { } +codesnippet: + before: '' + after: '' +translation_set: false +cache: false +page_title_hierarchy: false +page_title_hierarchy_exclude_home: true diff --git a/sites/all/modules/contrib/admin/matomo/config/schema/matomo.schema.yml b/sites/all/modules/contrib/admin/matomo/config/schema/matomo.schema.yml new file mode 100644 index 000000000..1b9d213b6 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/config/schema/matomo.schema.yml @@ -0,0 +1,120 @@ +# Schema for the configuration files of the matomo module. + +matomo.settings: + type: config_object + label: 'Matomo settings' + mapping: + site_id: + type: string + label: 'Matomo site ID' + url_http: + type: string + label: 'Matomo HTTP URL' + url_https: + type: string + label: 'Matomo HTTPS URL' + domain_mode: + type: integer + label: 'What are you tracking?' + visibility: + type: mapping + label: 'Visibility' + mapping: + request_path_mode: + type: integer + label: 'Add tracking to specific pages' + request_path_pages: + type: string + label: 'Pages by their paths' + user_role_mode: + type: integer + label: 'Add tracking for specific roles' + user_role_roles: + type: sequence + label: 'Roles' + sequence: + type: string + label: 'Role' + user_account_mode: + type: integer + label: 'Allow users to customize tracking on their account page' + track: + type: mapping + label: 'Links and downloads' + mapping: + mailto: + type: boolean + label: 'Track clicks on mailto links' + files: + type: boolean + label: 'Track downloads' + files_extensions: + type: string + label: 'File extension list' + colorbox: + type: boolean + label: 'Track content in colorbox modal dialogs' + userid: + type: boolean + label: 'Track User ID' + messages: + type: sequence + label: 'Track messages of type' + sequence: + type: string + label: 'Message type' + site_search: + type: boolean + label: 'Track internal search' + privacy: + type: mapping + label: 'Privacy' + mapping: + donottrack: + type: boolean + label: 'Universal web tracking opt-out' + custom: + type: mapping + label: 'Custom variables' + mapping: + variable: + type: sequence + label: 'Custom variable' + sequence: + type: mapping + label: 'Variable' + mapping: + slot: + type: integer + label: 'Slot number' + name: + type: string + label: 'The custom variable name.' + value: + type: string + label: 'The custom variable value.' + scope: + type: string + label: 'The scope for the custom variable.' + codesnippet: + type: mapping + label: 'Custom code snippets' + mapping: + before: + type: string + label: 'Code snippet (before)' + after: + type: string + label: 'Code snippet (after)' + translation_set: + type: boolean + label: 'Track translation sets as one unit' + cache: + type: boolean + label: 'Locally cache tracking code file' + page_title_hierarchy: + type: boolean + label: 'Show page titles as hierarchy like breadcrumbs' + page_title_hierarchy_exclude_home: + type: boolean + label: 'Hide home page from hierarchy' diff --git a/sites/all/modules/contrib/admin/matomo/js/matomo.admin.js b/sites/all/modules/contrib/admin/matomo/js/matomo.admin.js new file mode 100644 index 000000000..2f68188fe --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/js/matomo.admin.js @@ -0,0 +1,141 @@ +/** + * @file + * Matomo admin behaviors. + */ + +(function ($) { + + "use strict"; + + /** + * Provide the summary information for the tracking settings vertical tabs. + */ + Drupal.behaviors.trackingSettingsSummary = { + attach: function () { + // Make sure this behavior is processed only if drupalSetSummary is defined. + if (typeof jQuery.fn.drupalSetSummary === 'undefined') { + return; + } + + $('#edit-page-visibility-settings').drupalSetSummary(function (context) { + var $radio = $('input[name="matomo_visibility_request_path_mode"]:checked', context); + if ($radio.val() === '0') { + if (!$('textarea[name="matomo_visibility_request_path_pages"]', context).val()) { + return Drupal.t('Not restricted'); + } + else { + return Drupal.t('All pages with exceptions'); + } + } + else { + return Drupal.t('Restricted to certain pages'); + } + }); + + $('#edit-role-visibility-settings').drupalSetSummary(function (context) { + var vals = []; + $('input[type="checkbox"]:checked', context).each(function () { + vals.push($.trim($(this).next('label').text())); + }); + if (!vals.length) { + return Drupal.t('Not restricted'); + } + else if ($('input[name="matomo_visibility_user_role_mode"]:checked', context).val() === '1') { + return Drupal.t('Excepted: @roles', {'@roles': vals.join(', ')}); + } + else { + return vals.join(', '); + } + }); + + $('#edit-user-visibility-settings').drupalSetSummary(function (context) { + var $radio = $('input[name="matomo_visibility_user_account_mode"]:checked', context); + if ($radio.val() === '0') { + return Drupal.t('Not customizable'); + } + else if ($radio.val() === '1') { + return Drupal.t('On by default with opt out'); + } + else { + return Drupal.t('Off by default with opt in'); + } + }); + + $('#edit-linktracking').drupalSetSummary(function (context) { + var vals = []; + if ($('input#edit-matomo-trackmailto', context).is(':checked')) { + vals.push(Drupal.t('Mailto links')); + } + if ($('input#edit-matomo-trackfiles', context).is(':checked')) { + vals.push(Drupal.t('Outbound links')); + vals.push(Drupal.t('Downloads')); + } + if ($('input#edit-matomo-trackcolorbox', context).is(':checked')) { + vals.push(Drupal.t('Colorbox')); + } + if (!vals.length) { + return Drupal.t('Not tracked'); + } + return Drupal.t('@items enabled', {'@items': vals.join(', ')}); + }); + + $('#edit-messagetracking').drupalSetSummary(function (context) { + var vals = []; + $('input[type="checkbox"]:checked', context).each(function () { + vals.push($.trim($(this).next('label').text())); + }); + if (!vals.length) { + return Drupal.t('Not tracked'); + } + return Drupal.t('@items enabled', {'@items': vals.join(', ')}); + }); + + $('#edit-search').drupalSetSummary(function (context) { + var vals = []; + if ($('input#edit-matomo-site-search', context).is(':checked')) { + vals.push(Drupal.t('Site search')); + } + if (!vals.length) { + return Drupal.t('Not tracked'); + } + return Drupal.t('@items enabled', {'@items': vals.join(', ')}); + }); + + $('#edit-domain-tracking').drupalSetSummary(function (context) { + var $radio = $('input[name="matomo_domain_mode"]:checked', context); + if ($radio.val() === '0') { + return Drupal.t('A single domain'); + } + else if ($radio.val() === '1') { + return Drupal.t('One domain with multiple subdomains'); + } + }); + + $('#edit-page-title-hierarchy').drupalSetSummary(function (context) { + var vals = []; + if ($('input#edit-matomo-page-title-hierarchy', context).is(':checked')) { + vals.push(Drupal.t('Show page titles')); + } + if ($('input#edit-matomo-page-title-hierarchy-exclude-home', context).is(':checked')) { + vals.push(Drupal.t('Hide home page')); + } + if (!vals.length) { + return Drupal.t('Not tracked'); + } + return Drupal.t('@items enabled', {'@items': vals.join(', ')}); + }); + + $('#edit-privacy').drupalSetSummary(function (context) { + var vals = []; + if ($('input#edit-matomo-privacy-donottrack', context).is(':checked')) { + vals.push(Drupal.t('Universal web tracking opt-out')); + } + if (!vals.length) { + return Drupal.t('No privacy'); + } + return Drupal.t('@items enabled', {'@items': vals.join(', ')}); + }); + } + }; + +})(jQuery); diff --git a/sites/all/modules/contrib/admin/matomo/js/matomo.js b/sites/all/modules/contrib/admin/matomo/js/matomo.js new file mode 100644 index 000000000..9b3a7b34d --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/js/matomo.js @@ -0,0 +1,41 @@ +/** + * @file + * Attaches several event listener to a web page. + */ + +(function ($, drupalSettings) { + + "use strict"; + + $(document).ready(function () { + + // Attach mousedown, keyup, touchstart events to document only and catch + // clicks on all elements. + $(document.body).bind("mousedown keyup touchstart", function (event) { + + // Catch the closest surrounding link of a clicked element. + $(event.target).closest("a,area").each(function () { + + if (drupalSettings.matomo.trackMailto && $(this).is("a[href^='mailto:'],area[href^='mailto:']")) { + // Mailto link clicked. + _paq.push(["trackEvent", "Mails", "Click", this.href.substring(7)]); + } + + }); + }); + + // Colorbox: This event triggers when the transition has completed and the + // newly loaded content has been revealed. + if (drupalSettings.matomo.trackColorbox) { + $(document).bind("cbox_complete", function () { + var href = $.colorbox.element().attr("href"); + if (href) { + _paq.push(["setCustomUrl", href]); + _paq.push(["trackPageView"]); + } + }); + } + + }); + +})(jQuery, drupalSettings); diff --git a/sites/all/modules/contrib/admin/matomo/matomo.info.yml b/sites/all/modules/contrib/admin/matomo/matomo.info.yml new file mode 100644 index 000000000..3b94f898b --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.info.yml @@ -0,0 +1,15 @@ +name: 'Matomo Analytics' +type: module +description: "Adds Matomo javascript tracking code to all your site's pages." +package: Statistics +# core: 8.x +configure: matomo.admin_settings_form +test_dependencies: + - php:php + - token:token + +# Information added by Drupal.org packaging script on 2018-07-13 +version: '8.x-1.7' +core: '8.x' +project: 'matomo' +datestamp: 1531470224 diff --git a/sites/all/modules/contrib/admin/matomo/matomo.install b/sites/all/modules/contrib/admin/matomo/matomo.install new file mode 100644 index 000000000..324242621 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.install @@ -0,0 +1,54 @@ +grantPermission('opt-in or out of matomo tracking'); + $success = $role->save(); + if ($success) { + drupal_set_message(t('Module %module granted %permission permission to authenticated users.', ['%module' => 'Matomo Analytics', '%permission' => t('Opt-in or out of tracking')]), 'status'); + } +} + +/** + * Implements hook_uninstall(). + * + * Remove cache directory if module is uninstalled. + */ +function matomo_uninstall() { + matomo_clear_js_cache(); +} + +/** + * Implements hook_requirements(). + */ +function matomo_requirements($phase) { + $requirements = []; + + if ($phase == 'runtime') { + $config = \Drupal::config('matomo.settings'); + + // Raise warning if Matomo user account has not been set yet. + if (!preg_match('/^\d{1,}$/', $config->get('site_id'))) { + $requirements['matomo_site_id'] = [ + 'title' => t('Matomo module'), + 'description' => t('Matomo module has not been configured yet. Please configure its settings from the Matomo settings page.', [':url' => Url::fromRoute('matomo.admin_settings_form')->toString()]), + 'severity' => REQUIREMENT_WARNING, + 'value' => t('Not configured'), + ]; + } + } + + return $requirements; +} diff --git a/sites/all/modules/contrib/admin/matomo/matomo.libraries.yml b/sites/all/modules/contrib/admin/matomo/matomo.libraries.yml new file mode 100644 index 000000000..abcd74059 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.libraries.yml @@ -0,0 +1,15 @@ +matomo: + version: VERSION + js: + js/matomo.js: {} + dependencies: + - core/jquery + - core/drupalSettings + +matomo.admin: + version: VERSION + js: + js/matomo.admin.js: {} + dependencies: + - core/jquery + - core/drupal diff --git a/sites/all/modules/contrib/admin/matomo/matomo.links.menu.yml b/sites/all/modules/contrib/admin/matomo/matomo.links.menu.yml new file mode 100644 index 000000000..c88165a25 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.links.menu.yml @@ -0,0 +1,5 @@ +matomo.admin_settings_form: + title: 'Matomo Analytics' + parent: system.admin_config_system + description: 'Configure the settings used to generate your Matomo tracking code.' + route_name: matomo.admin_settings_form diff --git a/sites/all/modules/contrib/admin/matomo/matomo.links.task.yml b/sites/all/modules/contrib/admin/matomo/matomo.links.task.yml new file mode 100644 index 000000000..aa22e5a6e --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.links.task.yml @@ -0,0 +1,4 @@ +matomo.admin_settings_form_tab: + route_name: matomo.admin_settings_form + title: Settings + base_route: matomo.admin_settings_form diff --git a/sites/all/modules/contrib/admin/matomo/matomo.module b/sites/all/modules/contrib/admin/matomo/matomo.module new file mode 100644 index 000000000..380b66b34 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.module @@ -0,0 +1,732 @@ + + */ + +use Drupal\Component\Serialization\Json; +use Drupal\Component\Utility\Crypt; +use Drupal\Component\Utility\Unicode; +use Drupal\Component\Utility\UrlHelper; +use Drupal\Core\Cache\Cache; +use Drupal\Core\Form\FormStateInterface; +use Drupal\Core\Routing\RouteMatchInterface; +use Drupal\Core\Site\Settings; +use Drupal\Core\Url; +use Drupal\node\NodeInterface; +use GuzzleHttp\Exception\RequestException; +use Drupal\matomo\Component\Render\MatomoJavaScriptSnippet; + +/** + * Define the default file extension list that should be tracked as download. + */ +define('MATOMO_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip'); + +/** + * Implements hook_help(). + */ +function matomo_help($route_name, RouteMatchInterface $route_match) { + switch ($route_name) { + case 'matomo.admin_settings_form': + return t('Matomo Analytics is an open source (GPL license) web analytics software. It gives interesting reports on your website visitors, your popular pages, the search engines keywords they used, the language they speak... and so much more. Matomo aims to be an open source alternative to Google Analytics.', [':pk_url' => 'http://www.matomo.org/']); + } +} + +/** + * Implements hook_page_attachments(). + * + * Insert JavaScript to the appropriate scope/region of the page. + */ +function matomo_page_attachments(array &$page) { + $account = \Drupal::currentUser(); + $config = \Drupal::config('matomo.settings'); + $id = $config->get('site_id'); + $request = \Drupal::request(); + + // Add module cache tags. + $page['#cache']['tags'] = Cache::mergeTags(isset($page['#cache']['tags']) ? $page['#cache']['tags'] : [], $config->getCacheTags()); + + // Get page http status code for visibility filtering. + $status = NULL; + if ($exception = $request->attributes->get('exception')) { + $status = $exception->getStatusCode(); + } + $trackable_status_codes = [ + // "Forbidden" status code. + '403', + // "Not Found" status code. + '404', + ]; + + // 1. Check if the matomo account number has a valid value. + // 2. Track page views based on visibility value. + // 3. Check if we should track the currently active user's role. + if (preg_match('/^\d{1,}$/', $id) && (_matomo_visibility_pages() || in_array($status, $trackable_status_codes)) && _matomo_visibility_user($account)) { + + $url_http = $config->get('url_http'); + $url_https = $config->get('url_https'); + + $set_custom_url = ''; + $set_document_title = ''; + + // Add link tracking. + $link_settings = []; + $link_settings['trackMailto'] = $config->get('track.mailto'); + + if ((\Drupal::moduleHandler()->moduleExists('colorbox')) && $track_colorbox = $config->get('track.colorbox')) { + $link_settings['trackColorbox'] = $track_colorbox; + } + + $page['#attached']['drupalSettings']['matomo'] = $link_settings; + $page['#attached']['library'][] = 'matomo/matomo'; + + // Matomo can show a tree view of page titles that represents the site + // structure if setDocumentTitle() provides the page titles as a "/" + // delimited list. This may makes it easier to browse through the statistics + // of page titles on larger sites. + if ($config->get('page_title_hierarchy') == TRUE) { + $titles = _matomo_get_hierarchy_titles(); + + // Remove all empty titles. + $titles = array_filter($titles); + + if (!empty($titles)) { + // Encode title, at least to keep "/" intact. + $titles = array_map('rawurlencode', $titles); + + $set_document_title = Json::encode(implode('/', $titles)); + } + } + + // Add messages tracking. + $message_events = ''; + if ($message_types = $config->get('track.messages')) { + $message_types = array_values(array_filter($message_types)); + $status_heading = [ + 'status' => t('Status message'), + 'warning' => t('Warning message'), + 'error' => t('Error message'), + ]; + + foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) { + // Track only the selected message types. + if (in_array($type, $message_types)) { + foreach ($messages as $message) { + $message_events .= '_paq.push(["trackEvent", ' . Json::encode(t('Messages')) . ', ' . Json::encode($status_heading[$type]) . ', ' . Json::encode(strip_tags($message)) . ']);'; + } + } + } + } + + // If this node is a translation of another node, pass the original + // node instead. + if (\Drupal::moduleHandler()->moduleExists('content_translation') && $config->get('translation_set')) { + // Check if we have a node object, it has translation enabled, and its + // language code does not match its source language code. + if ($request->attributes->has('node')) { + $node = $request->attributes->get('node'); + if ($node instanceof NodeInterface && \Drupal::service('entity.repository')->getTranslationFromContext($node) !== $node->getUntranslated()) { + $set_custom_url = Json::encode(Url::fromRoute('entity.node.canonical', ['node' => $node->id()], ['language' => $node->getUntranslated()->language()])->toString()); + } + } + } + + // Track access denied (403) and file not found (404) pages. + if ($status == '403') { + $set_document_title = '"403/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)'; + } + elseif ($status == '404') { + $set_document_title = '"404/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)'; + } + + // #2693595: User has entered an invalid login and clicked on forgot + // password link. This link contains the username or email address and may + // get send to Matomo if we do not override it. Override only if 'name' + // query param exists. Last custom url condition, this need to win. + // + // URLs to protect are: + // - user/password?name=username + // - user/password?name=foo@example.com + if (\Drupal::routeMatch()->getRouteName() == 'user.pass' && $request->query->has('name')) { + $set_custom_url = Json::encode(Url::fromRoute('user.pass')->toString()); + } + + // Add custom variables. + $matomo_custom_vars = $config->get('custom.variable'); + $custom_variable = ''; + for ($i = 1; $i < 6; $i++) { + $custom_var_name = !empty($matomo_custom_vars[$i]['name']) ? $matomo_custom_vars[$i]['name'] : ''; + if (!empty($custom_var_name)) { + $custom_var_value = !empty($matomo_custom_vars[$i]['value']) ? $matomo_custom_vars[$i]['value'] : ''; + $custom_var_scope = !empty($matomo_custom_vars[$i]['scope']) ? $matomo_custom_vars[$i]['scope'] : 'visit'; + + $types = []; + if ($request->attributes->has('node')) { + $node = $request->attributes->get('node'); + if ($node instanceof NodeInterface) { + $types += ['node' => $node]; + } + } + $custom_var_name = \Drupal::token()->replace($custom_var_name, $types, ['clear' => TRUE]); + $custom_var_value = \Drupal::token()->replace($custom_var_value, $types, ['clear' => TRUE]); + + // Suppress empty custom names and/or variables. + if (!Unicode::strlen(trim($custom_var_name)) || !Unicode::strlen(trim($custom_var_value))) { + continue; + } + + // Custom variables names and values are limited to 200 characters in + // length. It is recommended to store values that are as small as + // possible to ensure that the Matomo Tracking request URL doesn't go + // over the URL limit for the webserver or browser. + $custom_var_name = rtrim(substr($custom_var_name, 0, 200)); + $custom_var_value = rtrim(substr($custom_var_value, 0, 200)); + + // Add variables to tracker. + $custom_variable .= '_paq.push(["setCustomVariable", ' . Json::encode($i) . ', ' . Json::encode($custom_var_name) . ', ' . Json::encode($custom_var_value) . ', ' . Json::encode($custom_var_scope) . ']);'; + } + } + + // Add any custom code snippets if specified. + $codesnippet_before = $config->get('codesnippet.before'); + $codesnippet_after = $config->get('codesnippet.after'); + + // Build tracker code. + // @see http://matomo.org/docs/javascript-tracking/#toc-asynchronous-tracking + $script = 'var _paq = _paq || [];'; + $script .= '(function(){'; + $script .= 'var u=(("https:" == document.location.protocol) ? "' . UrlHelper::filterBadProtocol($url_https) . '" : "' . UrlHelper::filterBadProtocol($url_http) . '");'; + $script .= '_paq.push(["setSiteId", ' . Json::encode($id) . ']);'; + $script .= '_paq.push(["setTrackerUrl", u+"piwik.php"]);'; + + // Track logged in users across all devices. + if ($config->get('track.userid') && $account->isAuthenticated()) { + $script .= '_paq.push(["setUserId", ' . Json::encode(matomo_user_id_hash($account->id())) . ']);'; + } + + // Set custom url. + if (!empty($set_custom_url)) { + $script .= '_paq.push(["setCustomUrl", ' . $set_custom_url . ']);'; + } + // Set custom document title. + if (!empty($set_document_title)) { + $script .= '_paq.push(["setDocumentTitle", ' . $set_document_title . ']);'; + } + + // Custom file download extensions. + if ($config->get('track.files') && !($config->get('track.files_extensions') == MATOMO_TRACKFILES_EXTENSIONS)) { + $script .= '_paq.push(["setDownloadExtensions", ' . Json::encode($config->get('track.files_extensions')) . ']);'; + } + + // Disable tracking for visitors who have opted out from tracking via DNT + // (Do-Not-Track) header. + if ($config->get('privacy.donottrack')) { + $script .= '_paq.push(["setDoNotTrack", 1]);'; + } + + // Domain tracking type. + global $cookie_domain; + $domain_mode = $config->get('domain_mode'); + + // Per RFC 2109, cookie domains must contain at least one dot other than the + // first. For hosts such as 'localhost' or IP Addresses we don't set a + // cookie domain. + if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) { + $script .= '_paq.push(["setCookieDomain", ' . Json::encode($cookie_domain) . ']);'; + } + + // Ordering $custom_variable before $codesnippet_before allows users to add + // custom code snippets that may use deleteCustomVariable() and/or + // getCustomVariable(). + if (!empty($custom_variable)) { + $script .= $custom_variable; + } + if (!empty($codesnippet_before)) { + $script .= $codesnippet_before; + } + + // Site search tracking support. + // NOTE: It's recommended not to call trackPageView() on the Site Search + // Result page. + if (\Drupal::moduleHandler()->moduleExists('search') && $config->get('track.site_search') && (strpos(\Drupal::routeMatch()->getRouteName(), 'search.view') === 0) && $keys = ($request->query->has('keys') ? trim($request->get('keys')) : '')) { + // Parameters: + // 1. Search keyword searched for. Example: "Banana" + // 2. Search category selected in your search engine. If you do not need + // this, set to false. Example: "Organic Food" + // 3. Number of results on the Search results page. Zero indicates a + // 'No Result Search Keyword'. Set to false if you don't know. + // + // hook_preprocess_search_results() is not executed if search result is + // empty. Make sure the counter is set to 0 if there are no results. + $script .= '_paq.push(["trackSiteSearch", ' . Json::encode($keys) . ', false, (window.matomo_search_results) ? window.matomo_search_results : 0]);'; + } + else { + $script .= '_paq.push(["trackPageView"]);'; + } + + // Add link tracking. + if ($config->get('track.files')) { + // Disable tracking of links with ".no-tracking" and ".colorbox" classes. + $ignore_classes = [ + 'no-tracking', + 'colorbox', + ]; + // Disable the download & outlink tracking for specific CSS classes. + // Custom code snippets with 'setIgnoreClasses' will override the value. + // @see http://developer.matomo.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes + $script .= '_paq.push(["setIgnoreClasses", ' . Json::encode($ignore_classes) . ']);'; + + // Enable download & outlink link tracking. + $script .= '_paq.push(["enableLinkTracking"]);'; + } + + if (!empty($message_events)) { + $script .= $message_events; + } + if (!empty($codesnippet_after)) { + $script .= $codesnippet_after; + } + + $script .= 'var d=document,'; + $script .= 'g=d.createElement("script"),'; + $script .= 's=d.getElementsByTagName("script")[0];'; + $script .= 'g.type="text/javascript";'; + $script .= 'g.defer=true;'; + $script .= 'g.async=true;'; + + // Should a local cached copy of the tracking code be used? + if ($config->get('cache') && $url = _matomo_cache($url_http . 'piwik.js')) { + // A dummy query-string is added to filenames, to gain control over + // browser-caching. The string changes on every update or full cache + // flush, forcing browsers to load a new copy of the files, as the + // URL changed. + $query_string = '?' . (\Drupal::state()->get('system.css_js_query_string') ?: '0'); + + $script .= 'g.src="' . $url . $query_string . '";'; + } + else { + $script .= 'g.src=u+"piwik.js";'; + } + + $script .= 's.parentNode.insertBefore(g,s);'; + $script .= '})();'; + + // Add tracker code. + $page['#attached']['html_head'][] = [ + [ + '#tag' => 'script', + '#value' => new MatomoJavaScriptSnippet($script), + ], + 'matomo_tracking_script', + ]; + } +} + +/** + * Generate user id hash to implement USER_ID. + * + * The USER_ID value should be a unique, persistent, and non-personally + * identifiable string identifier that represents a user or signed-in + * account across devices. + * + * @param int $uid + * User id. + * + * @return string + * User id hash. + */ +function matomo_user_id_hash($uid) { + return Crypt::hmacBase64($uid, \Drupal::service('private_key')->get() . Settings::getHashSalt()); +} + +/** + * Implements hook_entity_extra_field_info(). + */ +function matomo_entity_extra_field_info() { + $extra['user']['user']['form']['matomo'] = [ + 'label' => t('Matomo settings'), + 'description' => t('Matomo module form element.'), + 'weight' => 3, + ]; + + return $extra; +} + +/** + * Implements hook_form_FORM_ID_alter(). + * + * Allow users to decide if tracking code will be added to pages or not. + */ +function matomo_form_user_form_alter(&$form, FormStateInterface $form_state) { + $config = \Drupal::config('matomo.settings'); + $account = $form_state->getFormObject()->getEntity(); + + if ($account->hasPermission('opt-in or out of matomo tracking') && ($visibility_users = $config->get('visibility.user_account_mode')) != 0 && _matomo_visibility_roles($account)) { + $account_data_matomo = \Drupal::service('user.data')->get('matomo', $account->id()); + + $form['matomo'] = [ + '#type' => 'details', + '#title' => t('Matomo settings'), + '#weight' => 3, + '#open' => TRUE, + ]; + + switch ($visibility_users) { + case 1: + $description = t('Users are tracked by default, but you are able to opt out.'); + break; + + case 2: + $description = t('Users are not tracked by default, but you are able to opt in.'); + break; + } + + // Disable tracking for visitors who have opted out from tracking via DNT + // (Do-Not-Track) header. + $disabled = FALSE; + if ($config->get('privacy.donottrack') && !empty($_SERVER['HTTP_DNT'])) { + $disabled = TRUE; + + // Override settings value. + $account_data_matomo['users'] = FALSE; + + $description .= ''; + $description .= ' ' . t('You have opted out from tracking via browser privacy settings.'); + $description .= ''; + } + + // Migrate old piwik settings to matomo. + $account_data_piwik = \Drupal::service('user.data')->get('piwik', $account->id()); + if (isset($account_data_piwik['user_account_users'])) { + $account_data_matomo['user_account_users'] = $account_data_piwik['user_account_users']; + } + + $form['matomo']['user_account_users'] = [ + '#type' => 'checkbox', + '#title' => t('Enable user tracking'), + '#description' => $description, + '#default_value' => isset($account_data_matomo['user_account_users']) ? $account_data_matomo['user_account_users'] : ($visibility_users == 1), + '#disabled' => $disabled, + ]; + + // hook_user_update() is missing in D8, add custom submit handler. + $form['actions']['submit']['#submit'][] = 'matomo_user_profile_form_submit'; + } +} + +/** + * Submit callback for user profile form to save the Matomo setting. + */ +function matomo_user_profile_form_submit($form, FormStateInterface $form_state) { + $account = $form_state->getFormObject()->getEntity(); + if ($account->id() && $form_state->hasValue('user_account_users')) { + \Drupal::service('user.data')->set('matomo', $account->id(), 'user_account_users', (int) $form_state->getValue('user_account_users')); + } + + // Remove old piwik setting to complete migration to matomo. + $account_data_piwik = \Drupal::service('user.data')->get('piwik', $account->id()); + if (isset($account_data_piwik)) { + \Drupal::service('user.data')->delete('piwik', $account->id()); + } +} + +/** + * Implements hook_cron(). + */ +function matomo_cron() { + $config = \Drupal::config('matomo.settings'); + + // Regenerate the piwik.js every day. + if (REQUEST_TIME - \Drupal::state()->get('matomo.last_cache') >= 86400 && $config->get('cache')) { + _matomo_cache($config->get('url_http') . 'piwik.js', TRUE); + \Drupal::state()->set('matomo.last_cache', REQUEST_TIME); + } +} + +/** + * Implements hook_preprocess_item_list__search_results(). + * + * Collects and adds the number of search results to the head. + */ +function matomo_preprocess_item_list__search_results(&$variables) { + $config = \Drupal::config('matomo.settings'); + + // Only run on search results list. + if ($config->get('track.site_search')) { + // There is no search result $variable available that hold the number of + // items found. The variable $variables['items'] has the current page items + // only. But the pager item mumber can tell the number of search results. + global $pager_total_items; + + $variables['#attached']['html_head'][] = [ + [ + '#tag' => 'script', + '#value' => 'window.matomo_search_results = ' . intval($pager_total_items[0]) . ';', + '#weight' => JS_LIBRARY - 1, + ], + 'matomo_search_script', + ]; + } +} + +/** + * Download/Synchronize/Cache tracking code file locally. + * + * @param string $location + * The full URL to the external javascript file. + * @param bool $synchronize + * Synchronize to local cache if remote file has changed. + * + * @return mixed + * The path to the local javascript file on success, boolean FALSE on failure. + */ +function _matomo_cache($location, $synchronize = FALSE) { + $path = 'public://matomo'; + $file_destination = $path . '/' . basename($location); + + if (!file_exists($file_destination) || $synchronize) { + // Download the latest tracking code. + try { + $data = \Drupal::httpClient() + ->get($location) + ->getBody(TRUE); + + if (file_exists($file_destination)) { + // Synchronize tracking code and and replace local file if outdated. + $data_hash_local = Crypt::hashBase64(file_get_contents($file_destination)); + $data_hash_remote = Crypt::hashBase64($data); + // Check that the files directory is writable. + if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) { + // Save updated tracking code file to disk. + file_unmanaged_save_data($data, $file_destination, FILE_EXISTS_REPLACE); + // Based on Drupal Core class AssetDumper. + if (extension_loaded('zlib') && \Drupal::config('system.performance')->get('js.gzip')) { + file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE); + } + \Drupal::logger('matomo')->info('Locally cached tracking code file has been updated.'); + + // Change query-strings on css/js files to enforce reload for all + // users. + _drupal_flush_css_js(); + } + } + else { + // Check that the files directory is writable. + if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) { + // There is no need to flush JS here as core refreshes JS caches + // automatically, if new files are added. + file_unmanaged_save_data($data, $file_destination, FILE_EXISTS_REPLACE); + // Based on Drupal Core class AssetDumper. + if (extension_loaded('zlib') && \Drupal::config('system.performance')->get('js.gzip')) { + file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE); + } + \Drupal::logger('matomo')->info('Locally cached tracking code file has been saved.'); + + // Return the local JS file path. + return file_url_transform_relative(file_create_url($file_destination)); + } + } + } + catch (RequestException $exception) { + watchdog_exception('matomo', $exception); + } + } + else { + // Return the local JS file path. + return file_url_transform_relative(file_create_url($file_destination)); + } +} + +/** + * Delete cached files and directory. + */ +function matomo_clear_js_cache() { + $path = 'public://matomo'; + if (file_prepare_directory($path)) { + file_scan_directory($path, '/.*/', ['callback' => 'file_unmanaged_delete']); + \Drupal::service('file_system')->rmdir($path); + + // Change query-strings on css/js files to enforce reload for all users. + _drupal_flush_css_js(); + + \Drupal::logger('matomo')->info('Local cache has been purged.'); + } +} + +/** + * Tracking visibility check for an user object. + * + * @param object $account + * A user object containing an array of roles to check. + * + * @return bool + * TRUE if the current user is being tracked by Matomo, otherwise FALSE. + */ +function _matomo_visibility_user($account) { + $config = \Drupal::config('matomo.settings'); + $enabled = FALSE; + + // Is current user a member of a role that should be tracked? + if (_matomo_visibility_roles($account)) { + + // Use the user's block visibility setting, if necessary. + if (($visibility_user_account_mode = $config->get('visibility.user_account_mode')) != 0) { + $user_data_matomo = \Drupal::service('user.data')->get('matomo', $account->id()); + if ($account->id() && isset($user_data_matomo['user_account_users'])) { + $enabled = $user_data_matomo['user_account_users']; + } + else { + $enabled = ($visibility_user_account_mode == 1); + } + } + else { + $enabled = TRUE; + } + + } + + return $enabled; +} + +/** + * Tracking visibility check for user roles. + * + * Based on visibility setting this function returns TRUE if Matomo code should + * be added for the current role and otherwise FALSE. + * + * @param object $account + * A user object containing an array of roles to check. + * + * @return bool + * TRUE if JS code should be added for the current role and otherwise FALSE. + */ +function _matomo_visibility_roles($account) { + $config = \Drupal::config('matomo.settings'); + $enabled = $visibility_user_role_mode = $config->get('visibility.user_role_mode'); + $user_role_roles = $config->get('visibility.user_role_roles'); + + if (count($user_role_roles) > 0) { + // One or more roles are selected. + foreach (array_values($account->getRoles()) as $user_role) { + // Is the current user a member of one of these roles? + if (in_array($user_role, $user_role_roles)) { + // Current user is a member of a role that should be tracked/excluded + // from tracking. + $enabled = !$visibility_user_role_mode; + break; + } + } + } + else { + // No role is selected for tracking, therefore all roles should be tracked. + $enabled = TRUE; + } + + return $enabled; +} + +/** + * Tracking visibility check for pages. + * + * Based on visibility setting this function returns TRUE if JS code should + * be added to the current page and otherwise FALSE. + */ +function _matomo_visibility_pages() { + static $page_match; + + // Cache visibility result if function is called more than once. + if (!isset($page_match)) { + $config = \Drupal::config('matomo.settings'); + $visibility_request_path_mode = $config->get('visibility.request_path_mode'); + $visibility_request_path_pages = $config->get('visibility.request_path_pages'); + + // Match path if necessary. + if (!empty($visibility_request_path_pages)) { + // Convert path to lowercase. This allows comparison of the same path + // with different case. Ex: /Page, /page, /PAGE. + $pages = Unicode::strtolower($visibility_request_path_pages); + if ($visibility_request_path_mode < 2) { + // Compare the lowercase path alias (if any) and internal path. + $path = \Drupal::service('path.current')->getPath(); + $path_alias = Unicode::strtolower(\Drupal::service('path.alias_manager')->getAliasByPath($path)); + $page_match = \Drupal::service('path.matcher')->matchPath($path_alias, $pages) || (($path != $path_alias) && \Drupal::service('path.matcher')->matchPath($path, $pages)); + // When $visibility_request_path_mode has a value of 0, the tracking + // code is displayed on all pages except those listed in $pages. When + // set to 1, it is displayed only on those pages listed in $pages. + $page_match = !($visibility_request_path_mode xor $page_match); + } + elseif (\Drupal::moduleHandler()->moduleExists('php')) { + $page_match = php_eval($visibility_request_path_pages); + } + else { + $page_match = FALSE; + } + } + else { + $page_match = TRUE; + } + + } + return $page_match; +} + +/** + * Get the page titles trail for the current page. + * + * Based on menu_get_active_breadcrumb(). + * + * @return array + * All page titles, including current page. + */ +function _matomo_get_hierarchy_titles() { + $titles = []; + $path = Url::fromRoute('')->toString(); + $config = \Drupal::config('system.site'); + $matomo_conf = \Drupal::config('matomo.settings'); + + // No breadcrumb for the front page. + if (($path === Url::fromUserInput($config->get('page.front'))->toString())) { + return $titles; + } + + // Load up the menu tree. + // TODO: Check this is a sane approach. + $menu_tree = \Drupal::menuTree(); + $menu_name = \Drupal::config('system.menu.main')->get('id'); + + // Build the typical default set of menu tree parameters. + $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name); + + // Load the tree based on this set of parameters. + $tree = $menu_tree->load($menu_name, $parameters); + + // Transform the tree using the manipulators. + $manipulators = [ + // Only show links that are accessible for the current user. + ['callable' => 'menu.default_tree_manipulators:checkAccess'], + // Use the default sorting of menu links. + ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'], + // Fatten the menu. + ['callable' => 'menu.default_tree_manipulators:flatten'], + ]; + $tree = $menu_tree->transform($tree, $manipulators); + + if (!empty($tree)) { + foreach ($tree as $menu_item) { + // If the item is in the active trail and we don't have a front page link + // when we have set to exclude home from the breadcrumbs then add the + // title. + if ($menu_item->inActiveTrail && !($matomo_conf->get('page_title_hierarchy_exclude_home') && $menu_item->link->getRouteName() == '')) { + $titles[] = $menu_item->link->getTitle(); + } + } + } + + return $titles; +} diff --git a/sites/all/modules/contrib/admin/matomo/matomo.permissions.yml b/sites/all/modules/contrib/admin/matomo/matomo.permissions.yml new file mode 100644 index 000000000..27ad40274 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.permissions.yml @@ -0,0 +1,14 @@ +administer matomo: + title: 'Administer Matomo' + description: 'Perform maintenance tasks for Matomo.' +opt-in or out of matomo tracking: + title: 'Opt-in or out of tracking' + description: 'Allow users to decide if tracking code will be added to pages or not.' +use php for matomo tracking visibility: + title: 'Use PHP for tracking visibility' + description: 'Enter PHP code in the field for tracking visibility settings.' + restrict access: true +add js snippets for matomo: + title: 'Add JavaScript snippets' + description: 'Enter JavaScript code snippets for advanced Matomo functionality.' + restrict access: true diff --git a/sites/all/modules/contrib/admin/matomo/matomo.routing.yml b/sites/all/modules/contrib/admin/matomo/matomo.routing.yml new file mode 100644 index 000000000..68c1f0ae0 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.routing.yml @@ -0,0 +1,7 @@ +matomo.admin_settings_form: + path: '/admin/config/system/matomo' + defaults: + _form: '\Drupal\matomo\Form\MatomoAdminSettingsForm' + _title: 'Matomo Analytics' + requirements: + _permission: 'administer matomo' diff --git a/sites/all/modules/contrib/admin/matomo/matomo.tokens.inc b/sites/all/modules/contrib/admin/matomo/matomo.tokens.inc new file mode 100644 index 000000000..1b4cafa3b --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/matomo.tokens.inc @@ -0,0 +1,60 @@ + t('User role names'), + 'description' => t('The role names the user account is a member of as comma separated list.'), + 'needs-data' => 'user', + ]; + $user['matomo-role-ids'] = [ + 'name' => t('User role ids'), + 'description' => t('The role ids the user account is a member of as comma separated list.'), + 'needs-data' => 'user', + ]; + + return [ + 'tokens' => ['user' => $user], + ]; +} + +/** + * Implements hook_tokens(). + */ +function matomo_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) { + $sanitize = !empty($options['sanitize']); + $replacements = []; + + if ($type == 'user' && !empty($data['user'])) { + $account = $data['user']; + + foreach ($tokens as $name => $original) { + switch ($name) { + // Basic user account information. + case 'matomo-role-names': + $names = implode(',', $account->getRoles()); + $replacements[$original] = $sanitize ? Html::escape($names) : $names; + $bubbleable_metadata->addCacheableDependency($account); + break; + + case 'matomo-role-ids': + $ids = implode(',', array_keys($account->getRoles())); + $replacements[$original] = $sanitize ? Html::escape($ids) : $ids; + $bubbleable_metadata->addCacheableDependency($account); + break; + } + } + } + + return $replacements; +} diff --git a/sites/all/modules/contrib/admin/matomo/migration_templates/d6_matomo_settings.yml b/sites/all/modules/contrib/admin/matomo/migration_templates/d6_matomo_settings.yml new file mode 100644 index 000000000..dd365ed48 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/migration_templates/d6_matomo_settings.yml @@ -0,0 +1,70 @@ +id: d6_piwik_settings +label: Piwik 6 configuration +migration_tags: + - Drupal 6 + - Configuration +source: + plugin: variable + variables: + - piwik_cache + - piwik_codesnippet_after + - piwik_codesnippet_before + - piwik_custom + - piwik_domain_mode + - piwik_pages + - piwik_privacy_donottrack + - piwik_roles + - piwik_site_id + - piwik_site_search + - piwik_trackmessages + - piwik_track + - piwik_trackfiles_extensions + - piwik_trackmailto + - piwik_trackuserid + - piwik_translation_set + - piwik_url_http + - piwik_url_https + - piwik_visibility_pages + - piwik_visibility_roles + - piwik_page_title_hierarchy + - piwik_page_title_hierarchy_exclude_home + source_module: piwik +process: + cache: piwik_cache + 'codesnippet/after': piwik_codesnippet_after + 'codesnippet/before': piwik_codesnippet_before + domain_mode: piwik_domain_mode + 'privacy/donottrack': piwik_privacy_donottrack + site_id: piwik_site_id + 'track/files': piwik_track + 'track/files_extensions': piwik_trackfiles_extensions + 'track/mailto': piwik_trackmailto + 'track/messages': piwik_trackmessages + 'track/site_search': piwik_site_search + 'track/userid': piwik_trackuserid + 'translation_set': piwik_translation_set + url_http: piwik_url_http + url_https: piwik_url_https + 'visibility/user_account_mode': piwik_custom + 'visibility/request_path_mode': piwik_visibility_pages + 'visibility/request_path_pages': + plugin: matomo_visibility_pages + source: + - piwik_visibility_pages + - piwik_pages + # If Piwik uses PHP visibility, don't migrate it unless the PHP module is + # enabled. + skip_php: true + 'visibility/user_role_mode': piwik_visibility_roles + 'visibility/user_role_roles': + plugin: matomo_visibility_roles + source: + - piwik_roles + page_title_hierarchy: piwik_page_title_hierarchy + page_title_hierarchy_exclude_home: piwik_page_title_hierarchy_exclude_home +destination: + plugin: config + config_name: matomo.settings +migration_dependencies: + optional: + - d6_user_role diff --git a/sites/all/modules/contrib/admin/matomo/migration_templates/d6_matomo_user_settings.yml b/sites/all/modules/contrib/admin/matomo/migration_templates/d6_matomo_user_settings.yml new file mode 100644 index 000000000..65fcce9fd --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/migration_templates/d6_matomo_user_settings.yml @@ -0,0 +1,22 @@ +id: d6_piwik_user_settings +label: Piwik user settings +migration_tags: + - Drupal 6 +source: + plugin: d6_user + constants: + key: user_account_users + module: piwik +process: + uid: uid + key: 'constants/key' + module: 'constants/module' + settings: + plugin: skip_row_if_not_set + index: 'custom' + source: data/piwik +destination: + plugin: user_data +migration_dependencies: + required: + - d6_user diff --git a/sites/all/modules/contrib/admin/matomo/migration_templates/d7_matomo_settings.yml b/sites/all/modules/contrib/admin/matomo/migration_templates/d7_matomo_settings.yml new file mode 100644 index 000000000..601a69892 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/migration_templates/d7_matomo_settings.yml @@ -0,0 +1,77 @@ +id: d7_matomo_settings +label: Matomo 7 configuration +migration_tags: + - Drupal 7 + - Configuration +source: + plugin: variable + variables: + - matomo_cache + - matomo_codesnippet_after + - matomo_codesnippet_before + - matomo_custom + - matomo_custom_var + - matomo_domain_mode + - matomo_pages + - matomo_privacy_donottrack + - matomo_roles + - matomo_site_id + - matomo_site_search + - matomo_track + - matomo_trackcolorbox + - matomo_trackfiles_extensions + - matomo_trackmailto + - matomo_trackmessages + - matomo_trackuserid + - matomo_translation_set + - matomo_url_http + - matomo_url_https + - matomo_visibility_pages + - matomo_visibility_roles + - matomo_page_title_hierarchy + - matomo_page_title_hierarchy_exclude_home + source_module: matomo +process: + cache: matomo_cache + 'codesnippet/after': matomo_codesnippet_after + 'codesnippet/before': matomo_codesnippet_before + 'custom/variable': + plugin: matomo_custom_vars + source: + - matomo_custom_var + domain_mode: matomo_domain_mode + 'privacy/donottrack': matomo_privacy_donottrack + site_id: matomo_site_id + 'track/colorbox': matomo_trackcolorbox + 'track/files': matomo_track + 'track/files_extensions': matomo_trackfiles_extensions + 'track/mailto': matomo_trackmailto + 'track/messages': matomo_trackmessages + 'track/site_search': matomo_site_search + 'track/userid': matomo_trackuserid + 'translation_set': matomo_translation_set + url_http: matomo_url_http + url_https: matomo_url_https + 'visibility/user_account_mode': matomo_custom + 'visibility/request_path_mode': matomo_visibility_pages + 'visibility/request_path_pages': + plugin: matomo_visibility_pages + source: + - matomo_visibility_pages + - matomo_pages + # If Matomo uses PHP visibility, don't migrate it unless the PHP module is + # enabled. + skip_php: true + 'visibility/user_role_mode': matomo_visibility_roles + 'visibility/user_role_roles': + plugin: matomo_visibility_roles + source: + - matomo_roles + page_title_hierarchy: matomo_page_title_hierarchy + page_title_hierarchy_exclude_home: matomo_page_title_hierarchy_exclude_home +destination: + plugin: config + config_name: matomo.settings +migration_dependencies: + optional: + - d7_user_role diff --git a/sites/all/modules/contrib/admin/matomo/migration_templates/d7_matomo_user_settings.yml b/sites/all/modules/contrib/admin/matomo/migration_templates/d7_matomo_user_settings.yml new file mode 100644 index 000000000..676a9f792 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/migration_templates/d7_matomo_user_settings.yml @@ -0,0 +1,22 @@ +id: d7_matomo_user_settings +label: Matomo user settings +migration_tags: + - Drupal 7 +source: + plugin: d7_user + constants: + key: user_account_users + module: matomo +process: + uid: uid + key: 'constants/key' + module: 'constants/module' + settings: + plugin: skip_row_if_not_set + index: 'custom' + source: data/matomo +destination: + plugin: user_data +migration_dependencies: + required: + - d7_user diff --git a/sites/all/modules/contrib/admin/matomo/src/Component/Render/MatomoJavaScriptSnippet.php b/sites/all/modules/contrib/admin/matomo/src/Component/Render/MatomoJavaScriptSnippet.php new file mode 100644 index 000000000..3fd6ff84d --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Component/Render/MatomoJavaScriptSnippet.php @@ -0,0 +1,43 @@ +string = (string) $string; + } + + /** + * {@inheritdoc} + */ + public function __toString() { + return $this->string; + } + + /** + * {@inheritdoc} + */ + public function jsonSerialize() { + return $this->__toString(); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Form/MatomoAdminSettingsForm.php b/sites/all/modules/contrib/admin/matomo/src/Form/MatomoAdminSettingsForm.php new file mode 100644 index 000000000..a7a85e8ad --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Form/MatomoAdminSettingsForm.php @@ -0,0 +1,717 @@ +config('matomo.settings'); + + $form['general'] = [ + '#type' => 'details', + '#title' => $this->t('General settings'), + '#open' => TRUE, + ]; + + $form['general']['matomo_site_id'] = [ + '#default_value' => $config->get('site_id'), + '#description' => $this->t('The user account number is unique to the websites domain. Click the Settings link in your Matomo account, then the Websites tab and enter the appropriate site ID into this field.'), + '#maxlength' => 20, + '#required' => TRUE, + '#size' => 15, + '#title' => $this->t('Matomo site ID'), + '#type' => 'textfield', + ]; + $form['general']['matomo_url_http'] = [ + '#default_value' => $config->get('url_http'), + '#description' => $this->t('The URL to your Matomo base directory. Example: "http://www.example.com/matomo/".'), + '#maxlength' => 255, + '#required' => TRUE, + '#size' => 80, + '#title' => $this->t('Matomo HTTP URL'), + '#type' => 'textfield', + ]; + $form['general']['matomo_url_https'] = [ + '#default_value' => $config->get('url_https'), + '#description' => $this->t('The URL to your Matomo base directory with SSL certificate installed. Required if you track a SSL enabled website. Example: "https://www.example.com/matomo/".'), + '#maxlength' => 255, + '#size' => 80, + '#title' => $this->t('Matomo HTTPS URL'), + '#type' => 'textfield', + ]; + // Required for automated form save testing only. + $form['general']['matomo_url_skiperror'] = [ + '#type' => 'hidden', + '#default_value' => FALSE, + ]; + + // Visibility settings. + $form['tracking_scope'] = [ + '#type' => 'vertical_tabs', + '#title' => $this->t('Tracking scope'), + '#attached' => [ + 'library' => [ + 'matomo/matomo.admin', + ], + ], + ]; + + $form['tracking']['domain_tracking'] = [ + '#type' => 'details', + '#title' => $this->t('Domains'), + '#group' => 'tracking_scope', + ]; + + global $cookie_domain; + $multiple_sub_domains = []; + foreach (['www', 'app', 'shop'] as $subdomain) { + if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) { + $multiple_sub_domains[] = $subdomain . $cookie_domain; + } + // IP addresses or localhost. + else { + $multiple_sub_domains[] = $subdomain . '.example.com'; + } + } + + $form['tracking']['domain_tracking']['matomo_domain_mode'] = [ + '#type' => 'radios', + '#title' => $this->t('What are you tracking?'), + '#options' => [ + 0 => $this->t('A single domain (default)'), + 1 => $this->t('One domain with multiple subdomains'), + ], + 0 => [ + '#description' => $this->t('Domain: @domain', ['@domain' => $_SERVER['HTTP_HOST']]), + ], + 1 => [ + '#description' => $this->t('Examples: @domains', ['@domains' => implode(', ', $multiple_sub_domains)]), + ], + '#default_value' => $config->get('domain_mode'), + ]; + + // Page specific visibility configurations. + $account = \Drupal::currentUser(); + $php_access = $account->hasPermission('use php for matomo tracking visibility'); + $visibility_request_path_pages = $config->get('visibility.request_path_pages'); + + $form['tracking']['page_visibility_settings'] = [ + '#type' => 'details', + '#title' => $this->t('Pages'), + '#group' => 'tracking_scope', + ]; + + if ($config->get('visibility.request_path_mode') == 2 && !$php_access) { + // No permission to change PHP snippets, but keep existing settings. + $form['tracking']['page_visibility_settings'] = []; + $form['tracking']['page_visibility_settings']['matomo_visibility_request_path_mode'] = ['#type' => 'value', '#value' => 2]; + $form['tracking']['page_visibility_settings']['matomo_visibility_request_path_pages'] = ['#type' => 'value', '#value' => $visibility_request_path_pages]; + } + else { + $options = [ + $this->t('Every page except the listed pages'), + $this->t('The listed pages only'), + ]; + $description = $this->t("Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", ['%blog' => '/blog', '%blog-wildcard' => '/blog/*', '%front' => '']); + + if (\Drupal::moduleHandler()->moduleExists('php') && $php_access) { + $options[] = $this->t('Pages on which this PHP code returns TRUE (experts only)'); + $title = $this->t('Pages or PHP code'); + $description .= ' ' . $this->t('If the PHP option is chosen, enter PHP code between %php. Note that executing incorrect PHP code can break your Drupal site.', ['%php' => '']); + } + else { + $title = $this->t('Pages'); + } + $form['tracking']['page_visibility_settings']['matomo_visibility_request_path_mode'] = [ + '#type' => 'radios', + '#title' => $this->t('Add tracking to specific pages'), + '#options' => $options, + '#default_value' => $config->get('visibility.request_path_mode'), + ]; + $form['tracking']['page_visibility_settings']['matomo_visibility_request_path_pages'] = [ + '#type' => 'textarea', + '#title' => $title, + '#title_display' => 'invisible', + '#default_value' => !empty($visibility_request_path_pages) ? $visibility_request_path_pages : '', + '#description' => $description, + '#rows' => 10, + ]; + } + + // Render the role overview. + $visibility_user_role_roles = $config->get('visibility.user_role_roles'); + + $form['tracking']['role_visibility_settings'] = [ + '#type' => 'details', + '#title' => $this->t('Roles'), + '#group' => 'tracking_scope', + ]; + + $form['tracking']['role_visibility_settings']['matomo_visibility_user_role_mode'] = [ + '#type' => 'radios', + '#title' => $this->t('Add tracking for specific roles'), + '#options' => [ + $this->t('Add to the selected roles only'), + $this->t('Add to every role except the selected ones'), + ], + '#default_value' => $config->get('visibility.user_role_mode'), + ]; + $form['tracking']['role_visibility_settings']['matomo_visibility_user_role_roles'] = [ + '#type' => 'checkboxes', + '#title' => $this->t('Roles'), + '#default_value' => !empty($visibility_user_role_roles) ? $visibility_user_role_roles : [], + '#options' => array_map('\Drupal\Component\Utility\Html::escape', user_role_names()), + '#description' => $this->t('If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked (or excluded, depending on the setting above).'), + ]; + + // Standard tracking configurations. + $visibility_user_account_mode = $config->get('visibility.user_account_mode'); + + $form['tracking']['user_visibility_settings'] = [ + '#type' => 'details', + '#title' => $this->t('Users'), + '#group' => 'tracking_scope', + ]; + $t_permission = ['%permission' => $this->t('Opt-in or out of tracking')]; + $form['tracking']['user_visibility_settings']['matomo_visibility_user_account_mode'] = [ + '#type' => 'radios', + '#title' => $this->t('Allow users to customize tracking on their account page'), + '#options' => [ + 0 => $this->t('No customization allowed'), + 1 => $this->t('Tracking on by default, users with %permission permission can opt out', $t_permission), + 2 => $this->t('Tracking off by default, users with %permission permission can opt in', $t_permission), + ], + '#default_value' => !empty($visibility_user_account_mode) ? $visibility_user_account_mode : 1, + ]; + $form['tracking']['user_visibility_settings']['matomo_trackuserid'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Track User ID'), + '#default_value' => $config->get('track.userid'), + '#description' => $this->t('User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. Learn more about the benefits of using User ID.', [':url' => 'http://matomo.org/docs/user-id/']), + ]; + + // Link specific configurations. + $form['tracking']['linktracking'] = [ + '#type' => 'details', + '#title' => $this->t('Links and downloads'), + '#group' => 'tracking_scope', + ]; + $form['tracking']['linktracking']['matomo_trackmailto'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Track clicks on mailto links'), + '#default_value' => $config->get('track.mailto'), + ]; + $form['tracking']['linktracking']['matomo_trackfiles'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Track clicks on outbound links and downloads (clicks on file links) for the following extensions'), + '#default_value' => $config->get('track.files'), + ]; + $form['tracking']['linktracking']['matomo_trackfiles_extensions'] = [ + '#title' => $this->t('List of download file extensions'), + '#title_display' => 'invisible', + '#type' => 'textfield', + '#default_value' => $config->get('track.files_extensions'), + '#description' => $this->t('A file extension list separated by the | character that will be tracked as download when clicked. Regular expressions are supported. For example: @extensions', ['@extensions' => MATOMO_TRACKFILES_EXTENSIONS]), + '#maxlength' => 500, + '#states' => [ + 'enabled' => [ + ':input[name="matomo_trackfiles"]' => ['checked' => TRUE], + ], + // Note: Form required marker is not visible as title is invisible. + 'required' => [ + ':input[name="matomo_trackfiles"]' => ['checked' => TRUE], + ], + ], + ]; + + $colorbox_dependencies = '
'; + $colorbox_dependencies .= $this->t('Requires: @module-list', ['@module-list' => (\Drupal::moduleHandler()->moduleExists('colorbox') ? $this->t('@module (enabled)', ['@module' => 'Colorbox']) : $this->t('@module (disabled)', ['@module' => 'Colorbox']))]); + $colorbox_dependencies .= '
'; + + $form['tracking']['linktracking']['matomo_trackcolorbox'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Track content in colorbox modal dialogs'), + '#description' => $this->t('Enable to track the content shown in colorbox modal windows.') . $colorbox_dependencies, + '#default_value' => $config->get('track.colorbox'), + '#disabled' => (\Drupal::moduleHandler()->moduleExists('colorbox') ? FALSE : TRUE), + ]; + + // Message specific configurations. + $form['tracking']['messagetracking'] = [ + '#type' => 'details', + '#title' => $this->t('Messages'), + '#group' => 'tracking_scope', + ]; + $track_messages = $config->get('track.messages'); + $form['tracking']['messagetracking']['matomo_trackmessages'] = [ + '#type' => 'checkboxes', + '#title' => $this->t('Track messages of type'), + '#default_value' => !empty($track_messages) ? $track_messages : [], + '#description' => $this->t('This will track the selected message types shown to users. Tracking of form validation errors may help you identifying usability issues in your site. Every message is tracked as one individual event. Messages from excluded pages cannot be tracked.'), + '#options' => [ + 'status' => $this->t('Status message'), + 'warning' => $this->t('Warning message'), + 'error' => $this->t('Error message'), + ], + ]; + + $form['tracking']['search'] = [ + '#type' => 'details', + '#title' => $this->t('Search'), + '#group' => 'tracking_scope', + ]; + + $site_search_dependencies = '
'; + $site_search_dependencies .= $this->t('Requires: @module-list', ['@module-list' => (\Drupal::moduleHandler()->moduleExists('search') ? $this->t('@module (enabled)', ['@module' => 'Search']) : $this->t('@module (disabled)', ['@module' => 'Search']))]); + $site_search_dependencies .= '
'; + + $form['tracking']['search']['matomo_site_search'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Track internal search'), + '#description' => $this->t('If checked, internal search keywords are tracked.') . $site_search_dependencies, + '#default_value' => $config->get('track.site_search'), + '#disabled' => (\Drupal::moduleHandler()->moduleExists('search') ? FALSE : TRUE), + ]; + + // Privacy specific configurations. + $form['tracking']['privacy'] = [ + '#type' => 'details', + '#title' => $this->t('Privacy'), + '#group' => 'tracking_scope', + ]; + $form['tracking']['privacy']['matomo_privacy_donottrack'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Universal web tracking opt-out'), + '#description' => $this->t('If enabled and your Matomo server receives the Do-Not-Track header from the client browser, the Matomo server will not track the user. Compliance with Do Not Track could be purely voluntary, enforced by industry self-regulation, or mandated by state or federal law. Please accept your visitors privacy. If they have opt-out from tracking and advertising, you should accept their personal decision.'), + '#default_value' => $config->get('privacy.donottrack'), + ]; + + // Matomo page title tree view settings. + $form['page_title_hierarchy'] = [ + '#type' => 'details', + '#title' => $this->t('Page titles hierarchy'), + '#description' => $this->t('This functionality enables a dynamically expandable tree view of your site page titles in your Matomo statistics. See in Matomo statistics under Actions > Page titles.'), + '#group' => 'tracking_scope', + ]; + $form['page_title_hierarchy']['matomo_page_title_hierarchy'] = [ + '#type' => 'checkbox', + '#title' => $this->t("Show page titles as hierarchy like breadcrumbs"), + '#description' => $this->t('By default Matomo tracks the current page title and shows you a flat list of the most popular titles. This enables a breadcrumbs like tree view.'), + '#default_value' => $config->get('page_title_hierarchy'), + ]; + $form['page_title_hierarchy']['matomo_page_title_hierarchy_exclude_home'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Hide home page from hierarchy'), + '#description' => $this->t('If enabled, the "Home" item will be removed from the hierarchy to flatten the structure in the Matomo statistics. Hits to the home page will still be counted, but for other pages the hierarchy will start at level Home+1.'), + '#default_value' => $config->get('page_title_hierarchy_exclude_home'), + ]; + + // Custom variables. + $form['matomo_custom_var'] = [ + '#description' => $this->t('You can add Matomos Custom Variables here. These will be added to every page that Matomo tracking code appears on. Custom variable names and values are limited to 200 characters in length. Keep the names and values as short as possible and expect long values to get trimmed. You may use tokens in custom variable names and values. Global and user tokens are always available; on node pages, node tokens are also available.', [':custom_var_documentation' => 'http://matomo.org/docs/custom-variables/']), + '#title' => $this->t('Custom variables'), + '#tree' => TRUE, + '#type' => 'details', + ]; + + $form['matomo_custom_var']['slots'] = [ + '#type' => 'table', + '#header' => [ + ['data' => $this->t('Slot')], + ['data' => $this->t('Name')], + ['data' => $this->t('Value')], + ['data' => $this->t('Scope')], + ], + ]; + + $matomo_custom_vars = $config->get('custom.variable'); + + // Matomo supports up to 5 custom variables. + for ($i = 1; $i < 6; $i++) { + $form['matomo_custom_var']['slots'][$i]['slot'] = [ + '#default_value' => $i, + '#description' => $this->t('Slot number'), + '#disabled' => TRUE, + '#size' => 1, + '#title' => $this->t('Custom variable slot #@slot', ['@slot' => $i]), + '#title_display' => 'invisible', + '#type' => 'textfield', + ]; + $form['matomo_custom_var']['slots'][$i]['name'] = [ + '#default_value' => isset($matomo_custom_vars[$i]['name']) ? $matomo_custom_vars[$i]['name'] : '', + '#description' => $this->t('The custom variable name.'), + '#maxlength' => 100, + '#size' => 20, + '#title' => $this->t('Custom variable name #@slot', ['@slot' => $i]), + '#title_display' => 'invisible', + '#type' => 'textfield', + ]; + $form['matomo_custom_var']['slots'][$i]['value'] = [ + '#default_value' => isset($matomo_custom_vars[$i]['value']) ? $matomo_custom_vars[$i]['value'] : '', + '#description' => $this->t('The custom variable value.'), + '#maxlength' => 255, + '#title' => $this->t('Custom variable value #@slot', ['@slot' => $i]), + '#title_display' => 'invisible', + '#type' => 'textfield', + '#element_validate' => [[get_class($this), 'tokenElementValidate']], + '#token_types' => ['node'], + ]; + if (\Drupal::moduleHandler()->moduleExists('token')) { + $form['matomo_custom_var']['slots'][$i]['value']['#element_validate'][] = 'token_element_validate'; + } + $form['matomo_custom_var']['slots'][$i]['scope'] = [ + '#default_value' => isset($matomo_custom_vars[$i]['scope']) ? $matomo_custom_vars[$i]['scope'] : '', + '#description' => $this->t('The scope for the custom variable.'), + '#title' => $this->t('Custom variable slot #@slot', ['@slot' => $i]), + '#title_display' => 'invisible', + '#type' => 'select', + '#options' => [ + 'visit' => $this->t('Visit'), + 'page' => $this->t('Page'), + ], + ]; + } + + $form['matomo_custom_var']['matomo_custom_var_description'] = [ + '#type' => 'item', + '#description' => $this->t("You can supplement Matomos' basic IP address tracking of visitors by segmenting users based on custom variables. Make sure you will not associate (or permit any third party to associate) any data gathered from your websites (or such third parties' websites) with any personally identifying information from any source as part of your use (or such third parties' use) of the Matomo' service."), + ]; + if (\Drupal::moduleHandler()->moduleExists('token')) { + $form['matomo_custom_var']['matomo_custom_var_token_tree'] = [ + '#theme' => 'token_tree_link', + '#token_types' => ['node'], + ]; + } + + // Advanced feature configurations. + $form['advanced'] = [ + '#type' => 'details', + '#title' => $this->t('Advanced settings'), + '#open' => FALSE, + ]; + + $form['advanced']['matomo_cache'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Locally cache tracking code file'), + '#description' => $this->t('If checked, the tracking code file is retrieved from your Matomo site and cached locally. It is updated daily to ensure updates to tracking code are reflected in the local copy.'), + '#default_value' => $config->get('cache'), + ]; + + // Allow for tracking of the originating node when viewing translation sets. + if (\Drupal::moduleHandler()->moduleExists('content_translation')) { + $form['advanced']['matomo_translation_set'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Track translation sets as one unit'), + '#description' => $this->t('When a node is part of a translation set, record statistics for the originating node instead. This allows for a translation set to be treated as a single unit.'), + '#default_value' => $config->get('translation_set'), + ]; + } + + $user_access_add_js_snippets = !$this->currentUser()->hasPermission('add js snippets for matomo'); + $user_access_add_js_snippets_permission_warning = $user_access_add_js_snippets ? ' ' . $this->t('This field has been disabled because you do not have sufficient permissions to edit it.') . '' : ''; + $form['advanced']['codesnippet'] = [ + '#type' => 'details', + '#title' => $this->t('Custom JavaScript code'), + '#open' => TRUE, + '#description' => $this->t('You can add custom Matomo code snippets here. These will be added to every page that Matomo appears on. Do not include the <script> tags, and always end your code with a semicolon (;).', [':snippets' => 'http://matomo.org/docs/javascript-tracking/']), + ]; + $form['advanced']['codesnippet']['matomo_codesnippet_before'] = [ + '#type' => 'textarea', + '#title' => $this->t('Code snippet (before)'), + '#default_value' => $config->get('codesnippet.before'), + '#disabled' => $user_access_add_js_snippets, + '#rows' => 5, + '#description' => $this->t('Code in this textarea will be added before _paq.push(["trackPageView"]).') . $user_access_add_js_snippets_permission_warning, + ]; + $form['advanced']['codesnippet']['matomo_codesnippet_after'] = [ + '#type' => 'textarea', + '#title' => $this->t('Code snippet (after)'), + '#default_value' => $config->get('codesnippet.after'), + '#disabled' => $user_access_add_js_snippets, + '#rows' => 5, + '#description' => $this->t('Code in this textarea will be added after _paq.push(["trackPageView"]). This is useful if you\'d like to track a site in two accounts.') . $user_access_add_js_snippets_permission_warning, + ]; + + return parent::buildForm($form, $form_state); + } + + /** + * {@inheritdoc} + */ + public function validateForm(array &$form, FormStateInterface $form_state) { + parent::validateForm($form, $form_state); + + // Custom variables validation. + foreach ($form_state->getValue(['matomo_custom_var', 'slots']) as $custom_var) { + $form_state->setValue(['matomo_custom_var', 'slots', $custom_var['slot'], 'name'], trim($custom_var['name'])); + $form_state->setValue(['matomo_custom_var', 'slots', $custom_var['slot'], 'value'], trim($custom_var['value'])); + + // Validate empty names/values. + if (empty($custom_var['name']) && !empty($custom_var['value'])) { + $form_state->setErrorByName("matomo_custom_var][slots][" . $custom_var['slot'] . "][name", $this->t('The custom variable @slot-number requires a Name if a Value has been provided.', ['@slot-number' => $custom_var['slot']])); + } + elseif (!empty($custom_var['name']) && empty($custom_var['value'])) { + $form_state->setErrorByName("matomo_custom_var][slots][" . $custom_var['slot'] . "][value", $this->t('The custom variable @slot-number requires a Value if a Name has been provided.', ['@slot-number' => $custom_var['slot']])); + } + } + $form_state->setValue('matomo_custom_var', $form_state->getValue(['matomo_custom_var', 'slots'])); + + // Trim some text area values. + $form_state->setValue('matomo_site_id', trim($form_state->getValue('matomo_site_id'))); + $form_state->setValue('matomo_visibility_request_path_pages', trim($form_state->getValue('matomo_visibility_request_path_pages'))); + $form_state->setValue('matomo_codesnippet_before', trim($form_state->getValue('matomo_codesnippet_before'))); + $form_state->setValue('matomo_codesnippet_after', trim($form_state->getValue('matomo_codesnippet_after'))); + $form_state->setValue('matomo_visibility_user_role_roles', array_filter($form_state->getValue('matomo_visibility_user_role_roles'))); + $form_state->setValue('matomo_trackmessages', array_filter($form_state->getValue('matomo_trackmessages'))); + + if (!preg_match('/^\d{1,}$/', $form_state->getValue('matomo_site_id'))) { + $form_state->setErrorByName('matomo_site_id', $this->t('A valid Matomo site ID is an integer only.')); + } + + $url = $form_state->getValue('matomo_url_http') . 'piwik.php'; + try { + $result = \Drupal::httpClient()->get($url); + if ($result->getStatusCode() != 200 && $form_state->getValue('matomo_url_skiperror') == FALSE) { + $form_state->setErrorByName('matomo_url_http', $this->t('The validation of "@url" failed with error "@error" (HTTP code @code).', [ + '@url' => UrlHelper::filterBadProtocol($url), + '@error' => $result->getReasonPhrase(), + '@code' => $result->getStatusCode(), + ])); + } + } + catch (RequestException $exception) { + $form_state->setErrorByName('matomo_url_http', $this->t('The validation of "@url" failed with an exception "@error" (HTTP code @code).', [ + '@url' => UrlHelper::filterBadProtocol($url), + '@error' => $exception->getMessage(), + '@code' => $exception->getCode(), + ])); + } + + $matomo_url_https = $form_state->getValue('matomo_url_https'); + if (!empty($matomo_url_https)) { + $url = $matomo_url_https . 'piwik.php'; + try { + $result = \Drupal::httpClient()->get($url); + if ($result->getStatusCode() != 200 && $form_state->getValue('matomo_url_skiperror') == FALSE) { + $form_state->setErrorByName('matomo_url_https', $this->t('The validation of "@url" failed with error "@error" (HTTP code @code).', [ + '@url' => UrlHelper::filterBadProtocol($url), + '@error' => $result->getReasonPhrase(), + '@code' => $result->getStatusCode(), + ])); + } + } + catch (RequestException $exception) { + $form_state->setErrorByName('matomo_url_https', $this->t('The validation of "@url" failed with an exception "@error" (HTTP code @code).', [ + '@url' => UrlHelper::filterBadProtocol($url), + '@error' => $exception->getMessage(), + '@code' => $exception->getCode(), + ])); + } + } + + // Verify that every path is prefixed with a slash, but don't check PHP + // code snippets and do not check for slashes if no paths configured. + if ($form_state->getValue('matomo_visibility_request_path_mode') != 2 && !empty($form_state->getValue('matomo_visibility_request_path_pages'))) { + $pages = preg_split('/(\r\n?|\n)/', $form_state->getValue('matomo_visibility_request_path_pages')); + foreach ($pages as $page) { + if (strpos($page, '/') !== 0 && $page !== '') { + $form_state->setErrorByName('matomo_visibility_request_path_pages', $this->t('Path "@page" not prefixed with slash.', ['@page' => $page])); + // Drupal forms show one error only. + break; + } + } + } + + // Clear obsolete local cache if cache has been disabled. + if ($form_state->isValueEmpty('matomo_cache') && $form['advanced']['matomo_cache']['#default_value']) { + matomo_clear_js_cache(); + } + + // This is for the Newbie's who cannot read a text area description. + if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state->getValue('matomo_codesnippet_before'))) { + $form_state->setErrorByName('matomo_codesnippet_before', $this->t('Do not include the <script> tags in the javascript code snippets.')); + } + if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state->getValue('matomo_codesnippet_after'))) { + $form_state->setErrorByName('matomo_codesnippet_after', $this->t('Do not include the <script> tags in the javascript code snippets.')); + } + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + $config = $this->config('matomo.settings'); + $config + ->set('site_id', $form_state->getValue('matomo_site_id')) + ->set('url_http', $form_state->getValue('matomo_url_http')) + ->set('url_https', $form_state->getValue('matomo_url_https')) + ->set('codesnippet.before', $form_state->getValue('matomo_codesnippet_before')) + ->set('codesnippet.after', $form_state->getValue('matomo_codesnippet_after')) + ->set('custom.variable', $form_state->getValue('matomo_custom_var')) + ->set('domain_mode', $form_state->getValue('matomo_domain_mode')) + ->set('track.files', $form_state->getValue('matomo_trackfiles')) + ->set('track.files_extensions', $form_state->getValue('matomo_trackfiles_extensions')) + ->set('track.colorbox', $form_state->getValue('matomo_trackcolorbox')) + ->set('track.userid', $form_state->getValue('matomo_trackuserid')) + ->set('track.mailto', $form_state->getValue('matomo_trackmailto')) + ->set('track.messages', $form_state->getValue('matomo_trackmessages')) + ->set('track.site_search', $form_state->getValue('matomo_site_search')) + ->set('privacy.donottrack', $form_state->getValue('matomo_privacy_donottrack')) + ->set('cache', $form_state->getValue('matomo_cache')) + ->set('visibility.request_path_mode', $form_state->getValue('matomo_visibility_request_path_mode')) + ->set('visibility.request_path_pages', $form_state->getValue('matomo_visibility_request_path_pages')) + ->set('visibility.user_account_mode', $form_state->getValue('matomo_visibility_user_account_mode')) + ->set('visibility.user_role_mode', $form_state->getValue('matomo_visibility_user_role_mode')) + ->set('visibility.user_role_roles', $form_state->getValue('matomo_visibility_user_role_roles')) + ->save(); + + if ($form_state->hasValue('matomo_translation_set')) { + $config->set('translation_set', $form_state->getValue('matomo_translation_set'))->save(); + } + + parent::submitForm($form, $form_state); + } + + /** + * Validate a form element that should have tokens in it. + * + * For example: + * @code + * $form['my_node_text_element'] = [ + * '#type' => 'textfield', + * '#title' => $this->t('Some text to token-ize that has a node context.'), + * '#default_value' => 'The title of this node is [node:title].', + * '#element_validate' => [[get_class($this), 'tokenElementValidate']], + * ]; + * @endcode + */ + public static function tokenElementValidate(&$element, FormStateInterface $form_state) { + $value = isset($element['#value']) ? $element['#value'] : $element['#default_value']; + + if (!Unicode::strlen($value)) { + // Empty value needs no further validation since the element should depend + // on using the '#required' FAPI property. + return $element; + } + + $tokens = \Drupal::token()->scan($value); + $invalid_tokens = static::getForbiddenTokens($tokens); + if ($invalid_tokens) { + $form_state->setError($element, t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', ['%element-title' => $element['#title'], '@invalid-tokens' => implode(', ', $invalid_tokens)])); + } + + return $element; + } + + /** + * Get an array of all forbidden tokens. + * + * @param array $value + * An array of token values. + * + * @return array + * A unique array of invalid tokens. + */ + protected static function getForbiddenTokens(array $value) { + $invalid_tokens = []; + $value_tokens = is_string($value) ? \Drupal::token()->scan($value) : $value; + + foreach ($value_tokens as $tokens) { + if (array_filter($tokens, 'static::containsForbiddenToken')) { + $invalid_tokens = array_merge($invalid_tokens, array_values($tokens)); + } + } + + array_unique($invalid_tokens); + return $invalid_tokens; + } + + /** + * Validate if string contains forbidden tokens not allowed by privacy rules. + * + * @param string $token_string + * A string with one or more tokens to be validated. + * + * @return bool + * TRUE if blacklisted token has been found, otherwise FALSE. + */ + protected static function containsForbiddenToken($token_string) { + // List of strings in tokens with personal identifying information not + // allowed for privacy reasons. See section 8.1 of the Google Analytics + // terms of use for more detailed information. + // + // This list can never ever be complete. For this reason it tries to use a + // regex and may kill a few other valid tokens, but it's the only way to + // protect users as much as possible from admins with illegal ideas. + // + // User tokens are not prefixed with colon to catch 'current-user' and + // 'user'. + // + // TODO: If someone have better ideas, share them, please! + $token_blacklist = [ + ':account-name]', + ':author]', + ':author:edit-url]', + ':author:url]', + ':author:path]', + ':current-user]', + ':current-user:original]', + ':display-name]', + ':fid]', + ':mail]', + ':name]', + ':uid]', + ':one-time-login-url]', + ':owner]', + ':owner:cancel-url]', + ':owner:edit-url]', + ':owner:url]', + ':owner:path]', + 'user:cancel-url]', + 'user:edit-url]', + 'user:url]', + 'user:path]', + 'user:picture]', + // addressfield_tokens.module + ':first-name]', + ':last-name]', + ':name-line]', + ':mc-address]', + ':thoroughfare]', + ':premise]', + // realname.module + ':name-raw]', + // token.module + ':ip-address]', + ]; + + return preg_match('/' . implode('|', array_map('preg_quote', $token_blacklist)) . '/i', $token_string); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Plugin/migrate/process/MatomoCustomVars.php b/sites/all/modules/contrib/admin/matomo/src/Plugin/migrate/process/MatomoCustomVars.php new file mode 100644 index 000000000..cb2fde679 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Plugin/migrate/process/MatomoCustomVars.php @@ -0,0 +1,27 @@ +moduleHandler = $module_handler; + $this->migrationPlugin = $migration_plugin; + + if (isset($configuration['skip_php'])) { + $this->skipPHP = $configuration['skip_php']; + } + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) { + $migration_configuration = [ + 'migration' => [ + 'd6_user_role', + 'd7_user_role', + ], + ]; + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('module_handler'), + $container->get('plugin.manager.migrate.process')->createInstance('migration', $migration_configuration, $migration) + ); + } + + /** + * {@inheritdoc} + */ + public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { + list($old_visibility, $pages) = $value; + + $request_path_pages = ''; + + if ($pages) { + // 2 == BLOCK_VISIBILITY_PHP in Drupal 6 and 7. + if ($old_visibility == 2) { + // If the PHP module is present, migrate the visibility code unaltered. + if ($this->moduleHandler->moduleExists('php')) { + $request_path_pages = $pages; + } + // Skip the row if we're configured to. If not, we don't need to do + // anything else -- the block will simply have no PHP or request_path + // visibility configuration. + elseif ($this->skipPHP) { + throw new MigrateSkipRowException(); + } + } + else { + $paths = preg_split("(\r\n?|\n)", $pages); + foreach ($paths as $key => $path) { + $paths[$key] = $path === '' ? $path : '/' . ltrim($path, '/'); + } + $request_path_pages = implode("\n", $paths); + } + } + + return $request_path_pages; + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Plugin/migrate/process/MatomoVisibilityRoles.php b/sites/all/modules/contrib/admin/matomo/src/Plugin/migrate/process/MatomoVisibilityRoles.php new file mode 100644 index 000000000..d26907b46 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Plugin/migrate/process/MatomoVisibilityRoles.php @@ -0,0 +1,87 @@ +moduleHandler = $module_handler; + $this->migrationPlugin = $migration_plugin; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) { + $migration_configuration = [ + 'migration' => [ + 'd6_user_role', + 'd7_user_role', + ], + ]; + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('module_handler'), + $container->get('plugin.manager.migrate.process')->createInstance('migration', $migration_configuration, $migration) + ); + } + + /** + * {@inheritdoc} + */ + public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { + list($roles) = $value; + + // Remove role IDs disabled in D6/D7. + $roles = array_filter($roles); + + $user_role_roles = []; + + if ($roles) { + foreach ($roles as $key => $role_id) { + $roles[$key] = $this->migrationPlugin->transform($role_id, $migrate_executable, $row, $destination_property); + } + $user_role_roles = array_combine($roles, $roles); + } + + return $user_role_roles; + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoBasicTest.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoBasicTest.php new file mode 100644 index 000000000..bddf51de6 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoBasicTest.php @@ -0,0 +1,222 @@ +noSnippetUser = $this->drupalCreateUser($permissions); + $permissions[] = 'add js snippets for matomo'; + $this->admin_user = $this->drupalCreateUser($permissions); + $this->drupalLogin($this->admin_user); + } + + /** + * Tests if configuration is possible. + */ + public function testMatomoConfiguration() { + // Check for setting page's presence. + $this->drupalGet('admin/config/system/matomo'); + $this->assertRaw(t('Matomo site ID'), '[testMatomoConfiguration]: Settings page displayed.'); + + // Check for account code validation. + $edit['matomo_site_id'] = $this->randomMachineName(2); + $edit['matomo_url_http'] = 'http://www.example.com/matomo/'; + $this->drupalPostForm('admin/config/system/matomo', $edit, 'Save configuration'); + $this->assertRaw(t('A valid Matomo site ID is an integer only.'), '[testMatomoConfiguration]: Invalid Matomo site ID number validated.'); + + // Verify that invalid URLs throw a form error. + $edit = []; + $edit['matomo_site_id'] = 1; + $edit['matomo_url_http'] = 'http://www.example.com/matomo/'; + $edit['matomo_url_https'] = 'https://www.example.com/matomo/'; + $this->drupalPostForm('admin/config/system/matomo', $edit, t('Save configuration')); + $this->assertRaw('The validation of "http://www.example.com/matomo/piwik.php" failed with an exception', '[testMatomoConfiguration]: HTTP URL exception shown.'); + $this->assertRaw('The validation of "https://www.example.com/matomo/piwik.php" failed with an exception', '[testMatomoConfiguration]: HTTPS URL exception shown.'); + + // User should have access to code snippets. + $this->assertFieldByName('matomo_codesnippet_before'); + $this->assertFieldByName('matomo_codesnippet_after'); + $this->assertNoFieldByXPath("//textarea[@name='matomo_codesnippet_before' and @disabled='disabled']", NULL, '"Code snippet (before)" is enabled.'); + $this->assertNoFieldByXPath("//textarea[@name='matomo_codesnippet_after' and @disabled='disabled']", NULL, '"Code snippet (after)" is enabled.'); + + // Login as user without JS permissions. + $this->drupalLogin($this->noSnippetUser); + $this->drupalGet('admin/config/system/matomo'); + + // User should *not* have access to snippets, but create fields. + $this->assertFieldByName('matomo_codesnippet_before'); + $this->assertFieldByName('matomo_codesnippet_after'); + $this->assertFieldByXPath("//textarea[@name='matomo_codesnippet_before' and @disabled='disabled']", NULL, '"Code snippet (before)" is disabled.'); + $this->assertFieldByXPath("//textarea[@name='matomo_codesnippet_after' and @disabled='disabled']", NULL, '"Code snippet (after)" is disabled.'); + } + + /** + * Tests if page visibility works. + */ + public function testMatomoPageVisibility() { + $site_id = '1'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + // Show tracking on "every page except the listed pages". + $this->config('matomo.settings')->set('visibility.request_path_mode', 0)->save(); + // Disable tracking one "admin*" pages only. + $this->config('matomo.settings')->set('visibility.request_path_pages', "/admin\n/admin/*")->save(); + // Enable tracking only for authenticated users only. + $this->config('matomo.settings')->set('visibility.user_role_roles', [AccountInterface::AUTHENTICATED_ROLE => AccountInterface::AUTHENTICATED_ROLE])->save(); + + // Check tracking code visibility. + $this->drupalGet(''); + $this->assertRaw('/matomo/js/matomo.js', '[testMatomoPageVisibility]: Custom tracking script is is displayed for authenticated users.'); + $this->assertRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is displayed for authenticated users.'); + + // Test whether tracking code is not included on pages to omit. + $this->drupalGet('admin'); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is not displayed on admin page.'); + $this->drupalGet('admin/config/system/matomo'); + // Checking for tracking URI here, as $site_id is displayed in the form. + $this->assertNoRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is not displayed on admin subpage.'); + + // Test whether tracking code display is properly flipped. + $this->config('matomo.settings')->set('visibility.request_path_mode', 1)->save(); + $this->drupalGet('admin'); + $this->assertRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is displayed on admin page.'); + $this->drupalGet('admin/config/system/matomo'); + // Checking for tracking URI here, as $site_id is displayed in the form. + $this->assertRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is displayed on admin subpage.'); + $this->drupalGet(''); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is NOT displayed on front page.'); + + // Test whether tracking code is not display for anonymous. + $this->drupalLogout(); + $this->drupalGet(''); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is NOT displayed for anonymous.'); + + // Switch back to every page except the listed pages. + $this->config('matomo.settings')->set('visibility.request_path_mode', 0)->save(); + // Enable tracking code for all user roles. + $this->config('matomo.settings')->set('visibility.user_role_roles', [])->save(); + + // Test whether 403 forbidden tracking code is shown if user has no access. + $this->drupalGet('admin'); + $this->assertRaw('"403/URL = "', '[testMatomoPageVisibility]: 403 Forbidden tracking code shown if user has no access.'); + + // Test whether 404 not found tracking code is shown on non-existent pages. + $this->drupalGet($this->randomMachineName(64)); + $this->assertRaw('"404/URL = "', '[testMatomoPageVisibility]: 404 Not Found tracking code shown on non-existent page.'); + } + + /** + * Tests if tracking code is properly added to the page. + */ + public function testMatomoTrackingCode() { + $site_id = '2'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + // Show tracking code on every page except the listed pages. + $this->config('matomo.settings')->set('visibility.request_path_mode', 0)->save(); + // Enable tracking code for all user roles. + $this->config('matomo.settings')->set('visibility.user_role_roles', [])->save(); + + /* Sample JS code as added to page: + + */ + + // Test whether tracking code uses latest JS. + $this->config('matomo.settings')->set('cache', 0)->save(); + $this->drupalGet(''); + $this->assertRaw('u+"piwik.php"', '[testMatomoTrackingCode]: Latest tracking code used.'); + + // Test if tracking of User ID is enabled. + $this->config('matomo.settings')->set('track.userid', 1)->save(); + $this->drupalGet(''); + $this->assertRaw('_paq.push(["setUserId", ', '[testMatomoTrackingCode]: Tracking code for User ID is enabled.'); + + // Test if tracking of User ID is disabled. + $this->config('matomo.settings')->set('track.userid', 0)->save(); + $this->drupalGet(''); + $this->assertNoRaw('_paq.push(["setUserId", ', '[testMatomoTrackingCode]: Tracking code for User ID is disabled.'); + + // Test whether single domain tracking is active. + $this->drupalGet(''); + $this->assertNoRaw('_paq.push(["setCookieDomain"', '[testMatomoTrackingCode]: Single domain tracking is active.'); + + // Enable "One domain with multiple subdomains". + $this->config('matomo.settings')->set('domain_mode', 1)->save(); + $this->drupalGet(''); + + // Test may run on localhost, an ipaddress or real domain name. + // TODO: Workaround to run tests successfully. This feature cannot tested + // reliable. + global $cookie_domain; + if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) { + $this->assertRaw('_paq.push(["setCookieDomain"', '[testMatomoTrackingCode]: One domain with multiple subdomains is active on real host.'); + } + else { + // Special cases, Localhost and IP addresses don't show 'setCookieDomain'. + $this->assertNoRaw('_paq.push(["setCookieDomain"', '[testMatomoTrackingCode]: One domain with multiple subdomains may be active on localhost (test result is not reliable).'); + } + + // Test whether the BEFORE and AFTER code is added to the tracker. + $this->config('matomo.settings')->set('codesnippet.before', '_paq.push(["setLinkTrackingTimer", 250]);')->save(); + $this->config('matomo.settings')->set('codesnippet.after', '_paq.push(["t2.setSiteId", 2]);if(1 == 1 && 2 < 3 && 2 > 1){console.log("Matomo: Custom condition works.");}_gaq.push(["t2.trackPageView"]);')->save(); + $this->drupalGet(''); + $this->assertRaw('setLinkTrackingTimer', '[testMatomoTrackingCode]: Before codesnippet has been found with "setLinkTrackingTimer" set.'); + $this->assertRaw('t2.trackPageView', '[testMatomoTrackingCode]: After codesnippet with "t2" tracker has been found.'); + $this->assertRaw('if(1 == 1 && 2 < 3 && 2 > 1){console.log("Matomo: Custom condition works.");}', '[testMatomoTrackingCode]: JavaScript code is not HTML escaped.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoCustomUrls.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoCustomUrls.php new file mode 100644 index 000000000..f3e08520a --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoCustomUrls.php @@ -0,0 +1,59 @@ +admin_user = $this->drupalCreateUser($permissions); + } + + /** + * Tests if user password page urls are overridden. + */ + public function testMatomoUserPasswordPage() { + $base_path = base_path(); + $site_id = '1'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + $this->drupalGet('user/password', ['query' => ['name' => 'foo']]); + $this->assertRaw('_paq.push(["setCustomUrl", ' . Json::encode($base_path . 'user/password') . ']);'); + + $this->drupalGet('user/password', ['query' => ['name' => 'foo@example.com']]); + $this->assertRaw('_paq.push(["setCustomUrl", ' . Json::encode($base_path . 'user/password') . ']);'); + + $this->drupalGet('user/password'); + $this->assertNoRaw('_paq.push(["setCustomUrl", "', '[testMatomoCustomUrls]: Custom url not set.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoCustomVariablesTest.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoCustomVariablesTest.php new file mode 100644 index 000000000..ad1d33e02 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoCustomVariablesTest.php @@ -0,0 +1,133 @@ +admin_user = $this->drupalCreateUser($permissions); + } + + /** + * Tests if custom variables are properly added to the page. + */ + public function testMatomoCustomVariables() { + $site_id = '3'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + // Basic test if the feature works. + $custom_vars = [ + 1 => [ + 'slot' => 1, + 'name' => 'Foo 1', + 'value' => 'Bar 1', + 'scope' => 'visit', + ], + 2 => [ + 'slot' => 2, + 'name' => 'Foo 2', + 'value' => 'Bar 2', + 'scope' => 'page', + ], + 3 => [ + 'slot' => 3, + 'name' => 'Foo 3', + 'value' => 'Bar 3', + 'scope' => 'page', + ], + 4 => [ + 'slot' => 4, + 'name' => 'Foo 4', + 'value' => 'Bar 4', + 'scope' => 'visit', + ], + 5 => [ + 'slot' => 5, + 'name' => 'Foo 5', + 'value' => 'Bar 5', + 'scope' => 'visit', + ], + ]; + $this->config('matomo.settings')->set('custom.variable', $custom_vars)->save(); + $this->drupalGet(''); + + foreach ($custom_vars as $slot) { + $this->assertRaw('_paq.push(["setCustomVariable", ' . Json::encode($slot['slot']) . ', ' . Json::encode($slot['name']) . ', ' . Json::encode($slot['value']) . ', ' . Json::encode($slot['scope']) . ']);', '[testMatomoCustomVariables]: setCustomVariable ' . $slot['slot'] . ' is shown.'); + } + + // Test whether tokens are replaced in custom variable names. + $site_slogan = $this->randomMachineName(16); + $this->config('system.site')->set('slogan', $site_slogan)->save(); + + $custom_vars = [ + 1 => [ + 'slot' => 1, + 'name' => 'Name: [site:slogan]', + 'value' => 'Value: [site:slogan]', + 'scope' => 'visit', + ], + 2 => [ + 'slot' => 2, + 'name' => '', + 'value' => $this->randomMachineName(16), + 'scope' => 'page', + ], + 3 => [ + 'slot' => 3, + 'name' => $this->randomMachineName(16), + 'value' => '', + 'scope' => 'visit', + ], + 4 => [ + 'slot' => 4, + 'name' => '', + 'value' => '', + 'scope' => 'page', + ], + 5 => [ + 'slot' => 5, + 'name' => '', + 'value' => '', + 'scope' => 'visit', + ], + ]; + $this->config('matomo.settings')->set('custom.variable', $custom_vars)->save(); + $this->verbose('
' . print_r($custom_vars, TRUE) . '
'); + + $this->drupalGet(''); + $this->assertRaw('_paq.push(["setCustomVariable", 1, ' . Json::encode("Name: $site_slogan") . ', ' . Json::encode("Value: $site_slogan") . ', "visit"]', '[testMatomoCustomVariables]: Tokens have been replaced in custom variable.'); + $this->assertNoRaw('_paq.push(["setCustomVariable", 2,', '[testMatomoCustomVariables]: Value with empty name is not shown.'); + $this->assertNoRaw('_paq.push(["setCustomVariable", 3,', '[testMatomoCustomVariables]: Name with empty value is not shown.'); + $this->assertNoRaw('_paq.push(["setCustomVariable", 4,', '[testMatomoCustomVariables]: Empty name and value is not shown.'); + $this->assertNoRaw('_paq.push(["setCustomVariable", 5,', '[testMatomoCustomVariables]: Empty name and value is not shown.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoPhpFilterTest.php.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoPhpFilterTest.php.php new file mode 100644 index 000000000..47a43412d --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoPhpFilterTest.php.php @@ -0,0 +1,107 @@ +admin_user = $this->drupalCreateUser($permissions_admin_user); + + // Administrator who cannot configure tracking visibility with PHP. + $permissions_delegated_admin_user = [ + 'access administration pages', + 'administer matomo', + ]; + $this->delegated_admin_user = $this->drupalCreateUser($permissions_delegated_admin_user); + } + + /** + * Tests if PHP module integration works. + */ + public function testMatomoPhpFilter() { + $site_id = '1'; + $this->drupalLogin($this->admin_user); + + $edit = []; + $edit['matomo_site_id'] = $site_id; + $edit['matomo_url_http'] = 'http://www.example.com/matomo/'; + $edit['matomo_url_https'] = 'https://www.example.com/matomo/'; + // Skip url check errors in automated tests. + $edit['matomo_url_skiperror'] = TRUE; + $edit['matomo_visibility_request_path_mode'] = 2; + $edit['matomo_visibility_request_path_pages'] = ''; + $this->drupalPostForm('admin/config/system/matomo', $edit, t('Save configuration')); + + // Compare saved setting with posted setting. + $matomo_visibility_request_path_pages = \Drupal::config('matomo.settings')->get('visibility.request_path_pages'); + $this->assertEqual('', $matomo_visibility_request_path_pages, '[testMatomoPhpFilter]: PHP code snippet is intact.'); + + // Check tracking code visibility. + $this->config('matomo.settings')->set('visibility.request_path_pages', '')->save(); + $this->drupalGet(''); + $this->assertRaw('u+"piwik.php"', '[testMatomoPhpFilter]: Tracking is displayed on frontpage page.'); + $this->drupalGet('admin'); + $this->assertRaw('u+"piwik.php"', '[testMatomoPhpFilter]: Tracking is displayed on admin page.'); + + $this->config('matomo.settings')->set('visibility.request_path_pages', '')->save(); + $this->drupalGet(''); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoPhpFilter]: Tracking is not displayed on frontpage page.'); + + // Test administration form. + $this->config('matomo.settings')->set('visibility.request_path_pages', '')->save(); + $this->drupalGet('admin/config/system/matomo'); + $this->assertRaw(t('Pages on which this PHP code returns TRUE (experts only)'), '[testMatomoPhpFilter]: Permission to administer PHP for tracking visibility.'); + $this->assertRaw(Html::escape(''), '[testMatomoPhpFilter]: PHP code snippted is displayed.'); + + // Login the delegated user and check if fields are visible. + $this->drupalLogin($this->delegated_admin_user); + $this->drupalGet('admin/config/system/matomo'); + $this->assertNoRaw(t('Pages on which this PHP code returns TRUE (experts only)'), '[testMatomoPhpFilter]: No permission to administer PHP for tracking visibility.'); + $this->assertRaw(Html::escape(''), '[testMatomoPhpFilter]: No permission to view PHP code snippted.'); + + // Set a different value and verify that this is still the same after the + // post. + $this->config('matomo.settings')->set('visibility.request_path_pages', '')->save(); + + $edit = []; + $edit['matomo_site_id'] = $site_id; + $edit['matomo_url_http'] = 'http://www.example.com/matomo/'; + $edit['matomo_url_https'] = 'https://www.example.com/matomo/'; + // Required for testing only. + $edit['matomo_url_skiperror'] = TRUE; + $this->drupalPostForm('admin/config/system/matomo', $edit, t('Save configuration')); + + // Compare saved setting with posted setting. + $matomo_visibility_request_path_mode = $this->config('matomo.settings')->get('visibility.request_path_mode'); + $matomo_visibility_request_path_pages = $this->config('matomo.settings')->get('visibility.request_path_pages'); + $this->assertEqual(2, $matomo_visibility_request_path_mode, '[testMatomoPhpFilter]: Pages on which this PHP code returns TRUE is selected.'); + $this->assertEqual('', $matomo_visibility_request_path_pages, '[testMatomoPhpFilter]: PHP code snippet is intact.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoRolesTest.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoRolesTest.php new file mode 100644 index 000000000..92c01bb9f --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoRolesTest.php @@ -0,0 +1,107 @@ +admin_user = $this->drupalCreateUser($permissions); + } + + /** + * Tests if roles based tracking works. + */ + public function testMatomoRolesTracking() { + $site_id = '1'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + // Test if the default settings are working as expected. + // Add to the selected roles only. + $this->config('matomo.settings')->set('visibility.user_role_mode', 0)->save(); + // Enable tracking for all users. + $this->config('matomo.settings')->set('visibility.user_role_roles', [])->save(); + + // Check tracking code visibility. + $this->drupalGet(''); + $this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is displayed for anonymous users on frontpage with default settings.'); + $this->drupalGet('admin'); + $this->assertRaw('"403/URL = "', '[testMatomoRoleVisibility]: 403 Forbidden tracking code is displayed for anonymous users in admin section with default settings.'); + + $this->drupalLogin($this->admin_user); + + $this->drupalGet(''); + $this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is displayed for authenticated users on frontpage with default settings.'); + $this->drupalGet('admin'); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is NOT displayed for authenticated users in admin section with default settings.'); + + // Test if the non-default settings are working as expected. + // Enable tracking only for authenticated users. + $this->config('matomo.settings')->set('visibility.user_role_roles', [AccountInterface::AUTHENTICATED_ROLE => AccountInterface::AUTHENTICATED_ROLE])->save(); + + $this->drupalGet(''); + $this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is displayed for authenticated users only on frontpage.'); + + $this->drupalLogout(); + $this->drupalGet(''); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is NOT displayed for anonymous users on frontpage.'); + + // Add to every role except the selected ones. + $this->config('matomo.settings')->set('visibility.user_role_mode', 1)->save(); + // Enable tracking for all users. + $this->config('matomo.settings')->set('visibility.user_role_roles', [])->save(); + + // Check tracking code visibility. + $this->drupalGet(''); + $this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is added to every role and displayed for anonymous users.'); + $this->drupalGet('admin'); + $this->assertRaw('"403/URL = "', '[testMatomoRoleVisibility]: 403 Forbidden tracking code is shown for anonymous users if every role except the selected ones is selected.'); + + $this->drupalLogin($this->admin_user); + + $this->drupalGet(''); + $this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is added to every role and displayed on frontpage for authenticated users.'); + $this->drupalGet('admin'); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is added to every role and NOT displayed in admin section for authenticated users.'); + + // Disable tracking for authenticated users. + $this->config('matomo.settings')->set('visibility.user_role_roles', [AccountInterface::AUTHENTICATED_ROLE => AccountInterface::AUTHENTICATED_ROLE])->save(); + + $this->drupalGet(''); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is NOT displayed on frontpage for excluded authenticated users.'); + $this->drupalGet('admin'); + $this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is NOT displayed in admin section for excluded authenticated users.'); + + $this->drupalLogout(); + $this->drupalGet(''); + $this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is displayed on frontpage for included anonymous users.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoSearchTest.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoSearchTest.php new file mode 100644 index 000000000..154a0a80c --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoSearchTest.php @@ -0,0 +1,98 @@ +drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']); + + $permissions = [ + 'access administration pages', + 'administer matomo', + 'search content', + 'create page content', + 'edit own page content', + ]; + + // User to set up matomo. + $this->admin_user = $this->drupalCreateUser($permissions); + $this->drupalLogin($this->admin_user); + } + + /** + * Tests if search tracking is properly added to the page. + */ + public function testMatomoSearchTracking() { + $site_id = '1'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + // Check tracking code visibility. + $this->drupalGet(''); + $this->assertRaw($site_id, '[testMatomoSearch]: Tracking code is displayed for authenticated users.'); + + $this->drupalGet('search/node'); + $this->assertNoRaw('_paq.push(["trackSiteSearch", ', '[testMatomoSearch]: Search tracker not added to page.'); + + // Enable site search support. + $this->config('matomo.settings')->set('track.site_search', 1)->save(); + + // Search for random string. + $search = []; + $search['keys'] = $this->randomMachineName(8); + + // Create a node to search for. + // Create a node. + $edit = []; + $edit['title[0][value]'] = 'This is a test title'; + $edit['body[0][value]'] = 'This test content contains ' . $search['keys'] . ' string.'; + + // Fire a search, it's expected to get 0 results. + $this->drupalPostForm('search/node', $search, t('Search')); + $this->assertRaw('_paq.push(["trackSiteSearch", ', '[testMatomoSearch]: Search results tracker is displayed.'); + $this->assertRaw('window.matomo_search_results = 0;', '[testMatomoSearch]: Search yielded no results.'); + + // Save the node. + $this->drupalPostForm('node/add/page', $edit, t('Save')); + $this->assertText(t('@type @title has been created.', ['@type' => 'Basic page', '@title' => $edit['title[0][value]']]), 'Basic page created.'); + + // Index the node or it cannot found. + $this->cronRun(); + + $this->drupalPostForm('search/node', $search, t('Search')); + $this->assertRaw('_paq.push(["trackSiteSearch", ', '[testMatomoSearch]: Search results tracker is displayed.'); + $this->assertRaw('window.matomo_search_results = 1;', '[testMatomoSearch]: One search result found.'); + + $this->drupalPostForm('node/add/page', $edit, t('Save')); + $this->assertText(t('@type @title has been created.', ['@type' => 'Basic page', '@title' => $edit['title[0][value]']]), 'Basic page created.'); + + // Index the node or it cannot found. + $this->cronRun(); + + $this->drupalPostForm('search/node', $search, t('Search')); + $this->assertRaw('_paq.push(["trackSiteSearch", ', '[testMatomoSearch]: Search results tracker is displayed.'); + $this->assertRaw('window.matomo_search_results = 2;', '[testMatomoSearch]: Two search results found.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoStatusMessagesTest.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoStatusMessagesTest.php new file mode 100644 index 000000000..bf3582f0c --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoStatusMessagesTest.php @@ -0,0 +1,69 @@ +admin_user = $this->drupalCreateUser($permissions); + } + + /** + * Tests if status messages tracking is properly added to the page. + */ + public function testMatomoStatusMessages() { + $site_id = '1'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + // Enable logging of errors only. + $this->config('matomo.settings')->set('track.messages', ['error' => 'error'])->save(); + + $this->drupalPostForm('user/login', [], t('Log in')); + $this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Username field is required."]);', '[testMatomoStatusMessages]: trackEvent "Username field is required." is shown.'); + $this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Password field is required."]);', '[testMatomoStatusMessages]: trackEvent "Password field is required." is shown.'); + + // Testing this Drupal::messenger() requires an extra test module. + $this->drupalGet('matomo-test/drupal-messenger-add-message'); + $this->assertNoRaw('_paq.push(["trackEvent", "Messages", "Status message", "Example status message."]);', '[testMatomoStatusMessages]: Example status message is not enabled for tracking.'); + $this->assertNoRaw('_paq.push(["trackEvent", "Messages", "Warning message", "Example warning message."]);', '[testMatomoStatusMessages]: Example warning message is not enabled for tracking.'); + $this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Example error message."]);', '[testMatomoStatusMessages]: Example error message is shown.'); + $this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Example error message with html tags and link."]);', '[testMatomoStatusMessages]: HTML has been stripped successful from Example error message with html tags and link.'); + + // Enable logging of status, warnings and errors. + $this->config('matomo.settings')->set('track.messages', ['status' => 'status', 'warning' => 'warning', 'error' => 'error'])->save(); + + $this->drupalGet('matomo-test/drupal-messenger-add-message'); + $this->assertRaw('_paq.push(["trackEvent", "Messages", "Status message", "Example status message."]);', '[testMatomoStatusMessages]: Example status message is enabled for tracking.'); + $this->assertRaw('_paq.push(["trackEvent", "Messages", "Warning message", "Example warning message."]);', '[testMatomoStatusMessages]: Example warning message is enabled for tracking.'); + $this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Example error message."]);', '[testMatomoStatusMessages]: Example error message is shown.'); + $this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Example error message with html tags and link."]);', '[testMatomoStatusMessages]: HTML has been stripped successful from Example error message with html tags and link.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoUninstallTest.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoUninstallTest.php new file mode 100644 index 000000000..2807e9649 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoUninstallTest.php @@ -0,0 +1,78 @@ +admin_user = $this->drupalCreateUser($permissions); + $this->drupalLogin($this->admin_user); + } + + /** + * Tests if the module cleans up the disk on uninstall. + */ + public function testMatomoUninstall() { + $cache_path = 'public://matomo'; + $site_id = '1'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + // Enable local caching of piwik.js. + $this->config('matomo.settings')->set('cache', 1)->save(); + + // Load front page to get the piwik.js downloaded into local cache. But + // loading the piwik.js is not possible as "url_http" is a test dummy only. + // Create a dummy file to complete the rest of the tests. + file_prepare_directory($cache_path, FILE_CREATE_DIRECTORY); + $data = $this->randomMachineName(128); + $file_destination = $cache_path . '/piwik.js'; + file_unmanaged_save_data($data, $file_destination); + file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE); + + // Test if the directory and piwik.js exists. + $this->assertTrue(file_prepare_directory($cache_path), 'Cache directory "public://matomo" has been found.'); + $this->assertTrue(file_exists($cache_path . '/piwik.js'), 'Cached piwik.js tracking file has been found.'); + $this->assertTrue(file_exists($cache_path . '/piwik.js.gz'), 'Cached piwik.js.gz tracking file has been found.'); + + // Uninstall the module. + $edit = []; + $edit['uninstall[matomo]'] = TRUE; + $this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall')); + $this->assertNoText(\Drupal::translation()->translate('Configuration deletions'), 'No configuration deletions listed on the module install confirmation page.'); + $this->drupalPostForm(NULL, NULL, t('Uninstall')); + $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.'); + + // Test if the directory and all files have been removed. + $this->assertFalse(file_scan_directory($cache_path, '/.*/'), 'Cached JavaScript files have been removed.'); + $this->assertFalse(file_prepare_directory($cache_path), 'Cache directory "public://matomo" has been removed.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoUserFieldsTest.php b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoUserFieldsTest.php new file mode 100644 index 000000000..e56b3cda1 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/src/Tests/MatomoUserFieldsTest.php @@ -0,0 +1,73 @@ +admin_user = $this->drupalCreateUser($permissions); + $this->drupalLogin($this->admin_user); + } + + /** + * Tests if "allow users to customize tracking on their account page" works. + */ + public function testMatomoUserFields() { + $site_id = '1'; + $this->config('matomo.settings')->set('site_id', $site_id)->save(); + $this->config('matomo.settings')->set('url_http', 'http://www.example.com/matomo/')->save(); + $this->config('matomo.settings')->set('url_https', 'https://www.example.com/matomo/')->save(); + + // Check if the pseudo field is shown on account forms. + $this->drupalGet('admin/config/people/accounts/form-display'); + $this->assertResponse(200); + $this->assertRaw(t('Matomo settings'), '[testMatomoUserFields]: Matomo settings field exists on Manage form display.'); + + // No customization allowed. + $this->config('matomo.settings')->set('visibility.user_account_mode', 0)->save(); + $this->drupalGet('user/' . $this->admin_user->id() . '/edit'); + $this->assertResponse(200); + $this->assertNoRaw(t('Matomo settings'), '[testMatomoUserFields]: Matomo settings field does not exist on user edit page.'); + + // Tracking on by default, users with opt-in or out of matomo tracking permission + // can opt out. + $this->config('matomo.settings')->set('visibility.user_account_mode', 1)->save(); + $this->drupalGet('user/' . $this->admin_user->id() . '/edit'); + $this->assertResponse(200); + $this->assertRaw(t('Users are tracked by default, but you are able to opt out.'), '[testMatomoUserFields]: Matomo settings field exists on on user edit page'); + + // Tracking off by default, users with opt-in or out of matomo tracking permission + // can opt in. + $this->config('matomo.settings')->set('visibility.user_account_mode', 2)->save(); + $this->drupalGet('user/' . $this->admin_user->id() . '/edit'); + $this->assertResponse(200); + $this->assertRaw(t('Users are not tracked by default, but you are able to opt in.'), '[testMatomoUserFields]: Matomo settings field exists on on user edit page.'); + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/matomo_test.info.yml b/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/matomo_test.info.yml new file mode 100644 index 000000000..5abee1009 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/matomo_test.info.yml @@ -0,0 +1,11 @@ +name: 'Matomo test' +type: module +description: 'Support module for Matomo testing.' +package: Testing +# core: 8.x + +# Information added by Drupal.org packaging script on 2018-07-13 +version: '8.x-1.7' +core: '8.x' +project: 'matomo' +datestamp: 1531470224 diff --git a/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/matomo_test.routing.yml b/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/matomo_test.routing.yml new file mode 100644 index 000000000..ad1fcf645 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/matomo_test.routing.yml @@ -0,0 +1,7 @@ +matomo_test.drupal_messenger_add_message: + path: '/matomo-test/drupal-messenger-add-message' + defaults: + _title: 'Add messages with Drupal::messenger()' + _controller: '\Drupal\matomo_test\Controller\MatomoTestController::drupalAddMessageTest' + requirements: + _access: 'TRUE' diff --git a/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/src/Controller/MatomoTestController.php b/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/src/Controller/MatomoTestController.php new file mode 100644 index 000000000..4a0e8801d --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/tests/modules/matomo_test/src/Controller/MatomoTestController.php @@ -0,0 +1,28 @@ +t('Example status message.'), 'status'); + drupal_set_message($this->t('Example warning message.'), 'warning'); + drupal_set_message($this->t('Example error message.'), 'error'); + drupal_set_message($this->t('Example error message with html tags and link.'), 'error'); + + return []; + } + +} diff --git a/sites/all/modules/contrib/admin/matomo/tests/src/Functional/AdminSettingsFormTest.php b/sites/all/modules/contrib/admin/matomo/tests/src/Functional/AdminSettingsFormTest.php new file mode 100644 index 000000000..af155f120 --- /dev/null +++ b/sites/all/modules/contrib/admin/matomo/tests/src/Functional/AdminSettingsFormTest.php @@ -0,0 +1,103 @@ +adminUser = $this->drupalCreateUser($permissions); + $this->drupalLogin($this->adminUser); + } + + /** + * Tests the fields that allow to configure tracking of specific pages. + * + * @param string $pages + * A list of pages that should be tracked. One page per line. + * @param bool $validation_error_expected + * TRUE if a validation error should be thrown. FALSE otherwise. + * + * @dataProvider pageTrackingProvider + */ + public function testPageTracking($pages, $validation_error_expected) { + $edit = [ + 'matomo_visibility_request_path_mode' => 0, + 'matomo_visibility_request_path_pages' => $pages, + ]; + $this->drupalPostForm('admin/config/system/matomo', $edit, t('Save configuration')); + $has_validation_error = (bool) $this->getSession()->getPage()->find('css', '#edit-matomo-visibility-request-path-pages.error'); + $this->assertEquals($validation_error_expected, $has_validation_error); + } + + /** + * Provides test data for ::testPageTracking(). + * + * @return array + * An array of test cases, each test case is an array with two values: + * 0. A string containing a list of pages to track. + * 1. A boolean indicating whether or not a validation error is expected to + * be thrown. + */ + public function pageTrackingProvider() { + return [ + [ + // No validation error should be thrown for an empty page list. + '', + FALSE, + ], + [ + // No validation error should be thrown for a list of valid pages. + << +TXT + , + FALSE, + ], + [ + // A validation error should be thrown if one of the pages doesn't start + // with a slash. + << +TXT + , + TRUE, + ], + ]; + } + +} diff --git a/sites/all/modules/contrib/admin/piwik/composer.json b/sites/all/modules/contrib/admin/piwik/composer.json index d10a4ac55..5419bea3c 100644 --- a/sites/all/modules/contrib/admin/piwik/composer.json +++ b/sites/all/modules/contrib/admin/piwik/composer.json @@ -18,5 +18,7 @@ "source": "http://git.drupal.org/project/piwik.git" }, "license": "GPL-2.0+", - "require": {} + "require": { + "drupal/matomo": "^1.0" + } } diff --git a/sites/all/modules/contrib/admin/piwik/piwik.info.yml b/sites/all/modules/contrib/admin/piwik/piwik.info.yml index 9e3ef253b..8a5bf7f95 100644 --- a/sites/all/modules/contrib/admin/piwik/piwik.info.yml +++ b/sites/all/modules/contrib/admin/piwik/piwik.info.yml @@ -7,9 +7,11 @@ configure: piwik.admin_settings_form test_dependencies: - php:php - token:token +dependencies: + - matomo -# Information added by Drupal.org packaging script on 2017-11-11 -version: '8.x-1.2' +# Information added by Drupal.org packaging script on 2018-06-08 +version: '8.x-1.4' core: '8.x' project: 'piwik' -datestamp: 1510404815 +datestamp: 1528483684 diff --git a/sites/all/modules/contrib/admin/piwik/piwik.install b/sites/all/modules/contrib/admin/piwik/piwik.install index 93491593c..08cfbb8b9 100644 --- a/sites/all/modules/contrib/admin/piwik/piwik.install +++ b/sites/all/modules/contrib/admin/piwik/piwik.install @@ -22,19 +22,111 @@ function piwik_uninstall() { function piwik_requirements($phase) { $requirements = []; - if ($phase == 'runtime') { - $config = \Drupal::config('piwik.settings'); + switch ($phase) { + case 'install': + if (\Drupal::moduleHandler()->moduleExists('matomo')) { + // https://matomo.org/blog/2018/01/piwik-is-now-matomo/ + $requirements['piwik_matomo_is_installed'] = array( + 'title' => t('Piwik is now Matomo!'), + 'value' => t('Fails'), + 'severity' => REQUIREMENT_ERROR, + 'description' => t('Piwik has been renamed to Matomo Analytics. Piwik module is blocked now and cannot re-enabled! Please remove piwik module from your system. It is no longer used.'), + ); + } + break; - // Raise warning if Piwik user account has not been set yet. - if (!preg_match('/^\d{1,}$/', $config->get('site_id'))) { - $requirements['piwik_site_id'] = [ - 'title' => t('Piwik module'), - 'description' => t('Piwik module has not been configured yet. Please configure its settings from the Piwik settings page.', [':url' => Url::fromRoute('piwik.admin_settings_form')->toString()]), - 'severity' => REQUIREMENT_WARNING, - 'value' => t('Not configured'), - ]; - } + case 'runtime': + $config = \Drupal::config('piwik.settings'); + + // Raise warning if Piwik user account has not been set yet. + if (!preg_match('/^\d{1,}$/', $config->get('site_id'))) { + $requirements['piwik_site_id'] = [ + 'title' => t('Piwik module'), + 'description' => t('Piwik module has not been configured yet. Please configure its settings from the Piwik settings page.', [':url' => Url::fromRoute('piwik.admin_settings_form')->toString()]), + 'severity' => REQUIREMENT_WARNING, + 'value' => t('Not configured'), + ]; + } + break; } return $requirements; } + +/** + * Install Matomo module and migrate all settings. + */ +function piwik_update_8200() { + // Make the update hook failing so it can re-run later again. + if (!module_load_include('module', 'matomo', 'matomo')) { + throw new DrupalUpdateException(t('Matomo module is missing. Download it and re-run update.php')); + } + + $module_enabled = \Drupal::service('module_installer')->install(array('matomo')); + if ($module_enabled) { + $messages[] = t('Successfully installed matomo module.'); + + $piwik_config = \Drupal::configFactory()->getEditable('piwik.settings'); + $matomo_config = \Drupal::configFactory()->getEditable('matomo.settings'); + $matomo_config + ->set('site_id', $piwik_config->get('site_id')) + ->set('url_http', $piwik_config->get('url_http')) + ->set('url_https', $piwik_config->get('url_https')) + ->set('codesnippet.before', $piwik_config->get('codesnippet.before')) + ->set('codesnippet.after', $piwik_config->get('codesnippet.after')) + ->set('custom.variable', $piwik_config->get('custom.variable')) + ->set('domain_mode', $piwik_config->get('domain_mode')) + ->set('track.files', $piwik_config->get('track.files')) + ->set('track.files_extensions', $piwik_config->get('track.files_extensions')) + ->set('track.colorbox', $piwik_config->get('track.colorbox')) + ->set('track.userid', $piwik_config->get('track.userid')) + ->set('track.mailto', $piwik_config->get('track.mailto')) + ->set('track.messages', $piwik_config->get('track.messages')) + ->set('track.site_search', $piwik_config->get('track.site_search')) + ->set('translation_set', $piwik_config->get('translation_set')) + ->set('privacy.donottrack', $piwik_config->get('privacy.donottrack')) + ->set('cache', $piwik_config->get('cache')) + ->set('visibility.request_path_mode', $piwik_config->get('visibility.request_path_mode')) + ->set('visibility.request_path_pages', $piwik_config->get('visibility.request_path_pages')) + ->set('visibility.user_account_mode', $piwik_config->get('visibility.user_account_mode')) + ->set('visibility.user_role_mode', $piwik_config->get('visibility.user_role_mode')) + ->set('visibility.user_role_roles', $piwik_config->get('visibility.user_role_roles')) + ->save(); + $messages[] = t('Copied settings from piwik to matomo module.'); + + // Migrate piwik permissions to matomo. + $permissions = array( + 'administer piwik' => 'administer matomo', + 'opt-in or out of piwik tracking' => 'opt-in or out of matomo tracking', + 'use PHP for piwik tracking visibility' => 'use php for matomo tracking visibility', + 'add JS snippets for piwik' => 'add js snippets for matomo', + ); + foreach (user_roles(FALSE) as $rid => $name) { + $role = \Drupal\user\Entity\Role::load($rid); + foreach ($permissions as $permission_old_key => $permission_new_key) { + if ($role->hasPermission($permission_old_key)) { + $role->grantPermission($permission_new_key); + $messages[] = t('Role "@rid" has permission "@permission_old_key" and "@permission_new_key" granted.', array('@rid' => $rid, '@permission_old_key' => $permission_old_key, '@permission_new_key' => $permission_new_key)); + } + } + $role->save(); + } + $messages[] = t('Copied piwik permissions to matomo module.'); + + // Uninstall piwik module. + $module_uninstalled = \Drupal::service('module_installer')->uninstall(array('piwik'), FALSE); + if ($module_uninstalled) { + $messages[] = t('Successfully uninstalled piwik module. Please remove piwik from your system.'); + drupal_set_message('Piwik is now Matomo! Matomo has been installed. Please remove Piwik module from your system.', 'warning'); + } + else { + $messages[] = t('FAILED to uninstall piwik module.'); + + // Unconfigure piwik to remove piwik tracking code; if piwik module may failed to disable. + $piwik_config->set('site_id', ''); + $messages[] = t('Unconfigured site_id in piwik module to disable double tracking.'); + } + } + + return empty($messages) ? t('FAILED to migrate piwik to matomo module. Please uninstall piwik module and install matomo module manually!') : implode(' ', $messages); +} diff --git a/sites/all/modules/contrib/admin/piwik/tests/modules/piwik_test/piwik_test.info.yml b/sites/all/modules/contrib/admin/piwik/tests/modules/piwik_test/piwik_test.info.yml index bdb939d81..74c1d837e 100644 --- a/sites/all/modules/contrib/admin/piwik/tests/modules/piwik_test/piwik_test.info.yml +++ b/sites/all/modules/contrib/admin/piwik/tests/modules/piwik_test/piwik_test.info.yml @@ -4,8 +4,8 @@ description: 'Support module for Piwik testing.' package: Testing # core: 8.x -# Information added by Drupal.org packaging script on 2017-11-11 -version: '8.x-1.2' +# Information added by Drupal.org packaging script on 2018-06-08 +version: '8.x-1.4' core: '8.x' project: 'piwik' -datestamp: 1510404815 +datestamp: 1528483684 diff --git a/sites/all/modules/contrib/dev/config_filter/config_filter.info.yml b/sites/all/modules/contrib/dev/config_filter/config_filter.info.yml index fa43d41be..1ecd75772 100644 --- a/sites/all/modules/contrib/dev/config_filter/config_filter.info.yml +++ b/sites/all/modules/contrib/dev/config_filter/config_filter.info.yml @@ -4,8 +4,8 @@ description: Config Filter allows other modules to interact with a ConfigStorage # core: 8.x package: Config -# Information added by Drupal.org packaging script on 2017-11-27 -version: '8.x-1.1' +# Information added by Drupal.org packaging script on 2018-04-05 +version: '8.x-1.2' core: '8.x' project: 'config_filter' -datestamp: 1511779987 +datestamp: 1522943894 diff --git a/sites/all/modules/contrib/dev/config_filter/src/Config/FilteredStorage.php b/sites/all/modules/contrib/dev/config_filter/src/Config/FilteredStorage.php index 94175792a..9559df324 100644 --- a/sites/all/modules/contrib/dev/config_filter/src/Config/FilteredStorage.php +++ b/sites/all/modules/contrib/dev/config_filter/src/Config/FilteredStorage.php @@ -2,6 +2,7 @@ namespace Drupal\config_filter\Config; +use Drupal\config_filter\Exception\InvalidStorageFilterException; use Drupal\Core\Config\StorageInterface; /** @@ -43,6 +44,9 @@ class FilteredStorage implements FilteredStorageInterface { // Set the storage to all the filters. foreach ($this->filters as $filter) { + if (!$filter instanceof StorageFilterInterface) { + throw new InvalidStorageFilterException(); + } $filter->setSourceStorage(new ReadOnlyStorage($storage)); $filter->setFilteredStorage($this); } @@ -209,16 +213,7 @@ class FilteredStorage implements FilteredStorageInterface { } } - $storage = $this->storage->createCollection($collection); - $filtered = new static($storage, $filters); - - // Set the storage to all the filters. - foreach ($filters as $filter) { - $filter->setSourceStorage(new ReadOnlyStorage($storage)); - $filter->setFilteredStorage($filtered); - } - - return $filtered; + return new static($this->storage->createCollection($collection), $filters); } /** diff --git a/sites/all/modules/contrib/dev/config_filter/src/Config/GhostStorage.php b/sites/all/modules/contrib/dev/config_filter/src/Config/GhostStorage.php new file mode 100644 index 000000000..afd44f10e --- /dev/null +++ b/sites/all/modules/contrib/dev/config_filter/src/Config/GhostStorage.php @@ -0,0 +1,46 @@ +source = $storage; + } + + /** + * {@inheritdoc} + */ + public function setFilteredStorage(StorageInterface $storage) { + $this->filtered = $storage; + } + + /** + * Get the read-only source Storage. + * + * @return \Drupal\Core\Config\StorageInterface + * The source storage. + */ + protected function getSourceStorage() { + return $this->source; + } + + /** + * Get the decorator storage which applies the filters. + * + * @return \Drupal\Core\Config\StorageInterface + * The filtered decorator storage. + */ + protected function getFilteredStorage() { + return $this->filtered; + } + + /** + * {@inheritdoc} + */ + public function filterRead($name, $data) { + return $data; + } + + /** + * {@inheritdoc} + */ + public function filterWrite($name, array $data) { + return $data; + } + + /** + * {@inheritdoc} + */ + public function filterWriteEmptyIsDelete($name) { + return NULL; + } + + /** + * {@inheritdoc} + */ + public function filterExists($name, $exists) { + return $exists; + } + + /** + * {@inheritdoc} + */ + public function filterDelete($name, $delete) { + return $delete; + } + + /** + * {@inheritdoc} + */ + public function filterReadMultiple(array $names, array $data) { + return $data; + } + + /** + * {@inheritdoc} + */ + public function filterRename($name, $new_name, $rename) { + return $rename; + } + + /** + * {@inheritdoc} + */ + public function filterListAll($prefix, array $data) { + return $data; + } + + /** + * {@inheritdoc} + */ + public function filterDeleteAll($prefix, $delete) { + return $delete; + } + + /** + * {@inheritdoc} + */ + public function filterCreateCollection($collection) { + return clone $this; + } + + /** + * {@inheritdoc} + */ + public function filterGetAllCollectionNames(array $collections) { + return $collections; + } + + /** + * {@inheritdoc} + */ + public function filterGetCollectionName($collection) { + return $collection; + } + +} diff --git a/sites/all/modules/contrib/dev/config_filter/src/Exception/InvalidStorageFilterException.php b/sites/all/modules/contrib/dev/config_filter/src/Exception/InvalidStorageFilterException.php new file mode 100644 index 000000000..f3a62fe60 --- /dev/null +++ b/sites/all/modules/contrib/dev/config_filter/src/Exception/InvalidStorageFilterException.php @@ -0,0 +1,19 @@ +source = $storage; - } - - /** - * {@inheritdoc} - */ - public function setFilteredStorage(StorageInterface $storage) { - $this->filtered = $storage; - } - - /** - * Get the read-only source Storage. - * - * @return \Drupal\Core\Config\StorageInterface - * The source storage. - */ - protected function getSourceStorage() { - return $this->source; - } - - /** - * Get the decorator storage which applies the filters. - * - * @return \Drupal\Core\Config\StorageInterface - * The filtered decorator storage. - */ - protected function getFilteredStorage() { - return $this->filtered; - } - - /** - * {@inheritdoc} - */ - public function filterRead($name, $data) { - return $data; - } - - /** - * {@inheritdoc} - */ - public function filterWrite($name, array $data) { - return $data; - } - - /** - * {@inheritdoc} - */ - public function filterWriteEmptyIsDelete($name) { - return NULL; - } - - /** - * {@inheritdoc} - */ - public function filterExists($name, $exists) { - return $exists; - } - - /** - * {@inheritdoc} - */ - public function filterDelete($name, $delete) { - return $delete; - } - - /** - * {@inheritdoc} - */ - public function filterReadMultiple(array $names, array $data) { - return $data; - } - - /** - * {@inheritdoc} - */ - public function filterRename($name, $new_name, $rename) { - return $rename; - } - - /** - * {@inheritdoc} - */ - public function filterListAll($prefix, array $data) { - return $data; - } - - /** - * {@inheritdoc} - */ - public function filterDeleteAll($prefix, $delete) { - return $delete; - } - - /** - * {@inheritdoc} - */ - public function filterCreateCollection($collection) { - return clone $this; - } - - /** - * {@inheritdoc} - */ - public function filterGetAllCollectionNames(array $collections) { - return $collections; - } - - /** - * {@inheritdoc} - */ - public function filterGetCollectionName($collection) { - return $collection; - } + use TransparentStorageFilterTrait; } diff --git a/sites/all/modules/contrib/dev/config_filter/src/Tests/FilteredStorageTest.php b/sites/all/modules/contrib/dev/config_filter/src/Tests/FilteredStorageTest.php index 083414a82..fb1a2d47c 100644 --- a/sites/all/modules/contrib/dev/config_filter/src/Tests/FilteredStorageTest.php +++ b/sites/all/modules/contrib/dev/config_filter/src/Tests/FilteredStorageTest.php @@ -3,8 +3,10 @@ namespace Drupal\config_filter\Tests; use Drupal\config_filter\Config\FilteredStorage; +use Drupal\config_filter\Config\FilteredStorageInterface; use Drupal\config_filter\Config\ReadOnlyStorage; use Drupal\config_filter\Config\StorageFilterInterface; +use Drupal\config_filter\Exception\InvalidStorageFilterException; use Drupal\Core\Config\CachedStorage; use Drupal\Core\Config\StorageInterface; use Drupal\KernelTests\Core\Config\Storage\CachedStorageTest; @@ -31,12 +33,8 @@ class FilteredStorageTest extends CachedStorageTest { * Test that the storage is set on the filters. */ public function testSettingStorages() { - $filterReflection = new \ReflectionClass(FilteredStorage::class); - $filtersProperty = $filterReflection->getProperty('filters'); - $filtersProperty->setAccessible(TRUE); - /** @var \Drupal\config_filter\Tests\TransparentFilter[] $filters */ - $filters = $filtersProperty->getValue($this->storage); + $filters = static::getProtectedFilters($this->storage); foreach ($filters as $filter) { // Test that the source storage is a ReadonlyStorage and wraps the cached // storage from the inherited test. @@ -53,6 +51,69 @@ class FilteredStorageTest extends CachedStorageTest { } } + /** + * Test that creating collections keeps filters set to the correct storages. + */ + public function testCollectionStorages() { + $collection = $this->randomString(); + + // The storage is in its default state. + $this->assertEquals(StorageInterface::DEFAULT_COLLECTION, $this->storage->getCollectionName()); + + /** @var \Drupal\config_filter\Tests\TransparentFilter[] $filters */ + $filters = static::getProtectedFilters($this->storage); + foreach ($filters as $filter) { + // Test that the filters have the correct storage set. + $this->assertEquals($this->storage, $filter->getPrivateFilteredStorage()); + $this->assertEquals(StorageInterface::DEFAULT_COLLECTION, $filter->getPrivateSourceStorage()->getCollectionName()); + } + + // Create a collection which creates a clone of the storage and filters. + $collectionStorage = $this->storage->createCollection($collection); + $this->assertInstanceOf(FilteredStorageInterface::class, $collectionStorage); + + /** @var \Drupal\config_filter\Tests\TransparentFilter[] $collectionFilters */ + $collectionFilters = static::getProtectedFilters($collectionStorage); + foreach ($collectionFilters as $filter) { + // Test that the cloned filter has the correct storage set. + $this->assertEquals($collectionStorage, $filter->getPrivateFilteredStorage()); + $this->assertEquals($collection, $filter->getPrivateSourceStorage()->getCollectionName()); + } + + /** @var \Drupal\config_filter\Tests\TransparentFilter[] $filters */ + $filters = static::getProtectedFilters($this->storage); + foreach ($filters as $filter) { + // Test that the filters on the original storage are still correctly set. + $this->assertEquals($this->storage, $filter->getPrivateFilteredStorage()); + $this->assertEquals(StorageInterface::DEFAULT_COLLECTION, $filter->getPrivateSourceStorage()->getCollectionName()); + } + } + + /** + * Test setting up filters in FilteredStorage::createCollection(). + */ + public function testCreateCollectionFilter() { + $collection = $this->randomString(); + $filteredCollection = $this->randomString(); + + $filter = $this->prophesizeFilter(); + $filterC = $this->prophesizeFilter(); + $filterC->filterGetCollectionName($collection)->willReturn($filteredCollection); + $filter->filterCreateCollection($collection)->willReturn($filterC->reveal()); + + $source = $this->prophesize(StorageInterface::class); + $sourceC = $this->prophesize(StorageInterface::class); + $sourceC->getCollectionName()->willReturn($collection); + $source->createCollection($collection)->willReturn($sourceC->reveal()); + + $storage = new FilteredStorage($source->reveal(), [$filter->reveal()]); + // Creating a collection makes sure the filters were correctly set up. + $storageC = $storage->createCollection($collection); + + // Test that the collection is filtered in the collection storage. + $this->assertEquals($filteredCollection, $storageC->getCollectionName()); + } + /** * Test the read methods invokes the correct filter methods. * @@ -278,6 +339,23 @@ class FilteredStorageTest extends CachedStorageTest { ]; } + /** + * Test that an exception is thrown when invalid arguments are passed. + */ + public function testInvalidStorageFilterArgument() { + $source = $this->prophesize(StorageInterface::class); + + // We would do this with $this->expectException but alas drupal is stuck on + // phpunit 4 and we try not to add deprecated code. + try { + new FilteredStorage($source->reveal(), [new \stdClass()]); + $this->fail('An exception should have been thrown.'); + } + catch (InvalidStorageFilterException $exception) { + $this->assertTrue(TRUE); + } + } + /** * Prophesize a StorageFilter. */ @@ -288,6 +366,23 @@ class FilteredStorageTest extends CachedStorageTest { return $filter; } + /** + * Get the filters from a FilteredStorageInterface. + * + * @param \Drupal\Core\Config\StorageInterface $storage + * The storage with the protected filters property. + * + * @return \Drupal\config_filter\Config\StorageFilterInterface[] + * The array of filters. + */ + protected static function getProtectedFilters(StorageInterface $storage) { + $filterReflection = new \ReflectionClass(FilteredStorage::class); + $filtersProperty = $filterReflection->getProperty('filters'); + $filtersProperty->setAccessible(TRUE); + + return $filtersProperty->getValue($storage); + } + /** * Create a random array. */ diff --git a/sites/all/modules/contrib/dev/config_filter/src/Tests/GhostStorageTest.php b/sites/all/modules/contrib/dev/config_filter/src/Tests/GhostStorageTest.php new file mode 100644 index 000000000..a384badd5 --- /dev/null +++ b/sites/all/modules/contrib/dev/config_filter/src/Tests/GhostStorageTest.php @@ -0,0 +1,44 @@ +prophesize(StorageInterface::class); + $source->$method(Argument::any())->shouldNotBeCalled(); + + $storage = $this->getStorage($source->reveal()); + + $actual = call_user_func_array([$storage, $method], $arguments); + $this->assertTrue($actual); + } + +} diff --git a/sites/all/modules/contrib/dev/config_filter/tests/modules/config_filter_split_test/config_filter_split_test.info.yml b/sites/all/modules/contrib/dev/config_filter/tests/modules/config_filter_split_test/config_filter_split_test.info.yml index 2924e12be..e91f96830 100644 --- a/sites/all/modules/contrib/dev/config_filter/tests/modules/config_filter_split_test/config_filter_split_test.info.yml +++ b/sites/all/modules/contrib/dev/config_filter/tests/modules/config_filter_split_test/config_filter_split_test.info.yml @@ -3,10 +3,10 @@ type: module # core: 8.x package: Testing dependencies: - - drupal:config_filter + - config_filter:config_filter -# Information added by Drupal.org packaging script on 2017-11-27 -version: '8.x-1.1' +# Information added by Drupal.org packaging script on 2018-04-05 +version: '8.x-1.2' core: '8.x' project: 'config_filter' -datestamp: 1511779987 +datestamp: 1522943894 diff --git a/sites/all/modules/contrib/dev/config_filter/tests/modules/config_filter_test/config_filter_test.info.yml b/sites/all/modules/contrib/dev/config_filter/tests/modules/config_filter_test/config_filter_test.info.yml index 0cdd63a2a..7b18d8891 100644 --- a/sites/all/modules/contrib/dev/config_filter/tests/modules/config_filter_test/config_filter_test.info.yml +++ b/sites/all/modules/contrib/dev/config_filter/tests/modules/config_filter_test/config_filter_test.info.yml @@ -3,10 +3,10 @@ type: module # core: 8.x package: Testing dependencies: - - drupal:config_filter + - config_filter:config_filter -# Information added by Drupal.org packaging script on 2017-11-27 -version: '8.x-1.1' +# Information added by Drupal.org packaging script on 2018-04-05 +version: '8.x-1.2' core: '8.x' project: 'config_filter' -datestamp: 1511779987 +datestamp: 1522943894 diff --git a/sites/all/modules/contrib/fields/color_field/.gitignore b/sites/all/modules/contrib/fields/color_field/.gitignore new file mode 100644 index 000000000..9f11b755a --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/.gitignore @@ -0,0 +1 @@ +.idea/ diff --git a/sites/all/modules/contrib/fields/color_field/README.md b/sites/all/modules/contrib/fields/color_field/README.md new file mode 100644 index 000000000..a2e13ef73 --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/README.md @@ -0,0 +1,123 @@ +# Color Field - Drupal 8 + +## ABOUT & FEATURES + +### Formatters + + Plain text HEX code (#FFFFFF) + Css Declaration (color/background-color) + +### Widgets + +- *Color Boxes*: Provides a row of colored boxes to select from a configured +list of colors. If enabled, opacity is a number field. +- *Color Default*: Textbox to put in a hex value. If enabled, opacity is a +number field. +- *Color Grid*: Uses [jQuery Simple Color](https://github.com/recurser/jquery-simple-color) +to provide a pop up grid of color options. If enabled, opacity is a number +field. +- *Color HTML5*: Uses the color HTML5 input type to render in a browser/system +native manner. If enabled, opacity is a number field. +- *Color Spectrum*: Uses [Spectrum](https://github.com/bgrins/spectrum) to +provide a user friendly color palette to choose the correct color. This has an +integrated slider for opacity (if opacity is enabled). + +## ROAD MAP + +1) Make this module a base that could be used by any color picker. +2) include http://www.eyecon.ro/colorpicker/ +3) include http://www.dematte.at/colorPicker/ +4) include http://acko.net/blog/farbtastic-jquery-color-picker-plug-in/ + +## INSTALLATION + +Install as you would normally install a contributed Drupal module. See also +[Core Documentation](https://www.drupal.org/docs/8/extending-drupal-8/installing-modules) + +### DEPENDENCIES +There are JavaScript libraries required for a couple of the field widgets. If +you are not actively using those field widgets, you can skip their installation +if desired. + +#### COMPOSER +If you installed color field via [Composer](https://getcomposer.org), the +packages will have been suggested but not automatically installed. If you have +Asset Packagist already configured - as most Commerce users will - skip to just +requiring the desired package(s). +```bash +composer require bower-asset/jquery-simple-color bower-asset/spectrum +``` + +Otherwise, to install them you will need to add +[Asset Packagist](https://asset-packagist.org) to your composer.json and +do some and make a couple other changes to your `composer.json`. Specifically, +in the `extra` key add/adjust current values: +```json +"installer-types": [ + "npm-asset", + "bower-asset" +], +"installer-paths": { + "web/core": [ + "type:drupal-core" + ], + "web/libraries/{$name}": [ + "type:bower-asset", + "type:npm-asset", + "type:drupal-library" + ], + "web/modules/contrib/{$name}": [ + "type:drupal-module" + ], + "web/profiles/contrib/{$name}": [ + "type:drupal-profile" + ], + "web/themes/contrib/{$name}": [ + "type:drupal-theme" + ], + "drush/contrib/{$name}": [ + "type:drupal-drush" + ] +}, +``` + +then run +```bash +composer require oomphinc/composer-installers-extender +composer require bower-asset/jquery-simple-color bower-asset/spectrum +``` + +#### MANUAL +If you are not using Composer, you will need to manually install them. + +- [jQuery Simple Color](https://github.com/recurser/jquery-simple-color) +copy to `/libraries/jquery-simple-color` so that `jquery.simple-color.min.js` +is in that folder. Required for the Color Grid widget. +- [Spectrum](https://github.com/bgrins/spectrum) copy to `/libraries/spectrum` +so that `spectrum.js` exists in that folder. Required for the Spectrum widget. + +## USAGE + +Field +1. Add the field to an node/entity +2. Select the 'Color Field' field type +3. Select the 'Color' widget you want + +## CREDIT + +Original Creator: [targoo](https://www.drupal.org/u/targoo). + +Maintainers: + - [targoo](https://www.drupal.org/u/targoo) + - [Nick Wilde](https://www.drupal.org/u/nickwilde) + +Original development sponsored by Marique Calcus and written by Calcus David. +For professional support and development services contact targoo@gmail.com. + +## More info + +http://www.w3.org/TR/css3-color/#color +https://github.com/mikeemoo/ColorJizz-PHP +http://www.colorhexa.com/ff0000 +https://github.com/PrimalPHP/Color/blob/master/lib/Primal/Color/Parser.php +https://github.com/matthewbaggett/php-color/blob/master/Color.php diff --git a/sites/all/modules/contrib/fields/color_field/README.txt b/sites/all/modules/contrib/fields/color_field/README.txt deleted file mode 100644 index 8eb1cfe68..000000000 --- a/sites/all/modules/contrib/fields/color_field/README.txt +++ /dev/null @@ -1,66 +0,0 @@ ------------------------------------------------------------------------------ -CURRENT FEATURES ------------------------------------------------------------------------------ -Formatter - - Plain text HEX code (#FFFFFF) - Css Declaration (color/background-color) - -Widget - - Plain Text - Pre-selected Color Boxes - Simple Query Color - (http://recursive-design.com/projects/jquery-simple-color/) - ------------------------------------------------------------------------------ -ROAD MAP ------------------------------------------------------------------------------ -1) Make this module a base that could be used by any color picker. -2) include http://www.eyecon.ro/colorpicker/ -3) include http://www.dematte.at/colorPicker/ -4) include http://acko.net/blog/farbtastic-jquery-color-picker-plug-in/ ------------------------------------------------------------------------------ -REQUIREMENTS ------------------------------------------------------------------------------ -No specific requirement - ------------------------------------------------------------------------------ -INSTALLATION ------------------------------------------------------------------------------ -To use this module, simply enable it. - ------------------------------------------------------------------------------ -INSTALLATION - jQuery simple color ------------------------------------------------------------------------------ -If you want to use the jquery simple color plugin you need to download it and -place it in your libraries folder (this will usually be "sites/all/libraries/"). -You can download the plugin by using the following links or by Drush. - - http://recursive-design.com/projects/jquery-simple-color/ - https://github.com/recurser/jquery-simple-color - ------------------------------------------------------------------------------ -USAGE ------------------------------------------------------------------------------ -Field -1. Add the field to an node/entity -2. Select the 'Color Field' field type -3. Select the 'Color' widget you want - ------------------------------------------------------------------------------ -CREDIT ------------------------------------------------------------------------------ -Maintainer and developer: targoo - -Development sponsored by Marique Calcus and written by Calcus David. -For professional support and development services contact targoo@gmail.com. - ------------------------------------------------------------------------------ -More info ------------------------------------------------------------------------------ -http://www.w3.org/TR/css3-color/#color -https://github.com/mikeemoo/ColorJizz-PHP -http://www.colorhexa.com/ff0000 -https://github.com/PrimalPHP/Color/blob/master/lib/Primal/Color/Parser.php -https://github.com/matthewbaggett/php-color/blob/master/Color.php diff --git a/sites/all/modules/contrib/fields/color_field/color_field-2854199-7.patch b/sites/all/modules/contrib/fields/color_field/color_field-2854199-7.patch deleted file mode 100644 index 693d46df5..000000000 --- a/sites/all/modules/contrib/fields/color_field/color_field-2854199-7.patch +++ /dev/null @@ -1,26 +0,0 @@ -From ef19dd13dceeb972e9b0fe1920d846901a076dd4 Mon Sep 17 00:00:00 2001 -From: kristiaanvandeneynde -Date: Thu, 26 Oct 2017 14:24:28 +0200 -Subject: [PATCH] Issue #2854199 by pclaitte, kristiaanvandeneynde: Color Boxes - Widget default values doesn't works - ---- - src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php | 2 +- - 1 file changed, 1 insertion(+), 1 deletion(-) - -diff --git a/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php b/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php -index 8268704..ad05958 100644 ---- a/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php -+++ b/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php -@@ -96,7 +96,7 @@ class ColorFieldWidgetBox extends WidgetBase { - $default_colors = $this->getSetting('default_colors'); - preg_match_all("/#[0-9a-fA-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER); - foreach ($default_colors as $color) { -- $settings['palette'][] = $color[0]; -+ $settings['default_colors'][] = $color[0]; - } - $element['#attached']['drupalSettings']['color_field']['color_field_widget_box']['settings'] = $settings; - --- -2.4.9 (Apple Git-60) - diff --git a/sites/all/modules/contrib/fields/color_field/color_field.info.yml b/sites/all/modules/contrib/fields/color_field/color_field.info.yml index 43412fc52..efecbf13c 100644 --- a/sites/all/modules/contrib/fields/color_field/color_field.info.yml +++ b/sites/all/modules/contrib/fields/color_field/color_field.info.yml @@ -4,10 +4,12 @@ description: 'Provides a color field type to store the color value and opacity' # core: 8.x package: Field types dependencies: - - field + - drupal:field +test_dependencies: + - token:token -# Information added by Drupal.org packaging script on 2017-04-13 -version: '8.x-2.0-rc1+11-dev' +# Information added by Drupal.org packaging script on 2018-09-05 +version: '8.x-2.0' core: '8.x' project: 'color_field' -datestamp: 1492097733 +datestamp: 1536168814 diff --git a/sites/all/modules/contrib/fields/color_field/color_field.install b/sites/all/modules/contrib/fields/color_field/color_field.install new file mode 100644 index 000000000..612349e0f --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/color_field.install @@ -0,0 +1,53 @@ + t('Color Field library: jQuery Simple Color'), + 'value' => t('Missing'), + 'description' => t('Download the jQuery Simple Color library and copy it to :library', [ + ':url' => 'https://github.com/recurser/jquery-simple-color', + ':library' => DRUPAL_ROOT . '/libraries/jquery-simple-color/', + ]), + 'severity' => REQUIREMENT_WARNING, + ]; + } + else { + $requirements['color_field_simple'] = [ + 'title' => t('Color Field library: jQuery Simple Color'), + 'value' => t('Installed'), + 'severity' => REQUIREMENT_OK, + ]; + } + if (!file_exists(DRUPAL_ROOT . '/libraries/spectrum/spectrum.js')) { + $requirements['color_field_spectrum'] = [ + 'title' => t('Color Field library: Spectrum'), + 'value' => t('Missing'), + 'description' => t('Download the Spectrum library and copy it to :library', [ + ':url' => 'https://github.com/bgrins/spectrum', + ':library' => DRUPAL_ROOT . '/libraries/spectrum/', + ]), + 'severity' => REQUIREMENT_WARNING, + ]; + } + else { + $requirements['color_field_spectrum'] = [ + 'title' => t('Color Field library: Spectrum'), + 'value' => t('Installed'), + 'severity' => REQUIREMENT_OK, + ]; + } + } + + return $requirements; +} diff --git a/sites/all/modules/contrib/fields/color_field/color_field.module b/sites/all/modules/contrib/fields/color_field/color_field.module index 160606ccf..21068cc35 100644 --- a/sites/all/modules/contrib/fields/color_field/color_field.module +++ b/sites/all/modules/contrib/fields/color_field/color_field.module @@ -1,4 +1,5 @@ ' . t('About') . ''; - $output .= '

' . t('Color Field is simple field that use a hexadecimal notation (HEX) for the combination of Red, Green, and Blue color values (RGB). See the Field module help and the Field UI help pages for general information on fields and how to create and manage them. For more information, see the online documentation for the Link module.', array('!field' => Url::fromRoute('help.page', array('name' => 'field')), '!field_ui' => Url::fromRoute('help.page', array('name' => 'field_ui')), '!link_documentation' => 'https://drupal.org/documentation/modules/link')) . '

'; + $output .= '

' . t('Color Field is simple field that use a hexadecimal notation (HEX) for the combination of Red, Green, and Blue color values (RGB). See the Field module help and the Field UI help pages for general information on fields and how to create and manage them. For more information, see the online documentation for the Link module.', [ + '!field' => Url::fromRoute('help.page', ['name' => 'field']), + '!field_ui' => Url::fromRoute('help.page', ['name' => 'field_ui']), + '!link_documentation' => 'https://drupal.org/documentation/modules/link', + ]) . '

'; $output .= '

' . t('Uses') . '

'; $output .= '
'; $output .= '
' . t('Managing and displaying color fields') . '
'; - $output .= '
' . t('The settings and the display of the link field can be configured separately. See the Field UI help for more information on how to manage fields and their display.', array('!field_ui' => Url::fromRoute('help.page', array('name' => 'field_ui')))) . '
'; + $output .= '
' . t('The settings and the display of the link field can be configured separately. See the Field UI help for more information on how to manage fields and their display.', ['!field_ui' => Url::fromRoute('help.page', ['name' => 'field_ui'])]) . '
'; $output .= '
' . t('Adding link text') . '
'; $output .= '
' . t('In the field settings you can define additional link text to be optional or required in any link field.') . '
'; $output .= '
' . t('Displaying link text') . '
'; @@ -39,22 +44,14 @@ function color_field_help($route_name, RouteMatchInterface $route_match) { function color_field_theme() { $theme = []; - $theme['color_field_formatter_swatch'] = array( - 'variables' => array( - 'shape' => NULL, - 'color' => NULL, - 'width' => NULL, - 'height' => NULL, - ), - ); - - $theme['color_field_widget_box'] = array( - 'render element' => 'element', - ); - - $theme['color_field_widget_spectrum'] = array( - 'render element' => 'element', - ); + $theme['color_field_formatter_swatch'] = [ + 'variables' => [ + 'shape' => NULL, + 'color' => NULL, + 'width' => NULL, + 'height' => NULL, + ], + ]; return $theme; } @@ -73,88 +70,5 @@ function color_field_theme() { * - width: The width of the color swatch. * - height: The height of the color swatch. */ -function template_preprocess_color_field_formatter_swatch(&$variables) { -} - - -/** - * Prepares variables for color_field widget box wrapper template. - * - * Default template: color-field-widget-box.html.twig. - * - * @param array $variables - * An associative array containing: - * - element: An associative array containing the properties of the element. - * Properties used: #title, #children, #required, #attributes. - */ -function template_preprocess_color_field_widget_box(&$variables) { - $element = $variables['element']; - - if (!empty($element['#title'])) { - $variables['title'] = $element['#title']; - } - - if (!empty($element['#description'])) { - $variables['description'] = $element['#description']; - } - - $variables['color'] = $element['color']; - - if (!empty($element['opacity'])) { - $variables['opacity'] = $element['opacity']; - } - - // Suppress error messages. - $variables['errors'] = NULL; - - if (!empty($element['#description'])) { - $variables['description'] = $element['#description']; - } - - $variables['required'] = FALSE; - if (!empty($element['#required'])) { - $variables['required'] = TRUE; - } - -} - -/** - * Prepares variables for color_field widget box wrapper template. - * - * Default template: color-field-widget-box.html.twig. - * - * @param array $variables - * An associative array containing: - * - element: An associative array containing the properties of the element. - * Properties used: #title, #children, #required, #attributes. - */ -function template_preprocess_color_field_widget_spectrum(&$variables) { - $element = $variables['element']; - - if (!empty($element['#title'])) { - $variables['title'] = $element['#title']; - } - - if (!empty($element['#description'])) { - $variables['description'] = $element['#description']; - } - - $variables['color'] = $element['color']; - - if (!empty($element['opacity'])) { - $variables['opacity'] = $element['opacity']; - } - - // Suppress error messages. - $variables['errors'] = NULL; - - if (!empty($element['#description'])) { - $variables['description'] = $element['#description']; - } - - $variables['required'] = FALSE; - if (!empty($element['#required'])) { - $variables['required'] = TRUE; - } - +function template_preprocess_color_field_formatter_swatch(array &$variables) { } diff --git a/sites/all/modules/contrib/fields/color_field/color_field.post_update.php b/sites/all/modules/contrib/fields/color_field/color_field.post_update.php new file mode 100644 index 000000000..fc0b8d9fc --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/color_field.post_update.php @@ -0,0 +1,37 @@ +getComponents() as $name => $options) { + if (isset($options['type']) && $options['type'] === 'color_field_widget_spectrum') { + if ($options['settings']['palette']) { + $palette = explode(',', $options['settings']['palette']); + foreach ($palette as &$color) { + $color = '"' . trim($color) . '"'; + } + $options['settings']['palette'] = '[' . implode(',', $palette) . ']'; + $entity_form_display->setComponent($name, $options); + $changed = TRUE; + } + } + } + + if ($changed) { + $entity_form_display->save(); + } + } + + return t('The new palette format for spectrum color field widgets has been applied.'); +} diff --git a/sites/all/modules/contrib/fields/color_field/composer.json b/sites/all/modules/contrib/fields/color_field/composer.json new file mode 100644 index 000000000..ff155f4ba --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/composer.json @@ -0,0 +1,36 @@ +{ + "name": "drupal/color_field", + "require": { + "drupal/core": "*" + }, + "require-dev": { + "drupal/token": "~1.3" + }, + "suggest": { + "bower-asset/jquery-simple-color": "^v1.2.2: Provides JavaScript library necessary for the Color Grid widget", + "bower-asset/spectrum": "^1.8: Provides JavaScript library necessary for Spectrum widget." + }, + "type": "drupal-module", + "notification-url": "https://packages.drupal.org/8/downloads", + "license": [ + "GPL-2.0-or-later" + ], + "authors": [ + { + "name": "targoo", + "homepage": "https://www.drupal.org/user/431910", + "role": "Maintainer" + }, + { + "name": "Nick Wilde", + "homepage": "https://www.drupal.org/user/nickwilde", + "role": "Maintainer" + } + ], + "description": "Provides a color field type to store the color value and opacity", + "homepage": "https://www.drupal.org/project/color_field", + "support": { + "issues": "https://www.drupal.org/project/issues/color_field?version=8.x", + "source": "http://cgit.drupalcode.org/color_field" + } +} diff --git a/sites/all/modules/contrib/fields/color_field/config/schema/color_field.schema.yml b/sites/all/modules/contrib/fields/color_field/config/schema/color_field.schema.yml index a72261134..b5f3068da 100755 --- a/sites/all/modules/contrib/fields/color_field/config/schema/color_field.schema.yml +++ b/sites/all/modules/contrib/fields/color_field/config/schema/color_field.schema.yml @@ -1,5 +1,29 @@ # Schema for the configuration files of the color field module. +field.storage_settings.color_field_type: + type: mapping + mapping: + format: + type: label + label: 'Format' + +field.field_settings.color_field_type: + type: mapping + mapping: + opacity: + type: integer + label: 'Display opacity' + +field.value.color_field_type: + type: mapping + mapping: + color: + type: string + label: 'The hex color code' + opacity: + type: float + label: 'The opacity' + field.formatter.settings.color_field_formatter_text: type: mapping label: 'Color text format settings' diff --git a/sites/all/modules/contrib/fields/color_field/css/color_field_formatter_swatch.css b/sites/all/modules/contrib/fields/color_field/css/color_field_formatter_swatch.css index d66866d16..23003e29d 100644 --- a/sites/all/modules/contrib/fields/color_field/css/color_field_formatter_swatch.css +++ b/sites/all/modules/contrib/fields/color_field/css/color_field_formatter_swatch.css @@ -1,7 +1,7 @@ -.color_field {} -.color_field__swatch {} -.color_field__swatch--square { +.color_field__swatch { + display: inline-block; } + .color_field__swatch--circle { -moz-border-radius: 50%; -webkit-border-radius: 50%; @@ -12,4 +12,5 @@ -webkit-transform: skew(20deg); -moz-transform: skew(20deg); -o-transform: skew(20deg); + transform: skew(20deg); } diff --git a/sites/all/modules/contrib/fields/color_field/css/color_field_widget_box.css b/sites/all/modules/contrib/fields/color_field/css/color_field_widget_box.css index d224c0d82..54dd8219f 100644 --- a/sites/all/modules/contrib/fields/color_field/css/color_field_widget_box.css +++ b/sites/all/modules/contrib/fields/color_field/css/color_field_widget_box.css @@ -1,32 +1,30 @@ -.color_field_widget_box { -} - .color_field_widget_box__square { - border: 1px solid #ffffff; - cursor: pointer; - font-family: monospace; - font-size: 1.2em; - margin: 0 3px; - padding: 1px 8px; + border: 1px solid #000; + box-shadow: 0 0 1px #000; + height: 16px; + margin: 2px; + width: 16px; } .color_field_widget_box__square.active, .color_field_widget_box__square:hover { - padding: 9px 16px; + height: 32px; + width: 32px; } .color_field_widget_box__square--transparent { background-image: url("../images/transparent_box16.gif"); - background-position: 0 3px; background-repeat: no-repeat; - margin: 0 3px; - padding: 2px 8px; + border: 1px solid #000; + box-shadow: 0 0 1px #000; + height: 16px; + margin: 2px; + width: 16px; } .color_field_widget_box__square--transparent.active, .color_field_widget_box__square--transparent:hover { background-image: url(../images/transparent_box32.gif); - background-position: 0 3px; - background-repeat: no-repeat; - padding: 10px 16px; + height: 32px; + width: 32px; } diff --git a/sites/all/modules/contrib/fields/color_field/css/color_field_widget_grid.css b/sites/all/modules/contrib/fields/color_field/css/color_field_widget_grid.css index 1f1acb56e..1aaffd6ce 100644 --- a/sites/all/modules/contrib/fields/color_field/css/color_field_widget_grid.css +++ b/sites/all/modules/contrib/fields/color_field/css/color_field_widget_grid.css @@ -1,12 +1,4 @@ -.simpleColorDisplay { - float: left; -} - -.simpleColorContainer { - float: left; -} - .simpleColorChooser { z-index: 1; + max-width: 100%; } - diff --git a/sites/all/modules/contrib/fields/color_field/drupalci.yml b/sites/all/modules/contrib/fields/color_field/drupalci.yml new file mode 100644 index 000000000..a6cbfc4fe --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/drupalci.yml @@ -0,0 +1,50 @@ +build: + assessment: + validate_codebase: + phplint: { } + container_composer: { } + container_command: + commands: + - cd ${SOURCE_DIR} + - sudo -u www-data composer config repositories.asset {"composer","https://asset-packagist.org"} + - sudo -u www-data composer config extra.installer-types.0 "npm-asset" + - sudo -u www-data composer config extra.installer-types.1 "bower-asset" + - sudo -u www-data composer config extra.installer-paths.libraries\/\{\$name\} "[type:bower-asset]" + - sudo -u www-data sed -i 's/"\[type:bower-asset\]"/\["type:bower-asset"\]/' composer.json + - sudo -u www-data composer require "oomphinc/composer-installers-extender:^1.1" + - sudo -u www-data composer require "bower-asset/spectrum:^1.8" "bower-asset/jquery-simple-color:^v1.2.2" + - dir libraries + csslint: + halt-on-fail: false + eslint: + halt-on-fail: false + phpcs: + sniff-all-files: false + halt-on-fail: false + coder-version: ^8.2@stable + testing: + run_tests.standard: + types: 'Simpletest,PHPUnit-Unit,PHPUnit-Kernel,PHPUnit-Functional' + testgroups: '--all' + color: true + die-on-fail: false + keep-results: true + keep-results-table: false + verbose: false + concurrency: 0 + halt-on-fail: false + repeat: 1 + suppress-deprecations: true + run_tests.js: + concurrency: 1 + types: PHPUnit-FunctionalJavascript + testgroups: '--all' + color: true + die-on-fail: false + keep-results: true + keep-results-table: false + verbose: false + halt-on-fail: false + repeat: 1 + suppress-deprecations: true + nightwatchjs: { } diff --git a/sites/all/modules/contrib/fields/color_field/js/color_field_widget_box.jquery.js b/sites/all/modules/contrib/fields/color_field/js/color_field_widget_box.jquery.js index 23bef75a4..148f80a5c 100644 --- a/sites/all/modules/contrib/fields/color_field/js/color_field_widget_box.jquery.js +++ b/sites/all/modules/contrib/fields/color_field/js/color_field_widget_box.jquery.js @@ -20,17 +20,19 @@ var $context = $(context); - var default_colors = settings.color_field.color_field_widget_box.settings.default_colors; - $context.find('.color-field-widget-box-form').each(function (index, element) { var $element = $(element); var $input = $element.prev().find('input'); + $input.hide(); + var props = settings.color_field.color_field_widget_box.settings[$element.prop('id')]; + $element.empty().addColorPicker({ currentColor: $input.val(), - colors: default_colors, + colors: props.palette, blotchClass:'color_field_widget_box__square', blotchTransparentClass:'color_field_widget_box__square--transparent', - clickCallback: function(color) { + addTransparentBlotch: !props.required, + clickCallback: function (color) { $input.val(color).trigger('change'); } }); diff --git a/sites/all/modules/contrib/fields/color_field/js/color_field_widget_box.js b/sites/all/modules/contrib/fields/color_field/js/color_field_widget_box.js index 583999320..ea6b70d12 100644 --- a/sites/all/modules/contrib/fields/color_field/js/color_field_widget_box.js +++ b/sites/all/modules/contrib/fields/color_field/js/color_field_widget_box.js @@ -1,16 +1,25 @@ /** - * Color Field jQuery + * @file + * Color Field jQuery. */ + (function ($) { + jQuery.fn.addColorPicker = function (props) { - if (!props) { props = []; } + + 'use strict'; + + if (!props) { + props = []; + } props = jQuery.extend({ currentColor:'', - blotchElemType: 'span', + blotchElemType: 'button', blotchClass:'colorBox', blotchTransparentClass:'transparentBox', - clickCallback: function(ignoredColor) {}, + addTransparentBlotch: true, + clickCallback: function (ignoredColor) {}, iterationCallback: null, fillString: ' ', fillStringX: '?', @@ -23,20 +32,20 @@ jQuery.fn.addColorPicker = function (props) { ] }, props); - var count = props.colors.length; - for (var i = 0; i < count; ++i) { - var color = props.colors[i]; + this.addBlotchElement = function(color, blotchClass) { var elem = jQuery('<' + props.blotchElemType + '/>') - .addClass(props.blotchClass) + .addClass(blotchClass) .attr('color',color) + .attr('title', color) .css('background-color',color); - // jq bug: chaining here fails if color is null b/c .css() returns (new String('transparent'))! + // Jq bug: chaining here fails if color is null b/c .css() returns (new String('transparent'))! if (props.currentColor == color) { elem.addClass('active'); } if (props.clickCallback) { - elem.click(function() { - jQuery(this).parent().children('.' + props.blotchClass).removeClass('active'); + elem.click(function (event) { + event.preventDefault(); + jQuery(this).parent().children().removeClass('active'); jQuery(this).addClass('active'); props.clickCallback(jQuery(this).attr('color')); }); @@ -47,25 +56,13 @@ jQuery.fn.addColorPicker = function (props) { } } - var elem = jQuery('<' + props.blotchElemType + '/>') - .addClass(props.blotchTransparentClass) - .attr('color', '') - .css('background-color', ''); - - if (props.currentColor == '') { - elem.addClass('active'); + for (var i = 0; i < props.colors.length; ++i) { + var color = props.colors[i]; + this.addBlotchElement(color, props.blotchClass); } - if (props.clickCallback) { - elem.click(function() { - jQuery(this).parent().children('.' + props.blotchClass).removeClass('active'); - jQuery(this).addClass('active'); - props.clickCallback(jQuery(this).attr('color')); - }); - } - this.append(elem); - if (props.iterationCallback) { - props.iterationCallback(this, elem, color, i); + if (props.addTransparentBlotch) { + this.addBlotchElement('', props.blotchTransparentClass); } return this; diff --git a/sites/all/modules/contrib/fields/color_field/js/color_field_widget_grid.jquery.js b/sites/all/modules/contrib/fields/color_field/js/color_field_widget_grid.jquery.js index 6421572a1..a7bf70000 100644 --- a/sites/all/modules/contrib/fields/color_field/js/color_field_widget_grid.jquery.js +++ b/sites/all/modules/contrib/fields/color_field/js/color_field_widget_grid.jquery.js @@ -2,6 +2,7 @@ * @file * Javascript for Color Field. */ + (function ($, Drupal) { 'use strict'; @@ -17,19 +18,18 @@ Drupal.behaviors.color_field_jquery_simple_color = { attach: function (context, settings) { var $context = $(context); - var settings = settings.color_field.color_field_widget_grid; $context.find('.js-color-field-widget-grid__color').each(function (index, element) { var $element = $(element); + var widgetSettings = settings.color_field.color_field_widget_grid[$(this).attr('id')]; $element.simpleColor({ - cellWidth: settings.cell_width, - cellHeight: settings.cell_height, - cellMargin: settings.cell_margin, - boxWidth: settings.box_width, - boxHeight: settings.box_height + cellWidth: widgetSettings.cell_width, + cellHeight: widgetSettings.cell_height, + cellMargin: widgetSettings.cell_margin, + boxWidth: widgetSettings.box_width, + boxHeight: widgetSettings.box_height }); - }); } diff --git a/sites/all/modules/contrib/fields/color_field/js/color_field_widget_spectrum.jquery.js b/sites/all/modules/contrib/fields/color_field/js/color_field_widget_spectrum.jquery.js index 335103e0f..66b2e2083 100644 --- a/sites/all/modules/contrib/fields/color_field/js/color_field_widget_spectrum.jquery.js +++ b/sites/all/modules/contrib/fields/color_field/js/color_field_widget_spectrum.jquery.js @@ -2,6 +2,7 @@ * @file * Javascript for Color Field. */ + (function ($, Drupal) { 'use strict'; @@ -19,12 +20,18 @@ var $context = $(context); - var spectrum_settings = settings.color_field.color_field_widget_spectrum; $context.find('.js-color-field-widget-spectrum').each(function (index, element) { var $element = $(element); var $element_color = $element.find('.js-color-field-widget-spectrum__color'); var $element_opacity = $element.find('.js-color-field-widget-spectrum__opacity'); + var spectrum_settings = settings.color_field.color_field_widget_spectrum[$element.attr('id')]; + + // Hide the widget labels if the widgets are being shown. + if (!spectrum_settings.show_input) { + $('.js-color-field-widget-spectrum').find('label').hide(); + $element_opacity.hide(); + } $element_color.spectrum({ showInitial: true, @@ -32,14 +39,22 @@ showInput: spectrum_settings.show_input, showAlpha: spectrum_settings.show_alpha, showPalette: spectrum_settings.show_palette, - showPaletteOnly: !!spectrum_settings.show_palette_only, - palette: [spectrum_settings.palette], + showPaletteOnly: spectrum_settings.show_palette_only, + palette: JSON.parse('[' + spectrum_settings.palette + ']'), showButtons: spectrum_settings.show_buttons, allowEmpty: spectrum_settings.allow_empty, change: function(tinycolor) { - $element_color.val(tinycolor.toHexString()); - $element_opacity.val(tinycolor._roundA); + var hexColor = ''; + var opacity = ''; + + if (tinycolor) { + hexColor = tinycolor.toHexString(); + opacity = tinycolor._roundA; + } + + $element_color.val(hexColor); + $element_opacity.val(opacity); } }); diff --git a/sites/all/modules/contrib/fields/color_field/src/ColorBase.php b/sites/all/modules/contrib/fields/color_field/src/ColorBase.php index badf46729..0739dda95 100644 --- a/sites/all/modules/contrib/fields/color_field/src/ColorBase.php +++ b/sites/all/modules/contrib/fields/color_field/src/ColorBase.php @@ -2,58 +2,36 @@ namespace Drupal\color_field; +/** + * Base color class to ease implementations. + */ abstract class ColorBase implements ColorInterface { /** - * @var + * The opacity of the color. + * + * @var float */ protected $opacity; /** - * Convert the color to Hex format - * - * @return ColorHex - * The color in Hex format. - */ - abstract function toHex(); - - /** - * Convert the color to RGB format - * - * @return ColorRGB - * The color in RGB format. - */ - abstract function toRGB(); - - /** - * Convert the color to a string format - * - * @return String - * The color in string format. - */ - abstract function toString(); - - /** - * Get the opacity + * Get the opacity. * * @return float - * The opacity value between 0 and 1. + * The opacity value between 0 and 1. */ public function getOpacity() { - return $this->opacity;; + return $this->opacity; } /** - * Set the opacity - * - * @return float - * The opacity value between 0 and 1. + * Set the opacity. */ public function setOpacity($opacity) { $this->opacity = $opacity; } - static $patterns = array( + public static $patterns = [ 'cmyk' => '/^(?:device-)?cmyk\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d+(?:\.\d+)?|\.\d+)\s*\)/', 'rgba' => '/^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d+(?:\.\d+)?|\.\d+)\s*\)/', 'rgb' => '/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/', @@ -62,10 +40,10 @@ abstract class ColorBase implements ColorInterface { 'hsva' => '/^hsva\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%,\s*(\d+(?:\.\d+)?|\.\d+)\s*\)$/', 'hsv' => '/^hsv\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/', 'hex6' => '/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/', - 'hex3' => '/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/' - ); + 'hex3' => '/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/', + ]; - static $named_colors = array( + public static $namedColors = [ "aliceblue" => "f0f8ff", "antiquewhite" => "faebd7", "aqua" => "00ffff", @@ -208,7 +186,7 @@ abstract class ColorBase implements ColorInterface { "white" => "ffffff", "whitesmoke" => "f5f5f5", "yellow" => "ffff00", - "yellowgreen" => "9acd32" - ); + "yellowgreen" => "9acd32", + ]; } diff --git a/sites/all/modules/contrib/fields/color_field/src/ColorCMY.php b/sites/all/modules/contrib/fields/color_field/src/ColorCMY.php index 796952bf3..6c0d39a33 100644 --- a/sites/all/modules/contrib/fields/color_field/src/ColorCMY.php +++ b/sites/all/modules/contrib/fields/color_field/src/ColorCMY.php @@ -8,34 +8,37 @@ namespace Drupal\color_field; class ColorCMY extends ColorBase { /** - * The cyan + * The cyan. + * * @var float */ private $cyan; /** - * The magenta + * The magenta. + * * @var float */ private $magenta; /** - * The yellow + * The yellow. + * * @var float */ private $yellow; /** - * Create a new CMYK color + * Create a new CMYK color. * * @param float $cyan - * The cyan + * The cyan. * @param float $magenta - * The magenta + * The magenta. * @param float $yellow - * The yellow + * The yellow. * @param float $opacity - * The opacity + * The opacity. */ public function __construct($cyan, $magenta, $yellow, $opacity) { $this->cyan = $cyan; @@ -45,42 +48,46 @@ class ColorCMY extends ColorBase { } /** - * Get the amount of Cyan + * Get the amount of Cyan. * - * @return int The amount of cyan + * @return int + * The amount of cyan. */ public function getCyan() { return $this->cyan; } /** - * Get the amount of Magenta + * Get the amount of Magenta. * - * @return int The amount of magenta + * @return int + * The amount of magenta. */ public function getMagenta() { return $this->magenta; } /** - * Get the amount of Yellow + * Get the amount of Yellow. * - * @return int The amount of yellow + * @return int + * The amount of yellow. */ public function getYellow() { return $this->yellow; } /** - * A string representation of this color in the current format + * A string representation of this color in the current format. * * @param bool $opacity * Whether or not to display the opacity. * * @return string - * The color in format: #RRGGBB + * The color in format: #RRGGBB. */ public function toString($opacity = TRUE) { + return $this->toHex()->toString($opacity); } /** diff --git a/sites/all/modules/contrib/fields/color_field/src/ColorCMYK.php b/sites/all/modules/contrib/fields/color_field/src/ColorCMYK.php index a2e2cbcc6..c35d04e8f 100644 --- a/sites/all/modules/contrib/fields/color_field/src/ColorCMYK.php +++ b/sites/all/modules/contrib/fields/color_field/src/ColorCMYK.php @@ -8,38 +8,46 @@ namespace Drupal\color_field; class ColorCMYK extends ColorBase { /** - * The cyan + * The cyan. + * * @var float */ private $cyan; /** - * The magenta + * The magenta. + * * @var float */ private $magenta; /** - * The yellow + * The yellow. + * * @var float */ private $yellow; /** - * The key (black) + * The key (black). + * * @var float */ private $key; /** - * Create a new CMYK color + * Create a new CMYK color. * - * @param float $cyan The cyan - * @param float $magenta The magenta - * @param float $yellow The yellow - * @param float $key The key (black) + * @param float $cyan + * The cyan. + * @param float $magenta + * The magenta. + * @param float $yellow + * The yellow. + * @param float $key + * The key (black). * @param float $opacity - * The opacity + * The opacity. */ public function __construct($cyan, $magenta, $yellow, $key, $opacity) { $this->cyan = $cyan; @@ -50,51 +58,56 @@ class ColorCMYK extends ColorBase { } /** - * Get the amount of Cyan + * Get the amount of Cyan. * - * @return int The amount of cyan + * @return int + * The amount of cyan. */ public function getCyan() { return $this->cyan; } /** - * Get the amount of Magenta + * Get the amount of Magenta. * - * @return int The amount of magenta + * @return int + * The amount of magenta. */ public function getMagenta() { return $this->magenta; } /** - * Get the amount of Yellow + * Get the amount of Yellow. * - * @return int The amount of yellow + * @return int + * The amount of yellow. */ public function getYellow() { return $this->yellow; } /** - * Get the key (black) + * Get the key (black). * - * @return int The amount of black + * @return int + * The amount of black. */ public function getKey() { return $this->key; } /** - * A string representation of this color in the current format + * A string representation of this color in the current format. * * @param bool $opacity * Whether or not to display the opacity. * * @return string - * The color in format: #RRGGBB + * The color in format: #RRGGBB. */ public function toString($opacity = TRUE) { + return $this->toHex()->toString($opacity); } /** diff --git a/sites/all/modules/contrib/fields/color_field/src/ColorHex.php b/sites/all/modules/contrib/fields/color_field/src/ColorHex.php index b19b911eb..6c8b89194 100644 --- a/sites/all/modules/contrib/fields/color_field/src/ColorHex.php +++ b/sites/all/modules/contrib/fields/color_field/src/ColorHex.php @@ -3,12 +3,13 @@ namespace Drupal\color_field; /** - * Hex represents the Hex color format + * Hex represents the Hex color format. */ class ColorHex extends ColorBase { /** * The Hex triplet of the color. + * * @var int */ private $color; @@ -20,8 +21,7 @@ class ColorHex extends ColorBase { * The string hex value (i.e. "FFFFFF"). * @param string $opacity * The opacity value. - * @return ColorHex - * The ColorHex object. + * * @throws Exception */ public function __construct($color, $opacity) { @@ -46,13 +46,13 @@ class ColorHex extends ColorBase { } /** - * A string representation of this color in the current format + * A string representation of this color in the current format. * * @param bool $opacity * Whether or not to display the opacity. * * @return string - * The color in format: #RRGGBB + * The color in format: #RRGGBB. */ public function toString($opacity = TRUE) { $rgb = $this->toRGB(); diff --git a/sites/all/modules/contrib/fields/color_field/src/ColorInterface.php b/sites/all/modules/contrib/fields/color_field/src/ColorInterface.php index c7d755f2c..b84516983 100644 --- a/sites/all/modules/contrib/fields/color_field/src/ColorInterface.php +++ b/sites/all/modules/contrib/fields/color_field/src/ColorInterface.php @@ -7,20 +7,33 @@ namespace Drupal\color_field; */ interface ColorInterface { + /** + * Get the color as a string. + * + * @return string + * The color as a string. + */ public function toString(); + /** + * Get the color as a hex instance. + * + * @return \Drupal\color_field\ColorHex + * The color as a hex instance. + */ public function toHex(); + /** + * Get the color as a RGB instance. + * + * @return \Drupal\color_field\ColorRGB + * The color as a RGB instance. + */ public function toRGB(); - //public function toHSV(); - - //public function toHSL(); - - //public function toRGB(); - - //public function toCMYK(); - - //public function toCSS(); - + // Public function toHSV(); + // public function toHSL(); + // public function toRGB(); + // public function toCMYK(); + // public function toCSS(); } diff --git a/sites/all/modules/contrib/fields/color_field/src/ColorRGB.php b/sites/all/modules/contrib/fields/color_field/src/ColorRGB.php index 77d138ef5..ec7ae7a57 100644 --- a/sites/all/modules/contrib/fields/color_field/src/ColorRGB.php +++ b/sites/all/modules/contrib/fields/color_field/src/ColorRGB.php @@ -3,30 +3,33 @@ namespace Drupal\color_field; /** - * RGB represents the RGB color format + * RGB represents the RGB color format. */ class ColorRGB extends ColorBase { /** - * The red value (0-255) + * The red value (0-255). + * * @var float */ private $red; /** - * The green value (0-255) + * The green value (0-255). + * * @var float */ private $green; /** - * The blue value (0-255) + * The blue value (0-255). + * * @var float */ private $blue; /** - * Create a new RGB color + * Create a new RGB color. * * @param int $red * The red (0-255) @@ -35,7 +38,7 @@ class ColorRGB extends ColorBase { * @param int $blue * The blue (0-255) * @param float $opacity - * The opacity + * The opacity. * * @throws Exception */ @@ -58,34 +61,37 @@ class ColorRGB extends ColorBase { } /** - * Get the red value (rounded) + * Get the red value (rounded). * - * @return int The red value + * @return int + * The red value */ public function getRed() { return (0.5 + $this->red) | 0; } /** - * Get the green value (rounded) + * Get the green value (rounded). * - * @return int The green value + * @return int + * The green value */ public function getGreen() { return (0.5 + $this->green) | 0; } /** - * Get the blue value (rounded) + * Get the blue value (rounded). * - * @return int The blue value + * @return int + * The blue value */ public function getBlue() { return (0.5 + $this->blue) | 0; } /** - * A string representation of this color in the current format + * A string representation of this color in the current format. * * @param bool $opacity * Whether or not to display the opacity. diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterCss.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterCss.php index 585b192ca..a5c9d556a 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterCss.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterCss.php @@ -1,17 +1,16 @@ tokenService = $token_service; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + // @see \Drupal\Core\Field\FormatterPluginManager::createInstance(). + return new static( + $plugin_id, + $plugin_definition, + $configuration['field_definition'], + $configuration['settings'], + $configuration['label'], + $configuration['view_mode'], + $configuration['third_party_settings'], + $container->get('token') + ); + } /** * {@inheritdoc} */ public static function defaultSettings() { - return array( + return [ 'selector' => 'body', 'property' => 'background-color', 'important' => TRUE, 'opacity' => TRUE, - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { - $opacity = $this->getFieldSetting('opacity'); - $elements = []; - $elements['selector'] = array( - '#title' => t('Selector'), - '#description' => t('A valid CSS selector such as .links > li > a, #logo.'), + $elements['selector'] = [ + '#title' => $this->t('Selector'), + '#description' => $this->t('A valid CSS selector such as .links > li > a, #logo.'), '#type' => 'textarea', '#rows' => '1', '#default_value' => $this->getSetting('selector'), '#required' => TRUE, '#placeholder' => 'body > div > a', - ); - //$element['token'] = array( - // '#theme' => 'token_tree', - // '#token_types' => array($instance['entity_type']), - // '#dialog' => TRUE, - //); - $elements['property'] = array( - '#title' => t('Property'), - '#description' => t(''), + ]; + $elements['token_help'] = [ + '#theme' => 'token_tree_link', + '#token_types' => [$this->fieldDefinition->getTargetEntityTypeId()], + ]; + $elements['property'] = [ + '#title' => $this->t('Property'), '#type' => 'select', '#default_value' => $this->getSetting('property'), '#required' => TRUE, - '#options' => array( - 'background-color' => t('Background color'), - 'color' => t('Text color'), - ), - ); - $elements['important'] = array( - '#title' => t('Important'), - '#description' => t('Whenever this declaration is more important than others.'), + '#options' => [ + 'background-color' => $this->t('Background color'), + 'color' => $this->t('Text color'), + ], + ]; + $elements['important'] = [ + '#title' => $this->t('Important'), + '#description' => $this->t('Whenever this declaration is more important than others.'), '#type' => 'checkbox', '#default_value' => $this->getSetting('important'), - ); + ]; - if ($opacity) { - $elements['opacity'] = array( + if ($this->getFieldSetting('opacity')) { + $elements['opacity'] = [ '#type' => 'checkbox', - '#title' => t('Display opacity'), + '#title' => $this->t('Display opacity'), '#default_value' => $this->getSetting('opacity'), - ); + ]; } return $elements; @@ -99,12 +142,18 @@ class ColorFieldFormatterCss extends FormatterBase { $summary = []; - $summary[] = t('CSS selector : @css_selector', array('@css_selector' => $settings['selector'])); - $summary[] = t('CSS property : @css_property', array('@css_property' => $settings['property'])); - $summary[] = t('!important declaration : @important_declaration', array('@important_declaration' => (($settings['important']) ? t('Yes') : t('No')))); + $summary[] = $this->t('CSS selector : @css_selector', [ + '@css_selector' => $settings['selector'], + ]); + $summary[] = $this->t('CSS property : @css_property', [ + '@css_property' => $settings['property'], + ]); + $summary[] = $this->t('!important declaration : @important_declaration', [ + '@important_declaration' => (($settings['important']) ? $this->t('Yes') : $this->t('No')), + ]); if ($opacity && $settings['opacity']) { - $summary[] = t('Display with opacity.'); + $summary[] = $this->t('Display with opacity.'); } return $summary; @@ -118,10 +167,16 @@ class ColorFieldFormatterCss extends FormatterBase { $elements = []; + $entity = $items->getEntity(); + $tokens = [ + $entity->getEntityType()->id() => $entity, + ]; foreach ($items as $delta => $item) { - $value = $this->viewValue($item); - $selector = $settings['selector']; + $selector = $this->tokenService->replace( + $settings['selector'], + $tokens + ); $important = ($settings['important']) ? ' !important' : ''; $property = $settings['property']; @@ -133,7 +188,8 @@ class ColorFieldFormatterCss extends FormatterBase { $elements['#attached']['html_head'][] = [[ '#tag' => 'style', '#value' => $inline_css, - ], 'colorfield_css']; + ], sha1($inline_css), + ]; } return $elements; @@ -150,7 +206,8 @@ class ColorFieldFormatterCss extends FormatterBase { if ($opacity && $settings['opacity']) { $rgbtext = $color_hex->toRGB()->toString(TRUE); - } else { + } + else { $rgbtext = $color_hex->toRGB()->toString(FALSE); } diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterSwatch.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterSwatch.php index 7b0b5616f..ed7f91ae5 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterSwatch.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterSwatch.php @@ -1,15 +1,9 @@ 'square', 'width' => 50, 'height' => 50, 'opacity' => TRUE, - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** @@ -48,42 +42,47 @@ class ColorFieldFormatterSwatch extends FormatterBase { $elements = []; - $elements['shape'] = array( + $elements['shape'] = [ '#type' => 'select', - '#title' => t('Shape'), + '#title' => $this->t('Shape'), '#options' => $this->getShape(), '#default_value' => $this->getSetting('shape'), - '#description' => t(''), - ); - $elements['width'] = array( + '#description' => '', + ]; + $elements['width'] = [ '#type' => 'number', - '#title' => t('Width'), + '#title' => $this->t('Width'), '#default_value' => $this->getSetting('width'), '#min' => 1, - '#description' => t(''), - ); - $elements['height'] = array( + '#description' => '', + ]; + $elements['height'] = [ '#type' => 'number', - '#title' => t('Height'), + '#title' => $this->t('Height'), '#default_value' => $this->getSetting('height'), '#min' => 1, - '#description' => t(''), - ); + '#description' => '', + ]; if ($opacity) { - $elements['opacity'] = array( + $elements['opacity'] = [ '#type' => 'checkbox', - '#title' => t('Display opacity'), + '#title' => $this->t('Display opacity'), '#default_value' => $this->getSetting('opacity'), - ); + ]; } return $elements; } /** - * @param string $shape + * This is used to get the shape. + * + * @param string|null $shape + * The specific shape name to get. + * * @return array|string + * An array of shape ids/names or translated name of the specified shape. */ protected function getShape($shape = NULL) { $formats = []; @@ -106,17 +105,17 @@ class ColorFieldFormatterSwatch extends FormatterBase { $summary = []; - $summary[] = t('@shape', array( + $summary[] = $this->t('@shape', [ '@shape' => $this->getShape($settings['shape']), - )); + ]); - $summary[] = t('Width: @width Height: @height', array( + $summary[] = $this->t('Width: @width Height: @height', [ '@width' => $settings['width'], - '@height' => $settings['height'] - )); + '@height' => $settings['height'], + ]); if ($opacity && $settings['opacity']) { - $summary[] = t('Display with opacity.'); + $summary[] = $this->t('Display with opacity.'); } return $summary; @@ -133,13 +132,13 @@ class ColorFieldFormatterSwatch extends FormatterBase { $elements['#attached']['library'][] = 'color_field/color-field-formatter-swatch'; foreach ($items as $delta => $item) { - $elements[$delta] = array( + $elements[$delta] = [ '#theme' => 'color_field_formatter_swatch', '#color' => $this->viewValue($item), '#shape' => $settings['shape'], '#width' => $settings['width'], '#height' => $settings['height'], - ); + ]; } return $elements; @@ -156,7 +155,8 @@ class ColorFieldFormatterSwatch extends FormatterBase { if ($opacity && $settings['opacity']) { $rgbtext = $color_hex->toRGB()->toString(TRUE); - } else { + } + else { $rgbtext = $color_hex->toRGB()->toString(FALSE); } diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterText.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterText.php index b6ef971cb..93bdf9b24 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterText.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldFormatter/ColorFieldFormatterText.php @@ -1,10 +1,5 @@ 'hex', 'opacity' => TRUE, - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** @@ -45,27 +40,32 @@ class ColorFieldFormatterText extends FormatterBase { $elements = []; - $elements['format'] = array( + $elements['format'] = [ '#type' => 'select', - '#title' => t('Format'), + '#title' => $this->t('Format'), '#options' => $this->getColorFormat(), '#default_value' => $this->getSetting('format'), - ); + ]; if ($opacity) { - $elements['opacity'] = array( + $elements['opacity'] = [ '#type' => 'checkbox', - '#title' => t('Display opacity'), + '#title' => $this->t('Display opacity'), '#default_value' => $this->getSetting('opacity'), - ); + ]; } return $elements; } /** + * This function is used to get the color format. + * * @param string $format + * Format is of string type. + * * @return array|string + * Returns array or string. */ protected function getColorFormat($format = NULL) { $formats = []; @@ -87,12 +87,12 @@ class ColorFieldFormatterText extends FormatterBase { $summary = []; - $summary[] = t('@format', array( + $summary[] = $this->t('@format', [ '@format' => $this->getColorFormat($settings['format']), - )); + ]); if ($opacity && $settings['opacity']) { - $summary[] = t('Display with opacity.'); + $summary[] = $this->t('Display with opacity.'); } return $summary; @@ -124,7 +124,8 @@ class ColorFieldFormatterText extends FormatterBase { case 'hex': if ($opacity && $settings['opacity']) { $output = $color_hex->toString(TRUE); - } else { + } + else { $output = $color_hex->toString(FALSE); } break; @@ -132,7 +133,8 @@ class ColorFieldFormatterText extends FormatterBase { case 'rgb': if ($opacity && $settings['opacity']) { $output = $color_hex->toRGB()->toString(TRUE); - } else { + } + else { $output = $color_hex->toRGB()->toString(FALSE); } break; diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldType/ColorFieldType.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldType/ColorFieldType.php index db84a8e95..93719163d 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldType/ColorFieldType.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldType/ColorFieldType.php @@ -1,10 +1,5 @@ TRUE, - ) + parent::defaultFieldSettings(); + ] + parent::defaultFieldSettings(); } /** * {@inheritdoc} */ public static function defaultStorageSettings() { - return array( + return [ 'format' => '#HEXHEX', - ) + parent::defaultStorageSettings(); + ] + parent::defaultStorageSettings(); } /** @@ -52,18 +53,18 @@ class ColorFieldType extends FieldItemBase { public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) { $element = []; - $element['format'] = array( + $element['format'] = [ '#type' => 'select', - '#title' => t('Format storage'), - '#description' => t('Choose how to store the color.'), + '#title' => $this->t('Format storage'), + '#description' => $this->t('Choose how to store the color.'), '#default_value' => $this->getSetting('format'), - '#options' => array( - '#HEXHEX' => t('#123ABC'), - 'HEXHEX' => t('123ABC'), - '#hexhex' => t('#123abc'), - 'hexhex' => t('123abc'), - ), - ); + '#options' => [ + '#HEXHEX' => $this->t('#123ABC'), + 'HEXHEX' => $this->t('123ABC'), + '#hexhex' => $this->t('#123abc'), + 'hexhex' => $this->t('123abc'), + ], + ]; $element += parent::storageSettingsForm($form, $form_state, $has_data); @@ -76,12 +77,12 @@ class ColorFieldType extends FieldItemBase { public function fieldSettingsForm(array $form, FormStateInterface $form_state) { $element = []; - $element['opacity'] = array( + $element['opacity'] = [ '#type' => 'checkbox', - '#title' => t('Record opacity'), - '#description' => t('Whether or not to record.'), + '#title' => $this->t('Record opacity'), + '#description' => $this->t('Whether or not to record.'), '#default_value' => $this->getSetting('opacity'), - ); + ]; return $element; } @@ -91,26 +92,26 @@ class ColorFieldType extends FieldItemBase { */ public static function schema(FieldStorageDefinitionInterface $field_definition) { $format = $field_definition->getSetting('format'); - $color_length = isset($format) ? strlen($format) : 7 ; - return array( - 'columns' => array( - 'color' => array( + $color_length = isset($format) ? strlen($format) : 7; + return [ + 'columns' => [ + 'color' => [ 'description' => 'The color value', 'type' => 'varchar', 'length' => $color_length, 'not null' => FALSE, - ), - 'opacity' => array( + ], + 'opacity' => [ 'description' => 'The opacity/alphavalue property', 'type' => 'float', 'size' => 'tiny', 'not null' => FALSE, - ), - ), - 'indexes' => array( - 'color' => array('color'), - ), - ); + ], + ], + 'indexes' => [ + 'color' => ['color'], + ], + ]; } /** @@ -144,34 +145,34 @@ class ColorFieldType extends FieldItemBase { $label = $this->getFieldDefinition()->getLabel(); - $constraints[] = $constraint_manager->create('ComplexData', array( - 'color' => array( - 'Regex' => array( + $constraints[] = $constraint_manager->create('ComplexData', [ + 'color' => [ + 'Regex' => [ 'pattern' => '/^#?(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$/i', - ) - ), - )); + ], + ], + ]); if ($opacity = $this->getSetting('opacity')) { $min = 0; - $constraints[] = $constraint_manager->create('ComplexData', array( - 'opacity' => array( - 'Range' => array( + $constraints[] = $constraint_manager->create('ComplexData', [ + 'opacity' => [ + 'Range' => [ 'min' => $min, - 'minMessage' => t('%name: the opacity may be no less than %min.', array('%name' => $label, '%min' => $min)), - ) - ), - )); + 'minMessage' => $this->t('%name: the opacity may be no less than %min.', ['%name' => $label, '%min' => $min]), + ], + ], + ]); $max = 1; - $constraints[] = $constraint_manager->create('ComplexData', array( - 'opacity' => array( - 'Range' => array( + $constraints[] = $constraint_manager->create('ComplexData', [ + 'opacity' => [ + 'Range' => [ 'max' => $max, - 'maxMessage' => t('%name: the opacity may be no greater than %max.', array('%name' => $label, '%max' => $max)), - ) - ), - )); + 'maxMessage' => $this->t('%name: the opacity may be no greater than %max.', ['%name' => $label, '%max' => $max]), + ], + ], + ]); } return $constraints; @@ -188,12 +189,15 @@ class ColorFieldType extends FieldItemBase { case '#HEXHEX': $values['color'] = '#111AAA'; break; + case 'HEXHEX': $values['color'] = '111111'; break; + case '#hexhex': $values['color'] = '#111aaa'; break; + case 'hexhex': $values['color'] = '111111'; break; @@ -225,12 +229,15 @@ class ColorFieldType extends FieldItemBase { case '#HEXHEX': $color = '#' . strtoupper($color); break; + case 'HEXHEX': $color = strtoupper($color); break; + case '#hexhex': $color = '#' . strtolower($color); break; + case 'hexhex': $color = strtolower($color); break; @@ -238,6 +245,10 @@ class ColorFieldType extends FieldItemBase { $this->color = $color; } + + if (!$this->getSetting('opacity')) { + unset($this->opacity); + } } } diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetBase.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetBase.php new file mode 100644 index 000000000..d803d2d82 --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetBase.php @@ -0,0 +1,61 @@ +fieldDefinition->getName()); + + // Prepare color. + $color = NULL; + if (isset($items[$delta]->color)) { + $color = $items[$delta]->color; + if (substr($color, 0, 1) !== '#') { + $color = '#' . $color; + } + } + + $input = [ + '#type' => 'textfield', + '#maxlength' => 7, + '#size' => 7, + '#required' => $element['#required'], + '#default_value' => $color, + ]; + + if ($this->getFieldSetting('opacity')) { + $element['color'] = $input; + $element['color']['#title'] = $this->t('Color'); + $element['#type'] = 'fieldset'; + + $element['opacity'] = [ + '#title' => $this->t('Opacity'), + '#type' => 'number', + '#min' => 0, + '#max' => 1, + '#step' => 0.01, + '#required' => $element['#required'], + '#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL, + '#placeholder' => $this->getSetting('placeholder_opacity'), + ]; + } + else { + $element['color'] = $element + $input; + } + + return $element; + } + +} diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php index ad0595841..f56862789 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php @@ -1,14 +1,8 @@ ' #AC725E,#D06B64,#F83A22,#FA573C,#FF7537,#FFAD46 #42D692,#16A765,#7BD148,#B3DC6C,#FBE983 #92E1C0,#9FE1E7,#9FC6E7,#4986E7,#9A9CFF #B99AFF,#C2C2C2,#CABDBF,#CCA6AC,#F691B2 #CD74E6,#A47AE2', - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { - $element['default_colors'] = array( + $element['default_colors'] = [ '#type' => 'textarea', - '#title' => t('Default colors'), + '#title' => $this->t('Default colors'), '#default_value' => $this->getSetting('default_colors'), '#required' => TRUE, - '#description' => t('Default colors for pre-selected color boxes'), - ); + '#element_validate' => [ + [$this, 'settingsColorValidate'], + ], + '#description' => $this->t('Default colors for pre-selected color boxes. Enter as 6 digit upper case hex - such as #FF0000.'), + ]; return $element; } + /** + * Use element validator to make sure that hex values are in correct format. + * + * @param array $element + * The Default colors element. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The current state of the form. + */ + public function settingsColorValidate(array $element, FormStateInterface $form_state) { + $default_colors = $form_state->getValue($element['#parents']); + $colors = ''; + if (!empty($default_colors)) { + preg_match_all("/#[0-9a-fA-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER); + foreach ($default_colors as $color) { + if (!empty($colors)) { + $colors .= ','; + } + $colors .= strtoupper($color[0]); + } + } + $form_state->setValue($element['#parents'], $colors); + } + /** * {@inheritdoc} */ @@ -62,7 +82,7 @@ class ColorFieldWidgetBox extends WidgetBase { $default_colors = $this->getSetting('default_colors'); if (!empty($default_colors)) { - preg_match_all("/#[0-9a-fA-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER); + preg_match_all("/#[0-9A-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER); foreach ($default_colors as $color) { $colors = $color[0]; $summary[] = $colors; @@ -70,7 +90,7 @@ class ColorFieldWidgetBox extends WidgetBase { } if (empty($summary)) { - $summary[] = t('No default colors'); + $summary[] = $this->t('No default colors'); } return $summary; @@ -80,58 +100,29 @@ class ColorFieldWidgetBox extends WidgetBase { * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { - // We are nesting some sub-elements inside the parent, so we need a wrapper. - // We also need to add another #title attribute at the top level for ease in - // identifying this item in error messages. We do not want to display this - // title because the actual title display is handled at a higher level by - // the Field module. - - $element['#theme_wrappers'] = array('color_field_widget_box'); - $element['#attributes']['class'][] = 'container-inline'; + $element = parent::formElement($items, $delta, $element, $form, $form_state); + // Ensure the default value is the required format. + if ($element['color']['#default_value']) { + $element['color']['#default_value'] = strtoupper($element['color']['#default_value']); + if (strlen($element['color']['#default_value']) === 6) { + $element['color']['#default_value'] = '#' . $element['color']['#default_value']; + } + } $element['#attached']['library'][] = 'color_field/color-field-widget-box'; // Set Drupal settings. - $settings = []; + $settings[$element['#uid']] = [ + 'required' => $this->fieldDefinition->isRequired(), + ]; $default_colors = $this->getSetting('default_colors'); - preg_match_all("/#[0-9a-fA-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER); + preg_match_all("/#[0-9A-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER); foreach ($default_colors as $color) { - $settings['default_colors'][] = $color[0]; + $settings[$element['#uid']]['palette'][] = $color[0]; } $element['#attached']['drupalSettings']['color_field']['color_field_widget_box']['settings'] = $settings; - // Retrieve field label and description. - $element['#title'] = $this->fieldDefinition->getLabel();; - $element['#description'] = $this->fieldDefinition->getDescription(); - - // Prepare color. - $color = NULL; - if (isset($items[$delta]->color)) { - $color = $items[$delta]->color; - if (substr($color, 0, 1) !== '#') { - $color = '#' . $color; - } - } - - $element['color'] = array( - '#maxlength' => 7, - '#size' => 7, - '#type' => 'textfield', - '#default_value' => $color, - '#attributes' => array('class' => array('visually-hidden')), - ); - $element['color']['#suffix'] = "
"; - - if ($this->getFieldSetting('opacity')) { - $element['opacity'] = array( - '#title' => t('Opacity'), - '#type' => 'textfield', - '#maxlength' => 4, - '#size' => 4, - '#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL, - '#placeholder' => $this->getSetting('placeholder_opacity'), - ); - } + $element['color']['#suffix'] = "
"; return $element; } diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetDefault.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetDefault.php index d0bc37557..8caa85d37 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetDefault.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetDefault.php @@ -1,14 +1,8 @@ '', 'placeholder_opacity' => '', - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { - $element['placeholder_color'] = array( + $element['placeholder_color'] = [ '#type' => 'textfield', - '#title' => t('Color placeholder'), + '#title' => $this->t('Color placeholder'), '#default_value' => $this->getSetting('placeholder_color'), - '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'), - ); - $element['placeholder_opacity'] = array( + '#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'), + ]; + $element['placeholder_opacity'] = [ '#type' => 'textfield', - '#title' => t('Opacity placeholder'), + '#title' => $this->t('Opacity placeholder'), '#default_value' => $this->getSetting('placeholder_opacity'), - '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'), - ); + '#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'), + ]; return $element; } @@ -64,15 +58,15 @@ class ColorFieldWidgetDefault extends WidgetBase { $placeholder_opacity = $this->getSetting('placeholder_opacity'); if (!empty($placeholder_color)) { - $summary[] = t('Color placeholder: @placeholder_color', array('@placeholder_color' => $placeholder_color)); + $summary[] = $this->t('Color placeholder: @placeholder_color', ['@placeholder_color' => $placeholder_color]); } if (!empty($placeholder_opacity)) { - $summary[] = t('Opacity placeholder: @placeholder_opacity', array('@placeholder_opacity' => $placeholder_opacity)); + $summary[] = $this->t('Opacity placeholder: @placeholder_opacity', ['@placeholder_opacity' => $placeholder_opacity]); } if (empty($summary)) { - $summary[] = t('No placeholder'); + $summary[] = $this->t('No placeholder'); } return $summary; @@ -82,32 +76,11 @@ class ColorFieldWidgetDefault extends WidgetBase { * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { - - $label = $this->fieldDefinition->getLabel(); - - $element['color'] = array( - '#title' => t($label), - '#type' => 'textfield', - '#maxlength' => 7, - '#size' => 7, - '#required' => $element['#required'], - '#placeholder' => $this->getSetting('placeholder_color'), - '#default_value' => isset($items[$delta]->color) ? $items[$delta]->color : NULL, - ); + $element = parent::formElement($items, $delta, $element, $form, $form_state); + $element['color']['#placeholder'] = $this->getSetting('placeholder_color'); if ($this->getFieldSetting('opacity')) { - $element['color']['#prefix'] = '
'; - - $element['opacity'] = array( - '#title' => t('Opacity'), - '#type' => 'textfield', - '#maxlength' => 4, - '#size' => 4, - '#required' => $element['#required'], - '#placeholder' => $this->getSetting('placeholder_opacity'), - '#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL, - '#suffix' => '
', - ); + $element['opacity']['#placeholder'] = $this->getSetting('placeholder_opacity'); } return $element; diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetGrid.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetGrid.php index dda5b12c3..91057e883 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetGrid.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetGrid.php @@ -1,14 +1,8 @@ 10, 'cell_height' => 10, 'cell_margin' => 1, 'box_width' => 115, 'box_height' => 20, 'columns' => 16, - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** @@ -45,48 +39,48 @@ class ColorFieldWidgetGrid extends WidgetBase { public function settingsForm(array $form, FormStateInterface $form_state) { $element = []; - $element['cell_width'] = array( + $element['cell_width'] = [ '#type' => 'textfield', - '#title' => t('Cell width'), + '#title' => $this->t('Cell width'), '#default_value' => $this->getSetting('cell_width'), '#required' => TRUE, - '#description' => t('Width of each individual color cell.'), - ); - $element['cell_height'] = array( + '#description' => $this->t('Width of each individual color cell.'), + ]; + $element['cell_height'] = [ '#type' => 'textfield', - '#title' => t('Height width'), + '#title' => $this->t('Height width'), '#default_value' => $this->getSetting('cell_height'), '#required' => TRUE, - '#description' => t('Height of each individual color cell.'), - ); - $element['cell_margin'] = array( + '#description' => $this->t('Height of each individual color cell.'), + ]; + $element['cell_margin'] = [ '#type' => 'textfield', - '#title' => t('Cell margin'), + '#title' => $this->t('Cell margin'), '#default_value' => $this->getSetting('cell_margin'), '#required' => TRUE, - '#description' => t('Margin of each individual color cell.'), - ); - $element['box_width'] = array( + '#description' => $this->t('Margin of each individual color cell.'), + ]; + $element['box_width'] = [ '#type' => 'textfield', - '#title' => t('Box width'), + '#title' => $this->t('Box width'), '#default_value' => $this->getSetting('box_width'), '#required' => TRUE, - '#description' => t('Width of the color display box.'), - ); - $element['box_height'] = array( + '#description' => $this->t('Width of the color display box.'), + ]; + $element['box_height'] = [ '#type' => 'textfield', - '#title' => t('Box height'), + '#title' => $this->t('Box height'), '#default_value' => $this->getSetting('box_height'), '#required' => TRUE, - '#description' => t('Height of the color display box.'), - ); - $element['columns'] = array( + '#description' => $this->t('Height of the color display box.'), + ]; + $element['columns'] = [ '#type' => 'textfield', - '#title' => t('Columns number'), + '#title' => $this->t('Columns number'), '#default_value' => $this->getSetting('columns'), '#required' => TRUE, - '#description' => t('Number of columns to display. Color order may look strange if this is altered.'), - ); + '#description' => $this->t('Number of columns to display. Color order may look strange if this is altered.'), + ]; return $element; } @@ -104,31 +98,31 @@ class ColorFieldWidgetGrid extends WidgetBase { $columns = $this->getSetting('columns'); if (!empty($cell_width)) { - $summary[] = t('Cell width: @cell_width', array('@cell_width' => $cell_width)); + $summary[] = $this->t('Cell width: @cell_width', ['@cell_width' => $cell_width]); } if (!empty($cell_height)) { - $summary[] = t('Cell height: @cell_height', array('@cell_height' => $cell_height)); + $summary[] = $this->t('Cell height: @cell_height', ['@cell_height' => $cell_height]); } if (!empty($cell_margin)) { - $summary[] = t('Cell margin: @cell_margin', array('@cell_margin' => $cell_margin)); + $summary[] = $this->t('Cell margin: @cell_margin', ['@cell_margin' => $cell_margin]); } if (!empty($box_width)) { - $summary[] = t('Box width: @box_width', array('@box_width' => $box_width)); + $summary[] = $this->t('Box width: @box_width', ['@box_width' => $box_width]); } if (!empty($box_height)) { - $summary[] = t('Box height: @box_height', array('@box_height' => $box_height)); + $summary[] = $this->t('Box height: @box_height', ['@box_height' => $box_height]); } if (!empty($columns)) { - $summary[] = t('Columns: @columns', array('@columns' => $columns)); + $summary[] = $this->t('Columns: @columns', ['@columns' => $columns]); } if (empty($summary)) { - $summary[] = t('No placeholder'); + $summary[] = $this->t('No placeholder'); } return $summary; @@ -138,52 +132,23 @@ class ColorFieldWidgetGrid extends WidgetBase { * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { + $element = parent::formElement($items, $delta, $element, $form, $form_state); + // We are nesting some sub-elements inside the parent, so we need a wrapper. // We also need to add another #title attribute at the top level for ease in // identifying this item in error messages. We do not want to display this // title because the actual title display is handled at a higher level by // the Field module. - - //$element['#theme_wrappers'] = array('color_field_widget_grid'); - + // $element['#theme_wrappers'] = array('color_field_widget_grid');. $element['#attached']['library'][] = 'color_field/color-field-widget-grid'; // Set Drupal settings. $settings = $this->getSettings(); - $element['#attached']['drupalSettings']['color_field']['color_field_widget_grid'] = $settings; + $element['#attached']['drupalSettings']['color_field']['color_field_widget_grid'][$element['#uid']] = $settings; - // Prepare color. - $color = NULL; - if (isset($items[$delta]->color)) { - $color = $items[$delta]->color; - if (substr($color, 0, 1) !== '#') { - $color = '#' . $color; - } - } - - $element['color'] = array( - '#title' => t('Color'), - '#type' => 'textfield', - '#maxlength' => 7, - '#size' => 7, - '#required' => $element['#required'], - '#default_value' => $color, - '#attributes' => array('class' => array('js-color-field-widget-grid__color')), - ); - - if ($this->getFieldSetting('opacity')) { - $element['color']['#prefix'] = '
'; - - $element['opacity'] = array( - '#title' => t('Opacity'), - '#type' => 'textfield', - '#maxlength' => 4, - '#size' => 4, - '#required' => $element['#required'], - '#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL, - '#suffix' => '
', - ); - } + $element['color']['#attributes']['class'][] = 'js-color-field-widget-grid__color'; + $element['color']['#attributes']['id'] = $element['#uid']; + $element['color']['#wrapper_attributes']['class'][] = 'clearfix'; return $element; } diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetHTML5.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetHTML5.php index bb39cef19..f9e6ee7ea 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetHTML5.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetHTML5.php @@ -1,14 +1,8 @@ color)) { - $color = $items[$delta]->color; - if (substr($color, 0, 1) !== '#') { - $color = '#' . $color; - } - } - - $element['color'] = array( - '#title' => t('Color'), - '#type' => 'color', - '#maxlength' => 7, - '#size' => 7, - '#required' => $element['#required'], - '#default_value' => $color, - ); - - if ($this->getFieldSetting('opacity')) { - $element['color']['#prefix'] = '
'; - - $element['opacity'] = array( - '#title' => t('Opacity'), - '#type' => 'textfield', - '#maxlength' => 4, - '#size' => 4, - '#required' => $element['#required'], - '#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL, - '#suffix' => '
', - ); - } + $element = parent::formElement($items, $delta, $element, $form, $form_state); + $element['color']['#type'] = 'color'; return $element; } diff --git a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetSpectrum.php b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetSpectrum.php index 1b48b5ac9..c3c2be110 100644 --- a/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetSpectrum.php +++ b/sites/all/modules/contrib/fields/color_field/src/Plugin/Field/FieldWidget/ColorFieldWidgetSpectrum.php @@ -1,14 +1,8 @@ FALSE, 'show_palette' => FALSE, 'palette' => '', - 'show_palette_only' => TRUE, + 'show_palette_only' => FALSE, 'show_buttons' => FALSE, 'allow_empty' => FALSE, - ) + parent::defaultSettings(); + ] + parent::defaultSettings(); } /** @@ -45,47 +39,52 @@ class ColorFieldWidgetSpectrum extends WidgetBase { public function settingsForm(array $form, FormStateInterface $form_state) { $element = []; - $element['show_input'] = array( + $element['show_input'] = [ '#type' => 'checkbox', - '#title' => t('Show Input'), + '#title' => $this->t('Show Input'), '#default_value' => $this->getSetting('show_input'), - '#description' => t('Allow free form typing.'), - ); - $element['show_palette'] = array( + '#description' => $this->t('Allow free form typing.'), + ]; + $element['show_palette'] = [ '#type' => 'checkbox', - '#title' => t('Show Palette'), + '#title' => $this->t('Show Palette'), '#default_value' => $this->getSetting('show_palette'), - '#description' => t('Show or hide Palette in Spectrum Widget'), - ); - $element['palette'] = array( + '#description' => $this->t('Show or hide Palette in Spectrum Widget'), + ]; + $element['palette'] = [ '#type' => 'textarea', - '#title' => t('Color Palette'), + '#title' => $this->t('Color Palette'), '#default_value' => $this->getSetting('palette'), - '#description' => t('Selectable color palette to accompany the Spectrum Widget'), - '#states' => array( - 'visible' => array( - ':input[name="field[settings][show_palette]"]' => array('checked' => TRUE), - ), - ), - ); - $element['show_palette_only'] = array( + '#description' => $this->t('Selectable color palette to accompany the Spectrum Widget. Separate values with a comma, and group them with square brackets. Ex:
["#fff","#aaa","#f00","#00f"],
["#414141","#242424","#0a8db9"]'), + '#states' => [ + 'visible' => [ + ':input[name="fields[' . $this->fieldDefinition->getName() . '][settings_edit_form][settings][show_palette]"]' => ['checked' => TRUE], + ], + ], + ]; + $element['show_palette_only'] = [ '#type' => 'checkbox', - '#title' => t('Show Palette Only'), + '#title' => $this->t('Show Palette Only'), '#default_value' => $this->getSetting('show_palette_only'), - '#description' => t('Only show thePalette in Spectrum Widget and nothing else'), - ); - $element['show_buttons'] = array( + '#description' => $this->t('Only show the palette in Spectrum Widget and nothing else'), + '#states' => [ + 'visible' => [ + ':input[name="fields[' . $this->fieldDefinition->getName() . '][settings_edit_form][settings][show_palette]"]' => ['checked' => TRUE], + ], + ], + ]; + $element['show_buttons'] = [ '#type' => 'checkbox', - '#title' => t('Show Buttons'), + '#title' => $this->t('Show Buttons'), '#default_value' => $this->getSetting('show_buttons'), - '#description' => t('Add Cancel/Confirm Button.'), - ); - $element['allow_empty'] = array( + '#description' => $this->t('Add Cancel/Confirm Button.'), + ]; + $element['allow_empty'] = [ '#type' => 'checkbox', - '#title' => t('Allow Empty'), + '#title' => $this->t('Allow Empty'), '#default_value' => $this->getSetting('allow_empty'), - '#description' => t('Allow empty value.'), - ); + '#description' => $this->t('Allow empty value.'), + ]; return $element; } @@ -93,7 +92,7 @@ class ColorFieldWidgetSpectrum extends WidgetBase { * {@inheritdoc} */ public function settingsSummary() { - $summary = array(); + $summary = []; return $summary; } @@ -102,50 +101,43 @@ class ColorFieldWidgetSpectrum extends WidgetBase { * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { - // We are nesting some sub-elements inside the parent, so we need a wrapper. - // We also need to add another #title attribute at the top level for ease in - // identifying this item in error messages. We do not want to display this - // title because the actual title display is handled at a higher level by - // the Field module. - - $element['#theme_wrappers'] = array('color_field_widget_spectrum'); - + $element = parent::formElement($items, $delta, $element, $form, $form_state); $element['#attached']['library'][] = 'color_field/color-field-widget-spectrum'; // Set Drupal settings. $settings = $this->getSettings(); - $settings['show_alpha'] = $this->getFieldSetting('opacity'); - $element['#attached']['drupalSettings']['color_field']['color_field_widget_spectrum'] = $settings; - // Prepare color. - $color = NULL; - if (isset($items[$delta]->color)) { - $color = $items[$delta]->color; - if (substr($color, 0, 1) !== '#') { - $color = '#' . $color; + // Compare with default settings make sure they are the same datatype. + $defaults = self::defaultSettings(); + foreach ($settings as $key => $value) { + if (is_bool($defaults[$key])) { + $settings[$key] = boolval($value); } } - $element['color'] = array( - '#type' => 'textfield', - '#maxlength' => 7, - '#size' => 7, - '#required' => $element['#required'], - '#default_value' => $color, - '#attributes' => array('class' => array('js-color-field-widget-spectrum__color')), - ); + // Parsing Palette data so that it works with spectrum color picker. + // This will create a multidimensional array of hex values. + if (!empty($settings['palette'])) { + // Remove any whitespace. + $settings['palette'] = str_replace(' ', '', $settings['palette']); - if ($this->getFieldSetting('opacity')) { - $element['opacity'] = array( - '#type' => 'textfield', - '#maxlength' => 4, - '#size' => 4, - '#required' => $element['#required'], - '#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL, - '#attributes' => array('class' => array('js-color-field-widget-spectrum__opacity', 'visually-hidden')), - ); + // Parse each row first and reset the palette. + $rows = explode("\n", $settings['palette']); + $settings['palette'] = []; + + foreach ($rows as $row) { + // Next explode each row into an array of values. + $settings['palette'][] = $columns = explode(',', $row); + } } + $settings['show_alpha'] = (bool) $this->getFieldSetting('opacity'); + $element['#attributes']['id'] = $element['#uid']; + $element['#attributes']['class'][] = 'js-color-field-widget-spectrum'; + $element['#attached']['drupalSettings']['color_field']['color_field_widget_spectrum'][$element['#uid']] = $settings; + $element['color']['#attributes']['class'][] = 'js-color-field-widget-spectrum__color'; + $element['opacity']['#attributes']['class'][] = 'js-color-field-widget-spectrum__opacity'; + return $element; } diff --git a/sites/all/modules/contrib/fields/color_field/templates/color-field-formatter-swatch.html.twig b/sites/all/modules/contrib/fields/color_field/templates/color-field-formatter-swatch.html.twig index 323d22a4f..b3de021e3 100644 --- a/sites/all/modules/contrib/fields/color_field/templates/color-field-formatter-swatch.html.twig +++ b/sites/all/modules/contrib/fields/color_field/templates/color-field-formatter-swatch.html.twig @@ -16,4 +16,4 @@ */ #} -
+
diff --git a/sites/all/modules/contrib/fields/color_field/templates/color-field-widget-box.html.twig b/sites/all/modules/contrib/fields/color_field/templates/color-field-widget-box.html.twig deleted file mode 100644 index 4db9242e5..000000000 --- a/sites/all/modules/contrib/fields/color_field/templates/color-field-widget-box.html.twig +++ /dev/null @@ -1,41 +0,0 @@ -{# -/** - * @file - * Default theme implementation of a color box form wrapper. - * - * Available variables: - * - content: The form element to be output, usually a datelist, or datetime. - * - title: The title of the form element. - * - title_attributes: HTML attributes for the title wrapper. - * - description: Description text for the form element. - * - required: An indicator for whether the associated form element is required. - * - * @see template_preprocess() - * @see template_preprocess_color_field_widget_box() - * - * @ingroup themeable - */ -#} -{% -set title_classes = [ -required ? 'js-form-required', -required ? 'form-required', -] -%} - -{% if title %} - {{ title }} -{% endif %} - -
- {{ color }} - {{ opacity }} -
- -{% if errors %} -
- {{ errors }} -
-{% endif %} - -{{ description }} diff --git a/sites/all/modules/contrib/fields/color_field/templates/color-field-widget-spectrum.html.twig b/sites/all/modules/contrib/fields/color_field/templates/color-field-widget-spectrum.html.twig deleted file mode 100644 index 8d539e8ae..000000000 --- a/sites/all/modules/contrib/fields/color_field/templates/color-field-widget-spectrum.html.twig +++ /dev/null @@ -1,41 +0,0 @@ -{# -/** - * @file - * Default theme implementation of a color box form wrapper. - * - * Available variables: - * - content: The form element to be output, usually a datelist, or datetime. - * - title: The title of the form element. - * - title_attributes: HTML attributes for the title wrapper. - * - description: Description text for the form element. - * - required: An indicator for whether the associated form element is required. - * - * @see template_preprocess() - * @see template_preprocess_color_field_widget_box() - * - * @ingroup themeable - */ -#} -{% -set title_classes = [ -required ? 'js-form-required', -required ? 'form-required', -] -%} - -{% if title %} - {{ title }} -{% endif %} - -
- {{ color }} - {{ opacity }} -
- -{% if errors %} -
- {{ errors }} -
-{% endif %} - -{{ description }} diff --git a/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFormatterTest.php b/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFormatterTest.php new file mode 100644 index 000000000..be98a0888 --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFormatterTest.php @@ -0,0 +1,203 @@ +form->setComponent('field_color', [ + 'type' => 'color_field_widget_default', + 'settings' => [ + 'placeholder_color' => '#ABC123', + 'placeholder_opacity' => '1.0', + ], + ])->save(); + + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_text', + 'weight' => 1, + 'label' => 'hidden', + ])->save(); + + // Display creation form. + $this->drupalGet('node/add/article'); + $session = $this->assertSession(); + $session->fieldExists("field_color[0][color]"); + $session->fieldExists("field_color[0][opacity]"); + $session->responseContains('placeholder="#ABC123"'); + $session->responseContains('placeholder="1.0"'); + $session->responseContains('Freeform Color'); + $session->responseContains('Color field description'); + + // Test basic entry of color field. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#E70000", + 'field_color[0][opacity]' => 1, + ]; + + $this->drupalPostForm(NULL, $edit, t('Save')); + $this->assertSession()->responseContains('#E70000 1'); + + // Ensure alternate hex format works. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "FF8C00", + 'field_color[0][opacity]' => 0.5, + ]; + + // Render without opacity value. + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_text', + 'weight' => 1, + 'settings' => [ + 'opacity' => FALSE, + ], + ])->save(); + + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('#FF8C00'); + + // Test RGBA Render mode. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#FFEF00", + 'field_color[0][opacity]' => 0.9, + ]; + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_text', + 'weight' => 1, + 'settings' => [ + 'format' => 'rgb', + 'opacity' => TRUE, + ], + ])->save(); + + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('RGBA(255,239,0,0.9)'); + + // Test RGB render mode. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#00811F", + 'field_color[0][opacity]' => 0.8, + ]; + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_text', + 'weight' => 1, + 'settings' => [ + 'format' => 'rgb', + 'opacity' => FALSE, + ], + ])->save(); + + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('RGB(0,129,31)'); + } + + /** + * Test color_field_formatter_swatch formatter. + */ + public function testColorFieldFormatterSwatch() { + $this->form->setComponent('field_color', [ + 'type' => 'color_field_widget_default', + 'settings' => [ + 'placeholder_color' => '#ABC123', + 'placeholder_opacity' => '1.0', + ], + ])->save(); + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_swatch', + 'weight' => 1, + 'label' => 'hidden', + ])->save(); + + // Test square with opacity. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#0044FF", + 'field_color[0][opacity]' => 0.9, + ]; + + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('background-color: rgba(0,68,255,0.9)'); + $this->assertSession()->responseContains('color_field__swatch--square'); + + // Test circle without opacity. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#760089", + 'field_color[0][opacity]' => 1, + ]; + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_swatch', + 'weight' => 1, + 'settings' => [ + 'shape' => 'circle', + 'opacity' => FALSE, + ], + ])->save(); + + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('background-color: rgb(118,0,137)'); + $this->assertSession()->responseContains('color_field__swatch--circle'); + } + + /** + * Test color_field_formatter_css formatter. + */ + public function testColorFieldFormatterCss() { + $this->form->setComponent('field_color', [ + 'type' => 'color_field_widget_default', + 'settings' => [ + 'placeholder_color' => '#ABC123', + 'placeholder_opacity' => '1.0', + ], + ])->save(); + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_css', + 'weight' => 1, + 'label' => 'hidden', + ])->save(); + + // Test default options. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#FFF430", + 'field_color[0][opacity]' => 0.9, + ]; + + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('body { background-color: RGBA(255,244,48,0.9) !important; }'); + + // Test without opacity and not important. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#FFFFFF", + 'field_color[0][opacity]' => 1, + ]; + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_css', + 'weight' => 1, + 'settings' => [ + 'selector' => 'body', + 'property' => 'background-color', + 'important' => FALSE, + 'opacity' => FALSE, + ], + 'label' => 'hidden', + ])->save(); + + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('body { background-color: RGB(255,255,255); }'); + } + +} diff --git a/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFormatterTokenTest.php b/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFormatterTokenTest.php new file mode 100644 index 000000000..681aab1d6 --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFormatterTokenTest.php @@ -0,0 +1,95 @@ +form->setComponent('field_color', [ + 'type' => 'color_field_widget_default', + ])->save(); + + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#9C59D1", + 'field_color[0][opacity]' => 0.95, + ]; + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_css', + 'weight' => 1, + 'settings' => [ + 'selector' => '.node-[node:content-type]', + 'property' => 'background-color', + 'important' => FALSE, + 'opacity' => TRUE, + ], + 'label' => 'hidden', + ])->save(); + + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('.node-article { background-color: RGBA(156,89,209,0.95); }'); + + // Ensure 2 fields on the same entity are both rendered properly. + FieldStorageConfig::create([ + 'field_name' => 'field_text_color', + 'entity_type' => 'node', + 'type' => 'color_field_type', + ])->save(); + FieldConfig::create([ + 'field_name' => 'field_text_color', + 'label' => 'Text Color', + 'entity_type' => 'node', + 'bundle' => 'article', + ])->save(); + + $this->display->setComponent('field_text_color', [ + 'type' => 'color_field_formatter_css', + 'weight' => 1, + 'settings' => [ + 'selector' => '.node-[node:content-type]', + 'property' => 'color', + 'important' => FALSE, + 'opacity' => TRUE, + ], + 'label' => 'hidden', + ])->save(); + $this->form->setComponent('field_text_color', [ + 'type' => 'color_field_widget_default', + ])->save(); + + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#000000", + 'field_color[0][opacity]' => 0.1, + 'field_text_color[0][color]' => "#000000", + 'field_text_color[0][opacity]' => 1, + ]; + $this->drupalPostForm('node/add/article', $edit, t('Save')); + $this->assertSession()->responseContains('.node-article { background-color: RGBA(0,0,0,0.1); }'); + $this->assertSession()->responseContains('.node-article { color: RGBA(0,0,0,1); }'); + } + +} diff --git a/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFunctionalTestBase.php b/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFunctionalTestBase.php new file mode 100644 index 000000000..5afed6c46 --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldFunctionalTestBase.php @@ -0,0 +1,69 @@ +drupalCreateContentType(['type' => 'article']); + $user = $this->drupalCreateUser(['create article content', 'edit own article content']); + $this->drupalLogin($user); + $entityTypeManager = $this->container->get('entity_type.manager'); + FieldStorageConfig::create([ + 'field_name' => 'field_color', + 'entity_type' => 'node', + 'type' => 'color_field_type', + ])->save(); + FieldConfig::create([ + 'field_name' => 'field_color', + 'label' => 'Freeform Color', + 'description' => 'Color field description', + 'entity_type' => 'node', + 'bundle' => 'article', + ])->save(); + $this->form = $entityTypeManager->getStorage('entity_form_display') + ->load('node.article.default'); + $this->display = $entityTypeManager->getStorage('entity_view_display') + ->load('node.article.default'); + } + +} diff --git a/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldWidgetTest.php b/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldWidgetTest.php new file mode 100644 index 000000000..fad5bbb4d --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/tests/src/Functional/ColorFieldWidgetTest.php @@ -0,0 +1,45 @@ +form->setComponent('field_color', [ + 'type' => 'color_field_widget_html5', + ])->save(); + + $this->display->setComponent('field_color', [ + 'type' => 'color_field_formatter_text', + 'weight' => 1, + ])->save(); + + $session = $this->assertSession(); + + // Confirm field label and description are rendered. + $this->drupalGet('node/add/article'); + $session->fieldExists("field_color[0][color]"); + $session->fieldExists("field_color[0][opacity]"); + $session->responseContains('Freeform Color'); + $session->responseContains('Color field description'); + + // Test basic entry of color field. + $edit = [ + 'title[0][value]' => $this->randomMachineName(), + 'field_color[0][color]' => "#E70000", + 'field_color[0][opacity]' => 1, + ]; + + $this->drupalPostForm(NULL, $edit, t('Save')); + $session->responseContains('#E70000 1'); + } + +} diff --git a/sites/all/modules/contrib/fields/color_field/tests/src/FunctionalJavascript/ColorFieldWidgetJavascriptTests.php b/sites/all/modules/contrib/fields/color_field/tests/src/FunctionalJavascript/ColorFieldWidgetJavascriptTests.php new file mode 100644 index 000000000..add6c0ca1 --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/tests/src/FunctionalJavascript/ColorFieldWidgetJavascriptTests.php @@ -0,0 +1,260 @@ +drupalCreateContentType(['type' => 'article']); + $user = $this->drupalCreateUser(['create article content', 'edit own article content']); + $this->drupalLogin($user); + $entityTypeManager = $this->container->get('entity_type.manager'); + FieldStorageConfig::create([ + 'field_name' => 'field_color', + 'entity_type' => 'node', + 'type' => 'color_field_type', + ])->save(); + FieldConfig::create([ + 'field_name' => 'field_color', + 'label' => 'Freeform Color', + 'description' => 'Color field description', + 'entity_type' => 'node', + 'bundle' => 'article', + 'required' => TRUE, + 'default_value' => [ + [ + 'color' => 'ffb81c', + 'opacity' => 0.5, + ], + ], + ])->save(); + FieldStorageConfig::create([ + 'field_name' => 'field_color_repeat', + 'entity_type' => 'node', + 'type' => 'color_field_type', + ])->save(); + FieldConfig::create([ + 'field_name' => 'field_color_repeat', + 'label' => 'Repeat Color', + 'description' => 'Color repeat description', + 'entity_type' => 'node', + 'bundle' => 'article', + 'required' => FALSE, + ])->save(); + $this->form = $entityTypeManager->getStorage('entity_form_display') + ->load('node.article.default'); + $this->display = $entityTypeManager->getStorage('entity_view_display') + ->load('node.article.default'); + } + + /** + * Test color_field_widget_box. + */ + public function testColorFieldWidgetBox() { + $this->form + ->setComponent('field_color_repeat', [ + 'type' => 'color_field_widget_box', + 'settings' => [ + 'default_colors' => '#FF0000,#FFFFFF', + ], + ]) + ->setComponent('field_color', [ + 'type' => 'color_field_widget_box', + 'settings' => [ + 'default_colors' => '#007749,#000000,#FFFFFF,#FFB81C,#E03C31,#001489', + ], + ]) + ->save(); + + $session = $this->getSession(); + $web_assert = $this->assertSession(); + $this->drupalGet('node/add/article'); + + $page = $session->getPage(); + + // Wait for elements to be generated. + $web_assert->waitForElementVisible('css', '#color-field-field-color_repeat button'); + + $boxes = $page->findAll('css', '#color-field-field-color-repeat button'); + $this->assertEquals(3, count($boxes)); + + // Confirm that help text/label are present. + $web_assert->responseContains('Freeform Color'); + $web_assert->responseContains('Color field description'); + + // Confirm that two fields aren't sharing settings. + $boxes = $page->findAll('css', '#color-field-field-color button'); + $this->assertEquals(6, count($boxes)); + + /** @var \Behat\Mink\Element\NodeElement $box */ + $box = $boxes[0]; + $this->assertEquals('#007749', $box->getAttribute('color')); + + // Only one of the fields has a default, so it is the only one that should + // have a box that is selected. This also confirms that even if the storage + // setting isn't uppercase hash prefixed hex that it still correctly selects + // the right color in the color box widget. + $active = $page->findAll('css', 'button.color_field_widget_box__square.active'); + $this->assertEquals(1, count($active)); + + // Confirm that clicking the swatch sets the field value. + $box->click(); + $field = $page->findField('field_color[0][color]'); + $this->assertEquals('#007749', $field->getValue()); + } + + /** + * Test color_field_widget_spectrum widget. + * + * Unfortunately since the spectrum library uses clickable divs instead of + * buttons, we can't use full interaction of clicks with elements. So instead + * we just confirm that the right html has been generated and assume that the + * library tests itself. + */ + public function testColorFieldSpectrum() { + $this->form + ->setComponent('field_color_repeat', [ + 'type' => 'color_field_widget_spectrum', + 'settings' => [ + 'palette' => '["#0678BE","#53B0EB", "#96BC44"]', + 'show_palette' => FALSE, + ], + ]) + ->setComponent('field_color', [ + 'type' => 'color_field_widget_spectrum', + 'settings' => [ + 'palette' => '["#005493","#F5AA1C","#C63527","002754"]', + 'show_palette' => TRUE, + ], + ]) + ->save(); + + // Disable alpha on second field. + FieldConfig::load('node.article.field_color_repeat') + ->setSetting('opacity', 0) + ->save(); + + $session = $this->getSession(); + $web_assert = $this->assertSession(); + $this->drupalGet('node/add/article'); + + $page = $session->getPage(); + + // Confirm that help text/label are present. + $web_assert->responseContains('Freeform Color'); + $web_assert->responseContains('Color field description'); + + // Wait for elements to be generated. + $web_assert->waitForElementVisible('css', '.sp-preview'); + + // Confirm that two fields aren't sharing settings. + // Also confirms that custom palette is being used correctly and that the + // one field's palette isn't shown. 4 for the one palette plus one each for + // the widget and the current color value. + $boxes = $page->findAll('css', '.sp-thumb-el'); + $this->assertEquals(6, count($boxes)); + + // Confirm that alpha slider is hidden if the field doesn't support opacity. + $alpha = $page->findAll('css', '.sp-alpha-enabled'); + $this->assertEquals(1, count($alpha)); + } + + /** + * Test color_field_widget_grid widget. + * + * Unfortunately since the grid library ALSO uses clickable divs instead of + * buttons. We could use $session->evaluateScript() to do it but we'll + * presume it is tested internally and just test the basic integration. + */ + public function testColorFieldWidgetGrid() { + $this->form + ->setComponent('field_color_repeat', [ + 'type' => 'color_field_widget_grid', + 'settings' => [ + 'cell_width' => '20', + 'cell_height' => '20', + 'cell_margin' => '1', + 'box_width' => '250', + 'box_height' => '100', + 'columns' => '16', + ], + ]) + ->setComponent('field_color', [ + 'type' => 'color_field_widget_grid', + 'settings' => [ + 'cell_width' => '10', + 'cell_height' => '10', + 'cell_margin' => '1', + 'box_width' => '115', + 'box_height' => '20', + 'columns' => '16', + ], + ]) + ->save(); + + $session = $this->getSession(); + $web_assert = $this->assertSession(); + $this->drupalGet('node/add/article'); + + $page = $session->getPage(); + + // Confirm that help text/label are present. + $web_assert->responseContains('Freeform Color'); + $web_assert->responseContains('Color field description'); + + // Wait for elements to be generated. + $web_assert->waitForElementVisible('css', '.simpleColorDisplay'); + + // Confirm that two fields aren't sharing settings. + $boxes = $page->findAll('css', '.simpleColorDisplay'); + $this->assertEquals(2, count($boxes)); + $script = <<< HEREDOC + (function() { + fields = jQuery('.simpleColorDisplay'); + return jQuery(fields[0]).width() == jQuery(fields[1]).width() + })() +HEREDOC; + + $this->assertFalse($session->evaluateScript($script)); + } + +} diff --git a/sites/all/modules/contrib/fields/color_field/tests/src/Kernel/ColorFieldTypeTest.php b/sites/all/modules/contrib/fields/color_field/tests/src/Kernel/ColorFieldTypeTest.php new file mode 100644 index 000000000..e1e2f9797 --- /dev/null +++ b/sites/all/modules/contrib/fields/color_field/tests/src/Kernel/ColorFieldTypeTest.php @@ -0,0 +1,113 @@ + 'field_test', + 'entity_type' => 'entity_test', + 'type' => 'color_field_type', + ])->save(); + FieldConfig::create([ + 'entity_type' => 'entity_test', + 'field_name' => 'field_test', + 'bundle' => 'entity_test', + ])->save(); + + // Create a second field with different options. + FieldStorageConfig::create([ + 'field_name' => 'field_hex', + 'entity_type' => 'entity_test', + 'type' => 'color_field_type', + 'settings' => [ + 'format' => 'hexhex', + ], + ])->save(); + FieldConfig::create([ + 'entity_type' => 'entity_test', + 'field_name' => 'field_hex', + 'bundle' => 'entity_test', + 'settings' => [ + 'opacity' => FALSE, + ], + ])->save(); + } + + /** + * Tests using entity fields of the telephone field type. + */ + public function testTestItem() { + // Verify entity creation. + $entity = EntityTest::create(); + $color = '#5BCEFA'; + $lcolor = '5bcefa'; + $opacity = 0.5; + $entity->field_test->color = $color; + $entity->field_test->opacity = $opacity; + $entity->field_hex->opacity = 5; + $entity->field_hex->color = $color; + $entity->name->value = $this->randomMachineName(); + $entity->save(); + + // Verify entity has been created properly. + $id = $entity->id(); + $entity = EntityTest::load($id); + $this->assertTrue($entity->field_test instanceof FieldItemListInterface, 'Field implements interface.'); + $this->assertTrue($entity->field_test[0] instanceof FieldItemInterface, 'Field item implements interface.'); + $this->assertEquals($color, $entity->field_test->color); + $this->assertEquals($opacity, $entity->field_test->opacity); + $this->assertEquals($color, $entity->field_test[0]->color); + + // Verify field setting is respected. + $this->assertEquals($lcolor, $entity->field_hex->color); + $this->assertEquals('', $entity->field_hex->opacity); + + // Verify changing the field value. + $new_value = '#FFFFFF'; + $entity->field_test->color = $new_value; + $this->assertEquals($new_value, $entity->field_test->color); + + // Read changed entity and assert changed values. + $entity->save(); + $entity = EntityTest::load($id); + $this->assertEquals($new_value, $entity->field_test->color); + + // Verify setting the color with one format will save as the desired format. + $new_value = 'F5A9B8'; + $entity->field_test->color = $new_value; + $this->assertEquals($new_value, $entity->field_test->color); + + // Test sample item generation. + $entity = EntityTest::create(); + $entity->field_test->generateSampleItems(); + $this->entityValidateAndSave($entity); + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_plus/config/schema/migrate_plus.data_types.schema.yml b/sites/all/modules/contrib/migrate/migrate_plus/config/schema/migrate_plus.data_types.schema.yml index 27c8006f4..92e8288ec 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/config/schema/migrate_plus.data_types.schema.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/config/schema/migrate_plus.data_types.schema.yml @@ -6,7 +6,6 @@ migrate_plugin: plugin: type: string label: 'Plugin' - migrate_destination: type: migrate_plugin label: 'Destination' @@ -25,6 +24,35 @@ migrate_source: constants: type: ignore label: 'Constants' + ids: + type: ignore + label: 'Source IDs schema definition for migrate mapping table' + urls: + type: sequence + label: 'URLs from which to fetch' + sequence: + type: string + data_fetcher_plugin: + type: string + label: 'Fetcher plugin' + data_parser_plugin: + type: string + label: 'Parser plugin' + fields: + type: ignore + label: Mapping of field names to selectors + function: + type: string + label: 'Function to call on the service' + parameters: + type: ignore + label: 'Parameters to pass to function on the service' + response_type: + type: string + label: 'Type of response; XML string, object or array' + item_selector: + type: string + label: 'XPath selector' migrate_process: type: migrate_plugin diff --git a/sites/all/modules/contrib/migrate/migrate_plus/config/schema/migrate_plus.process.schema.yml b/sites/all/modules/contrib/migrate/migrate_plus/config/schema/migrate_plus.process.schema.yml index b1f123bc3..7b90a3d4e 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/config/schema/migrate_plus.process.schema.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/config/schema/migrate_plus.process.schema.yml @@ -71,9 +71,9 @@ migrate_plus.process.get: type: string label: 'Source key' -migrate_plus.process.iterator: +migrate_plus.process.sub_process: type: migrate_process - label: 'Iterator process' + label: 'Sub process' mapping: process: type: ignore diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_node.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_node.yml index 321c576df..7494d1f40 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_node.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_node.yml @@ -2,6 +2,8 @@ id: beer_node label: Beers of the world migration_group: beer +migration_tags: + - example source: plugin: beer_node destination: diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_term.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_term.yml index a8ab579b3..c091b63d7 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_term.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_term.yml @@ -12,6 +12,10 @@ label: Migrate style categories from the source database to taxonomy terms # configuration to be merged with our own configuration here). migration_group: beer +# The category or tag for the migration. +migration_tags: + - example + # Every migration must have a source plugin, which controls the delivery of our # source data. In this case, our source plugin has the name "beer_term", which # Drupal resolves to the PHP class defined in diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_user.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_user.yml index 4bd5b7f23..d31b7253e 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_user.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/config/install/migrate_plus.migration.beer_user.yml @@ -4,6 +4,8 @@ id: beer_user label: Beer Drinkers of the world migration_group: beer +migration_tags: + - example source: plugin: beer_user destination: diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/migrate_example.info.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/migrate_example.info.yml index bd446988f..5ff995788 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/migrate_example.info.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/migrate_example.info.yml @@ -10,8 +10,8 @@ dependencies: - drupal:menu_ui - drupal:path -# Information added by Drupal.org packaging script on 2018-02-23 -version: '8.x-4.0-beta3' +# Information added by Drupal.org packaging script on 2018-09-06 +version: '8.x-4.0' core: '8.x' project: 'migrate_plus' -datestamp: 1519400598 +datestamp: 1536264189 diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/migrate_example_setup/migrate_example_setup.info.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/migrate_example_setup/migrate_example_setup.info.yml index ab36c1e3d..b9dd2672c 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/migrate_example_setup/migrate_example_setup.info.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example/migrate_example_setup/migrate_example_setup.info.yml @@ -11,8 +11,8 @@ dependencies: - drupal:options - drupal:taxonomy -# Information added by Drupal.org packaging script on 2018-02-23 -version: '8.x-4.0-beta3' +# Information added by Drupal.org packaging script on 2018-09-06 +version: '8.x-4.0' core: '8.x' project: 'migrate_plus' -datestamp: 1519400598 +datestamp: 1536264189 diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.weather_soap.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.weather_soap.yml index ae2ad03ab..328bcca84 100755 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.weather_soap.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.weather_soap.yml @@ -2,13 +2,16 @@ id: weather_soap label: SOAP service providing weather. migration_group: wine +migration_tags: + - advanced example source: # We use the SOAP parser source plugin. plugin: url data_fetcher_plugin: http # Ignored - SoapClient does the fetching. data_parser_plugin: soap # URL of a WSDL endpoint. - urls: http://www.webservicex.net/globalweather.asmx?WSDL + urls: + - http://www.webservicex.net/globalweather.asmx?WSDL # The function to call on the service, and the parameters to pass. See # http://www.webservicex.net/New/Home/ServiceDetail/56 for the XML structure # of this feed - how CountryName is passed within the GetCitiesByCountry @@ -48,3 +51,6 @@ process: name: City destination: plugin: entity:taxonomy_term +migration_dependencies: + required: {} + optional: {} diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_role_json.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_role_json.yml index e8991a699..d7d3953af 100755 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_role_json.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_role_json.yml @@ -2,6 +2,8 @@ id: wine_role_json label: JSON feed of roles (positions) migration_group: wine +migration_tags: + - advanced example source: # We use the JSON source plugin. plugin: url @@ -17,7 +19,8 @@ source: # Normally, this is one or more fully-qualified URLs or file paths. Because # we can't hardcode your local URL, we provide a relative path here which # hook_install() will rewrite to a full URL for the current site. - urls: /migrate_example_advanced_position?_format=json + urls: + - /migrate_example_advanced_position?_format=json # An xpath-like selector corresponding to the items to be imported. item_selector: position # Under 'fields', we list the data items to be imported. The first level keys diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_role_xml.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_role_xml.yml index 6b7234c24..b5032a4f1 100755 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_role_xml.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_role_xml.yml @@ -2,6 +2,8 @@ id: wine_role_xml label: XML feed of roles (positions) migration_group: wine +migration_tags: + - advanced example source: # We use the XML data parser plugin. plugin: url @@ -10,7 +12,8 @@ source: # Normally, this is one or more fully-qualified URLs or file paths. Because # we can't hardcode your local URL, we provide a relative path here which # hook_install() will rewrite to a full URL for the current site. - urls: /migrate_example_advanced_position?_format=xml + urls: + - /migrate_example_advanced_position?_format=xml # Visit the URL above (relative to your site root) and look at it. You can see # that is the outer element, and each item we want to import is a # element. The item_xpath value is the xpath to use to query the diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_terms.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_terms.yml index 9f7e8047d..56eb27386 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_terms.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_terms.yml @@ -1,6 +1,8 @@ id: wine_terms label: Migrate all categories into Drupal taxonomy terms migration_group: wine +migration_tags: + - advanced example source: plugin: wine_term destination: diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_variety_list.yml.txt b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_variety_list.yml.txt index f8bd712d5..ff88862b2 100755 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_variety_list.yml.txt +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_variety_list.yml.txt @@ -3,13 +3,16 @@ id: wine_variety_list label: XML feed of varieties migration_group: wine +migration_tags: + - advanced example source: # We use the XML source plugin. plugin: xml # Normally, this is one or more fully-qualified URLs or file paths. Because # we can't hardcode your local URL, we provide a relative path here which # hook_install() will rewrite to a full URL for the current site. - urls: /migrate_example_advanced_variety_list?_format=xml + urls: + - /migrate_example_advanced_variety_list?_format=xml item_url: /migrate_example_advanced_variety_list/:id?_format=xml id_selector: /response/items # Visit the URL above (relative to your site root) and look at it. You can see diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_variety_multi_xml.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_variety_multi_xml.yml index 318b3c1b1..a501a7e75 100755 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_variety_multi_xml.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/config/install/migrate_plus.migration.wine_variety_multi_xml.yml @@ -2,6 +2,8 @@ id: wine_variety_multi_xml label: XML feed of varieties migration_group: wine +migration_tags: + - advanced example source: # We use the XML source plugin. plugin: url diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced.info.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced.info.yml index b0226fb3e..1d396e34b 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced.info.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced.info.yml @@ -8,8 +8,8 @@ dependencies: - migrate_plus:migrate_example_advanced_setup - migrate_plus:migrate_plus -# Information added by Drupal.org packaging script on 2018-02-23 -version: '8.x-4.0-beta3' +# Information added by Drupal.org packaging script on 2018-09-06 +version: '8.x-4.0' core: '8.x' project: 'migrate_plus' -datestamp: 1519400598 +datestamp: 1536264189 diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced.install b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced.install index fa931770c..2023bdee1 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced.install +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced.install @@ -21,7 +21,11 @@ function migrate_example_advanced_install() { if ($wine_role_xml_migration) { $source = $wine_role_xml_migration->get('source'); $request = \Drupal::request(); - $source['urls'] = 'http://' . $request->getHttpHost() . $source['urls']; + $urls = []; + foreach ($source['urls'] as $url) { + $urls[] = 'http://' . $request->getHttpHost() . $url; + } + $source['urls'] = $urls; $wine_role_xml_migration->set('source', $source); $wine_role_xml_migration->save(); } @@ -30,7 +34,11 @@ function migrate_example_advanced_install() { if ($wine_role_json_migration) { $source = $wine_role_json_migration->get('source'); $request = \Drupal::request(); - $source['urls'] = 'http://' . $request->getHttpHost() . $source['urls']; + $urls = []; + foreach ($source['urls'] as $url) { + $urls[] = 'http://' . $request->getHttpHost() . $url; + } + $source['urls'] = $urls; $wine_role_json_migration->set('source', $source); $wine_role_json_migration->save(); } diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced_setup/migrate_example_advanced_setup.info.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced_setup/migrate_example_advanced_setup.info.yml index 8913482e0..870586568 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced_setup/migrate_example_advanced_setup.info.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_example_advanced/migrate_example_advanced_setup/migrate_example_advanced_setup.info.yml @@ -11,8 +11,8 @@ dependencies: - drupal:taxonomy - drupal:rest -# Information added by Drupal.org packaging script on 2018-02-23 -version: '8.x-4.0-beta3' +# Information added by Drupal.org packaging script on 2018-09-06 +version: '8.x-4.0' core: '8.x' project: 'migrate_plus' -datestamp: 1519400598 +datestamp: 1536264189 diff --git a/sites/all/modules/contrib/migrate/migrate_plus/migrate_plus.info.yml b/sites/all/modules/contrib/migrate/migrate_plus/migrate_plus.info.yml index e63da44a9..c5c0e29c6 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/migrate_plus.info.yml +++ b/sites/all/modules/contrib/migrate/migrate_plus/migrate_plus.info.yml @@ -6,8 +6,8 @@ package: Migration dependencies: - drupal:migrate (>=8.3) -# Information added by Drupal.org packaging script on 2018-02-23 -version: '8.x-4.0-beta3' +# Information added by Drupal.org packaging script on 2018-09-06 +version: '8.x-4.0' core: '8.x' project: 'migrate_plus' -datestamp: 1519400598 +datestamp: 1536264189 diff --git a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/EntityGenerate.php b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/EntityGenerate.php index 7361f7327..a749a6388 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/EntityGenerate.php +++ b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/EntityGenerate.php @@ -2,8 +2,13 @@ namespace Drupal\migrate_plus\Plugin\migrate\process; +use Drupal\Core\Entity\EntityManagerInterface; +use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface; use Drupal\migrate\MigrateExecutableInterface; +use Drupal\migrate\Plugin\MigratePluginManager; +use Drupal\migrate\Plugin\MigrationInterface; use Drupal\migrate\Row; +use Symfony\Component\DependencyInjection\ContainerInterface; /** * This plugin generates entities within the process plugin. @@ -16,10 +21,10 @@ use Drupal\migrate\Row; * * All the configuration from the lookup plugin applies here. In its most * simple form, this plugin needs no configuration. If there are fields on the - * generated entity that are required or need some default value, that can be - * provided via a default_values configuration option. + * generated entity that are required or need some value, their values can be + * provided via values and/or default_values configuration options. * - * Example usage with default_values configuration: + * Example usage with values and default_values configuration: * @code * destination: * plugin: 'entity:node' @@ -27,20 +32,86 @@ use Drupal\migrate\Row; * type: * plugin: default_value * default_value: page + * foo: bar * field_tags: * plugin: entity_generate * source: tags * default_values: * description: Default description - * field_long_description: Default long description + * values: + * field_long_description: some_source_field + * field_foo: '@foo' * @endcode */ class EntityGenerate extends EntityLookup { + /** + * The row from the source to process. + * + * @var \Drupal\migrate\Row + */ + protected $row; + + /** + * The MigrateExecutable instance. + * + * @var \Drupal\migrate\MigrateExecutable + */ + protected $migrateExecutable; + + /** + * The get process plugin instance. + * + * @var \Drupal\migrate\Plugin\migrate\process\Get + */ + protected $getProcessPlugin; + + /** + * EntityGenerate constructor. + * + * @param array $configuration + * A configuration array containing information about the plugin instance. + * @param string $pluginId + * The plugin_id for the plugin instance. + * @param mixed $pluginDefinition + * The plugin implementation definition. + * @param \Drupal\migrate\Plugin\MigrationInterface $migration + * The migration. + * @param \Drupal\Core\Entity\EntityManagerInterface $entityManager + * The $entityManager instance. + * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface $selectionPluginManager + * The $selectionPluginManager instance. + * @param \Drupal\migrate\Plugin\MigratePluginManager $migratePluginManager + * The MigratePluginManager instance. + */ + public function __construct(array $configuration, $pluginId, $pluginDefinition, MigrationInterface $migration, EntityManagerInterface $entityManager, SelectionPluginManagerInterface $selectionPluginManager, MigratePluginManager $migratePluginManager) { + parent::__construct($configuration, $pluginId, $pluginDefinition, $migration, $entityManager, $selectionPluginManager); + if (isset($configuration['values'])) { + $this->getProcessPlugin = $migratePluginManager->createInstance('get', ['source' => $configuration['values']]); + } + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition, MigrationInterface $migration = NULL) { + return new static( + $configuration, + $pluginId, + $pluginDefinition, + $migration, + $container->get('entity.manager'), + $container->get('plugin.manager.entity_reference_selection'), + $container->get('plugin.manager.migrate.process') + ); + } + /** * {@inheritdoc} */ public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) { + $this->row = $row; + $this->migrateExecutable = $migrateExecutable; // Creates an entity if the lookup determines it doesn't exist. if (!($result = parent::transform($value, $migrateExecutable, $row, $destinationProperty))) { $result = $this->generateEntity($value); @@ -94,6 +165,13 @@ class EntityGenerate extends EntityLookup { $entity_values[$key] = $value; } } + // Gather any additional properties/fields. + if (isset($this->configuration['values']) && is_array($this->configuration['values'])) { + foreach ($this->configuration['values'] as $key => $property) { + $source_value = $this->getProcessPlugin->transform(NULL, $this->migrateExecutable, $this->row, $property); + $entity_values[$key] = $source_value; + } + } return $entity_values; } diff --git a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/EntityLookup.php b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/EntityLookup.php index d02bb9124..2ae0d07c1 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/EntityLookup.php +++ b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/EntityLookup.php @@ -2,6 +2,7 @@ namespace Drupal\migrate_plus\Plugin\migrate\process; +use Drupal\Core\Config\Entity\ConfigEntityInterface; use Drupal\Core\Entity\EntityManagerInterface; use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; @@ -152,6 +153,11 @@ class EntityLookup extends ProcessPluginBase implements ContainerFactoryPluginIn * {@inheritdoc} */ public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) { + // If the source data is an empty array, return the same. + if (gettype($value) === 'array' && count($value) === 0) { + return []; + } + // In case of subfields ('field_reference/target_id'), extract the field // name only. $parts = explode('/', $destinationProperty); @@ -270,7 +276,8 @@ class EntityLookup extends ProcessPluginBase implements ContainerFactoryPluginIn if (!$ignoreCase) { // Returns the entity's identifier. foreach ($results as $k => $identifier) { - $result_value = $this->entityManager->getStorage($this->lookupEntityType)->load($identifier)->{$this->lookupValueKey}->value; + $entity = $this->entityManager->getStorage($this->lookupEntityType)->load($identifier); + $result_value = $entity instanceof ConfigEntityInterface ? $entity->get($this->lookupValueKey) : $entity->get($this->lookupValueKey)->value; if (($multiple && !in_array($result_value, $value, TRUE)) || (!$multiple && $result_value !== $value)) { unset($results[$k]); } diff --git a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/Merge.php b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/Merge.php index 1e0467917..463595e9d 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/Merge.php +++ b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/Merge.php @@ -41,8 +41,8 @@ use Drupal\migrate\Row; * paragraphs_field: * plugin: merge * source: - * - @temp_body - * - @temp_images + * - '@temp_body' + * - '@temp_images' * destination: * plugin: 'entity:node' */ @@ -53,12 +53,12 @@ class Merge extends ProcessPluginBase { */ public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { if (!is_array($value)) { - throw new MigrateException('Input should be an array.'); + throw new MigrateException(sprintf('Merge process failed for destination property (%s): input is not an array.', $destination_property)); } $new_value = []; - foreach ($value as $item) { + foreach($value as $i => $item) { if (!is_array($item)) { - throw new MigrateException('One of the items is not an array that can be merged.'); + throw new MigrateException(sprintf('Merge process failed for destination property (%s): index (%s) in the source value is not an array that can be merged.', $destination_property, $i)); } $new_value = array_merge($new_value, $item); } diff --git a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/MultipleValues.php b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/MultipleValues.php new file mode 100644 index 000000000..be6779a12 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate/process/MultipleValues.php @@ -0,0 +1,58 @@ +configuration['value'])) { + $value_in_array = FALSE; + $not_equals = isset($this->configuration['not_equals']); + foreach ($this->configuration['value'] as $skipValue) { - if ($this->compareValue($value, $skipValue, !isset($this->configuration['not_equals']))) { - throw new MigrateSkipRowException(); - } + $value_in_array |= $this->compareValue($value, $skipValue); + } + + if (($not_equals && !$value_in_array) || (!$not_equals && $value_in_array)) { + throw new MigrateSkipRowException(); } } elseif ($this->compareValue($value, $this->configuration['value'], !isset($this->configuration['not_equals']))) { @@ -49,10 +92,15 @@ class SkipOnValue extends ProcessPluginBase { } if (is_array($this->configuration['value'])) { + $value_in_array = FALSE; + $not_equals = isset($this->configuration['not_equals']); + foreach ($this->configuration['value'] as $skipValue) { - if ($this->compareValue($value, $skipValue, !isset($this->configuration['not_equals']))) { - throw new MigrateSkipProcessException(); - } + $value_in_array |= $this->compareValue($value, $skipValue); + } + + if (($not_equals && !$value_in_array) || (!$not_equals && $value_in_array)) { + throw new MigrateSkipProcessException(); } } elseif ($this->compareValue($value, $this->configuration['value'], !isset($this->configuration['not_equals']))) { diff --git a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate_plus/data_parser/Json.php b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate_plus/data_parser/Json.php index df9b3fca8..c1220bc5f 100755 --- a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate_plus/data_parser/Json.php +++ b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate_plus/data_parser/Json.php @@ -15,13 +15,6 @@ use Drupal\migrate_plus\DataParserPluginBase; */ class Json extends DataParserPluginBase implements ContainerFactoryPluginInterface { - /** - * The request headers passed to the data fetcher. - * - * @var array - */ - protected $headers = []; - /** * Iterator over the JSON data. * @@ -119,7 +112,12 @@ class Json extends DataParserPluginBase implements ContainerFactoryPluginInterfa $field_data = $current; $field_selectors = explode('/', trim($selector, '/')); foreach ($field_selectors as $field_selector) { - $field_data = $field_data[$field_selector]; + if (is_array($field_data) && array_key_exists($field_selector, $field_data)) { + $field_data = $field_data[$field_selector]; + } + else { + $field_data = ''; + } } $this->currentItem[$field_name] = $field_data; } diff --git a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate_plus/data_parser/SimpleXml.php b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate_plus/data_parser/SimpleXml.php index a33b6a086..8a58d8b07 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate_plus/data_parser/SimpleXml.php +++ b/sites/all/modules/contrib/migrate/migrate_plus/src/Plugin/migrate_plus/data_parser/SimpleXml.php @@ -77,7 +77,7 @@ class SimpleXml extends DataParserPluginBase { } // Reduce single-value results to scalars. foreach ($this->currentItem as $field_name => $values) { - if (count($values) == 1) { + if (is_array($values) && count($values) == 1) { $this->currentItem[$field_name] = reset($values); } } diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/data/missing_properties.json b/sites/all/modules/contrib/migrate/migrate_plus/tests/data/missing_properties.json new file mode 100644 index 000000000..59b7d6a6e --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/data/missing_properties.json @@ -0,0 +1,21 @@ +[ + { + "id": "1", + "title": "Title", + "video": { + "title": "Video title", + "url": "https://localhost/" + } + }, + { + "id": "2", + "video": { + "title": "Video title", + "url": "https://localhost/" + } + }, + { + "id": "3", + "title": "Title 3" + } +] diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/data/simple_xml_reduce_single_value.xml b/sites/all/modules/contrib/migrate/migrate_plus/tests/data/simple_xml_reduce_single_value.xml new file mode 100644 index 000000000..0cffd2890 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/data/simple_xml_reduce_single_value.xml @@ -0,0 +1,14 @@ + + + + + Value 1 + Value 2 + + + + + Value 1 (single) + + + diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Functional/LoadTest.php b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Functional/LoadTest.php new file mode 100644 index 000000000..c9aceda72 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Functional/LoadTest.php @@ -0,0 +1,50 @@ +user = $this->drupalCreateUser(['administer site configuration']); + $this->drupalLogin($this->user); + } + + /** + * Tests that the home page loads with a 200 response. + */ + public function testLoad() { + $this->drupalGet(Url::fromRoute('')); + $this->assertSession()->statusCodeEquals(200); + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate/process/EntityGenerateTest.php b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate/process/EntityGenerateTest.php index a4c0f27f6..3d46496de 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate/process/EntityGenerateTest.php +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate/process/EntityGenerateTest.php @@ -2,6 +2,7 @@ namespace Drupal\Tests\migrate_plus\Kernel\Plugin\migrate\process; +use Drupal\Core\Config\Entity\ConfigEntityInterface; use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\Core\Language\LanguageInterface; use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait; @@ -119,12 +120,16 @@ class EntityGenerateTest extends KernelTestBase implements MigrateMessageInterfa public function testTransform(array $definition, array $expected, array $preSeed = []) { // Pre seed some test data. foreach ($preSeed as $storageName => $values) { - /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */ - $storage = $this->container - ->get('entity_type.manager') - ->getStorage($storageName); - $entity = $storage->create($values); - $entity->save(); + // If the first element of $values is a non-empty array, create multiple + // entities. Otherwise, create just one entity. + if (isset($values[0])) { + foreach ($values as $itemValues) { + $this->createTestData($storageName, $itemValues); + } + } + else { + $this->createTestData($storageName, $values); + } } /** @var \Drupal\migrate\Plugin\Migration $migration */ @@ -139,15 +144,54 @@ class EntityGenerateTest extends KernelTestBase implements MigrateMessageInterfa $properties = array_diff_key($row, array_flip(['id'])); foreach ($properties as $property => $value) { if (is_array($value)) { - foreach ($value as $key => $expectedValue) { - if (empty($expectedValue)) { - $this->assertEmpty($entity->{$property}->getValue(), "Expected value is empty but field $property is not empty."); - } - elseif ($entity->{$property}->getValue()) { - $this->assertEquals($expectedValue, $entity->{$property}[0]->entity->$key->value); + if (empty($value)) { + $this->assertEmpty($entity->{$property}->getValue(), "Expected value is 'unset' but field $property is set."); + } + else { + // Check if we're testing multiple values in one field. If so, loop + // through them one-by-one and check that they're present in the + // $entity. + if (isset($value[0])) { + foreach ($value as $valueID => $valueToCheck) { + foreach ($valueToCheck as $key => $expectedValue) { + if (empty($expectedValue)) { + if (!$entity->{$property}->isEmpty()) { + $this->assertTrue($entity->{$property}[0]->entity->$key->isEmpty(), "Expected value is empty but field $property.$key is not empty."); + } + else { + $this->assertTrue($entity->{$property}->isEmpty(), "FOOBAR Expected value is empty but field $property is not empty."); + } + } + elseif ($entity->{$property}->getValue()) { + $this->assertEquals($expectedValue, $entity->{$property}[$valueID]->entity->$key->value); + } + else { + $this->fail("Expected value: $expectedValue does not exist in $property."); + } + } + } } + // If we get to this point, we're only checking a + // single field value. else { - $this->fail("Expected value: $expectedValue does not exist in $property."); + foreach ($value as $key => $expectedValue) { + if (empty($expectedValue)) { + if (!$entity->{$property}->isEmpty()) { + $this->assertTrue($entity->{$property}[0]->entity->$key->isEmpty(), "Expected value is empty but field $property.$key is not empty."); + } + else { + $this->assertTrue($entity->{$property}->isEmpty(), "BINBAZ Expected value is empty but field $property is not empty."); + } + } + elseif ($entity->{$property}->getValue()) { + $referenced_entity = $entity->{$property}[0]->entity; + $result_value = $referenced_entity instanceof ConfigEntityInterface ? $referenced_entity->get($key) : $referenced_entity->get($key)->value; + $this->assertEquals($expectedValue, $result_value); + } + else { + $this->fail("Expected value: $expectedValue does not exist in $property."); + } + } } } } @@ -314,6 +358,406 @@ class EntityGenerateTest extends KernelTestBase implements MigrateMessageInterfa ], ], ], + 'provide values' => [ + 'definition' => [ + 'source' => [ + 'plugin' => 'embedded_data', + 'data_rows' => [ + [ + 'id' => 1, + 'title' => 'content item 1', + 'term' => 'Apples', + ], + [ + 'id' => 2, + 'title' => 'content item 2', + 'term' => 'Bananas', + ], + [ + 'id' => 3, + 'title' => 'content item 3', + 'term' => 'Grapes', + ], + ], + 'ids' => [ + 'id' => ['type' => 'integer'], + ], + ], + 'process' => [ + 'id' => 'id', + 'type' => [ + 'plugin' => 'default_value', + 'default_value' => $this->bundle, + ], + 'title' => 'title', + 'term_upper' => [ + 'plugin' => 'callback', + 'source' => 'term', + 'callable' => 'strtoupper', + ], + $this->fieldName => [ + 'plugin' => 'entity_generate', + 'source' => 'term', + 'values' => [ + 'description' => '@term_upper', + ], + ], + ], + 'destination' => [ + 'plugin' => 'entity:node', + ], + ], + 'expected' => [ + 'row 1' => [ + 'id' => 1, + 'title' => 'content item 1', + $this->fieldName => [ + 'tid' => 2, + 'name' => 'Apples', + 'description' => 'APPLES', + ], + ], + 'row 2' => [ + 'id' => 2, + 'title' => 'content item 2', + $this->fieldName => [ + 'tid' => 3, + 'name' => 'Bananas', + 'description' => 'BANANAS', + ], + ], + 'row 3' => [ + 'id' => 3, + 'title' => 'content item 3', + $this->fieldName => [ + 'tid' => 1, + 'name' => 'Grapes', + 'description' => NULL, + ], + ], + ], + 'pre seed' => [ + 'taxonomy_term' => [ + 'name' => 'Grapes', + 'vid' => $this->vocabulary, + 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, + ], + ], + ], + 'lookup single existing term returns correct term' => [ + 'definition' => [ + 'source' => [ + 'plugin' => 'embedded_data', + 'data_rows' => [ + [ + 'id' => 1, + 'title' => 'content item 1', + 'term' => 'Grapes', + ], + ], + 'ids' => [ + 'id' => ['type' => 'integer'], + ], + ], + 'process' => [ + 'id' => 'id', + 'type' => [ + 'plugin' => 'default_value', + 'default_value' => $this->bundle, + ], + 'title' => 'title', + $this->fieldName => [ + 'plugin' => 'entity_lookup', + 'source' => 'term', + ], + ], + 'destination' => [ + 'plugin' => 'entity:node', + ], + ], + 'expected' => [ + 'row 1' => [ + 'id' => 1, + 'title' => 'content item 1', + $this->fieldName => [ + 'tid' => 1, + 'name' => 'Grapes', + ], + ], + ], + 'pre seed' => [ + 'taxonomy_term' => [ + 'name' => 'Grapes', + 'vid' => $this->vocabulary, + 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, + ], + ], + ], + 'lookup single missing term returns null value' => [ + 'definition' => [ + 'source' => [ + 'plugin' => 'embedded_data', + 'data_rows' => [ + [ + 'id' => 1, + 'title' => 'content item 1', + 'term' => 'Apple', + ], + ], + 'ids' => [ + 'id' => ['type' => 'integer'], + ], + ], + 'process' => [ + 'id' => 'id', + 'type' => [ + 'plugin' => 'default_value', + 'default_value' => $this->bundle, + ], + 'title' => 'title', + $this->fieldName => [ + 'plugin' => 'entity_lookup', + 'source' => 'term', + ], + ], + 'destination' => [ + 'plugin' => 'entity:node', + ], + ], + 'expected' => [ + 'row 1' => [ + 'id' => 1, + 'title' => 'content item 1', + $this->fieldName => [], + ], + ], + 'pre seed' => [ + 'taxonomy_term' => [ + 'name' => 'Grapes', + 'vid' => $this->vocabulary, + 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, + ], + ], + ], + 'lookup multiple existing terms returns correct terms' => [ + 'definition' => [ + 'source' => [ + 'plugin' => 'embedded_data', + 'data_rows' => [ + [ + 'id' => 1, + 'title' => 'content item 1', + 'term' => [ + 'Grapes', + 'Apples', + ], + ], + ], + 'ids' => [ + 'id' => ['type' => 'integer'], + ], + ], + 'process' => [ + 'id' => 'id', + 'title' => 'title', + 'type' => [ + 'plugin' => 'default_value', + 'default_value' => $this->bundle, + ], + $this->fieldName => [ + 'plugin' => 'entity_lookup', + 'source' => 'term', + ], + ], + 'destination' => [ + 'plugin' => 'entity:node', + ], + ], + 'expected' => [ + 'row 1' => [ + 'id' => 1, + 'title' => 'content item 1', + $this->fieldName => [ + [ + 'tid' => 1, + 'name' => 'Grapes', + ], + [ + 'tid' => 2, + 'name' => 'Apples', + ], + ], + ], + ], + 'pre seed' => [ + 'taxonomy_term' => [ + [ + 'name' => 'Grapes', + 'vid' => $this->vocabulary, + 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, + ], + [ + 'name' => 'Apples', + 'vid' => $this->vocabulary, + 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, + ], + ], + ], + ], + 'lookup multiple mixed terms returns correct terms' => [ + 'definition' => [ + 'source' => [ + 'plugin' => 'embedded_data', + 'data_rows' => [ + [ + 'id' => 1, + 'title' => 'content item 1', + 'term' => [ + 'Grapes', + 'Pears', + ], + ], + ], + 'ids' => [ + 'id' => ['type' => 'integer'], + ], + ], + 'process' => [ + 'id' => 'id', + 'title' => 'title', + 'type' => [ + 'plugin' => 'default_value', + 'default_value' => $this->bundle, + ], + $this->fieldName => [ + 'plugin' => 'entity_lookup', + 'source' => 'term', + ], + ], + 'destination' => [ + 'plugin' => 'entity:node', + ], + ], + 'expected' => [ + 'row 1' => [ + 'id' => '1', + 'title' => 'content item 1', + $this->fieldName => [ + [ + 'tid' => 1, + 'name' => 'Grapes', + ], + ], + ], + ], + 'pre seed' => [ + 'taxonomy_term' => [ + [ + 'name' => 'Grapes', + 'vid' => $this->vocabulary, + 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, + ], + [ + 'name' => 'Apples', + 'vid' => $this->vocabulary, + 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, + ], + ], + ], + ], + 'lookup with empty term value returns no terms' => [ + 'definition' => [ + 'source' => [ + 'plugin' => 'embedded_data', + 'data_rows' => [ + [ + 'id' => 1, + 'title' => 'content item 1', + 'term' => [], + ], + ], + 'ids' => [ + 'id' => ['type' => 'integer'], + ], + ], + 'process' => [ + 'id' => 'id', + 'title' => 'title', + 'type' => [ + 'plugin' => 'default_value', + 'default_value' => $this->bundle, + ], + $this->fieldName => [ + 'plugin' => 'entity_lookup', + 'source' => 'term', + ], + ], + 'destination' => [ + 'plugin' => 'entity:node', + ], + ], + 'expected' => [ + 'row 1' => [ + 'id' => 1, + 'title' => 'content item 1', + $this->fieldName => [], + ], + ], + 'pre seed' => [ + 'taxonomy_term' => [ + 'name' => 'Grapes', + 'vid' => $this->vocabulary, + 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, + ], + ], + ], + 'lookup config entity' => [ + 'definition' => [ + 'source' => [ + 'plugin' => 'embedded_data', + 'data_rows' => [ + [ + 'id' => 1, + 'name' => 'user 1', + 'mail' => 'user1@user1.com', + 'roles' => ['role_1'], + ], + ], + 'ids' => [ + 'id' => ['type' => 'integer'], + ], + ], + 'process' => [ + 'id' => 'id', + 'name' => 'name', + 'roles' => [ + 'plugin' => 'entity_lookup', + 'entity_type' => 'user_role', + 'value_key' => 'id', + 'source' => 'roles', + ], + ], + 'destination' => [ + 'plugin' => 'entity:user', + ], + ], + 'expected' => [ + 'row 1' => [ + 'id' => 1, + 'name' => 'user 1', + 'roles' => [ + 'id' => 'role_1', + 'label' => 'Role 1', + ], + ], + ], + 'pre seed' => [ + 'user_role' => [ + 'id' => 'role_1', + 'label' => 'Role 1', + ], + ], + ], ]; } @@ -324,4 +768,21 @@ class EntityGenerateTest extends KernelTestBase implements MigrateMessageInterfa $this->assertTrue($type == 'status', $message); } + /** + * Create pre-seed test data. + * + * @param string $storageName + * The storage manager to create. + * @param array $values + * The values to use when creating the entity. + */ + private function createTestData($storageName, array $values) { + /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */ + $storage = $this->container + ->get('entity_type.manager') + ->getStorage($storageName); + $entity = $storage->create($values); + $entity->save(); + } + } diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate_plus/data_parser/JsonTest.php b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate_plus/data_parser/JsonTest.php new file mode 100644 index 000000000..2fb4f2458 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate_plus/data_parser/JsonTest.php @@ -0,0 +1,112 @@ +container + ->get('module_handler') + ->getModule('migrate_plus') + ->getPath(); + $url = $path . '/tests/data/' . $file; + + /** @var \Drupal\migrate_plus\DataParserPluginManager $plugin_manager */ + $plugin_manager = $this->container + ->get('plugin.manager.migrate_plus.data_parser'); + $conf = [ + 'plugin' => 'url', + 'data_fetcher_plugin' => 'file', + 'data_parser_plugin' => 'json', + 'destination' => 'node', + 'urls' => [$url], + 'ids' => $ids, + 'fields' => $fields, + 'item_selector' => NULL, + ]; + $json_parser = $plugin_manager->createInstance('json', $conf); + + $data = []; + foreach ($json_parser as $item) { + $data[] = $item; + } + + $this->assertEquals($expected, $data); + } + + /** + * Provides multiple test cases for the testMissingProperty method. + * + * @return array + * The test cases. + */ + public function jsonBaseDataProvider() { + return [ + 'missing properties' => [ + 'file' => 'missing_properties.json', + 'ids' => ['id' => ['type' => 'integer']], + 'fields' => [ + [ + 'name' => 'id', + 'label' => 'Id', + 'selector' => '/id', + ], + [ + 'name' => 'title', + 'label' => 'Title', + 'selector' => '/title', + ], + [ + 'name' => 'video_url', + 'label' => 'Video url', + 'selector' => '/video/url', + ], + ], + 'expected' => [ + [ + 'id' => '1', + 'title' => 'Title', + 'video_url' => 'https://localhost/', + ], + [ + 'id' => '2', + 'title' => '', + 'video_url' => 'https://localhost/', + ], + [ + 'id' => '3', + 'title' => 'Title 3', + 'video_url' => '', + ], + ], + ], + ]; + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate_plus/data_parser/SimpleXmlTest.php b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate_plus/data_parser/SimpleXmlTest.php new file mode 100644 index 000000000..fe6b345e1 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Kernel/Plugin/migrate_plus/data_parser/SimpleXmlTest.php @@ -0,0 +1,77 @@ +container + ->get('module_handler') + ->getModule('migrate_plus') + ->getPath(); + $url = $path . '/tests/data/simple_xml_reduce_single_value.xml'; + + /** @var \Drupal\migrate_plus\DataParserPluginManager $plugin_manager */ + $plugin_manager = $this->container + ->get('plugin.manager.migrate_plus.data_parser'); + $conf = [ + 'plugin' => 'url', + 'data_fetcher_plugin' => 'file', + 'data_parser_plugin' => 'simple_xml', + 'destination' => 'node', + 'urls' => [$url], + 'ids' => ['id' => ['type' => 'integer']], + 'fields' => [ + [ + 'name' => 'id', + 'label' => 'Id', + 'selector' => '@id', + ], + [ + 'name' => 'values', + 'label' => 'Values', + 'selector' => 'values', + ], + ], + 'item_selector' => '/items/item', + ]; + $parser = $plugin_manager->createInstance('simple_xml', $conf); + + $data = []; + foreach ($parser as $item) { + $values = []; + foreach ($item['values'] as $value) { + $values[] = (string) $value; + } + $data[] = $values; + } + + $expected = [ + [ + 'Value 1', + 'Value 2', + ], + [ + 'Value 1 (single)', + ], + ]; + + $this->assertEquals($expected, $data); + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/MultipleValuesTest.php b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/MultipleValuesTest.php new file mode 100644 index 000000000..60a520c0d --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/MultipleValuesTest.php @@ -0,0 +1,32 @@ +plugin = new MultipleValues([], 'multiple_values', []); + parent::setUp(); + } + + /** + * Test input treated as multiple value output. + */ + public function testTreatAsMultiple() { + $value = ['v1', 'v2', 'v3']; + $output = $this->plugin->transform($value, $this->migrateExecutable, $this->row, 'destinationproperty'); + $this->assertSame($output, $value); + $this->assertTrue($this->plugin->multiple()); + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/SingleValueTest.php b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/SingleValueTest.php new file mode 100644 index 000000000..203b1c5cb --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/SingleValueTest.php @@ -0,0 +1,32 @@ +plugin = new SingleValue([], 'single_value', []); + parent::setUp(); + } + + /** + * Test input treated as single value output. + */ + public function testTreatAsSingle() { + $value = ['v1', 'v2', 'v3']; + $output = $this->plugin->transform($value, $this->migrateExecutable, $this->row, 'destinationproperty'); + $this->assertSame($output, $value); + $this->assertFalse($this->plugin->multiple()); + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/SkipOnValueTest.php b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/SkipOnValueTest.php index c1bdfac23..968e6f0fb 100644 --- a/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/SkipOnValueTest.php +++ b/sites/all/modules/contrib/migrate/migrate_plus/tests/src/Unit/process/SkipOnValueTest.php @@ -65,6 +65,36 @@ class SkipOnValueTest extends MigrateProcessTestCase { $this->assertEquals($value, '4'); } + /** + * @covers ::process + */ + public function testProcessBypassesOnMultipleNonValue() { + $configuration['method'] = 'process'; + $configuration['value'] = [1, 1, 2, 3, 5, 8]; + $configuration['not_equals'] = TRUE; + $value = (new SkipOnValue($configuration, 'skip_on_value', [])) + ->transform(5, $this->migrateExecutable, $this->row, 'destinationproperty'); + $this->assertEquals($value, '5'); + $value = (new SkipOnValue($configuration, 'skip_on_value', [])) + ->transform(1, $this->migrateExecutable, $this->row, 'destinationproperty'); + $this->assertEquals($value, '1'); + } + + /** + * @covers ::row + */ + public function testRowBypassesOnMultipleNonValue() { + $configuration['method'] = 'row'; + $configuration['value'] = [1, 1, 2, 3, 5, 8]; + $configuration['not_equals'] = TRUE; + $value = (new SkipOnValue($configuration, 'skip_on_value', [])) + ->transform(5, $this->migrateExecutable, $this->row, 'destinationproperty'); + $this->assertEquals($value, '5'); + $value = (new SkipOnValue($configuration, 'skip_on_value', [])) + ->transform(1, $this->migrateExecutable, $this->row, 'destinationproperty'); + $this->assertEquals($value, '1'); + } + /** * @covers ::row */ diff --git a/sites/all/modules/contrib/migrate/migrate_tools/composer.json b/sites/all/modules/contrib/migrate/migrate_tools/composer.json index 562c6a254..d5c8fca8f 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/composer.json +++ b/sites/all/modules/contrib/migrate/migrate_tools/composer.json @@ -1,23 +1,27 @@ { - "name": "drupal/migrate_tools", - "description": "Tools to assist in developing and running migrations.", - "type": "drupal-module", - "homepage": "http://drupal.org/project/migrate_tools", - "support": { - "issues": "http://drupal.org/project/migrate_tools", - "irc": "irc://irc.freenode.org/drupal-migrate", - "source": "http://cgit.drupalcode.org/migrate_tools" - }, - "license": "GPL-2.0+", - "require-dev": { - "drupal/coder": "^8" - }, - "minimum-stability": "dev", - "extra": { - "drush": { - "services": { - "drush.services.yml": "^9" - } + "name": "drupal/migrate_tools", + "description": "Tools to assist in developing and running migrations.", + "type": "drupal-module", + "homepage": "http://drupal.org/project/migrate_tools", + "support": { + "issues": "http://drupal.org/project/migrate_tools", + "irc": "irc://irc.freenode.org/drupal-migrate", + "source": "http://cgit.drupalcode.org/migrate_tools" + }, + "license": "GPL-2.0+", + "require": { + "drupal/migrate_plus": "^4" + }, + "require-dev": { + "drupal/coder": "^8", + "drupal/migrate_source_csv": "^2.2" + }, + "minimum-stability": "dev", + "extra": { + "drush": { + "services": { + "drush.services.yml": "^9" } } + } } diff --git a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.info.yml b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.info.yml index 30ccca99f..e3cb18da2 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.info.yml +++ b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.info.yml @@ -6,9 +6,11 @@ package: Migration dependencies: - drupal:migrate (>=8.3) - migrate_plus:migrate_plus +test_dependencies: + - migrate_source_csv:migrate_source_csv (>=8.x-2.2) -# Information added by Drupal.org packaging script on 2018-02-23 -version: '8.x-4.0-beta3' +# Information added by Drupal.org packaging script on 2018-08-27 +version: '8.x-4.0' core: '8.x' project: 'migrate_tools' -datestamp: 1519400307 +datestamp: 1535380087 diff --git a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.links.task.yml b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.links.task.yml index 415d1780a..da508a0ff 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.links.task.yml +++ b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.links.task.yml @@ -39,3 +39,15 @@ entity.migration.delete_form: base_route: entity.migration.overview title: Delete weight: 10 + + +entity.migration.overview_general_edit: + title: Overview + route_name: entity.migration.edit_form + parent_id: entity.migration.edit_form + +entity.migration.overview_source_edit: + title: Source + route_name: migrate_tools.source_csv + parent_id: entity.migration.edit_form + weight: 1 diff --git a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.module b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.module index 6e4dde593..b8113fe3d 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.module +++ b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.module @@ -28,3 +28,31 @@ function migrate_tools_entity_type_build(array &$entity_types) { ->setLinkTemplate('edit-form', '/admin/structure/migrate/manage/{migration_group}') ->setLinkTemplate('delete-form', '/admin/structure/migrate/manage/{migration_group}/delete'); } + +/** + * Implements hook_migration_plugins_alter(). + */ +function migrate_tools_migration_plugins_alter(array &$migrations) { + /** @var \Drupal\Core\TempStore\PrivateTempStoreFactory $store */ + $tempStoreFactory = \Drupal::service('tempstore.private'); + $store = $tempStoreFactory->get('migrate_tools'); + // TODO: remove work-around after + // https://www.drupal.org/project/drupal/issues/2860341 is fixed. + if (!\Drupal::request()->hasSession()) { + $session = \Drupal::service('session'); + \Drupal::request()->setSession($session); + $session->start(); + } + // Get the list of changed migrations. + $migrationsChanged = $store->get('migrations_changed'); + if (isset($store) && (is_array($migrationsChanged))) { + // Alter the source column names for each changed migration. + foreach ($migrationsChanged as $id) { + $data = $store->get($id); + if (isset($data['changed'])) { + $migrations[$id]['source']['column_names'] = $data['changed']; + } + } + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.routing.yml b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.routing.yml index edb4965c7..08f43e5b5 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.routing.yml +++ b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.routing.yml @@ -58,67 +58,140 @@ entity.migration.overview: defaults: _controller: '\Drupal\migrate_tools\Controller\MigrationController::overview' _title: 'Migration overview' + _migrate_group: true requirements: _permission: 'administer migrations' + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group entity.migration.source: path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/source' defaults: _controller: '\Drupal\migrate_tools\Controller\MigrationController::source' _title: 'Source' + _migrate_group: true requirements: _permission: 'administer migrations' + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group entity.migration.process: path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/process' defaults: _controller: '\Drupal\migrate_tools\Controller\MigrationController::process' _title: 'Process' + _migrate_group: true requirements: _permission: 'administer migrations' + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group entity.migration.process.run: path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/process/run' defaults: _controller: '\Drupal\migrate_tools\Controller\MigrationController::run' _title: 'Run' + _migrate_group: true requirements: _permission: 'administer migrations' + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group entity.migration.destination: path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/destination' defaults: _controller: '\Drupal\migrate_tools\Controller\MigrationController::destination' _title: 'Destination' + _migrate_group: true requirements: _permission: 'administer migrations' - + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group # This is the router item for editing our migration entity. entity.migration.edit_form: path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/edit' defaults: _title: 'Edit migration' _entity_form: migration.edit + _migrate_group: true requirements: _entity_access: migration.update - + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group # This is the router item for deleting an instance of our migration entity. entity.migration.delete_form: path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/delete' defaults: _title: 'Delete migration' _entity_form: migration.delete + _migrate_group: true requirements: _entity_access: migration.delete - + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group migrate_tools.messages: path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/messages' defaults: _controller: '\Drupal\migrate_tools\Controller\MessageController::overview' _title: 'Messages' + _migrate_group: true requirements: _permission: 'administer migrations' - + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group migrate_tools.execute: path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/execute' defaults: _form: '\Drupal\migrate_tools\Form\MigrationExecuteForm' _title: 'Execute migration' + _migrate_group: true requirements: _permission: 'administer migrations' + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group +migrate_tools.source_csv: + path: '/admin/structure/migrate/manage/{migration_group}/migrations/{migration}/source/edit' + defaults: + _form: 'Drupal\migrate_tools\Form\SourceCsvForm' + _migrate_group: true + requirements: + _permission: 'administer migrations' + _custom_access: 'Drupal\migrate_tools\Form\SourceCsvForm::access' + options: + parameters: + migration: + type: entity:migration + migration_group: + type: entity:migration_group diff --git a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.services.yml b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.services.yml index 98aebdf28..fa61e007f 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.services.yml +++ b/sites/all/modules/contrib/migrate/migrate_tools/migrate_tools.services.yml @@ -3,3 +3,7 @@ services: class: Drupal\Core\Logger\LoggerChannel factory: logger.factory:get arguments: ['migrate_tools'] + route_processor.migrate_group: + class: Drupal\migrate_tools\Routing\RouteProcessor + tags: + - { name: route_processor_outbound } diff --git a/sites/all/modules/contrib/migrate/migrate_tools/src/Commands/MigrateToolsCommands.php b/sites/all/modules/contrib/migrate/migrate_tools/src/Commands/MigrateToolsCommands.php index 5d3402244..976b3c684 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/src/Commands/MigrateToolsCommands.php +++ b/sites/all/modules/contrib/migrate/migrate_tools/src/Commands/MigrateToolsCommands.php @@ -67,12 +67,7 @@ class MigrateToolsCommands extends DrushCommands { * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $keyValue * Key-value store service. */ - public function __construct( - MigrationPluginManager $migrationPluginManager, - DateFormatter $dateFormatter, - EntityTypeManagerInterface $entityTypeManager, - KeyValueFactoryInterface $keyValue - ) { + public function __construct(MigrationPluginManager $migrationPluginManager, DateFormatter $dateFormatter, EntityTypeManagerInterface $entityTypeManager, KeyValueFactoryInterface $keyValue) { parent::__construct(); $this->migrationPluginManager = $migrationPluginManager; $this->dateFormatter = $dateFormatter; @@ -123,14 +118,7 @@ class MigrateToolsCommands extends DrushCommands { * @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields * Migrations status formatted as table. */ - public function status( - $migration_names = '', - array $options = [ - 'group' => NULL, - 'tag' => NULL, - 'names-only' => NULL, - ] - ) { + public function status($migration_names = '', array $options = ['group' => NULL, 'tag' => NULL, 'names-only' => NULL]) { $names_only = $options['names-only']; $migrations = $this->migrationsList($migration_names, $options); @@ -271,20 +259,7 @@ class MigrateToolsCommands extends DrushCommands { * @throws \Exception * If there are not enough parameters to the command. */ - public function import( - $migration_names = '', - array $options = [ - 'all' => NULL, - 'group' => NULL, - 'tag' => NULL, - 'limit' => NULL, - 'feedback' => NULL, - 'idlist' => NULL, - 'update' => NULL, - 'force' => NULL, - 'execute-dependencies' => NULL, - ] - ) { + public function import($migration_names = '', array $options = ['all' => NULL, 'group' => NULL, 'tag' => NULL, 'limit' => NULL, 'feedback' => NULL, 'idlist' => NULL, 'update' => NULL, 'force' => NULL, 'execute-dependencies' => NULL]) { $group_names = $options['group']; $tag_names = $options['tag']; $all = $options['all']; @@ -293,7 +268,7 @@ class MigrateToolsCommands extends DrushCommands { throw new \Exception(dt('You must specify --all, --group, --tag or one or more migration names separated by commas')); } - foreach (['limit', 'feedback', 'idlist', 'update', 'force'] as $option) { + foreach (['limit', 'feedback', 'idlist', 'update', 'force', 'execute-dependencies'] as $option) { if ($options[$option]) { $additional_options[$option] = $options[$option]; } @@ -346,15 +321,7 @@ class MigrateToolsCommands extends DrushCommands { * @throws \Exception * If there are not enough parameters to the command. */ - public function rollback( - $migration_names = '', - array $options = [ - 'all' => NULL, - 'group' => NULL, - 'tag' => NULL, - 'feedback' => NULL, - ] - ) { + public function rollback($migration_names = '', array $options = ['all' => NULL, 'group' => NULL, 'tag' => NULL, 'feedback' => NULL]) { $group_names = $options['group']; $tag_names = $options['tag']; $all = $options['all']; @@ -496,52 +463,47 @@ class MigrateToolsCommands extends DrushCommands { * @validate-module-enabled migrate_tools * * @aliases mmsg,migrate-messages + * + * @field-labels + * source_ids_hash: Source IDs Hash + * level: Level + * message: Message + * @default-fields source_ids_hash,level,message + * + * @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields + * Source fields of the given migration formatted as a table. */ public function messages($migration_id, array $options = ['csv' => NULL]) { /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ $migration = $this->migrationPluginManager->createInstance( $migration_id ); - if ($migration) { - $map = $migration->getIdMap(); - $first = TRUE; - $table = []; - foreach ($map->getMessageIterator() as $row) { - unset($row->msgid); - if ($first) { - // @todo: Ideally, replace sourceid* with source key names. Or, should - // getMessageIterator() do that? - foreach ($row as $column => $value) { - $table[0][] = $column; - } - $first = FALSE; - } - $table[] = (array) $row; - } - if (empty($table)) { - $this->logger()->notice(dt('No messages for this migration')); - } - else { - if ($options['csv']) { - foreach ($table as $row) { - fputcsv(STDOUT, $row); - } - } - else { - $widths = []; - foreach ($table[0] as $header) { - $widths[] = strlen($header) + 1; - } - - drush_print_table($table); - } - } - } - else { + if (!$migration) { $this->logger()->error( dt('Migration @id does not exist', ['@id' => $migration_id]) ); + return NULL; } + + $map = $migration->getIdMap(); + $table = []; + foreach ($map->getMessageIterator() as $row) { + unset($row->msgid); + $table[] = (array) $row; + } + if (empty($table)) { + $this->logger()->notice(dt('No messages for this migration')); + return NULL; + } + + if ($options['csv']) { + fputcsv(STDOUT, array_keys($table[0])); + foreach ($table as $row) { + fputcsv(STDOUT, $row); + } + return NULL; + } + return new RowsOfFields($table); } /** @@ -558,6 +520,14 @@ class MigrateToolsCommands extends DrushCommands { * @validate-module-enabled migrate_tools * * @aliases mfs, migrate-fields-source + * + * @field-labels + * machine_name: Machine Name + * description: Description + * @default-fields machine_name,description + * + * @return \Consolidation\OutputFormatters\StructuredData\RowsOfFields + * Source fields of the given migration formatted as a table. */ public function fieldsSource($migration_id) { /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ @@ -568,9 +538,12 @@ class MigrateToolsCommands extends DrushCommands { $source = $migration->getSourcePlugin(); $table = []; foreach ($source->fields() as $machine_name => $description) { - $table[] = [strip_tags($description), $machine_name]; + $table[] = [ + 'machine_name' => $machine_name, + 'description' => strip_tags($description), + ]; } - drush_print_table($table); + return new RowsOfFields($table); } else { $this->logger()->error( @@ -690,17 +663,23 @@ class MigrateToolsCommands extends DrushCommands { * @throws \Exception * If some migrations failed during execution. */ - protected function executeMigration( - MigrationInterface $migration, - $migration_id, - array $options = [] - ) { + protected function executeMigration(MigrationInterface $migration, $migration_id, array $options = []) { + // Keep track of all migrations run during this command so the same + // migration is not run multiple times. + static $executed_migrations = []; + if (isset($options['execute-dependencies'])) { - if ($required_IDS = $migration->get('requirements')) { + $required_migrations = $migration->get('requirements'); + $required_migrations = array_filter($required_migrations, function ($value) use ($executed_migrations) { + return !isset($executed_migrations[$value]); + }); + + if (!empty($required_migrations)) { $manager = $this->migrationPluginManager; - $required_migrations = $manager->createInstances($required_IDS); + $required_migrations = $manager->createInstances($required_migrations); $dependency_options = array_merge($options, ['is_dependency' => TRUE]); - array_walk($required_migrations, __FUNCTION__, $dependency_options); + array_walk($required_migrations, [$this, __FUNCTION__], $dependency_options); + $executed_migrations += $required_migrations; } } if (!empty($options['force'])) { @@ -712,6 +691,7 @@ class MigrateToolsCommands extends DrushCommands { $executable = new MigrateExecutable($migration, $this->getMigrateMessage(), $options); // drush_op() provides --simulate support. drush_op([$executable, 'import']); + $executed_migrations += [$migration_id => $migration_id]; if ($count = $executable->getFailedCount()) { // Nudge Drush to use a non-zero exit code. throw new \Exception( diff --git a/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MessageController.php b/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MessageController.php index 068f9e148..fbd347c96 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MessageController.php +++ b/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MessageController.php @@ -7,6 +7,8 @@ use Drupal\Core\Controller\ControllerBase; use Drupal\Core\Database\Connection; use Drupal\migrate\Plugin\MigrationInterface; use Drupal\migrate\Plugin\MigrationPluginManagerInterface; +use Drupal\migrate_plus\Entity\MigrationGroupInterface; +use Drupal\migrate_plus\Entity\MigrationInterface as MigratePlusMigrationInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** @@ -71,21 +73,19 @@ class MessageController extends ControllerBase { * * Messages are truncated at 56 chars. * - * @param string $migration_group - * Machine name of the migration's group. - * - * @param string $migration - * Machine name of the migration. + * @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group + * The migration group. + * @param \Drupal\migrate_plus\Entity\MigrationInterface $migration + * The $migration. * * @return array * A render array as expected by drupal_render(). */ - public function overview($migration_group, $migration) { + public function overview(MigrationGroupInterface $migration_group, MigratePlusMigrationInterface $migration) { $rows = []; $classes = static::getLogLevelClassMap(); - /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ - $migration = $this->migrationPluginManager->createInstance($migration); - $source_id_field_names = array_keys($migration->getSourcePlugin()->getIds()); + $migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); + $source_id_field_names = array_keys($migration_plugin->getSourcePlugin()->getIds()); $column_number = 1; foreach ($source_id_field_names as $source_id_field_name) { $header[] = [ @@ -104,8 +104,8 @@ class MessageController extends ControllerBase { 'field' => 'message', ]; - $message_table = $migration->getIdMap()->messageTableName(); - $map_table = $migration->getIdMap()->mapTableName(); + $message_table = $migration_plugin->getIdMap()->messageTableName(); + $map_table = $migration_plugin->getIdMap()->mapTableName(); $query = $this->database->select($message_table, 'msg') ->extend('\Drupal\Core\Database\Query\PagerSelectExtender') ->extend('\Drupal\Core\Database\Query\TableSortExtender'); diff --git a/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MigrationController.php b/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MigrationController.php index 6004c3edb..15c90795c 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MigrationController.php +++ b/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MigrationController.php @@ -8,6 +8,8 @@ use Drupal\Component\Utility\Html; use Drupal\Core\Routing\CurrentRouteMatch; use Drupal\migrate\Plugin\MigrationPluginManagerInterface; use Drupal\Core\DependencyInjection\ContainerInjectionInterface; +use Drupal\migrate_plus\Entity\MigrationGroupInterface; +use Drupal\migrate_plus\Entity\MigrationInterface; use Drupal\migrate_tools\MigrateBatchExecutable; use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\Core\Url; @@ -58,19 +60,15 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn /** * Displays an overview of a migration entity. * - * @param string $migration_group - * Machine name of the migration's group. - * @param string $migration - * Machine name of the migration. + * @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group + * The migration group. + * @param \Drupal\migrate_plus\Entity\MigrationInterface $migration + * The $migration. * * @return array * A render array as expected by drupal_render(). */ - public function overview($migration_group, $migration) { - - /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ - $migration = $this->migrationPluginManager->createInstance($migration); - + public function overview(MigrationGroupInterface $migration_group, MigrationInterface $migration) { $build['overview'] = [ '#type' => 'fieldset', '#title' => $this->t('Overview'), @@ -78,7 +76,7 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn $build['overview']['group'] = [ '#title' => $this->t('Group:'), - '#markup' => Xss::filterAdmin($migration_group), + '#markup' => Xss::filterAdmin($migration_group->label()), '#type' => 'item', ]; @@ -87,8 +85,8 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn '#markup' => Xss::filterAdmin($migration->label()), '#type' => 'item', ]; - - $migration_dependencies = $migration->getMigrationDependencies(); + $migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); + $migration_dependencies = $migration_plugin->getMigrationDependencies(); if (!empty($migration_dependencies['required'])) { $build['overview']['dependencies'] = [ '#title' => $this->t('Migration Dependencies') , @@ -110,19 +108,15 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn /** * Display source information of a migration entity. * - * @param string $migration_group - * Machine name of the migration's group. - * @param string $migration - * Machine name of the migration. + * @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group + * The migration group. + * @param \Drupal\migrate_plus\Entity\MigrationInterface $migration + * The $migration. * * @return array * A render array as expected by drupal_render(). */ - public function source($migration_group, $migration) { - - /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ - $migration = $this->migrationPluginManager->createInstance($migration); - + public function source(MigrationGroupInterface $migration_group, MigrationInterface $migration) { // Source field information. $build['source'] = [ '#type' => 'fieldset', @@ -133,8 +127,8 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn 'id' => 'migration-detail-source', ], ]; - - $source = $migration->getSourcePlugin(); + $migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); + $source = $migration_plugin->getSourcePlugin(); $build['source']['query'] = [ '#type' => 'item', '#title' => $this->t('Query'), @@ -142,7 +136,7 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn ]; $header = [$this->t('Machine name'), $this->t('Description')]; $rows = []; - foreach ($source->fields($migration) as $machine_name => $description) { + foreach ($source->fields($migration_plugin) as $machine_name => $description) { $rows[] = [ ['data' => Html::escape($machine_name)], ['data' => Xss::filterAdmin($description)], @@ -162,22 +156,20 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn /** * Run a migration. * - * @param string $migration_group - * Machine name of the migration's group. - * @param string $migration - * Machine name of the migration. + * @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group + * The migration group. + * @param \Drupal\migrate_plus\Entity\MigrationInterface $migration + * The $migration. * * @return array * A render array as expected by drupal_render(). */ - public function run($migration_group, $migration) { - /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ - $migration = $this->migrationPluginManager->createInstance($migration); - + public function run(MigrationGroupInterface $migration_group, MigrationInterface $migration) { $migrateMessage = new MigrateMessage(); $options = []; - $executable = new MigrateBatchExecutable($migration, $migrateMessage, $options); + $migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); + $executable = new MigrateBatchExecutable($migration_plugin, $migrateMessage, $options); $executable->batchImport(); $migration_group = $this->currentRouteMatch->getParameter('migration_group'); @@ -191,18 +183,16 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn /** * Display process information of a migration entity. * - * @param string $migration_group - * Machine name of the migration's group. - * @param string $migration - * Machine name of the migration. + * @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group + * The migration group. + * @param \Drupal\migrate_plus\Entity\MigrationInterface $migration + * The $migration. * * @return array * A render array as expected by drupal_render(). */ - public function process($migration_group, $migration) { - - /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ - $migration = $this->migrationPluginManager->createInstance($migration); + public function process(MigrationGroupInterface $migration_group, MigrationInterface $migration) { + $migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); // Process information. $build['process'] = [ @@ -217,7 +207,7 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn $this->t('Default'), ]; $rows = []; - foreach ($migration->getProcess() as $destination_id => $process_line) { + foreach ($migration_plugin->getProcess() as $destination_id => $process_line) { $row = []; $row[] = ['data' => Html::escape($destination_id)]; if (isset($process_line[0]['source'])) { @@ -251,7 +241,7 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn $build['process']['run'] = [ '#type' => 'link', '#title' => $this->t('Run'), - '#url' => Url::fromRoute('entity.migration.process.run', ['migration_group' => $migration_group, 'migration' => $migration->id()]), + '#url' => Url::fromRoute('entity.migration.process.run', ['migration_group' => $migration_group->id(), 'migration' => $migration->id()]), ]; return $build; @@ -260,17 +250,16 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn /** * Displays destination information of a migration entity. * - * @param string $migration_group - * Machine name of the migration's group. - * @param string $migration - * Machine name of the migration. + * @param \Drupal\migrate_plus\Entity\MigrationGroupInterface $migration_group + * The migration group. + * @param \Drupal\migrate_plus\Entity\MigrationInterface $migration + * The $migration. * * @return array * A render array as expected by drupal_render(). */ - public function destination($migration_group, $migration) { - /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ - $migration = $this->migrationPluginManager->createInstance($migration); + public function destination(MigrationGroupInterface $migration_group, MigrationInterface $migration) { + $migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); // Destination field information. $build['destination'] = [ @@ -282,7 +271,7 @@ class MigrationController extends ControllerBase implements ContainerInjectionIn 'id' => 'migration-detail-destination', ], ]; - $destination = $migration->getDestinationPlugin(); + $destination = $migration_plugin->getDestinationPlugin(); $build['destination']['type'] = [ '#type' => 'item', '#title' => $this->t('Type'), diff --git a/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MigrationListBuilder.php b/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MigrationListBuilder.php index 14c3e550b..d078764ce 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MigrationListBuilder.php +++ b/sites/all/modules/contrib/migrate/migrate_tools/src/Controller/MigrationListBuilder.php @@ -161,7 +161,7 @@ class MigrationListBuilder extends ConfigEntityListBuilder implements EntityHand $row['status'] = $migration->getStatusLabel(); } catch (PluginException $e) { - $this->logger->warning('Migration entity id %id is malformed', ['%id' => $migration_entity->id()]); + $this->logger->warning('Migration entity id %id is malformed: %orig', ['%id' => $migration_entity->id(), '%orig' => $e->getMessage()]); return NULL; } diff --git a/sites/all/modules/contrib/migrate/migrate_tools/src/Form/MigrationExecuteForm.php b/sites/all/modules/contrib/migrate/migrate_tools/src/Form/MigrationExecuteForm.php index bf81215aa..d05b736eb 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/src/Form/MigrationExecuteForm.php +++ b/sites/all/modules/contrib/migrate/migrate_tools/src/Form/MigrationExecuteForm.php @@ -60,7 +60,6 @@ class MigrationExecuteForm extends FormBase { return $form; } - /** * Get Operations. */ @@ -124,7 +123,6 @@ class MigrationExecuteForm extends FormBase { return $form; } - /** * {@inheritdoc} */ @@ -162,12 +160,10 @@ class MigrationExecuteForm extends FormBase { $force = 0; } - $migration_name = \Drupal::routeMatch()->getParameter('migration'); - - if ($migration_name) { - - /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */ - $migration = $this->migrationPluginManager->createInstance($migration_name); + $migration = \Drupal::routeMatch()->getParameter('migration'); + if ($migration) { + /** @var \Drupal\migrate\Plugin\MigrationInterface $migration_plugin */ + $migration_plugin = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); $migrateMessage = new MigrateMessage(); switch ($operation) { @@ -179,7 +175,7 @@ class MigrationExecuteForm extends FormBase { 'force' => $force, ]; - $executable = new MigrateBatchExecutable($migration, $migrateMessage, $options); + $executable = new MigrateBatchExecutable($migration_plugin, $migrateMessage, $options); $executable->batchImport(); break; @@ -192,20 +188,20 @@ class MigrationExecuteForm extends FormBase { 'force' => $force, ]; - $executable = new MigrateBatchExecutable($migration, $migrateMessage, $options); + $executable = new MigrateBatchExecutable($migration_plugin, $migrateMessage, $options); $executable->rollback(); break; case 'stop': - $migration->interruptMigration(MigrationInterface::RESULT_STOPPED); + $migration_plugin->interruptMigration(MigrationInterface::RESULT_STOPPED); break; case 'reset': - $migration->setStatus(MigrationInterface::STATUS_IDLE); + $migration_plugin->setStatus(MigrationInterface::STATUS_IDLE); break; diff --git a/sites/all/modules/contrib/migrate/migrate_tools/src/Form/SourceCsvForm.php b/sites/all/modules/contrib/migrate/migrate_tools/src/Form/SourceCsvForm.php new file mode 100644 index 000000000..40b5dc3ba --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_tools/src/Form/SourceCsvForm.php @@ -0,0 +1,453 @@ + label 1 + * column_index2 + * property 2 => label 2 + * updated + * column_index1 + * property 2 => label 2 + * column_index2 + * property 1 => label 1 + * @endcode + * + * Example source configuration. + * @code + * custom_migration + * original + * 2 + * title => title + * 3 + * body => foo + * updated + * 8 + * title => new_title + * 9 + * body => new_body + * @endcode + */ +class SourceCsvForm extends FormBase { + + /** + * The database connection. + * + * @var \Drupal\Core\Database\Connection + */ + protected $connection; + + /** + * Plugin manager for migration plugins. + * + * @var \Drupal\migrate\Plugin\MigrationPluginManagerInterface + */ + protected $migrationPluginManager; + + /** + * The messenger service. + * + * @var \Drupal\Core\Messenger\MessengerInterface + */ + protected $messenger; + + /** + * Temporary store for column assignment changes. + * + * @var \Drupal\Core\TempStore\PrivateTempStoreFactory + */ + protected $store; + + /** + * The file object that reads the CSV file. + * + * @var \SplFileObject + */ + protected $file = NULL; + + /** + * The migration being examined. + * + * @var \Drupal\migrate\Plugin\MigrationInterface + */ + protected $migration; + + /** + * The migration plugin id. + * + * @var string + */ + protected $id; + + /** + * The array of columns names from the CSV source plugin. + * + * @var array + */ + protected $columnNames; + + /** + * An array of options for the column select form field.. + * + * @var array + */ + protected $options; + + /** + * An array of modified and original column_name source plugin configuration. + * + * @var array + */ + protected $sourceConfiguration; + + /** + * Constructs new SourceCsvForm object. + * + * @param \Drupal\Core\Database\Connection $connection + * The database connection. + * @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migration_plugin_manager + * The plugin manager for config entity-based migrations. + * @param \Drupal\Core\Messenger\MessengerInterface $messenger + * The messenger service. + * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $private_store + * The private store. + */ + public function __construct(Connection $connection, MigrationPluginManagerInterface $migration_plugin_manager, MessengerInterface $messenger, PrivateTempStoreFactory $private_store) { + $this->connection = $connection; + $this->migrationPluginManager = $migration_plugin_manager; + $this->messenger = $messenger; + $this->store = $private_store->get('migrate_tools'); + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('database'), + $container->get('plugin.manager.migration'), + $container->get('messenger'), + $container->get('tempstore.private') + ); + } + + /** + * A custom access check. + * + * @param \Drupal\Core\Session\AccountInterface $account + * Run access checks for this account. + * @param \Drupal\migrate_plus\Entity\MigrationInterface $migration + * The $migration. + * + * @return \Drupal\Core\Access\AccessResult + * Allowed or forbidden, neutral if tempstore is empty. + */ + public function access(AccountInterface $account, MigrationInterface $migration) { + try { + $this->migration = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); + } + catch (PluginException $e) { + return AccessResult::forbidden(); + } + + if ($this->migration) { + if ($source = $this->migration->getSourcePlugin()) { + if (is_a($source, CSV::class)) { + return AccessResult::allowed(); + } + } + } + return AccessResult::forbidden(); + } + + /** + * {@inheritdoc} + */ + public function buildForm(array $form, FormStateInterface $form_state, MigrationInterface $migration = NULL) { + try { + // @TODO: remove this horrible config work around after + // https://www.drupal.org/project/drupal/issues/2986665 is fixed. + $this->migration = $this->migrationPluginManager->createInstance($migration->id(), $migration->toArray()); + /** @var \Drupal\migrate_source_csv\Plugin\migrate\source\CSV $source */ + $source = $this->migration->getSourcePlugin(); + $source->setConfiguration($migration->toArray()['source']); + } + catch (PluginException $e) { + return AccessResult::forbidden(); + } + + // Get the source file after the properties are initialized. + $source->initializeIterator(); + $this->file = $source->getFile(); + + // Set the input field options to the header row values or, if there are + // no such values, use an indexed array. + if ($this->file->getHeaderRowCount() > 0) { + $this->options = $this->getHeaderColumnNames(); + } + else { + for ($i = 0; $i < $this->getFileColumnCount(); $i++) { + $this->options[$i] = $i; + } + } + + // Set the store key to the migration id. + $this->id = $this->migration->getPluginId(); + + // Get the column names from the file or from the store, if updated + // values are in the store. + $this->sourceConfiguration = $this->store->get($this->id); + if (isset($this->sourceConfiguration['changed'])) { + if ($config = $this->sourceConfiguration['changed']) { + $this->columnNames = $config; + } + } + else { + // Get the calculated column names. This is either the header rows or + // the configuration column_name value. + $this->columnNames = $this->file->getColumnNames(); + if (!isset($this->sourceConfiguration['original'])) { + // Save as the original values. + $this->sourceConfiguration['original'] = $this->columnNames; + $this->store->set($this->id, $this->sourceConfiguration); + } + } + $form['#title'] = $this->t('Column Aliases'); + + $form['heading'] = [ + '#type' => 'item', + '#title' => $this->t(':label', [':label' => $this->migration->label()]), + '#description' => '

' . $this->t('You can change the columns to be used by this migration for each source property.') . '

', + ]; + // Create a form field for each column in this migration. + foreach ($this->columnNames as $index => $data) { + $property_name = key($data); + $default_value = $index; + $label = $this->getLabel($this->sourceConfiguration['original'], $property_name); + + $description = $this->t('Select the column where the data for :label, property :property, will be found.', [ + ':label' => $label, + ':property' => $property_name, + ]); + $form['aliases'][$property_name] = [ + '#type' => 'select', + '#title' => $label, + '#description' => $description, + '#options' => $this->options, + '#default_value' => $default_value, + ]; + } + $form['actions'] = ['#type' => 'actions']; + $form['actions']['submit'] = [ + '#type' => 'submit', + '#button_type' => 'primary', + '#value' => $this->t('Submit'), + ]; + $form['actions']['cancel'] = [ + '#type' => 'submit', + '#value' => $this->t('Cancel'), + '#submit' => ['::cancel'], + '#limit_validation_errors' => [], + ]; + + return $form; + } + + /** + * {@inheritdoc} + */ + public function validateForm(array &$form, FormStateInterface $form_state) { + // Display an error message if two properties have the same source column. + $values = []; + foreach ($this->columnNames as $index => $data) { + $property_name = key($data); + $value = $form_state->getValue($property_name); + if (in_array($value, $values)) { + $form_state->setErrorByName($property_name, $this->t('Source properties can not share the same source column.')); + } + $values[] = $value; + } + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + // Create a new column_names configuration. + $new_column_names = []; + foreach ($this->columnNames as $index => $data) { + // Keep the property name as it is used in the process pipeline. + $property_name = key($data); + // Get the new column number from the form alias field for this property. + $new_index = $form_state->getValue($property_name); + // Get the new label from the options array. + $new_label = $this->options[$new_index]; + // Save using the new column number and new label. + $new_column_names[$new_index] = [$property_name => $new_label]; + } + // Update the file columns. + $this->file->setColumnNames($new_column_names); + // Save as updated in the store. + $this->sourceConfiguration['changed'] = $new_column_names; + $this->store->set($this->id, $this->sourceConfiguration); + + $changed = ($this->store->get('migrations_changed')) ? $this->store->get('migrations_changed') : []; + if (!in_array($this->id, $changed)) { + $changed[] = $this->id; + $this->store->set('migrations_changed', $changed); + } + } + + /** + * Form submission handler for the 'cancel' action. + * + * @param array $form + * An associative array containing the structure of the form. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The current state of the form. + */ + public function cancel(array $form, FormStateInterface $form_state) { + // Restore the file columns to the original settings. + $this->file->setColumnNames($this->sourceConfiguration['original']); + // Remove this migration from the store. + try { + $this->store->delete($this->id); + } + catch (TempStoreException $e) { + $this->messenger->addError($e->getMessage()); + } + + $migrationsChanged = $this->store->get('migrations_changed'); + unset($migrationsChanged[$this->id]); + try { + $this->store->set('migrations_changed', $migrationsChanged); + } + catch (TempStoreException $e) { + $this->messenger->addError($e->getMessage()); + } + $form_state->setRedirect('entity.migration_group.list'); + } + + /** + * {@inheritdoc} + */ + public function getFormId() { + return 'migrate_tools_source_csv'; + } + + /** + * {@inheritdoc} + */ + public function getQuestion() {} + + /** + * {@inheritdoc} + */ + public function getCancelUrl() { + return new Url('entity.migration_group.list'); + } + + /** + * Returns the header row. + * + * Use a new file handle so that CSVFileObject::current() is not executed. + * + * @return array + * The header row. + */ + public function getHeaderColumnNames() { + $row = []; + $fname = $this->file->getPathname(); + $handle = fopen($fname, 'r'); + if ($handle) { + fseek($handle, $this->file->getHeaderRowCount() - 1); + $row = fgetcsv($handle); + fclose($handle); + } + return $row; + } + + /** + * Returns the count of fields in the header row. + * + * Use a new file handle so that CSVFileObject::current() is not executed. + * + * @return int + * The number of fields in the header row. + */ + public function getFileColumnCount() { + $count = 0; + $fname = $this->file->getPathname(); + $handle = fopen($fname, 'r'); + if ($handle) { + $row = fgetcsv($handle); + $count = count($row); + fclose($handle); + } + return $count; + } + + /** + * Gets the label for a given property from a column_names array. + * + * @param array $column_names + * An array of column_names. + * @param string $property_name + * The property name to find a label for. + * + * @return string + * The label for this property. + */ + protected function getLabel(array $column_names, $property_name) { + $label = ''; + foreach ($column_names as $column) { + foreach ($column as $key => $value) { + if ($key === $property_name) { + $label = $value; + break; + } + } + } + return $label; + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_tools/src/MigrateExecutable.php b/sites/all/modules/contrib/migrate/migrate_tools/src/MigrateExecutable.php index 9d7f15069..2282ab8cb 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/src/MigrateExecutable.php +++ b/sites/all/modules/contrib/migrate/migrate_tools/src/MigrateExecutable.php @@ -35,6 +35,13 @@ class MigrateExecutable extends MigrateExecutableBase { MigrateIdMapInterface::STATUS_NEEDS_UPDATE => 0, ]; + /** + * Counter of map saves, used to detect the item limit threshold. + * + * @var int + */ + protected $itemLimitCounter = 0; + /** * Counter of map deletions. * @@ -128,6 +135,7 @@ class MigrateExecutable extends MigrateExecutableBase { // Only count saves for this migration. if ($event->getMap()->getQualifiedMapTableName() == $this->migration->getIdMap()->getQualifiedMapTableName()) { $fields = $event->getFields(); + $this->itemLimitCounter++; // Distinguish between creation and update. if ($fields['source_row_status'] == MigrateIdMapInterface::STATUS_IMPORTED && $this->preExistingItem @@ -378,7 +386,7 @@ class MigrateExecutable extends MigrateExecutableBase { $this->resetCounters(); } $this->counter++; - if ($this->itemLimit && ($this->getProcessedCount() + 1) >= $this->itemLimit) { + if ($this->itemLimit && ($this->itemLimitCounter + 1) >= $this->itemLimit) { $event->getMigration()->interruptMigration(MigrationInterface::RESULT_COMPLETED); } diff --git a/sites/all/modules/contrib/migrate/migrate_tools/src/Routing/RouteProcessor.php b/sites/all/modules/contrib/migrate/migrate_tools/src/Routing/RouteProcessor.php new file mode 100644 index 000000000..fe0c5e623 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_tools/src/Routing/RouteProcessor.php @@ -0,0 +1,27 @@ +hasDefault('_migrate_group')) { + if ($migration = \Drupal::entityTypeManager()->getStorage('migration')->load($parameters['migration'])) { + if ($group = $migration->get('migration_group')) { + $parameters['migration_group'] = $group; + } + } + } + } + +} diff --git a/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/config/install/migrate_plus.migration.csv_source_test.yml b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/config/install/migrate_plus.migration.csv_source_test.yml new file mode 100644 index 000000000..0d600a9ff --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/config/install/migrate_plus.migration.csv_source_test.yml @@ -0,0 +1,33 @@ +langcode: en +status: true +dependencies: { } +id: csv_source_test +label: Test edit of column aliases for CSV source plugin +class: null +field_plugin_method: null +cck_plugin_method: null +migration_tags: { } +migration_group: csv_test +source: + plugin: csv + path: 'public://test.csv' + header_row_count: 1 + enclosure: '"' + keys: + - vid + column_names: + 0: + vid: 'Vocabulary Id' + 1: + name: 'Name' + 2: + description: 'Description' +process: + vid: vid + name: name + description: description +destination: + plugin: entity:taxonomy_vocabulary +migration_dependencies: + required: { } + optional: { } diff --git a/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/config/install/migrate_plus.migration_group.csv_test.yml b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/config/install/migrate_plus.migration_group.csv_test.yml new file mode 100644 index 000000000..1c2b05931 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/config/install/migrate_plus.migration_group.csv_test.yml @@ -0,0 +1,4 @@ +id: csv_test +label: CSV source plugin edit test +description: Test editting of source plugin via the UI +source_type: CSV diff --git a/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/csv_source_test.info.yml b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/csv_source_test.info.yml new file mode 100644 index 000000000..f16e6bbd7 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/csv_source_test/csv_source_test.info.yml @@ -0,0 +1,15 @@ +type: module +name: CSV Source edit test +description: 'Test editing of source plugin via the UI.' +package: Testing +# core: 8.x +dependencies: + - drupal:migrate (>=8.3) + - migrate_plus:migrate_plus + - migrate_plus:migrate_source_csv + +# Information added by Drupal.org packaging script on 2018-08-27 +version: '8.x-4.0' +core: '8.x' +project: 'migrate_tools' +datestamp: 1535380087 diff --git a/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/migrate_tools_test/config/install/migrate_plus.migration.fruit_terms.yml b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/migrate_tools_test/config/install/migrate_plus.migration.fruit_terms.yml old mode 100755 new mode 100644 diff --git a/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/migrate_tools_test/migrate_tools_test.info.yml b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/migrate_tools_test/migrate_tools_test.info.yml index ca10d0196..bbeb69867 100644 --- a/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/migrate_tools_test/migrate_tools_test.info.yml +++ b/sites/all/modules/contrib/migrate/migrate_tools/tests/modules/migrate_tools_test/migrate_tools_test.info.yml @@ -7,8 +7,8 @@ dependencies: - drupal:migrate (>=8.3) - migrate_plus:migrate_plus -# Information added by Drupal.org packaging script on 2018-02-23 -version: '8.x-4.0-beta3' +# Information added by Drupal.org packaging script on 2018-08-27 +version: '8.x-4.0' core: '8.x' project: 'migrate_tools' -datestamp: 1519400307 +datestamp: 1535380087 diff --git a/sites/all/modules/contrib/migrate/migrate_tools/tests/src/Functional/SourceCsvFormTest.php b/sites/all/modules/contrib/migrate/migrate_tools/tests/src/Functional/SourceCsvFormTest.php new file mode 100644 index 000000000..767a9bfe0 --- /dev/null +++ b/sites/all/modules/contrib/migrate/migrate_tools/tests/src/Functional/SourceCsvFormTest.php @@ -0,0 +1,241 @@ +drupalLogin($this->rootUser); + + // Setup the file system so we create the source CSV. + $this->container->get('stream_wrapper_manager')->registerWrapper('public', PublicStream::class, StreamWrapperInterface::NORMAL); + $fs = \Drupal::service('file_system'); + $fs->mkdir('public://sites/default/files', NULL, TRUE); + + // The source data for this test. + $source_data = <<<'EOD' +vid,name,description,hierarchy,weight +tags,Tags,Use tags to group articles,0,0 +forums,Sujet de discussion,Forum navigation vocabulary,1,0 +test_vocabulary,Test Vocabulary,This is the vocabulary description,1,0 +genre,Genre,Genre description,1,0 +EOD; + + // Write the data to the filepath given in the test migration. + file_put_contents('public://test.csv', $source_data); + + // Get the store. + $tempStoreFactory = \Drupal::service('tempstore.private'); + $this->store = $tempStoreFactory->get('migrate_tools'); + + // Select the group and migration to test. + $this->group = 'csv_test'; + $this->migration = 'csv_source_test'; + } + + /** + * Tests the form to edit CSV column aliases. + * + * @throws \Behat\Mink\Exception\ExpectationException + */ + public function testSourceCsvForm() { + // Define the paths to be used. + $executeUrlPath = "/admin/structure/migrate/manage/{$this->group}/migrations/{$this->migration}/execute"; + $editUrlPath = "/admin/structure/migrate/manage/{$this->group}/migrations/{$this->migration}/source/edit"; + + // Assert the test migration is listed. + $this->drupalGet("/admin/structure/migrate/manage/{$this->group}/migrations"); + $session = $this->assertSession(); + $session->responseContains('Test edit of column aliases for CSV source plugin'); + + // Proceed to the edit page. + $this->drupalGet($editUrlPath); + $session->responseContains('You can change the columns to be used by this migration for each source property.'); + + // Test that there are 3 select fields available which match the number of + // properties in the process pipeline. + $this->assertTrue($session->optionExists('edit-vid', 'vid') + ->isSelected()); + $this->assertTrue($session->optionExists('edit-name', 'name') + ->isSelected()); + $this->assertTrue($session->optionExists('edit-description', 'description') + ->isSelected()); + $session->responseNotContains('edit-hierarchy'); + $session->responseNotContains('edit-weight'); + + // Test that all 5 columns in the CSV source are available as options on + // one of the select fields. + $this->assertTrue($session->optionExists('edit-description', 'vid')); + $this->assertTrue($session->optionExists('edit-description', 'name')); + $this->assertTrue($session->optionExists('edit-description', 'description')); + $this->assertTrue($session->optionExists('edit-description', 'hierarchy')); + $this->assertTrue($session->optionExists('edit-description', 'weight')); + + // Test that two aliases can not be the same. + $edit = [ + 'edit-vid' => 2, + 'edit-name' => 1, + 'edit-description' => 1, + ]; + $this->drupalPostForm($editUrlPath, $edit, t('Submit')); + $session->responseContains('Source properties can not share the same source column.'); + $this->assertTrue($session->optionExists('edit-vid', 'description') + ->isSelected()); + $this->assertTrue($session->optionExists('edit-name', 'name') + ->isSelected()); + $this->assertTrue($session->optionExists('edit-description', 'name') + ->isSelected()); + + // Test that changes to all the column aliases are saved. + $edit = [ + 'edit-vid' => 4, + 'edit-name' => 0, + 'edit-description' => 1, + ]; + $this->drupalPostForm($editUrlPath, $edit, t('Submit')); + $this->assertTrue($session->optionExists('edit-vid', 'weight') + ->isSelected()); + $this->assertTrue($session->optionExists('edit-name', 'vid') + ->isSelected()); + $this->assertTrue($session->optionExists('edit-description', 'name') + ->isSelected()); + + // Test that the changes are saved to store. + $columnConfiguration = $this->store->get('csv_source_test'); + $migrationsChanged = $this->store->get('migrations_changed'); + $this->assertSame(['csv_source_test'], $migrationsChanged); + $expected = + [ + 'original' => + [ + 0 => ['vid' => 'Vocabulary Id'], + 1 => ['name' => 'Name'], + 2 => ['description' => 'Description'], + ], + 'changed' => + [ + 4 => ['vid' => 'weight'], + 0 => ['name' => 'vid'], + 1 => ['description' => 'name'], + ], + ]; + $this->assertSame($expected, $columnConfiguration); + + // Test the migration with incorrect column aliases. Flush the cache to + // ensure the plugin alter is run. + drupal_flush_all_caches(); + $edit = [ + 'operation' => 'import', + ]; + $this->drupalPostForm($executeUrlPath, $edit, t('Execute')); + $session->responseContains("Processed 1 item (1 created, 0 updated, 0 failed, 0 ignored) - done with 'csv_source_test'"); + + // Rollback. + $edit = [ + 'operation' => 'rollback', + ]; + $this->drupalPostForm($executeUrlPath, $edit, t('Execute')); + + // Restore to an order that will succesfully migrate. + $edit = [ + 'edit-vid' => 0, + 'edit-name' => 1, + 'edit-description' => 2, + ]; + $this->drupalPostForm($editUrlPath, $edit, t('Submit')); + $this->assertTrue($session->optionExists('edit-vid', 'vid') + ->isSelected()); + $this->assertTrue($session->optionExists('edit-name', 'name') + ->isSelected()); + $this->assertTrue($session->optionExists('edit-description', 'description') + ->isSelected()); + + // Test the vocabulary migration. + $edit = [ + 'operation' => 'import', + ]; + drupal_flush_all_caches(); + $this->drupalPostForm($executeUrlPath, $edit, t('Execute')); + $session->responseContains("Processed 4 items (4 created, 0 updated, 0 failed, 0 ignored) - done with 'csv_source_test'"); + $this->assertEntity('tags', 'Tags', 'Use tags to group articles'); + $this->assertEntity('forums', 'Sujet de discussion', 'Forum navigation vocabulary'); + $this->assertEntity('test_vocabulary', 'Test Vocabulary', 'This is the vocabulary description'); + $this->assertEntity('genre', 'Genre', 'Genre description'); + } + + /** + * Validate a migrated vocabulary contains the expected values. + * + * @param string $id + * Entity ID to load and check. + * @param string $expected_name + * The name the migrated entity should have. + * @param string $expected_description + * The description the migrated entity should have. + */ + protected function assertEntity($id, $expected_name, $expected_description) { + /** @var \Drupal\taxonomy\VocabularyInterface $entity */ + $entity = Vocabulary::load($id); + $this->assertTrue($entity instanceof VocabularyInterface); + $this->assertSame($expected_name, $entity->label()); + $this->assertSame($expected_description, $entity->getDescription()); + } + +} diff --git a/sites/all/modules/contrib/security/honeypot/.travis.yml b/sites/all/modules/contrib/security/honeypot/.travis.yml index 784af29cf..2708a3279 100644 --- a/sites/all/modules/contrib/security/honeypot/.travis.yml +++ b/sites/all/modules/contrib/security/honeypot/.travis.yml @@ -4,7 +4,7 @@ php: '7.1' services: docker env: - DOCKER_COMPOSE_VERSION: 1.13.0 + DOCKER_COMPOSE_VERSION: 1.22.0 before_install: # List available docker-engine versions. @@ -28,13 +28,14 @@ before_install: script: # Build environment and install Honeypot. - docker-compose up -d - - docker exec honeypot install-drupal + - docker exec honeypot install-drupal 8.x-dev - docker exec honeypot ln -s /opt/honeypot/ /var/www/drupalvm/drupal/web/modules/honeypot - docker exec honeypot bash -c 'cd /var/www/drupalvm/drupal/web; drush en -y honeypot simpletest' # Fix permissions on the simpletest directories. + - docker exec honeypot mkdir -p /var/www/drupalvm/drupal/web/sites/simpletest - docker exec honeypot chown -R www-data:www-data /var/www/drupalvm/drupal/web/sites/simpletest - docker exec honeypot chown -R www-data:www-data /var/www/drupalvm/drupal/web/sites/default/files # Run module tests. - - docker exec honeypot bash -c 'sudo -u www-data php /var/www/drupalvm/drupal/web/core/scripts/run-tests.sh --verbose --module honeypot --url http://local.drupalhoneypot.com/' + - docker exec honeypot bash -c 'sudo -u www-data php /var/www/drupalvm/drupal/web/core/scripts/run-tests.sh --verbose --module honeypot --url http://localhost/' diff --git a/sites/all/modules/contrib/security/honeypot/README.md b/sites/all/modules/contrib/security/honeypot/README.md index bd0281b2b..7930749f9 100644 --- a/sites/all/modules/contrib/security/honeypot/README.md +++ b/sites/all/modules/contrib/security/honeypot/README.md @@ -49,6 +49,8 @@ Honeypot includes a `docker-compose.yml` file that can be used for testing purpo 5. Link the honeypot module directory into the Drupal modules directory: `docker exec honeypot ln -s /opt/honeypot/ /var/www/drupalvm/drupal/web/modules/honeypot` 6. Visit `http://local.drupalhoneypot.com/user` and log in using the admin credentials Drush displayed. +> Note: If you're using a Mac, you may also need to perform additional steps to get the hostname working; see [Managing your hosts file](http://docs.drupalvm.com/en/latest/other/docker/#managing-your-hosts-file) in the Drupal VM documentation. + ## Credit diff --git a/sites/all/modules/contrib/security/honeypot/honeypot.info.yml b/sites/all/modules/contrib/security/honeypot/honeypot.info.yml index 9d10e7f04..e4350f4f6 100644 --- a/sites/all/modules/contrib/security/honeypot/honeypot.info.yml +++ b/sites/all/modules/contrib/security/honeypot/honeypot.info.yml @@ -6,8 +6,8 @@ package: "Spam control" configure: honeypot.config hidden: false -# Information added by Drupal.org packaging script on 2017-07-12 -version: '8.x-1.27' +# Information added by Drupal.org packaging script on 2018-09-05 +version: '8.x-1.29' core: '8.x' project: 'honeypot' -datestamp: 1499867346 +datestamp: 1536179284 diff --git a/sites/all/modules/contrib/security/honeypot/honeypot.install b/sites/all/modules/contrib/security/honeypot/honeypot.install index e9245959f..a151b8bb4 100644 --- a/sites/all/modules/contrib/security/honeypot/honeypot.install +++ b/sites/all/modules/contrib/security/honeypot/honeypot.install @@ -61,6 +61,7 @@ function honeypot_install() { function honeypot_uninstall() { // Clear the bootstrap cache. \Drupal::cache('bootstrap')->deleteAll(); + \Drupal::configFactory()->getEditable('honeypot.settings.yml')->delete(); } /** diff --git a/sites/all/modules/contrib/security/honeypot/honeypot.module b/sites/all/modules/contrib/security/honeypot/honeypot.module index 3e0248dc4..55bec566e 100644 --- a/sites/all/modules/contrib/security/honeypot/honeypot.module +++ b/sites/all/modules/contrib/security/honeypot/honeypot.module @@ -7,6 +7,27 @@ use Drupal\Core\Form\FormStateInterface; use Drupal\Component\Utility\Crypt; +use Drupal\Core\Routing\RouteMatchInterface; + +/** + * Implements hook_help(). + */ +function honeypot_help($route_name, RouteMatchInterface $route_match) { + switch ($route_name) { + case 'help.page.honeypot': + $output = ''; + $output .= '

' . t('About') . '

'; + $output .= '

' . t('The Honeypot module uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site. These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user. For more information, see the online documentation for the Honeypot module.', [':url' => 'https://www.drupal.org/docs/8/modules/honeypot']) . '

'; + $output .= '

' . t('Uses') . '

'; + $output .= '
'; + $output .= '
' . t('Configuring Honeypot') . '
'; + $output .= '
' . t('All settings for this module are on the Honeypot configuration page, under the Configuration section, in the Content authoring settings. You can visit the configuration page directly from the Honeypot configuration link below. The configuration settings are described in the online documentation for the Honeypot module.', [':url' => 'https://www.drupal.org/docs/8/modules/honeypot/using-honeypot']) . '
'; + $output .= '
' . t('Setting up Honeypot in your own forms') . '
'; + $output .= '
' . t('Honeypot protection can be bypassed for certain user roles. For instance, site administrators, who just might be able to fill out a form in less than 5 seconds. And, Honeypot protection can be enabled only for certain forms. Or, it can protect all forms on the site. Finally, honeypot protection can be used in any of your own forms by simply including a little code snippet included on the module\'s project page.') . '
'; + $output .= '
'; + return $output; + } +} /** * Implements hook_cron(). @@ -15,7 +36,7 @@ function honeypot_cron() { // Delete {honeypot_user} entries older than the value of honeypot_expire. $expire_limit = \Drupal::config('honeypot.settings')->get('expire'); \Drupal::database()->delete('honeypot_user') - ->condition('timestamp', REQUEST_TIME - $expire_limit, '<') + ->condition('timestamp', \Drupal::time()->getRequestTime() - $expire_limit, '<') ->execute(); } @@ -43,7 +64,7 @@ function honeypot_form_alter(&$form, FormStateInterface $form_state, $form_id) { if ($protect_all_forms && !in_array($form_id, $unprotected_forms)) { // Don't protect system forms - only admins should have access, and system // forms may be programmatically submitted by drush and other modules. - if (strpos($form_id, 'system_') === FALSE && strpos($form_id, 'search_') === FALSE && strpos($form_id, 'views_exposed_form_') === FALSE) { + if (preg_match('/[^a-zA-Z]system_/', $form_id) === 0 && preg_match('/[^a-zA-Z]search_/', $form_id) === 0 && preg_match('/[^a-zA-Z]views_exposed_form_/', $form_id) === 0) { honeypot_add_form_protection($form, $form_state, ['honeypot', 'time_restriction']); } } @@ -147,7 +168,7 @@ function honeypot_add_form_protection(&$form, FormStateInterface $form_state, ar $input = $form_state->getUserInput(); if (empty($input['honeypot_time'])) { $identifier = Crypt::randomBytesBase64(); - \Drupal::service('keyvalue.expirable')->get('honeypot_time_restriction')->set($identifier, time(), 3600*24); + \Drupal::service('keyvalue.expirable')->get('honeypot_time_restriction')->setWithExpire($identifier, time(), 3600*24); } else { $identifier = $input['honeypot_time']; @@ -215,10 +236,10 @@ function _honeypot_time_restriction_validate($element, FormStateInterface $form_ // Make sure current time - (time_limit + form time value) is greater than 0. // If not, throw an error. - if (!$honeypot_time || REQUEST_TIME < ($honeypot_time + $time_limit)) { + if (!$honeypot_time || \Drupal::time()->getRequestTime() < ($honeypot_time + $time_limit)) { _honeypot_log($form_state->getValue('form_id'), 'honeypot_time'); $time_limit = honeypot_get_time_limit(); - \Drupal::service('keyvalue.expirable')->get('honeypot_time_restriction')->set($identifier, REQUEST_TIME, 3600*24); + \Drupal::service('keyvalue.expirable')->get('honeypot_time_restriction')->setWithExpire($identifier, \Drupal::time()->getRequestTime(), 3600*24); $form_state->setErrorByName('', t('There was a problem with your form submission. Please wait @limit seconds and try again.', ['@limit' => $time_limit])); } } @@ -263,7 +284,7 @@ function honeypot_get_time_limit(array $form_values = []) { $uid = $account->id(); $query = \Drupal::database()->select('honeypot_user', 'hu') ->condition('uid', $uid) - ->condition('timestamp', REQUEST_TIME - $expire_time, '>'); + ->condition('timestamp', \Drupal::time()->getRequestTime() - $expire_time, '>'); // For anonymous users, take the hostname into account. if ($uid === 0) { @@ -273,7 +294,7 @@ function honeypot_get_time_limit(array $form_values = []) { $number = $query->countQuery()->execute()->fetchField(); // Don't add more than 30 days' worth of extra time. - $honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, 2592000); + $honeypot_time_limit = (int) min($honeypot_time_limit + exp($number) - 1, $expire_time); // TODO - Only accepts two args. $additions = \Drupal::moduleHandler()->invokeAll('honeypot_time_limit', [ $honeypot_time_limit, @@ -306,7 +327,7 @@ function honeypot_log_failure($form_id, $type) { ->fields([ 'uid' => $uid, 'hostname' => Drupal::request()->getClientIp(), - 'timestamp' => REQUEST_TIME, + 'timestamp' => \Drupal::time()->getRequestTime(), ]) ->execute(); diff --git a/sites/all/modules/contrib/security/honeypot/tests/modules/honeypot_test/honeypot_test.info.yml b/sites/all/modules/contrib/security/honeypot/tests/modules/honeypot_test/honeypot_test.info.yml index fdb12f477..02df91108 100644 --- a/sites/all/modules/contrib/security/honeypot/tests/modules/honeypot_test/honeypot_test.info.yml +++ b/sites/all/modules/contrib/security/honeypot/tests/modules/honeypot_test/honeypot_test.info.yml @@ -5,8 +5,8 @@ description: Support module for Honeypot internal testing purposes. package: Testing hidden: true -# Information added by Drupal.org packaging script on 2017-07-12 -version: '8.x-1.27' +# Information added by Drupal.org packaging script on 2018-09-05 +version: '8.x-1.29' core: '8.x' project: 'honeypot' -datestamp: 1499867346 +datestamp: 1536179284 diff --git a/sites/default/config/sync/core.extension.yml b/sites/default/config/sync/core.extension.yml index 0e9801571..ae580f022 100644 --- a/sites/default/config/sync/core.extension.yml +++ b/sites/default/config/sync/core.extension.yml @@ -65,6 +65,7 @@ module: linkit: 0 locale: 0 maillog: 0 + matomo: 0 menu_ui: 0 migrate: 0 migrate_drupal: 0 @@ -77,7 +78,6 @@ module: page_cache: 0 path: 0 path_alias_xt: 0 - piwik: 0 profile: 0 redirect: 0 redis: 0 diff --git a/sites/default/config/sync/piwik.settings.yml b/sites/default/config/sync/matomo.settings.yml similarity index 95% rename from sites/default/config/sync/piwik.settings.yml rename to sites/default/config/sync/matomo.settings.yml index 1c656b5f7..b0c5a0d11 100644 --- a/sites/default/config/sync/piwik.settings.yml +++ b/sites/default/config/sync/matomo.settings.yml @@ -56,5 +56,5 @@ cache: true page_title_hierarchy: false page_title_hierarchy_exclude_home: true _core: - default_config_hash: a4NtJT7rQbnxB8tkCJH4-JtDHzCoyQxFbX8PvU8vhxU + default_config_hash: YGueb7ImKHSG1RRmIB1iqPHVGXTmI2yvCcB-RX7FPeY langcode: fr diff --git a/sites/default/config/sync/user.role.authenticated.yml b/sites/default/config/sync/user.role.authenticated.yml index 4d136dc37..c6903e163 100644 --- a/sites/default/config/sync/user.role.authenticated.yml +++ b/sites/default/config/sync/user.role.authenticated.yml @@ -22,6 +22,7 @@ permissions: - 'edit own chutier entities' - 'edit own composition entities' - 'edit own fil entities' + - 'opt-in or out of matomo tracking' - 'use chutier' - 'use text format wysiwyg' - 'view own unpublished chutier entities'