From 3e9ba2268c9b81e5ea91c7399999c4932ec8f299 Mon Sep 17 00:00:00 2001 From: Nikos Roussos Date: Thu, 5 Dec 2024 15:50:43 +0200 Subject: [PATCH] Retire ENForm block Removes all code exclusively required for the ENForm block. - Removes relevant styles from Counter block - Removes relevant locale text domains - Removes twig templates that no other block uses - Adjust locale text domains - Added migration to clean up database from block settings and forms --- admin/css/admin_en.css | 30 - admin/js/enforms.js | 865 ------------------ assets/src/blocks/Counter/CounterBlock.js | 6 - assets/src/blocks/Counter/CounterFrontend.js | 17 +- assets/src/blocks/ENForm/CountrySelector.js | 286 ------ assets/src/blocks/ENForm/ENFormBlock.js | 78 -- assets/src/blocks/ENForm/ENFormEditor.js | 46 - .../src/blocks/ENForm/ENFormEditorScript.js | 3 - assets/src/blocks/ENForm/ENFormFrontend.js | 487 ---------- assets/src/blocks/ENForm/ENFormInPlaceEdit.js | 375 -------- assets/src/blocks/ENForm/ENFormScript.js | 14 - assets/src/blocks/ENForm/ENFormSettings.js | 216 ----- assets/src/blocks/ENForm/FormGenerator.js | 358 -------- assets/src/blocks/ENForm/PositionSelector.js | 51 -- assets/src/blocks/ENForm/ShareButtons.js | 115 --- .../src/blocks/ENForm/deprecated/ENFormV1.js | 45 - .../src/blocks/ENForm/deprecated/ENFormV2.js | 12 - assets/src/blocks/ENForm/inputId.js | 17 - assets/src/scss/blocks.scss | 1 - .../src/scss/blocks/Counter/CounterStyle.scss | 25 - .../scss/blocks/ENForm/ENFormEditorStyle.scss | 55 -- .../src/scss/blocks/ENForm/ENFormStyle.scss | 9 - .../ENForm/campaigns/_campaign_enform.scss | 3 - .../scss/blocks/ENForm/campaigns/_mixins.scss | 47 - .../components/_enform-full-width-bg.scss | 78 -- .../ENForm/components/_enform-full-width.scss | 88 -- .../ENForm/components/_enform-side-style.scss | 169 ---- .../blocks/ENForm/components/_enform.scss | 301 ------ assets/src/scss/editorStyle.scss | 1 - exporter-helper.php | 4 - functions.php | 1 - phpcs.xml.dist | 2 +- src/Api/ENForm.php | 39 - src/BlockSettings.php | 11 - src/Blocks/BaseBlock.php | 21 - src/Blocks/ENForm.php | 427 --------- src/ControlPanel.php | 66 -- src/Controllers/Api/QuestionsController.php | 246 ----- src/Controllers/Api/RestController.php | 198 ---- src/Controllers/EnformFieldsListTable.php | 155 ---- src/Controllers/EnformQuestionsListTable.php | 171 ---- src/Controllers/EnsapiController.php | 424 --------- src/Controllers/Menu/EnSettingsController.php | 166 ---- src/Controllers/Menu/EnformPostController.php | 480 ---------- src/Features/EngagingNetworks.php | 46 - src/Importer.php | 5 - src/Loader.php | 16 - src/MasterBlocks.php | 50 - src/MasterSite.php | 6 +- src/Migrations/M001EnableEnFormFeature.php | 5 +- src/Migrations/M036RemoveEnFormOptions.php | 38 + src/Migrator.php | 2 + src/Model/QuestionsModel.php | 125 --- src/Settings/Features.php | 2 - src/View/View.php | 152 --- .../block_templates/block-error-message.twig | 1 - .../block_templates/en_selected_meta_box.twig | 56 -- templates/block_templates/enform.twig | 90 -- .../enform/country_select.twig | 267 ------ templates/block_templates/enform/enblock.twig | 84 -- .../block_templates/enform/enform_post.twig | 161 ---- .../enform/position_select.twig | 32 - .../enform/tease-thankyou.twig | 33 - .../selected_enform_fields.twig | 146 --- templates/block_templates/settings.twig | 65 -- tests/e2e/blocks/enform.spec.js | 264 ------ tests/e2e/fixtures/enform/enformData.js | 107 --- .../enform/ensapi_sample_fields_response.json | 676 -------------- .../enform/ensapi_sample_pages_response.json | 60 -- ...nsapi_sample_question_220954_response.json | 23 - ...nsapi_sample_question_236734_response.json | 14 - .../ensapi_sample_question_3877_response.json | 23 - .../ensapi_sample_questions_response.json | 268 ------ webpack.config.js | 2 - 74 files changed, 49 insertions(+), 8979 deletions(-) delete mode 100644 admin/css/admin_en.css delete mode 100644 admin/js/enforms.js delete mode 100644 assets/src/blocks/ENForm/CountrySelector.js delete mode 100644 assets/src/blocks/ENForm/ENFormBlock.js delete mode 100644 assets/src/blocks/ENForm/ENFormEditor.js delete mode 100644 assets/src/blocks/ENForm/ENFormEditorScript.js delete mode 100644 assets/src/blocks/ENForm/ENFormFrontend.js delete mode 100644 assets/src/blocks/ENForm/ENFormInPlaceEdit.js delete mode 100644 assets/src/blocks/ENForm/ENFormScript.js delete mode 100644 assets/src/blocks/ENForm/ENFormSettings.js delete mode 100644 assets/src/blocks/ENForm/FormGenerator.js delete mode 100644 assets/src/blocks/ENForm/PositionSelector.js delete mode 100644 assets/src/blocks/ENForm/ShareButtons.js delete mode 100644 assets/src/blocks/ENForm/deprecated/ENFormV1.js delete mode 100644 assets/src/blocks/ENForm/deprecated/ENFormV2.js delete mode 100644 assets/src/blocks/ENForm/inputId.js delete mode 100644 assets/src/scss/blocks/ENForm/ENFormEditorStyle.scss delete mode 100644 assets/src/scss/blocks/ENForm/ENFormStyle.scss delete mode 100644 assets/src/scss/blocks/ENForm/campaigns/_campaign_enform.scss delete mode 100644 assets/src/scss/blocks/ENForm/campaigns/_mixins.scss delete mode 100644 assets/src/scss/blocks/ENForm/components/_enform-full-width-bg.scss delete mode 100644 assets/src/scss/blocks/ENForm/components/_enform-full-width.scss delete mode 100644 assets/src/scss/blocks/ENForm/components/_enform-side-style.scss delete mode 100644 assets/src/scss/blocks/ENForm/components/_enform.scss delete mode 100644 src/Api/ENForm.php delete mode 100644 src/Blocks/ENForm.php delete mode 100644 src/Controllers/Api/QuestionsController.php delete mode 100644 src/Controllers/Api/RestController.php delete mode 100644 src/Controllers/EnformFieldsListTable.php delete mode 100644 src/Controllers/EnformQuestionsListTable.php delete mode 100644 src/Controllers/EnsapiController.php delete mode 100644 src/Controllers/Menu/EnSettingsController.php delete mode 100644 src/Controllers/Menu/EnformPostController.php delete mode 100644 src/Features/EngagingNetworks.php create mode 100644 src/Migrations/M036RemoveEnFormOptions.php delete mode 100644 src/Model/QuestionsModel.php delete mode 100644 src/View/View.php delete mode 100644 templates/block_templates/block-error-message.twig delete mode 100644 templates/block_templates/en_selected_meta_box.twig delete mode 100644 templates/block_templates/enform.twig delete mode 100644 templates/block_templates/enform/country_select.twig delete mode 100644 templates/block_templates/enform/enblock.twig delete mode 100644 templates/block_templates/enform/enform_post.twig delete mode 100644 templates/block_templates/enform/position_select.twig delete mode 100644 templates/block_templates/enform/tease-thankyou.twig delete mode 100644 templates/block_templates/selected_enform_fields.twig delete mode 100644 templates/block_templates/settings.twig delete mode 100644 tests/e2e/blocks/enform.spec.js delete mode 100644 tests/e2e/fixtures/enform/enformData.js delete mode 100644 tests/e2e/fixtures/enform/ensapi_sample_fields_response.json delete mode 100644 tests/e2e/fixtures/enform/ensapi_sample_pages_response.json delete mode 100644 tests/e2e/fixtures/enform/ensapi_sample_question_220954_response.json delete mode 100644 tests/e2e/fixtures/enform/ensapi_sample_question_236734_response.json delete mode 100644 tests/e2e/fixtures/enform/ensapi_sample_question_3877_response.json delete mode 100644 tests/e2e/fixtures/enform/ensapi_sample_questions_response.json diff --git a/admin/css/admin_en.css b/admin/css/admin_en.css deleted file mode 100644 index 9ae15af37e..0000000000 --- a/admin/css/admin_en.css +++ /dev/null @@ -1,30 +0,0 @@ -.enform-required-field { - border-color: #f75848 !important; -} - -#fields_list_box, #questions_list_box, #optins_list_box { - max-height: 400px; - overflow: auto; -} - -#meta-box-selected .inside { - overflow-x: auto; -} - -.add-en-field, .remove-en-field, .pointer { - cursor: pointer; -} - -.ui-tooltip { - background: #444; - border-radius: 5px; - box-shadow: 2px 2px 2px 0 rgba(0, 0, 0, .75); - color: white; - display: inline-block; - padding: 10px; - width: 100px; -} - -tr.not-tagged-field { - background-color: #faffd3 !important; -} diff --git a/admin/js/enforms.js b/admin/js/enforms.js deleted file mode 100644 index 8409ef7759..0000000000 --- a/admin/js/enforms.js +++ /dev/null @@ -1,865 +0,0 @@ -/* global ajaxurl, Backbone */ - -const enformTemplates = { - enSelectedField: data => { - const __ = wp.i18n.__; - const escAttr = wp.escapeHtml.escapeAttribute; - - return ` - - - ${data.name} - ${data.en_type} - - - - - - - - - - - ${data.input_type !== 'email' ? ` - - - ` : ''} - - - `; - }, - enTextFieldDialog: data => { - const __ = wp.i18n.__; - const escAttr = wp.escapeHtml.escapeAttribute; - - return ` - - `; - }, - enHiddenField: data => { - const __ = wp.i18n.__; - const escAttr = wp.escapeHtml.escapeAttribute; - - return ` - - `; - }, - enCheckboxDialog: data => { - const __ = wp.i18n.__; - const escAttr = wp.escapeHtml.escapeAttribute; - - const options = []; - Object.keys(data.locales || {}).forEach(locale => { - options.push(``); - }); - - let genOptions = []; - if (data.en_type === 'GEN') { - genOptions = data.question_options[data.selected_locale].map(opt => { - return `${opt.option_label}
`; - }); - } - - return ` - - `; - }, - enRadioDialog: data => { - const __ = wp.i18n.__; - const escAttr = wp.escapeHtml.escapeAttribute; - - const options = []; - Object.keys(data.locales).forEach(locale => { - options.push(``); - }); - - let radioOptions = []; - if (data.en_type === 'GEN') { - radioOptions = data.radio_options[data.selected_locale].map(opt => { - return `${opt.option_label}
`; - }); - } - return ` - - `; - }, - -}; - -/** - * Define models, collections, views for P4 ENForms. - */ -const p4_enform = ($ => { - const app = { - Models: {}, - Collections: {}, - Views: {}, - }; - - /** - * Model for ENForm field. - */ - app.Models.EnformField = Backbone.Model.extend({ - urlRoot: '', - defaults: { - id: 0, - name: null, - property: '', - label: '', - default_value: '', - js_validate_regex: '', - js_validate_regex_msg: '', - js_validate_function: '', - en_type: 'N', - hidden: false, - required: false, - input_type: '0', - htmlFieldType: '', - selected_locale: '', - locales: {}, - question_options: {}, - radio_options: {}, - selected: '', - dependency: '', - }, - }); - - /** - * Collection of fields. - */ - app.Collections.EnformFields = Backbone.Collection.extend( - { - model: app.Models.EnformField, - url: '', - }); - - /** - * A view for listing fields. - */ - app.Views.FieldsListView = Backbone.View.extend({ - el: '#en_form_selected_fields_table', - template: () => '', - events: { - 'click .remove-en-field': 'removeField', - 'update-sort': 'updateSort', - }, - views: {}, - - /** - * Initialize view. - */ - initialize() { - this.listenTo(this.collection, 'add', this.renderOne); - }, - - /** - * Render a single field. - * - * @param {Object} field Field model. - * @param {Object} collection Field model collection. - * @param {Object} actions Object with actions. - */ - renderOne(field, collection, actions) { - const fieldView = new app.Views.FieldsListItemView({model: field}); - - this.views[field.id] = fieldView; - $('#en_form_selected_fields_table > tbody').append(fieldView.render()); - $('.add-en-field').filter('*[data-id="' + field.id + '"]').prop('disabled', true); - fieldView._delegateEvents(); - - // If a field is being added and its html type has been retrieved from EN - // then auto-select the field type for Questions/Optins. Should happen after Delegate events. - if (actions.add && field.attributes.htmlFieldType) { - if ('OPT' === field.attributes.en_type || 'GEN' === field.attributes.en_type) { - $('.field-type-select', fieldView.$el).val(field.attributes.htmlFieldType).change(); - } - } - fieldView.createFieldDialog(); - }, - - /** - * Render view. - */ - render() { - this.collection.models.forEach(project => { - this.renderOne(project, this.collection, {add: false}); - }, this); - this.disableEmailField(); - }, - - /** - * Event listener for remove field/question button. - * - * @param {Object} e - */ - removeField(e) { - e.preventDefault(); - const $tr = $(e.target).closest('tr'); - const id = $tr.data('en-id'); - - $('.add-en-field').filter('*[data-id="' + id + '"]').prop('disabled', false); - this.collection.remove(this.collection.findWhere({id})); - this.views[id].destroy(); - $tr.remove(); - }, - - /** - * Reorder collection models. - * - * @param {Object} event Event object - * @param {Object} model Field Model. - * @param {number} position New index. - */ - updateSort(event, model, position) { - this.collection.remove(model, {silent: true}); - this.collection.add(model, {at: position, silent: true}); - }, - - /** - * Disable email field attributes besides label. - */ - disableEmailField() { - $('tr[data-en-name="Email"] span.remove-en-field').remove(); - $('tr[data-en-name="Email"] input[data-attribute="required"]').prop('checked', true).prop('disabled', true); - $('tr[data-en-name="Email"] select[data-attribute="input_type"]').val('email').prop('disabled', true); - const emailModel = this.collection.findWhere({property: 'emailAddress'}); - if ('undefined' !== typeof emailModel) { - emailModel - .set('input_type', 'email') - .set('required', true); - } - }, - }); - - /** - * A single field view. - */ - app.Views.FieldsListItemView = Backbone.View.extend({ - className: 'field-item', - template: enformTemplates.enSelectedField, - dialog_view: null, - - events: { - 'keyup input[type="text"]': 'inputChanged', - 'change input[type="text"]': 'inputChanged', - 'change input[type="checkbox"]': 'checkboxChanged', - 'change select.field-type-select': 'selectChanged', - 'sort-field': 'sortField', - }, - - /** - * Handles input text value changes and stores them to the model. - * - * @param {Object} event Event object. - */ - inputChanged(event) { - const $target = $(event.target); - const value = $target.val(); - const attr = $target.data('attribute'); - this.model.set(attr, value); - }, - - /** - * Handles input checkbox value changes and stores them to the model. - * - * @param {Object} event Event object. - */ - checkboxChanged(event) { - const $target = $(event.target); - const value = $target.is(':checked'); - const attr = $target.data('attribute'); - this.model.set(attr, value); - }, - - /** - * Register event listener for field type select box. - * - * @param {Object} event - */ - selectChanged(event) { - const input_type = $(event.target).val(); - const $tr = $(event.target).closest('tr'); - const id = $tr.data('en-id'); - const attr = $(event.target).data('attribute'); - const en_type = this.model.get('en_type'); - const $label = this.$el.find('input[data-attribute="label"]'); - const $required = this.$el.find('input[data-attribute="required"]'); - - this.model.set(attr, input_type); - $tr.find('.dashicons-edit').parent().remove(); - - switch (input_type) { - case 'checkbox': - if ('OPT' === en_type || 'GEN' === en_type) { - $required.prop('disabled', false); - $label.prop('disabled', true); - } else { - $label.prop('disabled', false); - } - this.$el.find('.actions').prepend(''); - this.createFieldDialog(); - break; - - case 'country': - $required.prop('disabled', false); - $label.prop('disabled', false); - break; - - case 'position': - $required.prop('disabled', false); - $label.prop('disabled', false); - break; - - case 'email': - $required.prop('disabled', false); - $label.prop('disabled', false); - break; - - case 'hidden': - $required.prop('checked', false).trigger('change').prop('disabled', true); - $label.prop('disabled', true); - $label.val('').trigger('change'); - this.$el.find('.actions').prepend(''); - this.createFieldDialog(); - break; - - case 'text': - $required.prop('disabled', false); - $label.prop('disabled', false); - this.$el.find('.actions').prepend(''); - this.createFieldDialog(); - break; - - case 'radio': - $required.prop('disabled', false); - if ('OPT' === en_type || 'GEN' === en_type) { - $label.prop('disabled', true); - } else { - $label.prop('disabled', false); - } - this.$el.find('.actions').prepend(''); - this.createFieldDialog(); - break; - - default: - if (null !== this.dialog_view) { - this.dialog_view.destroy(); - this.dialog_view = null; - } - $('body').find('.dialog-' + id).remove(); - this.$el.find('.dashicons-edit').parent().remove(); - } - }, - - /** - * Initialize view. - */ - initialize() { - this.listenTo(this.model, 'change', this.render); - }, - - /** - * Create field dialog view. - */ - createFieldDialog() { - const input_type = this.model.get('input_type'); - let tmpl = ''; - - switch (input_type) { - case 'text': - tmpl = enformTemplates.enTextFieldDialog; - break; - case 'hidden': - tmpl = enformTemplates.enHiddenField; - break; - case 'checkbox': - tmpl = enformTemplates.enCheckboxDialog; - break; - case 'radio': - tmpl = enformTemplates.enRadioDialog; - break; - } - - if (null !== this.dialog_view) { - this.dialog_view.destroy(); - $('body').find('.dialog-' + this.model.id).remove(); - } - - if (tmpl) { - this.dialog_view = new app.Views.FieldDialog({ - row: this.model.id, - model: this.model, - template: tmpl, - }); - } - }, - - /** - * Delegate events after view is rendered. - */ - _delegateEvents() { - this.$el = $('tr[data-en-id="' + this.model.id + '"]'); - this.delegateEvents(); - }, - - /** - * Render view. - * - * @return {Object} the template. - */ - render() { - return this.template(this.model.toJSON()); - }, - - /** - * Destroy view. - */ - destroy() { - if (null !== this.dialog_view) { - this.dialog_view.destroy(); - } - this.remove(); - }, - - /** - * Trigger collection sorting. - * - * @param {Object} event Event object - * @param {number} index New index for the field model. - */ - sortField(event, index) { - this.$el.trigger('update-sort', [this.model, index]); - }, - }); - - /** - * A single field view. - */ - app.Views.FieldDialog = Backbone.View.extend({ - row: null, - dialog: null, - events: { - 'keyup input': 'inputChanged', - 'change input[type="text"]': 'inputChanged', - 'change input[type="checkbox"]': 'checkboxChanged', - 'change .question-locale-select': 'localeChanged', - 'change .dependency-select': 'dependencyChanged', - }, - - /** - * Handles input text value changes and stores them to the model. - * - * @param {Object} event Event object. - */ - inputChanged(event) { - const $target = $(event.target); - const value = $target.val(); - const attr = $target.data('attribute'); - this.model.set(attr, value); - }, - - /** - * Handles input checkbox value changes and stores them to the model. - * - * @param {Object} event Event object. - */ - checkboxChanged(event) { - const $target = $(event.target); - const value = $target.is(':checked'); - const attr = $target.data('attribute'); - this.model.set(attr, value); - }, - - /** - * Handles locale select changes and stores them to the model. - * - * @param {Object} event Event object. - */ - localeChanged(event) { - const $target = $(event.target); - const $dialog = $target.closest('div.dialog'); - const field_id = $dialog.attr('data-en-id'); - const label = $(event.target).val(); - const locale = $('option:selected', $target).text(); - - $('input[data-attribute="label"]', $('tr[data-en-id="' + field_id + '"]')) - .prop('disabled', false) - .val(label) - .trigger('change') - .prop('disabled', true); - - this.model.set('label', label); - this.model.set('selected_locale', locale); - - // Get template's html, unwrap it to get rid of the most outer element and then update the dialog's html with it. - const dialog_html = $(this.template(this.model.toJSON())).unwrap().html(); - $dialog.html(dialog_html); - }, - - /** - * Handles dependency select changes and stores them to the model. - * - * @param {Object} event Event object. - */ - dependencyChanged(event) { - const $target = $(event.target); - const value = $('option:selected', $target).val(); - $('option:selected', $target).attr('selected', 'selected'); - this.model.set('dependency', value); - }, - - /** - * Initialize view instance. - * - * @param {Object} options Options object. - */ - initialize(options) { - this.template = options.template; - this.rowid = options.row; - this.row = $('tr[data-en-id="' + this.rowid + '"]'); - this.model = options.model; - this.render(); - }, - - /** - * Render dialog view - */ - render() { - $(this.row).find('.actions').prepend(this.template(this.model.toJSON())); - - this.dialog = $(this.row).find('.dialog').dialog({ - autoOpen: false, - height: 450, - width: 350, - modal: true, - title: 'Edit: ' + this.model.get('name'), - dialogClass: 'dialog-' + this.rowid, - buttons: { - 'Close'() { - dialog.dialog('close'); - }, - }, - }); - - this.el = '.dialog-' + this.rowid; - this.$el = $(this.el).find('.ui-dialog-content'); - const label = $('.question-locale-select', this.$el).val(); - this.delegateEvents(); - - const dialog = this.dialog; - $(this.row).find('.dashicons-edit').off('click').on('click', e => { - e.preventDefault(); - const button = e.target; - - // Filter dependency fields and add them on dialog popup. - let dependency_options = ''; - if ('checkbox' === $(button).closest('tr').find('.field-type-select').val()) { - const selected_en_fields = p4_enform.fields.models; - - if (selected_en_fields.length) { - const dependency_array = []; - let dependency_field = ''; - const field_name = $(button).closest('tr').find('td:eq(1)').text(); - selected_en_fields.forEach(field => { - if ('checkbox' === field.attributes.input_type && field.attributes.name !== field_name) { - dependency_array.push(field.attributes.name); - } - - if (field.attributes.name === field_name) { - dependency_field = field.attributes.dependency; - } - }); - - $.each(dependency_array, (key, value) => { - let selected_option = ''; - if (dependency_field === value) { - selected_option = 'selected'; - } - dependency_options += ''; - }); - } - } - - dialog.html(dialog.html().replace('', dependency_options + '')); - dialog.dialog('open'); - }); - - // Handle Label selection. - $('.question-label', this.$el).html(label); - $('.question-locale-select').change(); - }, - - /** - * Destroy dialog view. - * Set default values to model. - */ - destroy() { - this.dialog.dialog('destroy'); - this.model.set('default_value', ''); - this.model.set('js_validate_regex', ''); - this.model.set('js_validate_regex_msg', ''); - this.model.set('js_validate_function', ''); - this.model.set('hidden', false); - this.model.set('dependency', ''); - this.remove(); - }, - }); - - return app; -})(jQuery); - -jQuery($ => { - /** - * Event listener for add field/question button. - */ - $('.add-en-field').off('click').on('click', e => { - e.preventDefault(); - const escAttr = wp.escapeHtml.escapeAttribute; - const escHTML = wp.escapeHtml.escapeHTML; - - const button = e.target; - $(button).prop('disabled', true); - const field_data = { - name: $(button).data('name'), - en_type: $(button).data('type'), - property: $(button).data('property'), - id: $(button).data('id'), - htmlFieldType: '', - selected_locale: '', - locales: {}, - question_options: {}, - radio_options: {}, - selected: '', - }; - - // If we add an Opt-in then retrieve the labels for all locales that exist for it from EN. - if ('OPT' === field_data.en_type || 'GEN' === field_data.en_type) { - $.ajax({ - url: ajaxurl, - type: 'GET', - data: { - action: 'get_supporter_question_by_id', - id: $(button).data('id'), - }, - }).done(response => { - // Checking response type to avoid error if string was returned (in case of an error). - if ('object' === typeof response) { - $.each(response, (i, value) => { - if (value.content && 'undefined' !== typeof value.content.data[0]) { - field_data.htmlFieldType = value.htmlFieldType; - let label = ''; - let selected = ''; - - switch (field_data.htmlFieldType) { - case 'checkbox': - if ('OPT' === field_data.en_type) { - label = value.content.data[0].label; - selected = value.content.data[0].selected; - } else if ('GEN' === field_data.en_type) { - label = value.label; - field_data.question_options[value.locale] = []; - - $.each(value.content.data, (j, option) => { - field_data.question_options[value.locale].push({ - option_label: escHTML(option.label), - option_value: escAttr(option.value), - option_selected: option.selected, - }); - }); - } - field_data.locales[value.locale] = escHTML(label); - field_data.selected = selected; - break; - - case 'radio': - label = value.label; - field_data.locales[value.locale] = escHTML(label); - field_data.radio_options[value.locale] = []; - - $.each(value.content.data, (j, option) => { - field_data.radio_options[value.locale].push({ - option_label: escHTML(option.label), - option_value: escAttr(option.value), - option_selected: option.selected, - }); - }); - break; - } - } - }); - // Add new field. - p4_enform.fields.add(new p4_enform.Models.EnformField(field_data)); - } - }).fail(response => { - console.log(response); //eslint-disable-line no-console - }); - } else { - p4_enform.fields.add(new p4_enform.Models.EnformField(field_data)); - } - }); - - /** - * Make form selected fields table sortable. - */ - $('#en_form_selected_fields_table > tbody').sortable({ - handle: '.dashicons-sort', - stop(event, ui) { - ui.item.trigger('sort-field', ui.item.index()); - }, - }); - - /** - * Hook into post submit to inject form fields. - */ - $('#post').on('submit', () => { - $('#p4enform_fields').val(JSON.stringify(p4_enform.fields.toJSON())); - }); - - /** - * Disable preview form fields. - */ - $('#meta-box-form :input').prop('disabled', true); -}); - -// Handles initial page load of new/edit enform page. -// Create fields collections and views and populate views if there are any saved fields. -(($, app) => { - /** - * Initialize new/edit enform page. - */ - app.init_new_enform_page = () => { - // Create fields collection. - app.fields = new app.Collections.EnformFields(); - - // Instantiate fields collection. - let fields = $('#p4enform_fields').val(); - - // If fields are set populate the fields collection. - if ('' !== fields) { - fields = JSON.parse(fields); - if (fields) { - const fields_arr = []; - fields.forEach(field => { - fields_arr.push(new app.Models.EnformField(field)); - }); - app.fields.add(fields_arr); - } - } - - // If it is a new post, add email field. - if ('auto-draft' === $('#original_post_status').val()) { - $('button[class="add-en-field"][data-property="emailAddress"] ').click(); - } - - app.fields_view = new app.Views.FieldsListView({collection: app.fields}); - app.fields_view.render(); - }; - - /** - * Initialize app when page is loaded. - */ - $(document).ready(() => { - // Initialize app when document is loaded. - app.init_new_enform_page(); - - // Initialize tooltips. - app.fields_view.$el.tooltip({ - track: true, - show: {effect: 'fadeIn', duration: 500}, - }); - }); -})(jQuery, p4_enform); diff --git a/assets/src/blocks/Counter/CounterBlock.js b/assets/src/blocks/Counter/CounterBlock.js index 36c0ad6fd7..6b36757a89 100644 --- a/assets/src/blocks/Counter/CounterBlock.js +++ b/assets/src/blocks/Counter/CounterBlock.js @@ -96,12 +96,6 @@ export const registerCounterBlock = () => { }, ]; - if (window.p4_vars.features.feature_engaging_networks) { - styles.push({ - name: 'en-forms-bar', - label: 'Progress Bar inside EN Form', - }); - } // Add our custom styles registerBlockStyle(BLOCK_NAME, styles); }; diff --git a/assets/src/blocks/Counter/CounterFrontend.js b/assets/src/blocks/Counter/CounterFrontend.js index 675476d98c..277f4c1fc7 100644 --- a/assets/src/blocks/Counter/CounterFrontend.js +++ b/assets/src/blocks/Counter/CounterFrontend.js @@ -23,7 +23,6 @@ export class CounterFrontend extends Component { if (completed_api && completed_api.startsWith('https://')) { window.addEventListener('updateCounter', counter.calculateRemaining, false); } - this.appendENForm(); } componentWillUnmount() { @@ -40,18 +39,6 @@ export class CounterFrontend extends Component { if (target !== prevTarget || completed !== prevCompleted || completed_api !== prevCompletedApi) { this.calculateRemaining(); } - this.appendENForm(); - } - - appendENForm() { - // Append the counter inside the En-Form - const counterBar = document.querySelector('.wp-block-planet4-blocks-counter .counter-style-en-forms-bar')?.cloneNode(true); - const enFormHeader = document.querySelector('.enform-extra-header-placeholder'); - - if (counterBar && enFormHeader) { - enFormHeader.innerHTML = ''; - enFormHeader.append(counterBar); - } } calculateRemaining() { @@ -129,9 +116,9 @@ export class CounterFrontend extends Component {

}

- {(style === 'bar' || style === 'en-forms-bar') && + {(style === 'bar') &&
-
+
} {style === 'arc' && diff --git a/assets/src/blocks/ENForm/CountrySelector.js b/assets/src/blocks/ENForm/CountrySelector.js deleted file mode 100644 index 7626154f1f..0000000000 --- a/assets/src/blocks/ENForm/CountrySelector.js +++ /dev/null @@ -1,286 +0,0 @@ -export const CountrySelector = attributes => { - const { - name = 'country-selector', - id = null, - default_text = '', - class_name = '', - error_message = '', - required = false, - onInputChange = null, - onBlur = null, - } = attributes; - - const options = [ - , - ...countries.map(c => { - return ; - }), - ]; - - return ( - - ); -}; - -const countries = [ - {code: 'AF', name: 'Afghanistan'}, - {code: 'AX', name: 'Åland Islands'}, - {code: 'AL', name: 'Albania'}, - {code: 'DZ', name: 'Algeria'}, - {code: 'AS', name: 'American Samoa'}, - {code: 'AD', name: 'Andorra'}, - {code: 'AO', name: 'Angola'}, - {code: 'AI', name: 'Anguilla'}, - {code: 'AQ', name: 'Antarctica'}, - {code: 'AG', name: 'Antigua and Barbuda'}, - {code: 'AR', name: 'Argentina'}, - {code: 'AM', name: 'Armenia'}, - {code: 'AW', name: 'Aruba'}, - {code: 'AU', name: 'Australia'}, - {code: 'AT', name: 'Austria'}, - {code: 'AZ', name: 'Azerbaijan'}, - {code: 'BS', name: 'Bahamas'}, - {code: 'BH', name: 'Bahrain'}, - {code: 'BD', name: 'Bangladesh'}, - {code: 'BB', name: 'Barbados'}, - {code: 'BY', name: 'Belarus'}, - {code: 'BE', name: 'Belgium'}, - {code: 'BZ', name: 'Belize'}, - {code: 'BJ', name: 'Benin'}, - {code: 'BM', name: 'Bermuda'}, - {code: 'BT', name: 'Bhutan'}, - {code: 'BO', name: 'Bolivia, Plurinational State of'}, - {code: 'BQ', name: 'Bonaire, Sint Eustatius and Saba'}, - {code: 'BA', name: 'Bosnia and Herzegovina'}, - {code: 'BW', name: 'Botswana'}, - {code: 'BV', name: 'Bouvet Island'}, - {code: 'BR', name: 'Brazil'}, - {code: 'IO', name: 'British Indian Ocean Territory'}, - {code: 'BN', name: 'Brunei Darussalam'}, - {code: 'BG', name: 'Bulgaria'}, - {code: 'BF', name: 'Burkina Faso'}, - {code: 'BI', name: 'Burundi'}, - {code: 'CV', name: 'Cabo Verde'}, - {code: 'KH', name: 'Cambodia'}, - {code: 'CM', name: 'Cameroon'}, - {code: 'CA', name: 'Canada'}, - {code: 'KY', name: 'Cayman Islands'}, - {code: 'CF', name: 'Central African Republic'}, - {code: 'TD', name: 'Chad'}, - {code: 'CL', name: 'Chile'}, - {code: 'CN', name: 'China mainland'}, - {code: 'CX', name: 'Christmas Island'}, - {code: 'CC', name: 'Cocos (Keeling) Islands'}, - {code: 'CO', name: 'Colombia'}, - {code: 'KM', name: 'Comoros'}, - {code: 'CG', name: 'Congo'}, - {code: 'CD', name: 'Congo, the Democratic Republic of the'}, - {code: 'CK', name: 'Cook Islands'}, - {code: 'CR', name: 'Costa Rica'}, - {code: 'CI', name: 'Côte d\'Ivoire'}, - {code: 'HR', name: 'Croatia'}, - {code: 'CU', name: 'Cuba'}, - {code: 'CW', name: 'Curaçao'}, - {code: 'CY', name: 'Cyprus'}, - {code: 'CZ', name: 'Czech Republic'}, - {code: 'DK', name: 'Denmark'}, - {code: 'DJ', name: 'Djibouti'}, - {code: 'DM', name: 'Dominica'}, - {code: 'DO', name: 'Dominican Republic'}, - {code: 'EC', name: 'Ecuador'}, - {code: 'EG', name: 'Egypt'}, - {code: 'SV', name: 'El Salvador'}, - {code: 'GQ', name: 'Equatorial Guinea'}, - {code: 'ER', name: 'Eritrea'}, - {code: 'EE', name: 'Estonia'}, - {code: 'ET', name: 'Ethiopia'}, - {code: 'FK', name: 'Falkland Islands (Malvinas'}, - {code: 'FO', name: 'Faroe Islands'}, - {code: 'FJ', name: 'Fiji'}, - {code: 'FI', name: 'Finland'}, - {code: 'FR', name: 'France'}, - {code: 'GF', name: 'French Guiana'}, - {code: 'PF', name: 'French Polynesia'}, - {code: 'TF', name: 'French Southern Territories'}, - {code: 'GA', name: 'Gabon'}, - {code: 'GM', name: 'Gambia'}, - {code: 'GE', name: 'Georgia'}, - {code: 'DE', name: 'Germany'}, - {code: 'GH', name: 'Ghana'}, - {code: 'GI', name: 'Gibraltar'}, - {code: 'GR', name: 'Greece'}, - {code: 'GL', name: 'Greenland'}, - {code: 'GD', name: 'Grenada'}, - {code: 'GP', name: 'Guadeloupe'}, - {code: 'GU', name: 'Guam'}, - {code: 'GT', name: 'Guatemala'}, - {code: 'GG', name: 'Guernsey'}, - {code: 'GN', name: 'Guinea'}, - {code: 'GW', name: 'Guinea-Bissau'}, - {code: 'GY', name: 'Guyana'}, - {code: 'HT', name: 'Haiti'}, - {code: 'HM', name: 'Heard Island and McDonald Islands'}, - {code: 'VA', name: 'Holy See (Vatican City State'}, - {code: 'HN', name: 'Honduras'}, - {code: 'HK', name: 'Hong Kong'}, - {code: 'HU', name: 'Hungary'}, - {code: 'IS', name: 'Iceland'}, - {code: 'IN', name: 'India'}, - {code: 'ID', name: 'Indonesia'}, - {code: 'IR', name: 'Iran, Islamic Republic of'}, - {code: 'IQ', name: 'Iraq'}, - {code: 'IE', name: 'Ireland'}, - {code: 'IM', name: 'Isle of Man'}, - {code: 'IL', name: 'Israel'}, - {code: 'IT', name: 'Italy'}, - {code: 'JM', name: 'Jamaica'}, - {code: 'JP', name: 'Japan'}, - {code: 'JE', name: 'Jersey'}, - {code: 'JO', name: 'Jordan'}, - {code: 'KZ', name: 'Kazakhstan'}, - {code: 'KE', name: 'Kenya'}, - {code: 'KI', name: 'Kiribati'}, - {code: 'KP', name: 'Korea, Democratic People\'s Republic of'}, - {code: 'KR', name: 'Korea, Republic of'}, - {code: 'KW', name: 'Kuwait'}, - {code: 'KG', name: 'Kyrgyzstan'}, - {code: 'LA', name: 'Lao People\'s Democratic Republic'}, - {code: 'LV', name: 'Latvia'}, - {code: 'LB', name: 'Lebanon'}, - {code: 'LS', name: 'Lesotho'}, - {code: 'LR', name: 'Liberia'}, - {code: 'LY', name: 'Libya'}, - {code: 'LI', name: 'Liechtenstein'}, - {code: 'LT', name: 'Lithuania'}, - {code: 'LU', name: 'Luxembourg'}, - {code: 'MO', name: 'Macao'}, - {code: 'MK', name: 'Macedonia, the former Yugoslav Republic of'}, - {code: 'MG', name: 'Madagascar'}, - {code: 'MW', name: 'Malawi'}, - {code: 'MY', name: 'Malaysia'}, - {code: 'MV', name: 'Maldives'}, - {code: 'ML', name: 'Mali'}, - {code: 'MT', name: 'Malta'}, - {code: 'MH', name: 'Marshall Islands'}, - {code: 'MQ', name: 'Martinique'}, - {code: 'MR', name: 'Mauritania'}, - {code: 'MU', name: 'Mauritius'}, - {code: 'YT', name: 'Mayotte'}, - {code: 'MX', name: 'Mexico'}, - {code: 'FM', name: 'Micronesia, Federated States of'}, - {code: 'MD', name: 'Moldova, Republic of'}, - {code: 'MC', name: 'Monaco'}, - {code: 'MN', name: 'Mongolia'}, - {code: 'ME', name: 'Montenegro'}, - {code: 'MS', name: 'Montserrat'}, - {code: 'MA', name: 'Morocco'}, - {code: 'MZ', name: 'Mozambique'}, - {code: 'MM', name: 'Myanmar'}, - {code: 'NA', name: 'Namibia'}, - {code: 'NR', name: 'Nauru'}, - {code: 'NP', name: 'Nepal'}, - {code: 'NL', name: 'Netherlands'}, - {code: 'NC', name: 'New Caledonia'}, - {code: 'NZ', name: 'New Zealand'}, - {code: 'NI', name: 'Nicaragua'}, - {code: 'NE', name: 'Niger'}, - {code: 'NG', name: 'Nigeria'}, - {code: 'NU', name: 'Niue'}, - {code: 'NF', name: 'Norfolk Island'}, - {code: 'MP', name: 'Northern Mariana Islands'}, - {code: 'NO', name: 'Norway'}, - {code: 'OM', name: 'Oman'}, - {code: 'PK', name: 'Pakistan'}, - {code: 'PW', name: 'Palau'}, - {code: 'PS', name: 'Palestine, State of'}, - {code: 'PA', name: 'Panama'}, - {code: 'PG', name: 'Papua New Guinea'}, - {code: 'PY', name: 'Paraguay'}, - {code: 'PE', name: 'Peru'}, - {code: 'PH', name: 'Philippines'}, - {code: 'PN', name: 'Pitcairn'}, - {code: 'PL', name: 'Poland'}, - {code: 'PT', name: 'Portugal'}, - {code: 'PR', name: 'Puerto Rico'}, - {code: 'QA', name: 'Qatar'}, - {code: 'RE', name: 'Réunion'}, - {code: 'RO', name: 'Romania'}, - {code: 'RU', name: 'Russian Federation'}, - {code: 'RW', name: 'Rwanda'}, - {code: 'BL', name: 'Saint Barthélemy'}, - {code: 'SH', name: 'Saint Helena, Ascension and Tristan da Cunha'}, - {code: 'KN', name: 'Saint Kitts and Nevis'}, - {code: 'LC', name: 'Saint Lucia'}, - {code: 'MF', name: 'Saint Martin (French part'}, - {code: 'PM', name: 'Saint Pierre and Miquelon'}, - {code: 'VC', name: 'Saint Vincent and the Grenadines'}, - {code: 'WS', name: 'Samoa'}, - {code: 'SM', name: 'San Marino'}, - {code: 'ST', name: 'Sao Tome and Principe'}, - {code: 'SA', name: 'Saudi Arabia'}, - {code: 'SN', name: 'Senegal'}, - {code: 'RS', name: 'Serbia'}, - {code: 'SC', name: 'Seychelles'}, - {code: 'SL', name: 'Sierra Leone'}, - {code: 'SG', name: 'Singapore'}, - {code: 'SX', name: 'Sint Maarten (Dutch part'}, - {code: 'SK', name: 'Slovakia'}, - {code: 'SI', name: 'Slovenia'}, - {code: 'SB', name: 'Solomon Islands'}, - {code: 'SO', name: 'Somalia'}, - {code: 'ZA', name: 'South Africa'}, - {code: 'GS', name: 'South Georgia and the South Sandwich Islands'}, - {code: 'SS', name: 'South Sudan'}, - {code: 'ES', name: 'Spain'}, - {code: 'LK', name: 'Sri Lanka'}, - {code: 'SD', name: 'Sudan'}, - {code: 'SR', name: 'Suriname'}, - {code: 'SJ', name: 'Svalbard and Jan Mayen'}, - {code: 'SZ', name: 'Swaziland'}, - {code: 'SE', name: 'Sweden'}, - {code: 'CH', name: 'Switzerland'}, - {code: 'SY', name: 'Syrian Arab Republic'}, - {code: 'TW', name: 'Taiwan'}, - {code: 'TJ', name: 'Tajikistan'}, - {code: 'TZ', name: 'Tanzania, United Republic of'}, - {code: 'TH', name: 'Thailand'}, - {code: 'TL', name: 'Timor-Leste'}, - {code: 'TG', name: 'Togo'}, - {code: 'TK', name: 'Tokelau'}, - {code: 'TO', name: 'Tonga'}, - {code: 'TT', name: 'Trinidad and Tobago'}, - {code: 'TN', name: 'Tunisia'}, - {code: 'TR', name: 'Turkey'}, - {code: 'TM', name: 'Turkmenistan'}, - {code: 'TC', name: 'Turks and Caicos Islands'}, - {code: 'TV', name: 'Tuvalu'}, - {code: 'UG', name: 'Uganda'}, - {code: 'UA', name: 'Ukraine'}, - {code: 'AE', name: 'United Arab Emirates'}, - {code: 'GB', name: 'United Kingdom'}, - {code: 'US', name: 'United States'}, - {code: 'UM', name: 'United States Minor Outlying Islands'}, - {code: 'UY', name: 'Uruguay'}, - {code: 'UZ', name: 'Uzbekistan'}, - {code: 'VU', name: 'Vanuatu'}, - {code: 'VE', name: 'Venezuela, Bolivarian Republic of'}, - {code: 'VN', name: 'Viet Nam'}, - {code: 'VG', name: 'Virgin Islands, British'}, - {code: 'VI', name: 'Virgin Islands, U.S'}, - {code: 'WF', name: 'Wallis and Futuna'}, - {code: 'EH', name: 'Western Sahara'}, - {code: 'YE', name: 'Yemen'}, - {code: 'ZM', name: 'Zambia'}, - {code: 'ZW', name: 'Zimbabwe'}, -]; diff --git a/assets/src/blocks/ENForm/ENFormBlock.js b/assets/src/blocks/ENForm/ENFormBlock.js deleted file mode 100644 index d6129c0d18..0000000000 --- a/assets/src/blocks/ENForm/ENFormBlock.js +++ /dev/null @@ -1,78 +0,0 @@ -import {renderToString} from 'react-dom/server'; -import {ENFormEditor} from './ENFormEditor'; -import {ENFormFrontend} from './ENFormFrontend'; -import {ENFormV1} from './deprecated/ENFormV1.js'; -import {ENFormV2} from './deprecated/ENFormV2.js'; - -const {__} = wp.i18n; - -export const BLOCK_NAME = 'planet4-blocks/enform'; - -export const attributes = { - en_page_id: {type: 'integer'}, - enform_goal: {type: 'string'}, - en_form_style: {type: 'string', default: 'side-style'}, - title: {type: 'string'}, - description: {type: 'string'}, - campaign_logo: {type: 'boolean'}, - content_title: {type: 'string'}, - content_title_size: {type: 'string', default: 'h1'}, - content_description: {type: 'string'}, - button_text: {type: 'string'}, - text_below_button: {type: 'string'}, - thankyou_title: {type: 'string'}, - thankyou_subtitle: {type: 'string'}, - thankyou_donate_message: {type: 'string'}, - thankyou_social_media_message: {type: 'string'}, - donate_button_checkbox: {type: 'boolean'}, - donate_text: {type: 'string', default: __('Donate', 'planet4-engagingnetworks')}, - thankyou_url: {type: 'string'}, - custom_donate_url: {type: 'string'}, - background: {type: 'integer'}, - background_image_src: {type: 'string', default: ''}, - background_image_srcset: {type: 'string'}, - background_image_sizes: {type: 'string'}, - background_image_focus: {type: 'string', default: '50% 50%'}, - en_form_id: {type: 'integer'}, - en_form_fields: {type: 'array', default: []}, - social: {type: 'object', default: {}}, - social_accounts: {type: 'object', default: {}}, -}; - -export const registerENForm = () => { - const {registerBlockType} = wp.blocks; - const {RawHTML} = wp.element; - - registerBlockType(BLOCK_NAME, { - title: 'EN Form', - description: __('Allows for adding in-page call to actions with data collected and sent to the relevant engaging network account.', 'planet4-blocks-backend'), - icon: 'feedback', - category: 'planet4-blocks', - supports: { - multiple: false, - }, - styles: [ - {name: 'full-width-bg', label: 'Full page width with background'}, - {name: 'full-width', label: 'Page body/text size width'}, - {name: 'side-style', label: 'Form on the side', isDefault: true}, - ], - attributes, - edit: ENFormEditor, - save: props => { - // Sort attributes in a predictable order - const orderedAttributes = Object.fromEntries(Object.entries(props.attributes).sort()); - - const markup = renderToString(
- -
); - return {markup}; - }, - deprecated: [ - ENFormV2, - ENFormV1, - ], - }); -}; diff --git a/assets/src/blocks/ENForm/ENFormEditor.js b/assets/src/blocks/ENForm/ENFormEditor.js deleted file mode 100644 index cc83c13be6..0000000000 --- a/assets/src/blocks/ENForm/ENFormEditor.js +++ /dev/null @@ -1,46 +0,0 @@ -import {ENFormInPlaceEdit} from './ENFormInPlaceEdit'; -import {ENFormSettings} from './ENFormSettings'; -import {getStyleFromClassName} from '../../functions/getStyleFromClassName'; - -const {useSelect} = wp.data; - -export const ENFormEditor = ({attributes, setAttributes}) => { - return ( - renderEdit(attributes, setAttributes) - ); -}; - -const renderEdit = (attributes, setAttributes) => { - const {en_form_style, className, background, background_image_src} = attributes; - - if (className && className.length > 0) { - setAttributes({ - en_form_style: getStyleFromClassName(className), - }); - } - - if (!en_form_style || en_form_style.length <= 0) { - setAttributes({en_form_style: 'side-style'}); - } - - // Retrieve background for legacy blocks - if (background > 0 && background_image_src.length <= 0) { - setAttributes({ - background_image_src: useSelect(select => { - const img = select('core').getMedia(background); - return img?.source_url || ''; - }), - }); - } - - const charLimit = {title: 40, description: 400}; - const params = {attributes, charLimit, setAttributes}; - - return ( - <> - - - - ); -}; - diff --git a/assets/src/blocks/ENForm/ENFormEditorScript.js b/assets/src/blocks/ENForm/ENFormEditorScript.js deleted file mode 100644 index 8d63753142..0000000000 --- a/assets/src/blocks/ENForm/ENFormEditorScript.js +++ /dev/null @@ -1,3 +0,0 @@ -import {registerENForm} from './ENFormBlock'; - -registerENForm(); diff --git a/assets/src/blocks/ENForm/ENFormFrontend.js b/assets/src/blocks/ENForm/ENFormFrontend.js deleted file mode 100644 index 1cef1817ca..0000000000 --- a/assets/src/blocks/ENForm/ENFormFrontend.js +++ /dev/null @@ -1,487 +0,0 @@ -import {ShareButtons} from './ShareButtons'; -import {FormGenerator} from './FormGenerator'; -import {unescape} from '../../functions/unescape'; -import {inputId} from './inputId'; - -const {useState} = wp.element; -const {__} = wp.i18n; - -export const ENFormFrontend = ({attributes}) => { - const { - en_page_id, - en_form_style, - en_form_fields, - enform_goal, - content_title, - content_title_size, - content_description, - thankyou_url, - background, - background_image_src, - background_image_srcset, - background_image_sizes, - background_image_focus, - campaign_logo, - campaign_logo_path, - className, - } = attributes; - - const section_style = (style => { - switch (style) { - case 'side-style': - return 'block-header alignfull'; - case 'full-width-bg': - return 'block-footer alignfull'; - default: - return ''; - } - })(en_form_style); - - const style_has_image = ['full-width-bg', 'side-style'].includes(en_form_style); - const is_side_style = en_form_style === 'side-style'; - const fields = en_form_fields ?? []; - - const HeadingTag = content_title_size || 'h1'; - - const [activeTplId, setActiveTplId] = useState('signup'); - const [errors, setErrors] = useState({}); - const [error_msg, setErrorMsg] = useState(null); - const [form_data, setFormData] = useState( - fields.reduce((acc, f) => { - return {...acc, [inputId(f).name]: null}; - }, {}) - ); - - const onInputChange = (field, e) => { - setErrors(errs => { - return {...errs, [field.id]: null}; - }); - - const target = e.target; - const value = target.type === 'checkbox' ? target.checked : target.value; - const name = target.name; - - setFormData({...form_data, [name]: value}); - }; - - const onBlur = field => { - validateField(field, form_data, setErrors); - }; - - const onFormSubmit = e => { - e.preventDefault(); - - setErrorMsg(null); - if (!validateForm(form_data, fields, setErrors)) { - // eslint-disable-next-line no-console - console.error('Validation error.', errors); - return; - } - - submitENForm({form_data, fields, enform_goal, thankyou_url, setErrorMsg, setActiveTplId, en_page_id}); - }; - - return ( -
- {style_has_image && background_image_src && - - 0 ? `wp-image-${background}` : ''} - alt="" - /> - - } - -
- -
-
-
- - {is_side_style && -
- {campaign_logo && campaign_logo_path && - {content_title - } - -
-
- } - - {activeTplId === 'signup' && - - } - {activeTplId === 'thankyou' && - - } -
-
-
-
- ); -}; - -const Signup = ({attributes, fields, form_data, onInputChange, onBlur, onFormSubmit, error_msg, errors}) => { - const { - en_form_style, - title, - description, - text_below_button, - button_text, - } = attributes; - - const is_side_style = en_form_style === 'side-style'; - // Keep extra content between repaints - const extra_content = document.querySelector('.enform-extra-header-placeholder')?.innerHTML; - - return ( -
-
- -
- {title && -

- } - {is_side_style && -
- } - {description && -
- } -
- -
-
-
-
- -
- -
- -
- {en_form_style === 'full-width-bg' && -
-

-

- } -
- - {en_form_style !== 'full-width-bg' && -
-

-

- } -
- {error_msg && - { error_msg } - } -
-
-
-
-
- ); -}; - -const submitENForm = props => { - const { - form_data, - fields, - enform_goal, - thankyou_url, - setErrorMsg, - setActiveTplId, - en_page_id, - } = props; - - const post_data = makePostData(form_data, fields); - - // Send form - const baseUrl = document.body.dataset.nro; - const post_url = `${baseUrl}/wp-json/planet4/v1/enform/${en_page_id}`; - fetch(post_url, { - method: 'POST', - contentType: 'application/json', - mode: 'cors', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(post_data), - }) - .then(response => { - if (response.status !== 200) { - throw new Error(`Error submitting form: ${response.statusText || 'unknown error'}`); - } - return response.json(); - }) - .then(() => { - // Submit Hotjar success - if (typeof hj === 'function') { - hj('formSubmitSuccessful'); // eslint-disable-line no-undef - } - - // DataLayer push event on successful EN form submission. - // eslint-disable-next-line no-undef - if (typeof google_tag_value !== 'undefined' && google_tag_value) { - const dataLayerPayload = { - event: 'petitionSignup', - }; - if (enform_goal) { - dataLayerPayload.gGoal = enform_goal; - } - // eslint-disable-next-line no-undef - dataLayer.push(dataLayerPayload); - } - - // redirect or thanks - if (thankyou_url && urlIsValid(thankyou_url)) { - window.location = thankyou_url; - } else { - setActiveTplId('thankyou'); - } - }) - .catch(error => { - // eslint-disable-next-line no-console - console.error('Error:', error); - // Submit Hotjar failure - if (typeof hj === 'function') { - hj('formSubmitFailed'); // eslint-disable-line no-undef - } - setErrorMsg(error.message); - }); -}; - -/** - * Build data to be posted on form submit - * - * @param {Object} form_data The form data - * @param {Array} fields The fields - * @return {Object} Formatted data for EN - */ -const makePostData = (form_data, fields) => { - const supporter = { - questions: {}, - }; - - for (const key in form_data) { - const field = fields.find(f => inputId(f).name === key); - if (!field) { - continue; - } - - // Questions via checkbox or text question - if (key.startsWith('supporter.questions.')) { - const value = typeof form_data[key] === 'string' ? form_data[key] : checkboxValue(form_data[key]); - supporter.questions['question.' + field.id] = value; - continue; - } - - // Remove fields without name - if (!field.property) { - continue; - } - - // Basic data & hidden field - if (null !== form_data[key]) { - supporter[field.property] = form_data[key]; - } else if (field.input_type === 'hidden') { - supporter[field.property] = field.default_value; - } - } - - return { - standardFieldNames: true, - supporter, - }; -}; - -const checkboxValue = value => true === value ? 'Y' : 'N'; - -const validateForm = (form_data, fields, setErrors) => { - setErrors({}); - - let formIsValid = true; - fields.forEach(field => { - if (!validateField(field, form_data, setErrors)) { - formIsValid = false; - } - }); - - return formIsValid; -}; - -const validateField = (field, form_data, setErrors) => { - const {id, name} = inputId(field); - const value = form_data[name]; - const element = document.getElementById(id); - - if (!element) { - return true; - } - - if (field.required && [null, false, ''].includes(value)) { - setErrors(errors => { - return {...errors, [field.id]: element.dataset.errormessage}; - }); - return false; - } - - if (element.type === 'email') { - return validateEmail(field, element, setErrors, value); - } - - if (element.type === 'radio') { - return validateRadio(field, element, setErrors, name); - } - - const regexPattern = element.dataset.validate_regex; - if (regexPattern?.length) { - return validateRegex(field, element, setErrors, value, regexPattern); - } - - const callbackFunction = element.dataset.validate_callback; - if ('function' === typeof window[callbackFunction]) { - return validateCallback(field, element, setErrors, callbackFunction); - } - - return true; -}; - -const validateEmail = (field, element, setErrors, value) => { - // Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#basic_validation - const re = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; - if (!re.test(String(value).toLowerCase())) { - setErrors(errors => { - return {...errors, [field.id]: element.dataset.errormessage}; - }); - return false; - } - return true; -}; - -const validateRadio = (field, element, setErrors, name, fields) => { - const sibling_radios_checked = fields.find(f => { - const {id: f_id, name: f_name} = inputId(f); - const f_element = document.getElementById(f_id); - return f_name === name && f_element && f_element.checked === true; - }); - if (!sibling_radios_checked) { - setErrors(errors => { - return {...errors, [field.id]: element.dataset.errormessage}; - }); - return false; - } - return true; -}; - -const validateRegex = (field, element, setErrors, value, regexPattern) => { - const regex = new RegExp(regexPattern); - if (!regex.test(value)) { - setErrors(errors => { - return {...errors, [field.id]: element.dataset.validate_regex_msg}; - }); - return false; - } - return true; -}; - -const validateCallback = (field, element, setErrors, callbackFunction) => { - const validate = window[callbackFunction](element.value); - if (true !== validate) { - setErrors(errors => { - return {...errors, [field.id]: validate}; - }); - return false; - } - return true; -}; - -const urlIsValid = url_str => { - try { - const url = new URL(url_str); - return ['http:', 'https:'].includes(url.protocol); - } catch (e) { - // eslint-disable-next-line no-console - console.log(e); - } - - return false; -}; - -const ThankYou = ({attributes, error_msg}) => { - const { - en_form_style, - thankyou_title, - thankyou_subtitle, - thankyou_social_media_message, - thankyou_donate_message, - donate_button_checkbox, - donate_text, - donatelink, - social, - social_accounts, - } = attributes; - - const social_params = {...social, utm_medium: 'thank-you'}; - - return ( -
-
- {error_msg && - { error_msg } - } - -
-

{ unescape(thankyou_title) }

-
-

- -

- -
-
{ thankyou_social_media_message }
-
- -
- -
- - {!donate_button_checkbox && - <> -
-
{thankyou_donate_message}
-
- - - - } - -
-
-
- ); -}; diff --git a/assets/src/blocks/ENForm/ENFormInPlaceEdit.js b/assets/src/blocks/ENForm/ENFormInPlaceEdit.js deleted file mode 100644 index ce93657eb3..0000000000 --- a/assets/src/blocks/ENForm/ENFormInPlaceEdit.js +++ /dev/null @@ -1,375 +0,0 @@ -import {FormGenerator} from './FormGenerator'; -import {ShareButtons} from './ShareButtons'; - -const {useSelect} = wp.data; -const {RichText, BlockControls} = wp.blockEditor; -const {ToolbarGroup} = wp.components; -const {useState} = wp.element; -const {__} = wp.i18n; - -export const ENFormInPlaceEdit = ({attributes, setAttributes}) => { - const { - en_form_style, - className, - } = attributes; - - // Switch between signup form and thank you message - const templates = [ - { - id: 'signup', - icon: 'format-aside', - title: __('Signup form', 'planet4-blocks-backend'), - }, - { - id: 'thankyou', - icon: 'awards', - title: __('Thank you message', 'planet4-blocks-backend'), - }, - ]; - const [activeTplId, setActiveTplId] = useState('signup'); - const activeTpl = templates.find(tpl => tpl.id === activeTplId); - - // Style specific params - const is_side_style = en_form_style === 'side-style'; - const style_has_image = en_form_style === 'full-width-bg' || en_form_style === 'side-style'; - const section_style = (style => { - switch (style) { - case 'side-style': - return 'block-header alignfull'; - case 'full-width-bg': - return 'block-footer alignfull'; - default: - return ''; - } - })(en_form_style); - - return ( - <> - - { - return { - icon: tpl.icon, - title: tpl.title, - isActive: activeTplId === tpl.id, - onClick: () => setActiveTplId(tpl.id), - }; - })} - /> - - -
- {style_has_image && - - } -
-
-
- {is_side_style && - - } - {activeTplId === 'signup' && - - } - {activeTplId === 'thankyou' && - - } -
-
-
-
- - ); -}; - -const BackgroundImage = ({attributes}) => { - const { - background, - background_image_src, - background_image_srcset, - background_image_sizes, - background_image_focus, - } = attributes; - - if (!background) { - return null; - } - - return ( - - 0 ? `wp-image-${background}` : ''} - alt="" - /> - - ); -}; - -const SideContent = ({attributes, setAttributes}) => { - const { - content_title, - content_description, - content_title_size, - campaign_logo, - campaign_logo_path, - } = attributes; - - const title_size = content_title_size ?? 'h1'; - - return ( - <> - - { - return { - isActive: title_size === size, - icon: 'heading', - title: size.toUpperCase(), - onClick: () => setAttributes({content_title_size: size}), - }; - })} - /> - -
- {campaign_logo && campaign_logo_path && - {content_title - } - setAttributes({content_title: title})} - placeholder={__('Enter title', 'planet4-blocks-backend')} - withoutInteractiveFormatting - allowedFormats={[]} - /> - setAttributes({content_description: desc})} - placeholder={__('Enter description', 'planet4-blocks-backend')} - allowedFormats={['core/bold', 'core/italic']} - /> -
- - ); -}; - -const Signup = ({attributes, setAttributes}) => { - const { - title, - description, - en_form_id, - } = attributes; - - const fields = useSelect(select => { - const enform_post = en_form_id ? select('core').getEntityRecord('postType', 'p4en_form', en_form_id) : {}; - return enform_post?.p4enform_fields || []; - }, [en_form_id]); - setAttributes({en_form_fields: fields}); - - return ( -
-
- -
- setAttributes({title: titl})} - placeholder={__('Enter form title', 'planet4-blocks-backend')} - withoutInteractiveFormatting - allowedFormats={[]} - /> - setAttributes({description: des})} - placeholder={__('Enter form description', 'planet4-blocks-backend')} - allowedFormats={['core/bold', 'core/italic']} - /> -
- -
- -
- -
-
- ); -}; - -const ThankYou = ({attributes, setAttributes}) => { - const { - en_form_style, - thankyou_title, - thankyou_subtitle, - thankyou_donate_message, - thankyou_social_media_message, - donate_button_checkbox, - donate_text, - donatelink, - social, - social_accounts, - } = attributes; - - const social_params = {...social, utm_medium: 'thank-you'}; - - const toAttribute = attributeName => { - return value => { - setAttributes({[attributeName]: value}); - }; - }; - - const container_class = `thankyou ${en_form_style !== 'side-style' ? 'full-width' : ''}`; - - const error = ''; - if (error) { - return ( -
- {error && - { error } - } -
- ); - } - - return ( -
-
-
- -
- - -
-
- -
- -
- -
- - {!donate_button_checkbox && - <> -
- -
- -
- -
- - } -
-
-
- ); -}; - -const FormContent = ({attributes, setAttributes, fields}) => { - const { - en_form_style, - button_text, - text_below_button, - } = attributes; - - const fwbg = en_form_style === 'full-width-bg'; - - return ( -
-
-
- -
- -
- setAttributes({button_text: text})} - placeholder={__('Sign', 'planet4-blocks-backend')} - /> - {fwbg && -
- setAttributes({text_below_button: text})} - /> -
- } -
- {!fwbg && -
- setAttributes({text_below_button: text})} - /> -
- } -
-
- ); -}; diff --git a/assets/src/blocks/ENForm/ENFormScript.js b/assets/src/blocks/ENForm/ENFormScript.js deleted file mode 100644 index b3f5d6933e..0000000000 --- a/assets/src/blocks/ENForm/ENFormScript.js +++ /dev/null @@ -1,14 +0,0 @@ -import {createRoot} from 'react-dom/client'; -import {ENFormFrontend} from './ENFormFrontend'; -import {hydrateBlock} from '../../functions/hydrateBlock'; - -hydrateBlock('planet4-blocks/enform', ENFormFrontend); - -// Fallback for non migrated content. Remove after migration. -document.querySelectorAll('[data-render="planet4-blocks/enform"]').forEach( - blockNode => { - const attributes = JSON.parse(blockNode.dataset.attributes); - const rootElement = createRoot(blockNode); - rootElement.render(); - } -); diff --git a/assets/src/blocks/ENForm/ENFormSettings.js b/assets/src/blocks/ENForm/ENFormSettings.js deleted file mode 100644 index 4dcd9d69aa..0000000000 --- a/assets/src/blocks/ENForm/ENFormSettings.js +++ /dev/null @@ -1,216 +0,0 @@ -import {URLInput} from '../../block-editor/URLInput/URLInput'; -import {ImageOrButton} from '../../block-editor/ImageOrButton/ImageOrButton'; - -const {InspectorControls} = wp.blockEditor; -const {BaseControl, FocalPointPicker, PanelBody, SelectControl, ToggleControl} = wp.components; -const {getCurrentPostType} = wp.data.select('core/editor'); -const {__} = wp.i18n; - -export const ENFormSettings = ({attributes, setAttributes}) => { - const { - en_page_id, - en_form_id, - en_form_style, - enform_goal, - background, - background_image_src, - background_image_focus, - donate_button_checkbox, - custom_donate_url, - thankyou_url, - campaign_logo, - } = attributes; - - const page_list = getPageListByType(); - const en_forms = getFormList(); - const is_campaign = getCurrentPostType() === 'campaign'; - - const style_has_image = en_form_style === 'full-width-bg' || en_form_style === 'side-style'; - const focus_bg_image_obj = convertFocalStringToObj(background_image_focus || null); - const focal_picker_dimensions = {width: 400, height: 100}; - - const onFocalChange = (focal_name, {x, y}) => { - setAttributes({[focal_name]: `${parseInt(x * 100)}% ${parseInt(y * 100)}%`}); - }; - - const onBackgroundChange = image => { - setAttributes({ - background: image.id, - background_image_src: image.url, - }); - }; - - const onCampaignLogoChange = use_logo => { - setAttributes({ - campaign_logo: use_logo, - campaign_logo_path: '', - campaign_template: '', - }); - }; - - const toAttribute = attributeName => value => { - setAttributes({[attributeName]: value}); - }; - - return ( - - -
- {is_campaign && - onCampaignLogoChange(campaignLogo)} - /> - } - setAttributes({en_page_id: parseInt(id)})} - required={true} - /> - - - - setAttributes({en_form_id: parseInt(id)})} - help={en_forms.length > 0 ? - __('Select the P4EN Form that will be displayed.', 'planet4-engagingnetworks-backend') : - __('Create an EN Form', 'planet4-engagingnetworks-backend')} - /> - - {style_has_image && - - onBackgroundChange(image)} - imageId={background} - imageUrl={background_image_src} - buttonLabel={__('+ Select background image', 'planet4-blocks-backend')} - disabled={false} - /> - {background_image_src && -
- {__('Select focal point for background image', 'planet4-blocks-backend')} - onFocalChange('background_image_focus', focus)} - /> -
- } -
- } -
-
- - - - - {!donate_button_checkbox && - Donate button" will be used', 'planet4-engagingnetworks-backend')} - /> - } - - - - -

- - P4 Handbook EN Form - - {' '} ✍️ -

-
-
- ); -}; - -/** - * Convert focal point values from : 10% 80% => {x:0.1, y:0.8} - * - * @param {string} focal_str - * @return {Object} vector points - */ -const convertFocalStringToObj = focal_str => { - if (!focal_str || focal_str.length <= 0) { - return {x: 0.5, y: 0.5}; - } - const [x, y] = focal_str.replace(/\%/g, '').split(' '); - return {x: (parseInt(x) / 100), y: (parseInt(y) / 100)}; -}; - -const getPageListByType = () => { - const pages = window.p4_vars?.pages; - if (!pages || pages.length <= 0) { - return []; - } - - let flattenedPages = []; - for (const i in pages) { - const pagesByType = pages[i].map(page => { - return {label: page.name, value: page.id}; - }); - flattenedPages = flattenedPages.concat( - {label: '-- ' + i, value: i}, // Page type label - ...pagesByType - ); - } - - return flattenedPages; -}; - -const getFormList = () => { - const forms = window.p4_vars?.forms; - if (!forms || forms.length <= 0) { - return []; - } - - return forms.map(form => { - return {label: form.post_title, value: form.ID}; - }); -}; diff --git a/assets/src/blocks/ENForm/FormGenerator.js b/assets/src/blocks/ENForm/FormGenerator.js deleted file mode 100644 index f446517a76..0000000000 --- a/assets/src/blocks/ENForm/FormGenerator.js +++ /dev/null @@ -1,358 +0,0 @@ -import {CountrySelector} from './CountrySelector'; -import {PositionSelector} from './PositionSelector'; -import {inputId} from './inputId'; - -const {__} = wp.i18n; - -export const FormGenerator = ({fields, attributes, onInputChange, onBlur, errors}) => { - const {en_form_style} = attributes; - const is_side_style = 'side-style' === en_form_style; - - const control_fields = {}; - for (const f of fields) { - if (f.dependency) { - // eslint-disable-next-line no-unused-expressions - control_fields[f.dependency] ? - control_fields[f.dependency].push(f.name) : - control_fields[f.dependency] = [f.name]; - } - } - - return ( -
- {fields.map((field, index) => { - return ( - - ); - })} -
- ); -}; - -const Input = props => { - const { - field, - index, - onInputChange = () => { - // no action by default - }, - onBlur = () => { - // no action by default - }, - control_fields, - errors, - is_side_style, - } = props; - - return (returnField => { - switch (returnField?.input_type) { - case 'text': - case 'email': - return ; - case 'checkbox': - return ; - case 'radio': - return ; - case 'country': - return ; - case 'position': - return ; - case 'hidden': - return ; - default: - throw `Input type <${returnField?.input_type}> unknown.`; - } - })(field); -}; - -const HiddenInput = ({field}) => { - const {name} = inputId(field); - return ( - - ); -}; - -const TextInput = ({field, onInputChange, onBlur, errors, is_side_style}) => { - const {id, name} = inputId(field); - const has_error = errors && errors[field.id]; - const errorMessage = field.input_type === 'email' ? - __('Please enter a valid e-mail address.', 'planet4-engagingnetworks') : - __('This field is required', 'planet4-engagingnetworks'); - - const label = `${field.label}${field.required ? ' *' : ''}`; - - return ( -
-
- onInputChange(field, e)} - onBlur={e => onBlur(field, e)} - /> - {is_side_style && - - } - {has_error && -
{ errors[field.id] ?? errorMessage }
- } -
-
- ); -}; - -const CheckboxInput = ({field, onInputChange, onBlur, index, control_fields, errors}) => { - return field.en_type === 'GEN' ? - : - ; -}; - -const CheckboxOpt = ({field, onInputChange, onBlur, control_fields, errors}) => { - const {id, name} = inputId(field); - const has_error = errors && errors[field.id]; - const errorMessage = __('This field is required', 'planet4-engagingnetworks'); - - return ( -
-
- -
-
- ); -}; - -const CheckboxGen = ({field, onInputChange, onBlur, control_fields, errors}) => { - const {id, name} = inputId(field); - const question_option = {}; - const has_error = errors && errors[field.id]; - const errorMessage = __('This field is required', 'planet4-engagingnetworks'); - - return ( -
-
- -
-
- ); -}; - -const RadioInput = ({field, onInputChange, onBlur, errors}) => { - const {id, name} = inputId(field); - const options = field.radio_options[field.locale] || []; - const has_error = errors && errors[field.id]; - - const inputs = options.map((opt, index) => { - return ( -
-
- -
-
- ); - }); - - if (inputs.length <= 0) { - return null; - } - - const errorMessage = __('This field is required', 'planet4-engagingnetworks'); - - return ( -
- - {field.label} -
- { inputs } - {has_error && -
{errors[field.id] ?? errorMessage}
- } -
- ); -}; - -const CountryInput = ({field, onInputChange, onBlur, errors}) => { - const {id, name} = inputId(field); - const has_error = errors && errors[field.id]; - const error_message = __('Please select a country.', 'planet4-engagingnetworks'); - const props = { - id, - name, - class_name: `en__field__input en__field__input--select en_select_country form-select ${has_error ? 'is-invalid' : ''}`, - default_text: `${__('Select Country or Region', 'planet4-engagingnetworks')}${field.required ? ' *' : ''}`, - error_message, - required: field?.required || false, - label: `${field.label}${field.required ? ' *' : ''}`, - onInputChange: e => onInputChange(field, e), - onBlur: e => onBlur(field, e), - }; - - return ( -
-
- - {has_error && -
{ errors[field.id] ?? error_message }
- } -
-
- ); -}; - -const PositionInput = ({field, onInputChange, onBlur, errors, is_side_style}) => { - const {id, name} = inputId(field); - const has_error = errors && errors[field.id]; - const error_message = __('Please select a position.', 'planet4-engagingnetworks'); - const props = { - id, - name, - class_name: `en__field__input en__field__input--select en_select_position form-select ${has_error ? 'is-invalid' : ''}`, - default_text: `${__('Select Affiliation, Position or Profession', 'planet4-engagingnetworks')}${field.required ? ' *' : ''}`, - error_message, - required: field?.required || false, - onInputChange: e => onInputChange(field, e), - onBlur: e => onBlur(field, e), - }; - - return ( -
-
- {is_side_style && - - } - - {has_error && -
{ errors[field.id] ?? error_message }
- } -
-
- ); -}; - -/** - * Toggles availability of checkboxes depending on the one clicked - * - * @param {Object} e - */ -const toggleDependencies = e => { - const target = e.target; - const dependencies = target?.dataset?.dependency; - if (!target || !dependencies) { - return; - } - - for (const dependency of dependencies.split(',')) { - const dep_element = document.querySelector(`.dependency-${dependency}`); - if (!dep_element) { - continue; - } - - if (target.checked) { - dep_element.removeAttribute('disabled'); - // eslint-disable-next-line no-unused-expressions - dep_element.parentElement?.classList.remove('disable-checkbox'); - } else { - dep_element.setAttribute('disabled', ''); - dep_element.checked = false; - // eslint-disable-next-line no-unused-expressions - dep_element.parentElement?.classList.add('disable-checkbox'); - } - } -}; diff --git a/assets/src/blocks/ENForm/PositionSelector.js b/assets/src/blocks/ENForm/PositionSelector.js deleted file mode 100644 index 4a1aec2e0b..0000000000 --- a/assets/src/blocks/ENForm/PositionSelector.js +++ /dev/null @@ -1,51 +0,0 @@ -export const PositionSelector = attributes => { - const { - name = 'position-selector', - id = null, - default_text = '', - class_name = '', - error_message = '', - required = false, - onInputChange = null, - onBlur = null, - } = attributes; - - const options = [ - , - ...positions.map(p => { - return ; - }), - ]; - - return ( - - ); -}; - -const positions = [ - {code: 'politician', name: 'Politician / Political figure'}, - {code: 'scientist', name: 'Scientist / Academic'}, - {code: 'business_leader', name: 'Business leader / Business'}, - {code: 'indigenous_leader', name: 'Indigenous leader or organisation'}, - {code: 'artists', name: 'Artists'}, - {code: 'faith_leader', name: 'Faith leader / Faith community'}, - {code: 'civil_society_leader', name: 'Civil society leader or organisation'}, - {code: 'minister', name: 'Minister or former Minister'}, - {code: 'cultural_leader', name: 'Cultural leader or organisation'}, - {code: 'youth_leader', name: 'Youth leader or organisation'}, - {code: 'unions', name: 'Unions'}, - {code: 'sports', name: 'Sports / Athlete'}, - {code: 'public_private_institution', name: 'Public and private institution'}, - {code: 'other', name: 'Other public representative'}, -]; diff --git a/assets/src/blocks/ENForm/ShareButtons.js b/assets/src/blocks/ENForm/ShareButtons.js deleted file mode 100644 index e893230037..0000000000 --- a/assets/src/blocks/ENForm/ShareButtons.js +++ /dev/null @@ -1,115 +0,0 @@ -const {__} = wp.i18n; -window.dataLayer = window.dataLayer || []; - -const SvgIcon = props => { - const theme_dir = window.p4_vars.themeUrl; - const { - name, - sprite = `${theme_dir}/assets/build/sprite.symbol.svg`, - class_name = 'icon', - } = props; - - return ( - - - - ); -}; - -export const ShareButtons = ({social_params, social_accounts}) => { - const { - link = document.URL, - title = document.title, - description = '', - utm_medium = '', - utm_content = '', - utm_campaign = '', - } = social_params; - - const share = (action, label) => { - const shared = { - eventCategory: 'Social Share', - eventAction: action, - eventLabel: label, - }; - - window.dataLayer.push({ - event: 'uaevent', - ...shared, - }); - - window.dataLayer.push({ - event: 'page_shared', - channel: action, - ...shared, - }); - }; - - return ( - - ); -}; - -const twitterUrl = (link, title, description, account) => { - return `https://x.com/share?url=${encodeURIComponent(link)}` + - `&text=${encodeURIComponent(title)}` + - (description ? ` - ${encodeURIComponent(description)}` : '') + - (account ? ` via @${encodeURIComponent(account)}&related=${encodeURIComponent(account)}` : ''); -}; - -const utm = (utm_source, utm_medium, utm_content, utm_campaign) => { - return [ - utm_source ? `utm_source=${encodeURIComponent(utm_source)}` : null, - utm_medium ? `utm_medium=${encodeURIComponent(utm_medium)}` : null, - utm_content ? `utm_content=${encodeURIComponent(utm_content)}` : null, - utm_campaign ? `utm_campaign=${encodeURIComponent(utm_campaign)}` : null, - ].filter(x => x).join('&'); -}; diff --git a/assets/src/blocks/ENForm/deprecated/ENFormV1.js b/assets/src/blocks/ENForm/deprecated/ENFormV1.js deleted file mode 100644 index 0ea7f104a2..0000000000 --- a/assets/src/blocks/ENForm/deprecated/ENFormV1.js +++ /dev/null @@ -1,45 +0,0 @@ -const {__} = wp.i18n; - -export const ENFormV1 = { - attributes: { - en_page_id: {type: 'integer'}, - enform_goal: {type: 'string'}, - en_form_style: {type: 'string'}, - title: {type: 'string'}, - description: {type: 'string'}, - campaign_logo: {type: 'boolean'}, - content_title: {type: 'string'}, - content_title_size: {type: 'string'}, - content_description: {type: 'string'}, - button_text: {type: 'string'}, - text_below_button: {type: 'string'}, - thankyou_title: {type: 'string'}, - thankyou_subtitle: {type: 'string'}, - thankyou_donate_message: {type: 'string'}, - thankyou_social_media_message: {type: 'string'}, - donate_button_checkbox: {type: 'boolean'}, - custom_donate_url: {type: 'string'}, - thankyou_url: {type: 'string'}, - background: {type: 'integer'}, - en_form_id: {type: 'integer'}, - }, - isEligible(attributes) { - return typeof attributes.social === 'undefined'; - }, - migrate(attributes) { - return { - ...attributes, - background_image_src: '', - background_image_srcset: null, - background_image_sizes: null, - background_image_focus: '50% 50%', - donate_text: __('Donate', 'planet4-engagingnetworks'), - en_form_fields: [], - social: {}, - social_accounts: {}, - }; - }, - save() { - return null; - }, -}; diff --git a/assets/src/blocks/ENForm/deprecated/ENFormV2.js b/assets/src/blocks/ENForm/deprecated/ENFormV2.js deleted file mode 100644 index 8dfbcf6c13..0000000000 --- a/assets/src/blocks/ENForm/deprecated/ENFormV2.js +++ /dev/null @@ -1,12 +0,0 @@ -import {BLOCK_NAME, attributes} from '../ENFormBlock'; -import {frontendRendered} from '../../../functions/frontendRendered'; - -export const ENFormV2 = { - attributes, - save: props => { - // Sort attributes in a predictable order - const ordered_attrs = Object.fromEntries(Object.entries(props.attributes).sort()); - - return frontendRendered(BLOCK_NAME)(ordered_attrs, props?.className); - }, -}; diff --git a/assets/src/blocks/ENForm/inputId.js b/assets/src/blocks/ENForm/inputId.js deleted file mode 100644 index 0bc8c6f237..0000000000 --- a/assets/src/blocks/ENForm/inputId.js +++ /dev/null @@ -1,17 +0,0 @@ - -export const inputId = field => { - switch (field.en_type) { - case 'GEN': - case 'OPT': - return { - id: `en__field_supporter_questions_${field.id}`, - name: `supporter.questions.${field.id}`, - }; - case 'Field': - default: - return { - id: `en__field_supporter_${field.property}`, - name: `supporter.${field.property}`, - }; - } -}; diff --git a/assets/src/scss/blocks.scss b/assets/src/scss/blocks.scss index 3cf1b37df4..404dd70073 100644 --- a/assets/src/scss/blocks.scss +++ b/assets/src/scss/blocks.scss @@ -10,7 +10,6 @@ @import "blocks/Cookies/CookiesStyle"; @import "blocks/Counter/CounterStyle"; @import "blocks/Covers/CoversStyle"; -@import "blocks/ENForm/ENFormStyle"; @import "blocks/HappyPoint/HappyPointStyle"; @import "blocks/SocialMedia/SocialMediaStyle"; @import "blocks/Spreadsheet"; diff --git a/assets/src/scss/blocks/Counter/CounterStyle.scss b/assets/src/scss/blocks/Counter/CounterStyle.scss index 2ec854fda3..473b69be74 100644 --- a/assets/src/scss/blocks/Counter/CounterStyle.scss +++ b/assets/src/scss/blocks/Counter/CounterStyle.scss @@ -14,22 +14,6 @@ white-space: pre-wrap; } - .enform-extra-header-placeholder & { - margin-top: 40px; - margin-bottom: 30px; - - .counter-text { - text-align: left; - } - - .progress-container { - _-- { - display: block; - } - height: 20px; - } - } - &.counter-style-4 { display: none; } @@ -71,10 +55,6 @@ margin-left: -10px; } - .enform-progress-bar _-- { - background: var(--gp-green-400); - } - .progress-arc { _-- { max-width: 225px; @@ -104,8 +84,3 @@ font-weight: bold; } } - -.wp-block-planet4-blocks-counter.is-style-en-forms-bar, -.wp-block-planet4-blocks-counter .counter-style-en-forms-bar { - display: none; -} diff --git a/assets/src/scss/blocks/ENForm/ENFormEditorStyle.scss b/assets/src/scss/blocks/ENForm/ENFormEditorStyle.scss deleted file mode 100644 index ed770323a5..0000000000 --- a/assets/src/scss/blocks/ENForm/ENFormEditorStyle.scss +++ /dev/null @@ -1,55 +0,0 @@ -.enform { - background: none; -} - -.enform .form-container { - input { - box-sizing: border-box; - } -} - -.wp-core-ui { - .enform a.btn-primary { - color: var(--btn-primary-color, #fff); - } - /* Let select inputs follow the flow */ - .enform select { - max-width: 90%; - } - /* Nullify default editor border */ - .enform input[type="checkbox"] { - border: 0; - } - - .enform-side-style, - .enform-full-width-bg { - width: 100%; - - .container { - z-index: 1; - } - } - - .enform-full-width { - /* Default enform text color is white, editor background color too */ - background: var(--p4-dark-green-800); - - div.submit div.btn { - width: 32%; - margin-top: 32px; - } - } - - .enform-full-width-bg { - div.submit { - padding: 0; - } - } - - .enform-side-style { - .submit div.btn { - padding: 0; - margin-top: 32px; - } - } -} diff --git a/assets/src/scss/blocks/ENForm/ENFormStyle.scss b/assets/src/scss/blocks/ENForm/ENFormStyle.scss deleted file mode 100644 index 6e790f50ec..0000000000 --- a/assets/src/scss/blocks/ENForm/ENFormStyle.scss +++ /dev/null @@ -1,9 +0,0 @@ -// EN Blocks -@import "components/enform"; -@import "components/enform-full-width-bg"; -@import "components/enform-full-width"; -@import "components/enform-side-style"; -// Campaigns - mixins -@import "campaigns/mixins"; -// Campaigns - themes -@import "campaigns/campaign_enform"; diff --git a/assets/src/scss/blocks/ENForm/campaigns/_campaign_enform.scss b/assets/src/scss/blocks/ENForm/campaigns/_campaign_enform.scss deleted file mode 100644 index 784f735ebc..0000000000 --- a/assets/src/scss/blocks/ENForm/campaigns/_campaign_enform.scss +++ /dev/null @@ -1,3 +0,0 @@ -.enform-wrap { - @include campaign-en-block(); -} diff --git a/assets/src/scss/blocks/ENForm/campaigns/_mixins.scss b/assets/src/scss/blocks/ENForm/campaigns/_mixins.scss deleted file mode 100644 index 6032b1330b..0000000000 --- a/assets/src/scss/blocks/ENForm/campaigns/_mixins.scss +++ /dev/null @@ -1,47 +0,0 @@ -@mixin campaign-en-block($form-caption-transform: false) { - .form-caption { - padding-bottom: $sp-8; - - h1, h2, h3 { - @if $form-caption-transform { - text-transform: $form-caption-transform; - } - } - - p { - font-size: $font-size-sm; - line-height: 1.875rem; - } - - h1 { - font-size: 3.62rem; - color: white !important; - margin-bottom: 16px; - line-height: 1.225; - } - - h2 { - margin-bottom: 18px; - } - - h3 { - margin-bottom: 16px; - } - - .campaign-logo { - width: 380px; - max-width: 100%; - padding-bottom: 30px; - padding-top: 10px; - display: block; - } - } - - .enform { - .submit button { - margin-bottom: 0; - box-sizing: border-box; - width: 100%; - } - } -} diff --git a/assets/src/scss/blocks/ENForm/components/_enform-full-width-bg.scss b/assets/src/scss/blocks/ENForm/components/_enform-full-width-bg.scss deleted file mode 100644 index 1751505d9d..0000000000 --- a/assets/src/scss/blocks/ENForm/components/_enform-full-width-bg.scss +++ /dev/null @@ -1,78 +0,0 @@ -.enform-full-width-bg { - @include background-before-opacity($beige-100); - width: 100vw; - min-height: 444px; - overflow: hidden; - display: flex; - align-items: center; - - picture { - align-self: start; - - img { - position: absolute; - height: auto; - width: 100%; - object-fit: cover; - object-position: center center; - opacity: 0.3; - - @supports (object-fit: cover) { - & { - height: 100%; - } - } - } - } - - .enform { - .form-description { - margin-bottom: 16px; - } - - .title-and-description { - h2 { - margin-bottom: $sp-4; - } - - p { - margin-bottom: $sp-4; - } - } - - form { - .submit { - @include medium-and-up { - margin-top: 0; - } - - @include large-and-up { - padding-left: 0; - margin-top: 0; - } - - @include medium-and-up { - flex-direction: unset; - } - - button { - min-width: 100%; - padding: 0; - margin-top: 0; - } - - .enform-legal { - min-width: 100%; - } - } - - .formblock-flex { - .en__field { - @include large-and-up { - width: 49%; - } - } - } - } - } -} diff --git a/assets/src/scss/blocks/ENForm/components/_enform-full-width.scss b/assets/src/scss/blocks/ENForm/components/_enform-full-width.scss deleted file mode 100644 index 9ccb4afd86..0000000000 --- a/assets/src/scss/blocks/ENForm/components/_enform-full-width.scss +++ /dev/null @@ -1,88 +0,0 @@ -.enform-full-width { - background: var(--p4-dark-green-800); - - .container { - padding: 0; - } - - .enform { - color: white; - padding: $sp-4; - padding-bottom: 42px; - - .title-and-description { - h2 { - margin-bottom: 16px; - } - - .form-description { - margin-bottom: 32px; - } - } - - form { - .custom-control .custom-control-description { - color: var(--white); - - a { - color: var(--white); - } - } - - .en__field--check { - margin-top: 16px; - - @include medium-and-up { - width: 100%; - } - - label { - margin-bottom: 0; - } - - .form-group { - margin-bottom: 0; - } - } - - .form-check-label-block { - padding: 0; - } - - .submit { - display: flex; - margin-top: 0; - - @include medium-and-up { - justify-content: center; - } - - @include large-and-up { - justify-content: left; - } - - button { - padding: 0; - margin-bottom: 0; - - @include medium-and-up { - width: 380px !important; - } - - @include large-and-up { - width: 32% !important; - } - } - } - - .enform-legal { - margin-top: 24px; - - @include large-and-up { - margin-top: 16px; - width: 66%; - } - } - } - } -} diff --git a/assets/src/scss/blocks/ENForm/components/_enform-side-style.scss b/assets/src/scss/blocks/ENForm/components/_enform-side-style.scss deleted file mode 100644 index 5de136ec0d..0000000000 --- a/assets/src/scss/blocks/ENForm/components/_enform-side-style.scss +++ /dev/null @@ -1,169 +0,0 @@ -.enform-side-style { - width: 100vw; - min-height: 444px; - overflow: hidden; - display: flex; - align-items: center; - - &:only-child { - margin-bottom: 0; - } - - .caption-overlay { - display: block; - background: url("../../images/carousel-blurred-overlay.png"); - background-position: bottom right; - background-size: cover; - height: 100%; - width: 90%; - position: absolute; - margin-left: 0; - z-index: 1; - - html[dir="rtl"] & { - background-position: bottom left; - } - - @include medium-and-up { - width: 50%; - } - } - - // Darken background - &::after { - @include fill-container; - content: ""; - background: rgba(30, 30, 30, 0.45); - } - - picture { - align-self: start; - - @include large-and-up { - display: block; - } - - img { - position: absolute; - height: auto; - width: 100%; - object-fit: cover; - object-position: center center; - opacity: 1; - - @supports (object-fit: cover) { - & { - height: 100%; - } - } - } - } - - .enform { - overflow: hidden; - align-items: center; - min-height: 444px; - background: white; - padding-top: 28px; - float: none; - width: 100vw; - margin-top: 0; - margin-bottom: 0; - - margin-left: calc(((100vw - 100%) / 2) * -1); - padding-left: calc(((100vw - 100%) / 2)); - padding-right: calc(((100vw - 100%) / 2)); - - @include large-and-up { - margin-top: 96px; - margin-bottom: 60px; - float: right; - - html[dir="rtl"] & { - float: left; - } - - width: 40%; - max-width: 444px; - box-sizing: content-box; - box-shadow: 0 2px 5px rgba(0, 0, 0, .25); - padding: $sp-6 30px 34px; - } - - .en__field--check { - margin-top: $sp-2; - - .form-group { - padding-top: 0; - margin-bottom: 0; - } - - label { - margin-bottom: 0; - } - - p { - html[dir="rtl"] & { - display: inline; - } - } - } - } - - .title-and-description { - padding: $sp-2; - - @include large-and-up { - padding: 0; - } - - .enform-extra-header-placeholder { - .container { - padding-top: 0; - } - - .counter-block _-- { - margin-bottom: 0; - margin-top: 32px; - } - - .progress-container { - margin-bottom: $sp-2; - height: $sp-1x; - - html[dir="rtl"] & { - margin-bottom: $sp-4; - } - } - - .counter-text { - margin-bottom: 0; - - html[dir="rtl"] & { - text-align: right; - } - } - } - - .form-description { - margin-bottom: $sp-4; - - html[dir="rtl"] & { - font-size: 0.75rem; - } - } - } - - .form-container { - background: var(--white); - padding: $sp-2; - - @include large-and-up { - padding: 0; - } - - .formblock-flex .en__field { - width: 100%; - } - } -} diff --git a/assets/src/scss/blocks/ENForm/components/_enform.scss b/assets/src/scss/blocks/ENForm/components/_enform.scss deleted file mode 100644 index dec69492fa..0000000000 --- a/assets/src/scss/blocks/ENForm/components/_enform.scss +++ /dev/null @@ -1,301 +0,0 @@ -.form-caption { - float: none; - width: 100%; - - --block-enform--caption-- { - padding-top: 53px; - padding-bottom: 53px; - padding-left: 15px; - padding-right: 15px; - - @include medium-and-up { - padding-top: 106px; - padding-bottom: 106px; - } - - @include large-and-up { - padding-top: 117px; - padding-left: 0; - padding-right: 0; - width: 50%; - } - } - @include large-and-up { - float: left; - - html[dir="rtl"] & { - float: right; - } - - .form-caption-background { - display: none; - } - } - - h1, h2, h3 { - --block-enform--caption-heading-- { - color: white; - } - } - - h1 { - margin-bottom: 24px; - line-height: 1.1; - - @include large-and-up { - margin-bottom: $sp-4; - } - } - - h2 { - margin-bottom: 18px; - line-height: 1.2; - - @include large-and-up { - margin-bottom: 24px; - } - } - - h3 { - margin-bottom: 8px; - font-size: 1.25rem; - - @include medium-and-up { - font-size: 1.675rem; - } - - @include large-and-up { - font-size: 1.75rem; - } - } - - p { - --block-enform--caption--paragraph-- { - color: var(--white); - font-size: 1rem; - line-height: 1.37rem; - } - - html[dir="rtl"] & { - font-size: 1rem; - } - } - - .campaign-logo { - max-height: 17.5rem; - margin-bottom: 2rem; - } -} - -.enform { - _-- { - font-family: var(--font-family-primary); - } - margin-top: 36px; - height: inherit; - width: 100%; - - form { - margin: 0; - - input, - select.form-control.en__field__input--select, - button { - min-width: 200px; - - @include large-and-up { - width: 100% !important; - } - } - - .disable-checkbox { - opacity: 0.5; - } - - .formblock-flex { - display: flex; - flex-wrap: wrap; - width: 100%; - - @include medium-and-up { - justify-content: space-between; - } - - .en__field { - width: 100%; - - @include large-and-up { - width: 32%; - } - } - } - - .submit { - margin: 0; - margin-top: 19px; - line-height: 1; - - button, .btn { - box-sizing: border-box; - width: 100% !important; - margin-top: $sp-4; - } - } - - input[type=submit] { - margin-bottom: 0; - line-height: 1; - } - - .enform-legal { - margin-top: $sp-2; - - html[dir="rtl"] & { - margin-top: $sp-6; - - @include large-and-up { - margin-top: $sp-4; - } - } - - p { - --block-enform--text-- { - font-size: .75rem; - font-family: var(--font-family-tertiary) !important; - line-height: 1rem; - } - margin-bottom: 0; - float: none; - } - } - } - - h2 { - .enform-full-width & { - color: white; - - html[dir="rtl"] & { - font-size: 2rem; - - @include large-and-up { - font-size: 1.75rem; - } - } - } - - &.thankyou { - margin-bottom: 0; - } - - @include medium-and-up { - font-size: 1.75rem; - line-height: 2.5rem; - } - - @include large-and-up { - font-size: 2.125rem; - } - - @include x-large-and-up { - font-size: 2.25rem; - } - } - - .thankyou-subtitle { - font-weight: normal; - } -} - -.en-spinner { - border-color: var(--white) !important; - border-right-color: transparent!important; - display: none; - vertical-align: middle; -} - -.thankyou { - position: relative; - min-height: inherit; - - @include mobile-only { - margin: 0 20px; - } - - &.full-width { - max-width: 444px; - - @include large-and-up { - left: 33%; - - html[dir="rtl"] & { - right: 33%; - } - } - - .sub-section { - margin-bottom: 2em; - width: 100%; - - .form-group { - margin-bottom: 2em; - } - } - } - - .page-section-header { - line-height: 1.2; - } - - .page-section-description { - line-height: 1.4; - } - - .btn { - width: 100% !important; - box-sizing: border-box !important; - } - - .sub-section { - margin-bottom: 2em; - width: 100%; - - .form-group { - margin-bottom: 2em; - } - - .social-media { - .share-buttons { - float: none; - display: flex; - } - - .share-btn { - flex-grow: 1; - box-shadow: 0 2px 5px rgba(0, 0, 0, .25); - - &:not(:last-child) { - margin-right: 5px; - } - } - - .twitter { - background: #00acee none repeat scroll 0 0; - } - } - } -} - -.en__field--select { - width: 100%; - margin-bottom: 1rem; - - .en__field__element--select { - margin-bottom: 0; - - select.form-control.en__field__input--select { - width: 100%; - display: block; - margin-bottom: 0; - } - } -} diff --git a/assets/src/scss/editorStyle.scss b/assets/src/scss/editorStyle.scss index 6a8c21242c..da5a9a83ad 100644 --- a/assets/src/scss/editorStyle.scss +++ b/assets/src/scss/editorStyle.scss @@ -40,7 +40,6 @@ @import "blocks/Columns/ColumnsEditorStyle"; @import "blocks/Cookies/CookiesEditorStyle"; @import "blocks/Covers/CoversEditorStyle"; -@import "blocks/ENForm/ENFormEditorStyle"; @import "blocks/HappyPoint/HappyPointEditorStyle"; @import "blocks/TableOfContents/TableOfContentsEditorStyle"; @import "blocks/TakeActionBoxout/TakeActionBoxoutEditorStyle"; diff --git a/exporter-helper.php b/exporter-helper.php index bdbef0489d..33aac918d0 100644 --- a/exporter-helper.php +++ b/exporter-helper.php @@ -21,10 +21,6 @@ function get_attachments_used_in_content(string $content): array foreach ($blocks as $block) { // Fetch the attachement id/s from block fields. switch ($block['blockName']) { - case 'planet4-blocks/enform': - $attachment_ids[] = $block['attrs']['background'] ?? ''; - break; - case 'core/media-text': $attachment_ids[] = $block['attrs']['mediaId'] ?? ''; $attachment_ids[] = $block['attrs']['mediaLink'] ?? ''; diff --git a/functions.php b/functions.php index 763b49116d..e389e99ff6 100644 --- a/functions.php +++ b/functions.php @@ -101,7 +101,6 @@ function (): void { Api\Gallery::register_endpoint(); Api\Search::register_endpoint(); Api\Settings::register_endpoint(); - Api\ENForm::register_endpoint(); Api\Covers::register_endpoint(); Api\Articles::register_endpoint(); Api\SocialMedia::register_endpoint(); diff --git a/phpcs.xml.dist b/phpcs.xml.dist index d1705371e1..d7c3d82e03 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -27,7 +27,7 @@ - + diff --git a/src/Api/ENForm.php b/src/Api/ENForm.php deleted file mode 100644 index 409122e2ce..0000000000 --- a/src/Api/ENForm.php +++ /dev/null @@ -1,39 +0,0 @@ -\d+)/ - */ - public static function register_endpoint(): void - { - /** - * Endpoint to get data for the Enform block - */ - register_rest_route( - 'planet4/v1', - '/enform/(?P\d+)', - [ - [ - 'methods' => WP_REST_Server::CREATABLE, - 'callback' => static function ($request) { - return ENFormBlock::send_enform($request); - }, - 'permission_callback' => static function () { - return true; - }, - ], - ] - ); - } -} diff --git a/src/BlockSettings.php b/src/BlockSettings.php index e801b6f472..3faac3a6bc 100644 --- a/src/BlockSettings.php +++ b/src/BlockSettings.php @@ -2,7 +2,6 @@ namespace P4\MasterTheme; -use P4\MasterTheme\Migrations\M001EnableEnFormFeature; use P4\MasterTheme\Settings\Features; /** @@ -56,7 +55,6 @@ class BlockSettings self::P4_BLOCKS_PREFIX . '/submenu', self::P4_BLOCKS_PREFIX . '/take-action-boxout', self::P4_BLOCKS_PREFIX . '/timeline', - self::P4_BLOCKS_PREFIX . '/enform', self::P4_BLOCKS_PREFIX . '/guestbook', self::HUBSPOT_FORMS_BLOCK, self::GRAVITY_FORMS_BLOCK, @@ -80,7 +78,6 @@ class BlockSettings self::P4_BLOCKS_PREFIX . '/spreadsheet', self::P4_BLOCKS_PREFIX . '/sub-pages', self::P4_BLOCKS_PREFIX . '/timeline', - self::P4_BLOCKS_PREFIX . '/enform', self::P4_BLOCKS_PREFIX . '/guestbook', self::HUBSPOT_FORMS_BLOCK, self::GRAVITY_FORMS_BLOCK, @@ -106,7 +103,6 @@ class BlockSettings self::P4_BLOCKS_PREFIX . '/submenu', self::P4_BLOCKS_PREFIX . '/take-action-boxout', self::P4_BLOCKS_PREFIX . '/timeline', - self::P4_BLOCKS_PREFIX . '/enform', self::P4_BLOCKS_PREFIX . '/guestbook', self::P4_BLOCKS_PREFIX . '/sub-pages', self::HUBSPOT_FORMS_BLOCK, @@ -211,28 +207,21 @@ public function set_allowed_block_types(array|bool $allowed_block_types, object } $post_type = $context->post ? $context->post->post_type : null; - $migration_ran = MigrationLog::from_wp_options()->already_ran(M001EnableEnFormFeature::get_id()); - - $enform_active = ! $migration_ran || Features::is_active(self::ALL_BLOCKS_FEATURE); - $page_block_types = array_merge( self::PAGE_BLOCK_TYPES, ! Features::is_active(self::BETA_BLOCKS_FEATURE) ? [] : self::BETA_PAGE_BLOCK_TYPES, - ! $enform_active ? [] : [ self::P4_BLOCKS_PREFIX . '/enform' ], self::BLOCK_TEMPLATES, ); $campaign_block_types = array_merge( self::CAMPAIGN_BLOCK_TYPES, ! Features::is_active(self::BETA_BLOCKS_FEATURE) ? [] : self::BETA_CAMPAIGN_BLOCK_TYPES, - ! $enform_active ? [] : [ self::P4_BLOCKS_PREFIX . '/enform' ], self::BLOCK_TEMPLATES, ); $action_block_types = array_merge( self::ACTION_BLOCK_TYPES, ! Features::is_active(self::BETA_BLOCKS_FEATURE) ? [] : self::BETA_ACTION_BLOCK_TYPES, - ! $enform_active ? [] : [ self::P4_BLOCKS_PREFIX . '/enform' ], self::BLOCK_TEMPLATES, ); diff --git a/src/Blocks/BaseBlock.php b/src/Blocks/BaseBlock.php index 4c2d38afa6..42ad81c28e 100644 --- a/src/Blocks/BaseBlock.php +++ b/src/Blocks/BaseBlock.php @@ -49,27 +49,6 @@ public function render(array $attributes) return ctype_space($block_output) ? $empty_content : $block_output; } - /** - * Outputs an error message. - * - * @param string $message Error message. - */ - public function render_error_message(string $message): void - { - // Ensure only editors see the error, not visitors to the website. - if (! current_user_can('edit_posts')) { - return; - } - - \Timber::render( - 'block_templates/block-error-message.twig', - [ - 'category' => __('Error', 'planet4-blocks'), - 'message' => $message, - ] - ); - } - /** * Returns if current request is a rest api request. */ diff --git a/src/Blocks/ENForm.php b/src/Blocks/ENForm.php deleted file mode 100644 index 3cc5b60589..0000000000 --- a/src/Blocks/ENForm.php +++ /dev/null @@ -1,427 +0,0 @@ - ['type' => 'integer'], - 'enform_goal' => ['type' => 'string'], - 'en_form_style' => [ - 'type' => 'string', - 'default' => 'side-style', - ], - 'title' => ['type' => 'string'], - 'description' => ['type' => 'string'], - 'campaign_logo' => ['type' => 'boolean'], - 'content_title' => ['type' => 'string'], - 'content_title_size' => [ - 'type' => 'string', - 'default' => 'h1', - ], - 'content_description' => ['type' => 'string'], - 'button_text' => ['type' => 'string'], - 'text_below_button' => ['type' => 'string'], - 'thankyou_title' => ['type' => 'string'], - 'thankyou_subtitle' => ['type' => 'string'], - 'thankyou_donate_message' => ['type' => 'string'], - 'thankyou_social_media_message' => ['type' => 'string'], - 'donate_button_checkbox' => ['type' => 'boolean'], - 'donate_text' => ['type' => 'string'], - 'thankyou_url' => ['type' => 'string'], - 'custom_donate_url' => ['type' => 'string'], - 'background' => ['type' => 'integer'], - 'background_image_src' => [ - 'type' => 'string', - 'default' => '', - ], - 'background_image_srcset' => ['type' => 'string'], - 'background_image_sizes' => ['type' => 'string'], - 'background_image_focus' => [ - 'type' => 'string', - 'default' => '50% 50%', - ], - 'en_form_id' => ['type' => 'integer'], - 'en_form_fields' => [ - 'type' => 'array', - 'default' => [], - ], - 'social' => ['type' => 'object'], - 'social_accounts' => ['type' => 'object'], - ]; - - /** - * ENForm constructor. - */ - public function __construct() - { - $this->register_enform_block(); - } - - /** - * Register block. - */ - public function register_enform_block(): void - { - // Registering meta field to make it appear in REST API. - \register_post_meta( - 'p4en_form', - self::FIELDS_META, - [ - 'type' => 'object', - 'properties' => ['id' => ['type' => 'integer']], - 'show_in_rest' => true, - 'single' => true, - ] - ); - - \register_block_type( - self::get_full_block_name(), - [ - 'attributes' => static::$attributes, - 'render_callback' => function ($attributes, $content) { - $attributes = static::update_data($attributes); - - return self::hydrate_frontend($attributes, $content); - }, - ] - ); - - add_action('wp_ajax_get_en_session_token', [self::class, 'get_session_token']); - add_action('wp_ajax_nopriv_get_en_session_token', [self::class, 'get_session_token']); - - add_action('enqueue_block_editor_assets', [self::class, 'enqueue_editor_assets']); - add_action('wp_enqueue_scripts', [self::class, 'enqueue_frontend_assets']); - } - - /** - * @param array $attributes Block attributes. - */ - public static function update_data(array $attributes): array - { - $form_id = (int) ($attributes['en_form_id'] ?? 0); - $post = get_post($form_id); - - $attributes['content_description'] = isset($attributes['content_description']) - ? wpautop($attributes['content_description']) - : ''; - - if (empty($attributes['en_form_fields']) && $form_id) { - $attributes['en_form_fields'] = get_post_meta($form_id, self::FIELDS_META, true); - } - - if (isset($attributes['background']) && empty($attributes['background_src'])) { - $attributes = array_merge($attributes, self::get_background_data($attributes)); - } - - if ('campaign' === get_post_type() && isset($attributes['campaign_logo']) && $attributes['campaign_logo']) { - $attributes = array_merge($attributes, self::get_campaign_data($post)); - } - $post_id = get_the_ID(); - $attributes['social_accounts'] = self::get_social_accounts(); - $attributes['social'] = $post_id ? self::get_shareable_data($post_id) : []; - - $attributes['donatelink'] = !empty($attributes['custom_donate_url']) - ? $attributes['custom_donate_url'] - : planet4_get_option('donate_button', ''); - - return $attributes; - } - - /** - * Return camelized version of block name. - */ - public static function get_camelized_block_name(): string - { - return 'ENForm'; - } - - /** - * Load assets for the EN block frontend. - */ - public static function enqueue_frontend_assets(): void - { - parent::enqueue_frontend_assets(); - - wp_localize_script( - 'plugin-engagingnetworks', - 'p4_vars', - ['ajaxurl' => admin_url('admin-ajax.php')] - ); - - wp_localize_script( - 'engagingnetworks-submit', - 'en_vars', - ['ajaxurl' => admin_url('admin-ajax.php')] - ); - } - - /** - * Additional background image data. - * - * @param array $attributes Block attributes. - */ - private static function get_background_data(array $attributes): array - { - $image_id = empty($attributes['background']) ? 0 : $attributes['background']; - if (empty($image_id)) { - $opts = get_option('planet4_options'); - $image_id = empty($opts['happy_point_bg_image_id']) ? 0 : $opts['happy_point_bg_image_id']; - } - $img_meta = wp_get_attachment_metadata($image_id); - - return [ - 'background_image_src' => wp_get_attachment_image_src($image_id, 'retina-large')[0], - 'background_image_srcset' => wp_get_attachment_image_srcset($image_id, 'retina-large', $img_meta), - 'background_image_sizes' => wp_calculate_image_sizes('retina-large', null, null, $image_id), - ]; - } - - /** - * Get the campaign data. - * - * @param WP_Post $post The post. - * - * @return array The campaign data. - */ - private static function get_campaign_data(WP_Post $post): array - { - $page_meta_data = get_post_meta($post->ID); - if (!empty($page_meta_data['theme'])) { - $campaign_template = $page_meta_data['theme']; - } else { - $campaign_template = !empty($page_meta_data['_campaign_page_template'][0]) - ? $page_meta_data['_campaign_page_template'][0] - : null; - } - - if (empty($campaign_template)) { - return []; - } - - $logo_path = get_bloginfo('template_directory') . '/images/' . $campaign_template . '/logo-light.png'; - if (!file_exists($logo_path)) { - return []; - } - - return [ - 'campaign_template' => $campaign_template, - 'campaign_logo_path' => $logo_path, - ]; - } - - /** - * Get post data to share via social sharing functionalities. - * - * @param int $post_id Post ID. - */ - private static function get_shareable_data(int $post_id): array - { - $og_title = ''; - $og_description = ''; - $link = ''; - if ($post_id > 0) { - $og_title = get_post_meta($post_id, 'p4_og_title', true); - if (empty($og_title)) { - $og_title = get_the_title($post_id); - } - $og_description = get_post_meta($post_id, 'p4_og_description', true); - $link = get_permalink($post_id); - } - - $page_meta_data = get_post_meta($post_id); - - return [ - 'title' => esc_attr($og_title), - 'description' => esc_attr(wp_strip_all_tags($og_description)), - 'link' => $link ? esc_url($link) : '', - 'utm_content' => 'postid-' . $post_id, - 'utm_campaign' => $page_meta_data['p4_local_project'] ?? null, - ]; - } - - /** - * Social accounts. - * - * @return array List of social accounts. - */ - private static function get_social_accounts(): array - { - $social_accounts = []; - $social_menu = wp_get_nav_menu_items('Footer Social'); - - if (!isset($social_menu) || !is_iterable($social_menu)) { - return $social_accounts; - } - - $brands = [ - 'facebook', - 'twitter', - 'youtube', - 'instagram', - ]; - foreach ($social_menu as $social_menu_item) { - $url_parts = explode('/', rtrim($social_menu_item->url, '/')); - foreach ($brands as $brand) { - if (false === strpos($social_menu_item->url, $brand)) { - continue; - } - $social_accounts[$brand] = count($url_parts) > 0 ? $url_parts[count($url_parts) - 1] : ''; - } - } - - return $social_accounts; - } - - /** - * Get all the data that will be needed to render the block correctly. - * - * @param array $attributes This is the array of fields of this block. - * @phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter - */ - public function prepare_data(array $attributes): array - { - return []; - } - // @phpcs:enable SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter - - /** - * Get en session token for frontend api calls. - */ - public static function get_session_token(): string - { - $main_settings = get_option('p4en_main_settings'); - $ens_private_token = $main_settings['p4en_frontend_private_api']; - $ens_api = new EnsapiController($ens_private_token, false); - - return $ens_api->get_public_session_token(); - } - - /** - * Function to send an ENForm. - * - * @param WP_REST_Request $request the form data. - */ - public static function send_enform(WP_REST_Request $request): array|WP_Error - { - $form = $request->get_json_params(); - $token = self::get_session_token(); - $en_page_id = (int) $request['en_page_id'] ?? null; - if (! $en_page_id) { - self::log_message('Invalid EN page ID', ['page_id' => $en_page_id]); - return new WP_Error( - 'no_en_page_id', - 'Invalid EN page ID', - ['status' => 404] - ); - } - - $form = apply_filters('planet4_enform_data', $form, $en_page_id); - $request = [ - 'url' => 'https://e-activist.com/ens/service/page/' . $en_page_id . '/process', - 'args' => [ - 'headers' => [ - 'content-type' => 'application/json', - 'ens-auth-token' => $token, - ], - 'body' => wp_json_encode($form), - ], - ]; - $response = wp_remote_post($request['url'], $request['args']); - - if (is_wp_error($response)) { - self::log_message( - 'Error submitting EN form', - [ - 'en_api_request' => $request, - 'wp_error' => $response->get_all_error_data(), - ] - ); - - return $response; - } - - $response_code = $response['response']['code'] ?? 0; - if (200 !== $response_code) { - self::log_message( - 'Error submitting EN form', - [ - 'en_api_request' => $request, - 'en_api_response' => $response ?? [], - ] - ); - - return new WP_Error( - 'submit_error', - 'Error submitting EN form', - [ - 'status' => $response['response']['code'], - 'response' => $response['response'], - ] - ); - } - - return rest_ensure_response([]); - } - - /** - * Log API response to Sentry. - * - * @param string $message Message. - * @param array $data Data to log. - */ - private static function log_message(string $message, array $data = []): void - { - if (! function_exists('\\Sentry\\withScope')) { - return; - } - - \Sentry\withScope( - function (\Sentry\State\Scope $scope) use ($message, $data): void { - foreach ($data as $key => $val) { - $scope->setContext($key, $val); - } - \Sentry\captureMessage($message); - } - ); - } -} diff --git a/src/ControlPanel.php b/src/ControlPanel.php index 338bfa517c..09ec7a9fe2 100644 --- a/src/ControlPanel.php +++ b/src/ControlPanel.php @@ -2,7 +2,6 @@ namespace P4\MasterTheme; -use P4GEN\Controllers\Ensapi_Controller as ENS_API; use ElasticPress\Elasticsearch as ES; use WP_Error; @@ -84,20 +83,6 @@ public function add_items(): void ); } - if (is_plugin_active('planet4-plugin-gutenberg-engagingnetworks/planet4-gutenberg-engagingnetworks.php')) { - $this->add_item( - [ - 'title' => __('Engaging Networks', 'planet4-master-theme-backend'), - 'subitems' => [ - [ - 'title' => __('Check Engaging Networks', 'planet4-master-theme-backend'), - 'action' => 'check_engaging_networks', - ], - ], - ] - ); - } - if (!is_plugin_active('elasticpress/elasticpress.php')) { return; } @@ -221,57 +206,6 @@ public function check_cache(): void wp_die(); } - /** - * Adds a check cache button to check the ENS API. - */ - public function check_engaging_networks(): void - { - // If this is an ajax call. - if (!wp_doing_ajax()) { - return; - } - - // Allow this action only to Administrators. - if (! current_user_can('manage_options')) { - return; - } - $cp_nonce = sanitize_text_field($_GET['_wpnonce']); - $cp_action = sanitize_text_field($_GET['cp-action']); - - // CSRF check and action check. - if (wp_verify_nonce($cp_nonce, 'cp-action') && 'check_engaging_networks' === $cp_action) { - $response = []; - $main_settings = get_option('p4en_main_settings'); // Retrieve stored EN Private API key. - - if (isset($main_settings['p4en_private_api']) && $main_settings['p4en_private_api']) { - $ens_private_token = $main_settings['p4en_private_api']; - $ens_api = new ENS_API($ens_private_token); - - if ($ens_api->is_authenticated()) { - $response['message'] = __( - 'Planet4 is connected to EngagingNetworks', - 'planet4-master-theme-backend' - ); - $response['class'] = 'cp-success'; - } else { - $response['message'] = __('Planet4 is not connected to EngagingNetworks. Please, make sure you have registered your IP address for the ENS API key you have supplied in plugin settings page.', 'planet4-master-theme-backend'); // phpcs:ignore Generic.Files.LineLength.MaxExceeded - $response['class'] = 'cp-error'; - } - } else { - $response['message'] = __( - 'Please check your EngagingNetworks plugin settings', - 'planet4-master-theme-backend' - ); - $response['class'] = 'cp-error'; - } - - if ($response) { - echo wp_json_encode($response); - } - } - wp_die(); - } - /** * Adds a check button to check communication to the ES cluster. */ diff --git a/src/Controllers/Api/QuestionsController.php b/src/Controllers/Api/QuestionsController.php deleted file mode 100644 index 3296ebfef5..0000000000 --- a/src/Controllers/Api/QuestionsController.php +++ /dev/null @@ -1,246 +0,0 @@ -model = new QuestionsModel(); - } - - /** - * Validate question's attributes. - * - * @param array $question The question attributes to be validated. - */ - private function validate_question(array $question): array|bool - { - if (! is_array($question) || empty($question)) { - return ['No data']; - } - - $messages = []; - if (! isset($question['name'])) { - $messages[] = 'Name is not set'; - } elseif (1 !== preg_match('/[A-Za-z0-9_\-\.]+$/', $question['name'])) { - $messages[] = 'Name should contain alphanumeric characters'; - } - - if (! isset($question['label'])) { - $messages[] = 'Label is not set'; - } elseif ('' === $question['label']) { - $messages[] = 'Mandatory should be boolean'; - } - - if (! isset($question['type'])) { - $messages[] = 'Type is not set'; - } elseif (! in_array($question['type'], ['GEN', 'OPT', 'question', 'number'], true)) { - $messages[] = 'Type should be one of these values: text, country, question'; - } - - if (empty($messages)) { - return true; - } - - return $messages; - } - - /** - * Callback for add question api route. - * - * @param \WP_REST_Request $request Rest request object. - */ - public function add_question(\WP_REST_Request $request): \WP_REST_Response - { - // Get question data. - $question_data = $request->get_json_params(); - - // Validate question data. - $validation = $this->validate_question($question_data); - if (true !== $validation) { - $response_data = [ - 'messages' => $validation, - ]; - $response = new \WP_REST_Response($response_data); - $response->set_status(400); - - return $response; - } - - // Add question to en WordPress option. - $updated = $this->model->add_question($question_data); - if (! $updated) { - $response_data = [ - 'messages' => ['Question could not be added'], - ]; - $response = new \WP_REST_Response($response_data); - $response->set_status(500); - - return $response; - } - - $question = $this->model->get_question($question_data['id']); - - $response_data = [ - 'messages' => ['Question created successfully'], - 'question' => $question, - ]; - $response = new \WP_REST_Response($response_data); - $response->set_status(201); - - return $response; - } - - /** - * Callback for get question api route. - * - * @param \WP_REST_Request $request Rest request object. - */ - public function get_question(\WP_REST_Request $request): \WP_Error|\WP_REST_Response - { - // Get question id. - $id = $request['id']; - $question = $this->model->get_question($id); - $response_data = $question; - $response = new \WP_REST_Response($response_data); - $response->set_status(200); - - return $response; - } - - /** - * Callback for get questions api route. - * - * @param \WP_REST_Request $request Rest request object. - * phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter - */ - public function get_available_questions(\WP_REST_Request $request): \WP_Error|\WP_REST_Response - { - $main_settings = get_option('p4en_main_settings'); - - if (isset($main_settings['p4en_private_api'])) { - $ens_private_token = $main_settings['p4en_private_api']; - $ens_api = new Ensapi($ens_private_token); - $supporter_questions = $ens_api->get_supporter_questions(); - } else { - $supporter_questions = []; - } - - $response = new \WP_REST_Response($supporter_questions); - $response->set_status(200); - - return $response; - } - // phpcs:enable SlevomatCodingStandard.Functions.UnusedParameter - - /** - * Get questions from the model. - * - * @param \WP_REST_Request $request The request object. - * phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter - */ - public function get_questions(\WP_REST_Request $request): \WP_REST_Response - { - $questions = $this->model->get_questions(); - $response = new \WP_REST_Response($questions); - $response->set_status(200); - - return $response; - } - // phpcs:enable SlevomatCodingStandard.Functions.UnusedParameter - - /** - * Callback for delete question api route. - * - * @param \WP_REST_Request $request Rest request object. - */ - public function delete_question(\WP_REST_Request $request): \WP_REST_Response - { - // Get question id. - $id = $request['id']; - - // Add question to en WordPress option. - $updated = $this->model->delete_question($id); - if (! $updated) { - $response_data = [ - 'messages' => ['Question could not be added'], - ]; - $response = new \WP_REST_Response($response_data); - $response->set_status(500); - - return $response; - } - - $response_data = [ - 'messages' => [], - ]; - $response = new \WP_REST_Response($response_data); - $response->set_status(200); - - return $response; - } - - /** - * Callback for update question api route. - * - * @param \WP_REST_Request $request Rest request object. - */ - public function update_question(\WP_REST_Request $request): \WP_REST_Response - { - // Get question data. - $question_data = $request->get_json_params(); - - // Validate question data. - $validation = $this->validate_question($question_data); - if (true !== $validation) { - $response_data = [ - 'messages' => $validation, - ]; - $response = new \WP_REST_Response($response_data); - $response->set_status(400); - - return $response; - } - - // Add question to en WordPress option. - $updated = $this->model->update_question($question_data); - if (! $updated) { - $response_data = [ - 'messages' => ['Question could not be added'], - ]; - $response = new \WP_REST_Response($response_data); - $response->set_status(500); - - return $response; - } - - $question = $this->model->get_question($question_data['id']); - $response_data = [ - 'messages' => [], - 'question' => $question, - ]; - $response = new \WP_REST_Response($response_data); - $response->set_status(200); - - return $response; - } -} diff --git a/src/Controllers/Api/RestController.php b/src/Controllers/Api/RestController.php deleted file mode 100644 index 02f238ea61..0000000000 --- a/src/Controllers/Api/RestController.php +++ /dev/null @@ -1,198 +0,0 @@ -set_rest_hooks(); - } - - /** - * Action for the wp rest api initialization. - */ - private function set_rest_hooks(): void - { - add_action('rest_api_init', [$this, 'setup_rest']); - } - - /** - * Setup rest endpoints if REST_REQUEST is defined. - */ - public function setup_rest(): void - { - if (! defined('REST_REQUEST') || ! REST_REQUEST) { - return; - } - $this->setup_rest_endpoints(); - } - - /** - * Setup the REST endpoints for en plugin. - */ - private function setup_rest_endpoints(): void - { - $version = 'v1'; - - $questions_controller = new QuestionsController(); - - /** - * Get a single form's questions. - * - * Requires authentication. - * - * @route wp-json/planet4-engaging-networks/v1/questions_available - * @method \WP_REST_Server::READABLE (GET) - * - * @returns \WP_REST_Response - */ - register_rest_route( - P4_REST_SLUG . '/' . $version, - '/questions_available', - [ - 'methods' => \WP_REST_Server::READABLE, - 'callback' => [$questions_controller, 'get_available_questions'], - 'permission_callback' => [$this, 'is_allowed'], - ] - ); - - /** - * Get a single form's questions. - * - * Requires authentication. - * - * @route wp-json/planet4-engaging-networks/v1/questions - * @method \WP_REST_Server::READABLE (GET) - * - * @returns \WP_REST_Response - */ - register_rest_route( - P4_REST_SLUG . '/' . $version, - '/questions', - [ - 'methods' => \WP_REST_Server::READABLE, - 'callback' => [$questions_controller, 'get_questions'], - 'permission_callback' => [$this, 'is_allowed'], - ] - ); - - /** - * Add a single location. - * - * Requires authentication. - * - * @route wp-json/planet4-engaging-networks//questions - * @method \WP_REST_Server::EDITABLE (POST, PUT, PATCH) - * - * @params int id required , question id. - * @params string label required, question label. - * @params string name required, question name. - * @params string type required, specify question's type. - * - * @returns \WP_REST_Response - */ - register_rest_route( - P4_REST_SLUG . '/' . $version, - '/questions', - [ - 'methods' => \WP_REST_Server::EDITABLE, - 'callback' => [$questions_controller, 'add_question'], - 'permission_callback' => [$this, 'is_allowed'], - ] - ); - - /** - * Get a single form's questions. - * - * Requires authentication. - * - * @route wp-json/planet4-engaging-networks//questions - * @method \WP_REST_Server::READABLE (GET) - * - * @returns \WP_REST_Response - */ - register_rest_route( - P4_REST_SLUG . '/' . $version, - '/questions/(?P\d+)', - [ - 'methods' => \WP_REST_Server::READABLE, - 'callback' => [$questions_controller, 'get_question'], - 'permission_callback' => [$this, 'is_allowed'], - ] - ); - - /** - * Update a single location. - * - * Requires authentication. - * - * @route wp-json/planet4-engaging-networks/v1/questions/ - * @method \WP_REST_Server::EDITABLE (POST, PUT, PATCH) - * - * @params int id required , question id. - * @params string label required, question label. - * @params string name required, question name. - * @params string type required, specify question's type. - * - * @returns \WP_REST_Response - */ - register_rest_route( - P4_REST_SLUG . '/' . $version, - '/questions/(?P\d+)', - [ - 'methods' => \WP_REST_Server::EDITABLE, - 'callback' => [$questions_controller, 'update_question'], - 'permission_callback' => [$this, 'is_allowed'], - ] - ); - - /** - * Delete a single location. - * - * Requires authentication. - * - * @route wp-json/planet4-engaging-networks/v1/questions/ - * @method \WP_REST_Server::DELETABLE (DELETE) - * - * @returns \WP_REST_Response - */ - register_rest_route( - P4_REST_SLUG . '/' . $version, - '/questions/(?P\d+)', - [ - 'methods' => \WP_REST_Server::DELETABLE, - 'callback' => [$questions_controller, 'delete_question'], - 'permission_callback' => [$this, 'is_allowed'], - ] - ); - } - - /** - * Check if user is allowed to access api routes. - */ - public function is_allowed(): bool - { - return current_user_can('manage_options'); - } -} diff --git a/src/Controllers/EnformFieldsListTable.php b/src/Controllers/EnformFieldsListTable.php deleted file mode 100644 index 14da2ef35f..0000000000 --- a/src/Controllers/EnformFieldsListTable.php +++ /dev/null @@ -1,155 +0,0 @@ - false, - ] - ); - - $this->error = ''; - } - - /** - * Implements parent's abstract function. - * Prepares the list of items for displaying. - * - * @see \WP_List_Table::prepare_items - */ - public function prepare_items(): void - { - $supporter_fields = []; - $main_settings = get_option('p4en_main_settings'); - - if (isset($main_settings['p4en_private_api'])) { - $ens_private_token = $main_settings['p4en_private_api']; - $ens_api = new Ensapi($ens_private_token); - $supporter_fields = $ens_api->get_supporter_fields(); - - if (! is_array($supporter_fields)) { - $this->error = $supporter_fields . ' : ' . - __('Could not fetch results from engaging networks', 'planet4-engagingnetworks-backend'); - } - } - - $columns = $this->get_columns(); - - $hidden = []; - $sortable = []; - $this->_column_headers = [$columns, $hidden, $sortable]; - $this->items = is_array($supporter_fields) ? $supporter_fields : []; - } - - /** - * Implements parent's abstract function. - * Get a list of columns. The format is: - * 'internal-name' => 'Title' - * - * @return array Columns array. - */ - public function get_columns(): array - { - $columns = [ - 'id' => __('Id', 'planet4-engagingnetworks-backend'), - 'name' => __('Name', 'planet4-engagingnetworks-backend'), - 'tag' => __('Tag', 'planet4-engagingnetworks-backend'), - 'property' => __('Property', 'planet4-engagingnetworks-backend'), - 'actions' => __('Actions', 'planet4-engagingnetworks-backend'), - ]; - - return $columns; - } - - /** - * Generates content for a column that does not have each own function defined. - * - * @param array $item Item data. - * @param string $column_name Column name. - * - * @return string Content for column. - */ - // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint -- compatible with parent class - protected function column_default($item, $column_name): ?string - { - switch ($column_name) { - case 'id': - case 'name': - case 'property': - case 'tag': - return $item[$column_name]; - } - return null; - } - - /** - * Generates content for the actions column. - * - * @param array $item Column data. - * - * @return string Content for actions column. - */ - public function column_actions(array $item): string - { - $data_attributes = [ - 'id' => $item['id'], - 'name' => $item['name'], - 'property' => $item['property'], - 'type' => __('Field', 'planet4-engagingnetworks-backend'), - ]; - - $attributes_string = ''; - foreach ($data_attributes as $attr => $value) { - $attributes_string .= " data-$attr=\"" . esc_attr($value) . '"'; - } - - return ''; - } - - /** - * Overrides parent function to disable nonce generation, bulk actions and pagination. - * Used to display errors (if any) that come from en api. - * - * @param string $which Navigation position. - * - * @see \WP_List_Table::display_tablenav - */ - // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint -- compatible with parent class - protected function display_tablenav($which): void - { - if (empty($this->error) || 'top' !== $which) { - return; - } - echo '

' . esc_html($this->error) . '

'; - } -} diff --git a/src/Controllers/EnformQuestionsListTable.php b/src/Controllers/EnformQuestionsListTable.php deleted file mode 100644 index 8a6cc94ff2..0000000000 --- a/src/Controllers/EnformQuestionsListTable.php +++ /dev/null @@ -1,171 +0,0 @@ - false, - ] - ); - $this->error = ''; - $this->type = $type; - } - - /** - * Implements parent's abstract function. - * Prepares the list of items for displaying. - * - * @see \WP_List_Table::prepare_items - */ - public function prepare_items(): void - { - $supporter_questions = []; - $main_settings = get_option('p4en_main_settings'); - - if (isset($main_settings['p4en_private_api'])) { - $ens_private_token = $main_settings['p4en_private_api']; - $ens_api = new Ensapi($ens_private_token); - $supporter_questions = $ens_api->get_supporter_questions(); - - if (is_array($supporter_questions)) { - $supporter_questions = array_filter($supporter_questions, [$this, 'check_type']); - } else { - $this->error = $supporter_questions . ' : ' . - __('Could not fetch results from engaging networks', 'planet4-engagingnetworks-backend'); - } - } - - $columns = $this->get_columns(); - - $hidden = []; - $sortable = []; - $this->_column_headers = [$columns, $hidden, $sortable]; - $this->items = is_array($supporter_questions) ? $supporter_questions : []; - } - - /** - * Used to filter items array based on question type. - * - * @param array $item Item in array. - */ - private function check_type(array $item): bool - { - return $this->type === $item['type']; - } - - /** - * Implements parent's abstract function. - * Get a list of columns. The format is: - * 'internal-name' => 'Title' - * - * @return array Columns array. - */ - public function get_columns(): array - { - $columns = [ - 'id' => __('Id', 'planet4-engagingnetworks-backend'), - 'name' => __('Name', 'planet4-engagingnetworks-backend'), - 'type' => __('Type', 'planet4-engagingnetworks-backend'), - 'actions' => __('Actions', 'planet4-engagingnetworks-backend'), - ]; - - return $columns; - } - - /** - * Generates content for a column that does not have each own function defined. - * - * @param object $item array Column data. - * @param string $column_name Column Name. - * - * @return string Content for column. - */ - // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint -- compatible with parent class - protected function column_default($item, $column_name): string - { - switch ($column_name) { - case 'id': - case 'name': - case 'type': - return $item[$column_name]; - } - return ''; - } - - /** - * Generates content for the actions column. - * - * @param array $item Column data. - * - * @return string Content for actions column. - */ - public function column_actions(array $item): string - { - $data_attributes = [ - 'id' => $item['id'], - 'name' => $item['name'], - 'type' => $item['type'], - ]; - - $attributes_string = ''; - foreach ($data_attributes as $attr => $value) { - $attributes_string .= " data-$attr=\"" . esc_attr($value) . '"'; - } - - return ''; - } - - /** - * Overrides parent function to disable nonce generation, bulk actions and pagination. - * Used to display errors (if any) that come from en api. - * - * @param string $which Navigation position. - * - * @see \WP_List_Table::display_tablenav - */ - // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint -- compatible with parent class - protected function display_tablenav($which): void - { - if (empty($this->error) || 'top' !== $which) { - return; - } - echo '

' . esc_html($this->error) . '

'; - } -} diff --git a/src/Controllers/EnsapiController.php b/src/Controllers/EnsapiController.php deleted file mode 100644 index 6b610768d2..0000000000 --- a/src/Controllers/EnsapiController.php +++ /dev/null @@ -1,424 +0,0 @@ -authenticate($ens_private_token, $token_type); - } - - /** - * Returns the auth token. If communication is not authenticated then the auth token is an empty string. - * - * @return mixed The auth token. - */ - public function is_authenticated(): mixed - { - return $this->ens_auth_token; - } - - /** - * Authenticates usage of ENS API calls. - * - * @param string $ens_private_token The private api token to be used in order to authenticate for ENS API. - * @param string $token_name Defines the token name. - */ - private function authenticate(string $ens_private_token, string $token_name): void - { - // Get cached auth token. - $ens_auth_token = get_transient($token_name); - - if (!$ens_auth_token) { - $url = self::ENS_AUTH_URL; - // With the safe version of wp_remote_{VERB) functions, the URL is validated to avoid redirection - // and request forgery attacks. - $response = wp_safe_remote_post( - $url, - [ - 'headers' => [ - 'Content-Type' => 'application/json; charset=UTF-8', - ], - 'body' => $ens_private_token, - 'timeout' => self::ENS_CALL_TIMEOUT, - ] - ); - - // Communication with ENS API is authenticated. - if (is_array($response) && \WP_Http::OK === $response['response']['code'] && $response['body']) { - $body = json_decode($response['body'], true); - // Time period in seconds to keep the ens_auth_token before refreshing. Typically 1 hour. - $expiration = (int) ($body['expires'] / 1000); - $ens_auth_token = $body['ens-auth-token']; - set_transient($token_name, $ens_auth_token, $expiration); - } - } - $this->$token_name = $ens_auth_token; - } - - /** - * Retrieves all EN pages whose type is included in the $types array. - * - * @param array $types Array with the types of the EN pages to be retrieved. - * @param string $status The status of the EN pages to be retrieved. - * - * @return array Array with data of the retrieved EN pages. - */ - public function get_pages_by_types_status(array $types, string $status = 'all'): array - { - $pages = []; - if ($types) { - $params['status'] = $status; - foreach ($types as $type) { - $params['type'] = $type; - $response = $this->get_pages($params); - if (!is_array($response)) { - continue; - } - $pages[ $params['type'] ] = $response; - } - } - - return $pages; - } - - /** - * Gets all the information on the available pages built in EN. - * - * @param array $params The query parameters to be added in the url. - * - * @return array|string An associative array with the response - * (under key 'body') or a string with an error message in case of a failure. - */ - public function get_pages(array $params = [ - 'type' => self::ENS_TYPES_DEFAULT, - 'status' => self::ENS_STATUS_DEFAULT, - ]): array|string - { - $from_cache = get_transient('ens_pages_response_' . implode('_', $params)); - if ($from_cache) { - return json_decode($from_cache, true); - } - - $url = add_query_arg( - [ - 'type' => strtolower($params['type']), - 'status' => $params['status'], - ], - self::ENS_PAGES_URL - ); - - // With the safe version of wp_remote_{VERB) functions, the URL is validated to avoid redirection - // and request forgery attacks. - $response = wp_safe_remote_get( - $url, - [ - 'headers' => [ - 'ens-auth-token' => $this->ens_auth_token, - ], - 'timeout' => self::ENS_CALL_TIMEOUT, - ] - ); - - if (is_wp_error($response)) { - return $response->get_error_message() . ' ' . $response->get_error_code(); - } - - if (is_array($response) && \WP_Http::OK !== $response['response']['code']) { - // Authentication failed. - return $response['response']['message'] . ' ' . $response['response']['code']; - } - set_transient('ens_pages_response_' . implode('_', $params), $response['body'], self::ENS_CACHE_TTL); - - return json_decode($response['body'], true); - } - - /** - * Process an EN Page. - * - * @param int $page_id The id of the EN page that the submitted data will be sent to. - * @param array $fields The submitted fields which will be passed to the body of the API call. - * - * @return array|string An associative array with the response (under key 'body') - * or a string with an error message in case of a failure. - */ - public function process_page(int $page_id, array $fields): array|string - { - $url = self::ENS_PAGES_URL . '/' . $page_id . '/process'; - - // If Email address is found then supporter exists and its data will be updated with the values - // inside the supporter key. Else a new supporter with this Email address will be created by EN. - $supporter_keys_fields = [ - 'Title' => 'supporter.title', - 'First name' => 'supporter.firstName', - 'Last name' => 'supporter.lastName', - 'Address 1' => 'supporter.address1', - 'Address 2' => 'supporter.address2', - 'City' => 'supporter.city', - 'Country' => 'supporter.country', - 'Position' => 'supporter.position', - 'Postcode' => 'supporter.postcode', - 'Email' => 'supporter.emailAddress', - 'Phone Number' => 'supporter.phoneNumber', - 'Date of Birth' => 'supporter.birthday', - 'questions' => 'supporter.questions', - ]; - - // Supporter fields are updated only if they exist as fields within the submitted form. - foreach ($supporter_keys_fields as $api_key => $field_name) { - if (!isset($fields[$field_name])) { - continue; - } - $supporter[$api_key] = $fields[$field_name]; - } - - $body = [ - 'supporter' => $supporter ?? [], - ]; - - // With the safe version of wp_remote_{VERB) functions, the URL is validated to avoid redirection - // and request forgery attacks. - $response = wp_safe_remote_post( - $url, - [ - 'headers' => [ - 'ens-auth-token' => $this->ens_auth_token, - 'Content-Type' => 'application/json; charset=UTF-8', - ], - 'body' => wp_json_encode($body), - 'timeout' => self::ENS_CALL_TIMEOUT, - ] - ); - - // Authentication failure. - if (is_wp_error($response)) { - return $response->get_error_message() . ' ' . $response->get_error_code(); - } - - if (is_array($response) && \WP_Http::OK !== $response['response']['code']) { - return $response['response']['message'] . ' ' . $response['response']['code']; - } - return $response; - } - - /** - * Gets all the supporter fields that exist in the EN client account. - * - * @return array|string Array with the fields or a message if something goes wrong. - */ - public function get_supporter_fields(): array|string - { - $from_cache = get_transient('ens_supporter_fields_response'); - if ($from_cache) { - return json_decode($from_cache, true); - } - - $url = self::ENS_SUPPORTER_URL . '/fields'; - - // With the safe version of wp_remote_{VERB) functions, the URL is validated to avoid redirection - // and request forgery attacks. - $response = wp_safe_remote_get( - $url, - [ - 'headers' => [ - 'ens-auth-token' => $this->ens_auth_token, - 'Content-Type' => 'application/json; charset=UTF-8', - ], - 'timeout' => self::ENS_CALL_TIMEOUT, - ] - ); - - // Authentication failure. - if (is_wp_error($response)) { - return $response->get_error_message() . ' ' . $response->get_error_code(); - } - - if (is_array($response) && \WP_Http::OK !== $response['response']['code']) { - return $response['response']['message'] . ' ' . $response['response']['code']; - } - set_transient('ens_supporter_fields_response', (string) $response['body'], self::ENS_CACHE_TTL); - - return json_decode($response['body'], true); - } - - /** - * Gets all the supporter questions/optins that exist in the EN client account. - * - * @return array|string Array with the fields or a message if something goes wrong. - */ - public function get_supporter_questions(): array|string - { - $response['body'] = get_transient('ens_supporter_questions_response'); - if ($response['body']) { - return json_decode($response['body'], true); - } - - $url = self::ENS_SUPPORTER_URL . '/questions'; - - // With the safe version of wp_remote_{VERB) functions, the URL is validated to avoid redirection - // and request forgery attacks. - $response = wp_safe_remote_get( - $url, - [ - 'headers' => [ - 'ens-auth-token' => $this->ens_auth_token, - 'Content-Type' => 'application/json; charset=UTF-8', - ], - 'timeout' => self::ENS_CALL_TIMEOUT, - ] - ); - - // Authentication failure. - if (is_wp_error($response)) { - return $response->get_error_message() . ' ' . $response->get_error_code(); - } - - if (is_array($response) && \WP_Http::OK !== $response['response']['code']) { - return $response['response']['message'] . ' ' . $response['response']['code']; - } - set_transient('ens_supporter_questions_response', (string) $response['body'], self::ENS_CACHE_TTL); - - return json_decode($response['body'], true); - } - - /** - * Gets specific questions/optin that exists in the EN client account. - * - * @param int $question_id The id of the question/optin. - * - * @return array|string Array with the fields or a message if something goes wrong. - */ - public function get_supporter_question_by_id(int $question_id): array|string - { - $from_cache = get_transient('ens_supporter_question_by_id_response_' . $question_id); - if ($from_cache) { - return json_decode($from_cache, true); - } - - $url = self::ENS_SUPPORTER_URL . '/questions/' . $question_id; - - // With the safe version of wp_remote_{VERB) functions, the URL is validated to avoid redirection - // and request forgery attacks. - $response = wp_safe_remote_get( - $url, - [ - 'headers' => [ - 'ens-auth-token' => $this->ens_auth_token, - 'Content-Type' => 'application/json; charset=UTF-8', - ], - 'timeout' => self::ENS_CALL_TIMEOUT, - ] - ); - - // Authentication failure. - if (is_wp_error($response)) { - return $response->get_error_message() . ' ' . $response->get_error_code(); - } - - if (is_array($response) && \WP_Http::OK !== $response['response']['code']) { - return $response['response']['message'] . ' ' . $response['response']['code']; - } - set_transient( - 'ens_supporter_question_by_id_response_' . $question_id, - (string) $response['body'], - self::ENS_CACHE_TTL, - ); - - return json_decode($response['body'], true); - } - - /** - * Authenticates usage of ENS API calls. - * - * @param string $email The supporter's email address. - * @param bool $include_questions True if we want to include the supporters data for questions/optins. - * - * @return array|string An associative array with the response (under key 'body') - * or a string with an error message in case of a failure. - */ - public function get_supporter_by_email(string $email, bool $include_questions = true): array|string - { - $url = add_query_arg( - [ - 'email' => $email, - 'includeQuestions' => $include_questions ? 'true' : 'false', - ], - self::ENS_SUPPORTER_URL - ); - - // With the safe version of wp_remote_{VERB) functions, the URL is validated to avoid redirection - // and request forgery attacks. - $response = wp_safe_remote_get( - $url, - [ - 'headers' => [ - 'ens-auth-token' => $this->ens_auth_token, - 'Content-Type' => 'application/json; charset=UTF-8', - ], - 'timeout' => self::ENS_CALL_TIMEOUT, - ] - ); - - // Authentication failure. - if (is_wp_error($response)) { - return $response->get_error_message() . ' ' . $response->get_error_code(); - } - - if (is_array($response) && \WP_Http::OK !== $response['response']['code']) { - return $response['response']['message'] . ' ' . $response['response']['code']; - } - return $response; - } - - /** - * Get session token for public user. - * - * @return mixed EN Service Token. - */ - public function get_public_session_token(): mixed - { - if (!$this->ens_auth_public_token) { - $main_settings = get_option('p4en_main_settings'); - $ens_private_token = $main_settings['p4en_frontend_private_api']; - $this->authenticate($ens_private_token, 'ens_auth_public_token'); - } - - return $this->ens_auth_public_token; - } -} diff --git a/src/Controllers/Menu/EnSettingsController.php b/src/Controllers/Menu/EnSettingsController.php deleted file mode 100644 index ada1841c47..0000000000 --- a/src/Controllers/Menu/EnSettingsController.php +++ /dev/null @@ -1,166 +0,0 @@ -already_ran(M001EnableEnFormFeature::get_id()); - $feature_is_active = ! $migration_ran || Features::is_active('feature_engaging_networks'); - - if ($feature_is_active && current_user_can('manage_options')) { - add_menu_page( - 'Engaging Networks', - 'Engaging Networks', - 'edit_pages', - P4_MASTER_THEME_EN_SLUG_NAME, - '', - get_template_directory_uri() . '/images/en.png' - ); - - add_submenu_page( - P4_MASTER_THEME_EN_SLUG_NAME, - __('Settings', 'planet4-engagingnetworks-backend'), - __('Settings', 'planet4-engagingnetworks-backend'), - 'manage_options', - 'en-settings', - [$this, 'prepare_settings'] - ); - } - add_action('admin_init', [$this, 'register_settings']); - } - - /** - * Render the settings page of the plugin. - */ - public function prepare_settings(): void - { - $this->view->settings( - [ - 'settings' => get_option('p4en_main_settings'), - 'available_languages' => P4_MASTER_THEME_LANGUAGES, - 'domain' => 'planet4-engagingnetworks-backend', - ] - ); - } - - /** - * Register and store the settings and their data. - */ - public function register_settings(): void - { - $args = [ - 'type' => 'string', - 'group' => 'p4en_main_settings_group', - 'description' => 'Planet 4 - EngagingNetworks settings', - 'sanitize_callback' => [$this, 'valitize'], - 'show_in_rest' => false, - ]; - register_setting('p4en_main_settings_group', 'p4en_main_settings', $args); - } - - /** - * Validates and sanitizes the settings input. - * - * @param array $settings The associative array with the settings that are registered for the plugin. - * - * @return mixed Array if validation is ok, false if validation fails. - */ - public function valitize(array $settings): mixed - { - if ($this->validate($settings)) { - $this->sanitize($settings); - } - return $settings; - } - - /** - * Validates the settings input. - * - * @param array $settings The associative array with the settings that are registered for the plugin. - */ - public function validate(array $settings): bool - { - if (! $settings) { - return true; - } - - $has_errors = false; - - if (isset($settings['p4en_public_api']) && 36 !== strlen($settings['p4en_public_api'])) { - add_settings_error( - 'p4en_main_settings-p4en_public_api', - esc_attr('p4en_main_settings-p4en_public_api'), - __('Invalid value for Public API', 'planet4-engagingnetworks-backend'), - 'error' - ); - $has_errors = true; - } - if (isset($settings['p4en_private_api']) && 36 !== strlen($settings['p4en_private_api'])) { - add_settings_error( - 'p4en_main_settings-p4en_private_api', - esc_attr('p4en_main_settings-p4en_private_api'), - __('Invalid value for Private API', 'planet4-engagingnetworks-backend'), - 'error' - ); - $has_errors = true; - } - if (isset($settings['p4en_frontend_public_api']) && 36 !== strlen($settings['p4en_frontend_public_api'])) { - add_settings_error( - 'p4en_main_settings-p4en_frontend_public_api', - esc_attr('p4en_main_settings-p4en_frontend_public_api'), - __('Invalid value for Frontend Public API', 'planet4-engagingnetworks-backend'), - 'error' - ); - $has_errors = true; - } - if (isset($settings['p4en_frontend_private_api']) && 36 !== strlen($settings['p4en_frontend_private_api'])) { - add_settings_error( - 'p4en_main_settings-p4en_frontend_private_api', - esc_attr('p4en_main_settings-p4en_frontend_private_api'), - __('Invalid value for Frontend Private API', 'planet4-engagingnetworks-backend'), - 'error' - ); - $has_errors = true; - } - - return ! $has_errors; - } - - /** - * Sanitizes the settings input. - * - * @param array $settings The associative array with the settings that are registered for the plugin. - */ - public function sanitize(array &$settings): void - { - if (! $settings) { - return; - } - - foreach ($settings as $name => $setting) { - $settings[$name] = sanitize_text_field($setting); - } - } -} diff --git a/src/Controllers/Menu/EnformPostController.php b/src/Controllers/Menu/EnformPostController.php deleted file mode 100644 index 477887d51f..0000000000 --- a/src/Controllers/Menu/EnformPostController.php +++ /dev/null @@ -1,480 +0,0 @@ -hooks(); - } - - /** - * Class hooks. - */ - private function hooks(): void - { - add_action('init', [$this, 'register_post_type']); - add_shortcode(self::POST_TYPE, [$this, 'handle_form_shortcode']); - add_filter('post_row_actions', [$this, 'modify_post_row_actions'], 10, 2); - - add_action('add_meta_boxes', [$this, 'add_form_meta_box'], 10, 2); - add_action('add_meta_boxes', [$this, 'add_selected_meta_box'], 11, 2); - add_action('add_meta_boxes', [$this, 'add_fields_meta_box'], 12, 2); - add_action('add_meta_boxes', [$this, 'add_questions_custom_box']); - add_action('add_meta_boxes', [$this, 'add_optins_custom_box']); - add_action('save_post_' . self::POST_TYPE, [$this, 'save_fields_meta_box'], 10, 2); - - add_action('wp_ajax_get_supporter_question_by_id', [$this, 'get_supporter_question_by_id']); - add_action('wp_ajax_nopriv_get_supporter_question_by_id', [$this, 'get_supporter_question_by_id']); - } - - /** - * Create menu/submenu entry. - */ - public function create_admin_menu(): void - { - $current_user = wp_get_current_user(); - - if ( - ! in_array('administrator', $current_user->roles, true) && - ! in_array('editor', $current_user->roles, true) - ) { - return; - } - add_submenu_page( - P4_MASTER_THEME_EN_SLUG_NAME, - __('All EN Forms', 'planet4-engagingnetworks-backend'), - __('All EN Forms', 'planet4-engagingnetworks-backend'), - 'edit_posts', - 'edit.php?post_type=' . self::POST_TYPE - ); - - add_submenu_page( - P4_MASTER_THEME_EN_SLUG_NAME, - __('Add New', 'planet4-engagingnetworks-backend'), - __('Add New', 'planet4-engagingnetworks-backend'), - 'edit_posts', - 'post-new.php?post_type=' . self::POST_TYPE - ); - - // Set hook after screen is determined to load assets for add/edit page. - add_action('current_screen', [$this, 'load_assets']); - } - - /** - * Register en forms custom post type. - */ - public function register_post_type(): void - { - $labels = [ - 'name' => _x('Engaging Network Forms', 'en forms', 'planet4-engagingnetworks-backend'), - 'singular_name' => _x('Engaging Network Form', 'en form', 'planet4-engagingnetworks-backend'), - 'menu_name' => _x('En Forms Menu', 'admin menu', 'planet4-engagingnetworks-backend'), - 'name_admin_bar' => _x('En Form', 'add new on admin bar', 'planet4-engagingnetworks-backend'), - 'add_new' => _x('Add New', 'en form', 'planet4-engagingnetworks-backend'), - 'add_new_item' => __('Add New EN Form', 'planet4-engagingnetworks-backend'), - 'new_item' => __('New EN Form', 'planet4-engagingnetworks-backend'), - 'edit_item' => __('Edit EN Form', 'planet4-engagingnetworks-backend'), - 'view_item' => __('View EN Form', 'planet4-engagingnetworks-backend'), - 'all_items' => __('All EN Forms', 'planet4-engagingnetworks-backend'), - 'search_items' => __('Search EN Forms', 'planet4-engagingnetworks-backend'), - 'parent_item_colon' => __('Parent EN Forms:', 'planet4-engagingnetworks-backend'), - 'not_found' => __('No en forms found.', 'planet4-engagingnetworks-backend'), - 'not_found_in_trash' => __('No en forms found in Trash.', 'planet4-engagingnetworks-backend'), - ]; - - register_post_type( - self::POST_TYPE, - [ - 'labels' => $labels, - 'description' => __('EN Forms', 'planet4-engagingnetworks-backend'), - 'rewrite' => false, - 'query_var' => false, - 'public' => false, - 'publicly_queryable' => false, - 'capability_type' => 'page', - 'has_archive' => true, - 'hierarchical' => false, - 'menu_position' => null, - 'exclude_from_search' => true, - 'map_meta_cap' => true, - // necessary in order to use WordPress default custom post type list page. - 'show_ui' => true, - // hide it from menu, as we are using custom submenu pages. - 'show_in_menu' => false, - 'supports' => ['title'], - 'show_in_rest' => true, - ] - ); - - $custom_meta_args = [ - 'type' => 'string', - 'single' => true, - 'show_in_rest' => true, - ]; - register_meta(self::POST_TYPE, self::FIELDS_META, $custom_meta_args); - - \register_rest_field( - self::POST_TYPE, - self::FIELDS_META, - [ - 'get_callback' => function ($obj) { - return \get_post_meta( - (int) $obj['id'], - self::FIELDS_META, - true - ); - }, - ] - ); - } - - /** - * Filter for post_row_actions. Alters edit action link and removes Quick edit action. - * - * @param array $actions An array of row action links. Defaults are - * 'Edit', 'Quick Edit', 'Restore', 'Trash', - * 'Delete Permanently', 'Preview', and 'View'. - * @param \WP_Post $post The post object. - * - * @return array The filtered actions array. - */ - public function modify_post_row_actions(array $actions, \WP_Post $post): array - { - // Check if post is of p4en_form_post type. - if (self::POST_TYPE === $post->post_type) { - /* - * Hide Quick Edit. - */ - $custom_actions = [ - 'inline hide-if-no-js' => '', - ]; - - $actions = array_merge($actions, $custom_actions); - } - - return $actions; - } - - /** - * Adds shortcode for this custom post type. - * - * @param array $atts Array of attributes for the shortcode. - */ - public function handle_form_shortcode(array $atts): void - { - global $pagenow; - - // Define attributes and their defaults. - $atts = array_merge( - [ - 'id' => 'id', - 'en_form_style' => 'full-width', - ], - $atts - ); - - $post_id = filter_input(INPUT_GET, 'post', FILTER_VALIDATE_INT); - - if ( - ! is_admin() && - ! ('post.php' === $pagenow && $post_id && self::POST_TYPE === get_post_type($post_id)) && - ! ('admin-ajax.php' === $pagenow && self::POST_TYPE === get_post_type($atts['id'])) - ) { - return; - } - $fields = get_post_meta($atts['id'], self::FIELDS_META, true); - - $data = [ - 'form_fields' => $fields, - 'en_form_style' => $atts['en_form_style'], - ]; - - $this->view->enform_post($data); - } - - /** - * Creates a Meta box for the Selected Components of the current EN Form. - * - * @param string $post_type The current post type (unused). - * @param WP_Post|WP_Comment $post The currently Added/Edited EN Form. - * phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter - */ - public function add_form_meta_box(string $post_type, $post): void - { - add_meta_box( - 'meta-box-form', - __('Form preview', 'planet4-engagingnetworks-backend'), - [$this, 'view_meta_box_form'], - [self::POST_TYPE], - 'normal', - 'high', - $post - ); - } - // phpcs:enable SlevomatCodingStandard.Functions.UnusedParameter - - /** - * View an EN form. - * - * @param \WP_Post $post The currently Added/Edited EN Form. - */ - public function view_meta_box_form(\WP_Post $post): void - { - echo do_shortcode('[' . self::POST_TYPE . ' id="' . $post->ID . '" /]'); - } - - /** - * Creates a Meta box for the Selected Components of the current EN Form. - * - * @param string $post_type The current post type (unused). - * @param WP_Post|WP_Comment $post The currently Added/Edited EN Form. - * phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter - */ - public function add_selected_meta_box(string $post_type, $post): void - { - add_meta_box( - 'meta-box-selected', - __('Selected Components', 'planet4-engagingnetworks-backend'), - [$this, 'view_selected_meta_box'], - [self::POST_TYPE], - 'normal', - 'high', - $post - ); - } - // phpcs:enable SlevomatCodingStandard.Functions.UnusedParameter - - /** - * Prepares data to render the Selected Components meta box. - * - * @param \WP_Post $post The currently Added/Edited EN Form. - */ - public function view_selected_meta_box(\WP_Post $post): void - { - $form_fields = get_post_meta($post->ID, self::FIELDS_META, true); - $this->view->en_selected_meta_box( - [ - 'fields' => wp_json_encode($form_fields), - ] - ); - } - - /** - * Adds available fields custom meta box to p4en_form edit post page. - * - * @param string $post_type The current post type (unused). - * @param WP_Post|WP_Comment $post The currently Added/Edited EN Form. - * phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter - */ - public function add_fields_meta_box(string $post_type, $post): void - { - add_meta_box( - 'fields_list_box', - __('Available Fields', 'planet4-engagingnetworks-backend'), - [$this, 'display_fields_custom_box'], - self::POST_TYPE, - 'normal', - 'high', - $post - ); - } - // phpcs:enable SlevomatCodingStandard.Functions.UnusedParameter - - /** - * Display fields custom box content. - */ - public function display_fields_custom_box(): void - { - $list_table = new EnformFieldsListTable(); - $list_table->prepare_items(); - $list_table->display(); - } - - /** - * Adds a meta box for the EN questions. - * - * Adds available questions custom meta box to p4en_form edit post page. - */ - public function add_questions_custom_box(): void - { - add_meta_box( - 'questions_list_box', - __('Available Questions', 'planet4-engagingnetworks-backend'), - [$this, 'display_questions_custom_box'], - self::POST_TYPE - ); - } - - /** - * Display questions custom box content. - */ - public function display_questions_custom_box(): void - { - $list_table = new EnformQuestionsListTable('GEN'); - $list_table->prepare_items(); - $list_table->display(); - } - - /** - * Adds available opt-ins custom meta box to p4en_form edit post page. - */ - public function add_optins_custom_box(): void - { - add_meta_box( - 'optins_list_box', - __('Available Opt-ins', 'planet4-engagingnetworks-backend'), - [$this, 'display_optins_custom_box'], - self::POST_TYPE - ); - } - - /** - * Display opt-ins custom box content. - */ - public function display_optins_custom_box(): void - { - $list_table = new EnformQuestionsListTable('OPT'); - $list_table->prepare_items(); - $list_table->display(); - } - - /** - * Retrieves data of a specific question/opt-in. - */ - public function get_supporter_question_by_id(): void - { - // If this is an ajax call. - if (! wp_doing_ajax()) { - return; - } - $id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); - $main_settings = get_option('p4en_main_settings'); - $ens_private_token = $main_settings['p4en_private_api']; - $ens_api = new Ensapi($ens_private_token); - $response = $ens_api->get_supporter_question_by_id($id); - - wp_send_json($response); - } - - /** - * Add underscore templates to footer. - */ - public function print_admin_footer_scripts(): void - { - $this->view->view_template('selected_enform_fields', [], 'block_templates/'); - } - - /** - * Hook load new page assets conditionally based on current page. - */ - public function load_assets(): void - { - global $pagenow, $typenow; - $pages = [ - 'post.php', - 'post-new.php', - ]; - - // Load assets conditionally using pagenow, typenow on new/edit form page. - if (! in_array($pagenow, $pages, true) || self::POST_TYPE !== $typenow) { - return; - } - add_action("load-$pagenow", [$this, 'load__new_page_assets']); - add_action('admin_print_footer_scripts', [$this, 'print_admin_footer_scripts'], 1); - } - - /** - * Load assets for new/edit form page. - */ - public function load__new_page_assets(): void - { - wp_enqueue_script('jquery-ui-core'); - wp_enqueue_script('jquery-ui-sortable'); - wp_enqueue_script('jquery-ui-dialog'); - wp_enqueue_script('jquery-ui-tooltip'); - wp_enqueue_style('wp-jquery-ui-dialog'); - wp_enqueue_style( - 'p4en_admin_style_blocks', - get_template_directory_uri() . '/admin/css/admin_en.css', - [], - \P4\MasterTheme\Loader::theme_file_ver('admin/css/admin_en.css'), - ); - \P4\MasterTheme\Loader::enqueue_versioned_script( - 'admin/js/enforms.js', - [ - 'jquery', - 'wp-backbone', - ] - ); - } - - /** - * Saves the p4 enform fields of the Post. - * - * @param int $post_id The ID of the current Post. - * @param \WP_Post $post The current Post. - * phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter - */ - public function save_fields_meta_box(int $post_id, \WP_Post $post): void - { - global $pagenow; - - // Ignore autosave. - if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { - return; - } - - // Check user's capabilities. - if (! current_user_can('edit_post', $post_id)) { - return; - } - - // Check post input. - $form_fields = filter_input( - INPUT_POST, - self::FIELDS_META - ); - - // If this is a new post then set form fields meta. - if (! $form_fields || 'post.php' !== $pagenow) { - return; - } - - $form_fields = json_decode(($form_fields)); - - // Store form fields meta. - update_post_meta($post_id, self::FIELDS_META, $form_fields); - } - // phpcs:enable SlevomatCodingStandard.Functions.UnusedParameter -} diff --git a/src/Features/EngagingNetworks.php b/src/Features/EngagingNetworks.php deleted file mode 100644 index 86f56b59e4..0000000000 --- a/src/Features/EngagingNetworks.php +++ /dev/null @@ -1,46 +0,0 @@ -load(); - } } /** @@ -204,7 +189,6 @@ public static function add_blocks(): void new Blocks\Cookies();//NOSONAR new Blocks\Counter();//NOSONAR new Blocks\Covers();//NOSONAR - new Blocks\ENForm();//NOSONAR new Blocks\Gallery();//NOSONAR new Blocks\GuestBook();//NOSONAR new Blocks\HappyPoint();//NOSONAR diff --git a/src/MasterBlocks.php b/src/MasterBlocks.php index cbe915911d..bfb5f9b576 100644 --- a/src/MasterBlocks.php +++ b/src/MasterBlocks.php @@ -2,8 +2,6 @@ namespace P4\MasterTheme; -use P4\MasterTheme\Controllers\EnsapiController; -use P4\MasterTheme\Blocks\ENForm; use P4\MasterTheme\Features\Dev\BetaBlocks; use Twig_SimpleFilter; @@ -203,52 +201,6 @@ private function get_p4_features(): array return get_option('planet4_features'); } - /** - * Get all available EN pages. - */ - public function get_en_pages(): array - { - $main_settings = get_option('p4en_main_settings'); - - // Get EN pages only on admin panel. - if (!is_admin() || !isset($main_settings['p4en_private_api'])) { - return []; - } - - $pages = []; - $pages[] = $main_settings['p4en_private_api']; - $ens_private_token = $main_settings['p4en_private_api']; - $ens_api = new EnsapiController($ens_private_token); - $pages = $ens_api->get_pages_by_types_status(ENForm::ENFORM_PAGE_TYPES, 'live'); - uasort( - $pages, - function ($a, $b) { - return ($a['name'] ?? '') <=> ($b['name'] ?? ''); - } - ); - - return $pages; - } - - /** - * Get all available EN forms. - */ - public function get_en_forms(): array - { - // Get EN Forms. - $query = new \WP_Query( - [ - 'post_status' => 'publish', - 'post_type' => 'p4en_form', - 'orderby' => 'post_title', - 'order' => 'asc', - 'suppress_filters' => false, - 'posts_per_page' => -1, - ] - ); - return $query->posts; - } - /** * Add variables reflected from PHP to JS. */ @@ -260,8 +212,6 @@ public function reflect_js_variables(): array 'news_page_link' => $news_page ? get_permalink($news_page) : null, 'options' => $this->get_p4_options(), 'features' => $this->get_p4_features(), - 'pages' => $this->get_en_pages(), - 'forms' => $this->get_en_forms(), 'themeUrl' => get_template_directory_uri(), ]; } diff --git a/src/MasterSite.php b/src/MasterSite.php index 37b0cdb73d..37b991320a 100644 --- a/src/MasterSite.php +++ b/src/MasterSite.php @@ -604,14 +604,14 @@ public function p4_master_theme_setup(): void $domains = [ 'planet4-master-theme', 'planet4-master-theme-backend', - 'planet4-engagingnetworks', - 'planet4-engagingnetworks-backend', + 'blocks/planet4-blocks', + 'blocks/planet4-blocks-backend', ]; $locale = is_admin() ? get_user_locale() : get_locale(); foreach ($domains as $domain) { $mofile = get_template_directory() . '/languages/' . $domain . '-' . $locale . '.mo'; - load_textdomain($domain, $mofile); + load_textdomain(str_replace('blocks/', '', $domain), $mofile); } } diff --git a/src/Migrations/M001EnableEnFormFeature.php b/src/Migrations/M001EnableEnFormFeature.php index 6e832402da..5670577c1c 100644 --- a/src/Migrations/M001EnableEnFormFeature.php +++ b/src/Migrations/M001EnableEnFormFeature.php @@ -2,7 +2,6 @@ namespace P4\MasterTheme\Migrations; -use P4\MasterTheme\Features; use P4\MasterTheme\MigrationRecord; use P4\MasterTheme\MigrationScript; @@ -19,7 +18,9 @@ class M001EnableEnFormFeature extends MigrationScript */ protected static function execute(MigrationRecord $record): void { - Features\EngagingNetworks::enable(); + $features = get_option('planet4_features'); + $features['feature_engaging_networks'] = true; + update_option('planet4_features', $features); } // phpcs:enable SlevomatCodingStandard.Functions.UnusedParameter } diff --git a/src/Migrations/M036RemoveEnFormOptions.php b/src/Migrations/M036RemoveEnFormOptions.php new file mode 100644 index 0000000000..8f3f432de9 --- /dev/null +++ b/src/Migrations/M036RemoveEnFormOptions.php @@ -0,0 +1,38 @@ + 'p4en_form', + ]); + foreach ($posts as $post) { + echo 'Parsing post ', $post->ID, ': ', $post->post_title, '\n'; + wp_delete_post($post->ID, true); + } + } +} diff --git a/src/Migrator.php b/src/Migrator.php index 688a8360f6..46349bc11b 100644 --- a/src/Migrator.php +++ b/src/Migrator.php @@ -37,6 +37,7 @@ use P4\MasterTheme\Migrations\M033MigrateSocialMediaTwitterBlockToEmbedBlock; use P4\MasterTheme\Migrations\M034PrePopulateOldPostsArchiveNotice; use P4\MasterTheme\Migrations\M035MigrateCampaignCoversToP4ColumnsBlock; +use P4\MasterTheme\Migrations\M036RemoveEnFormOptions; /** * Run any new migration scripts and record results in the log. @@ -91,6 +92,7 @@ public static function migrate(): void M033MigrateSocialMediaTwitterBlockToEmbedBlock::class, M034PrePopulateOldPostsArchiveNotice::class, M035MigrateCampaignCoversToP4ColumnsBlock::class, + M036RemoveEnFormOptions::class, ]; // Loop migrations and run those that haven't run yet. diff --git a/src/Model/QuestionsModel.php b/src/Model/QuestionsModel.php deleted file mode 100644 index 9b7da3ecb7..0000000000 --- a/src/Model/QuestionsModel.php +++ /dev/null @@ -1,125 +0,0 @@ -questions_option); - - if (isset($options['questions']) && ! empty($options['questions'])) { - $questions = $options['questions']; - foreach ($questions as $question) { - if ((int) $question['id'] === (int) $id) { - return $question; - } - } - } - - return []; - } - - /** - * Retrieve all the questions. - */ - public function get_questions(): array - { - $options = get_option($this->questions_option); - $questions = $options ? array_values($options) : []; - - return $questions; - } - - /** - * Add question. - * - * @param array $question Field attributes. - */ - public function add_question(array $question): bool - { - $options = get_option($this->questions_option); // Added default value for the first time. - if (is_array($options) || false === $options) { - $questions = array_values($options); - $questions[] = $question; - $updated = update_option($this->questions_option, $questions); - - return $updated; - } - - return false; - } - - /** - * Update question. - * - * @param array $question Field attributes. - */ - public function update_question(array $question): bool - { - $options = get_option($this->questions_option); - - if (is_array($options)) { - $questions = array_values($options); - $index = false; - $questions_length = count($questions); - for ($i = 0; $i < $questions_length; $i++) { - if ((int) $questions[ $i ]['id'] === (int) $question['id']) { - $index = $i; - break; - } - } - if ($index >= 0) { - $questions[ $index ] = $question; - $updated = update_option($this->questions_option, $questions); - - return $updated; - } - } - - return false; - } - - /** - * Delete question. - * - * @param mixed $id Field id. - */ - public function delete_question(mixed $id): bool - { - $options = get_option($this->questions_option); - if (is_array($options)) { - $questions = $options; - $questions = - array_filter( - $questions, - function ($e) use ($id) { - return (int) $e['id'] !== (int) $id; - } - ); - $updated = update_option($this->questions_option, $questions); - - return $updated; - } - - return false; - } -} diff --git a/src/Settings/Features.php b/src/Settings/Features.php index b92ae99d17..da65ec7bea 100644 --- a/src/Settings/Features.php +++ b/src/Settings/Features.php @@ -7,7 +7,6 @@ use P4\MasterTheme\Features\Dev\BetaBlocks; use P4\MasterTheme\Features\Dev\CoreBlockPatterns; use P4\MasterTheme\Features\Dev\DisableDataSync; -use P4\MasterTheme\Features\EngagingNetworks; use P4\MasterTheme\Features\LazyYoutubePlayer; use P4\MasterTheme\Features\RedirectRedirectPages; use P4\MasterTheme\Features\Planet4Blocks; @@ -95,7 +94,6 @@ public static function all_features(): array // Perhaps an alphabetical order within a group would make most sense? // That way controlling whether the feature is live is in one place. return [ - EngagingNetworks::class, CloudflareDeployPurge::class, LazyYoutubePlayer::class, RedirectRedirectPages::class, diff --git a/src/View/View.php b/src/View/View.php deleted file mode 100644 index be5c21ff7b..0000000000 --- a/src/View/View.php +++ /dev/null @@ -1,152 +0,0 @@ -get_template_dir($template_name, $relevant_dir); - - return Timber::compile([$relevant_dir . $template_name . '.twig'], $data); - } - - /** - * Uses the appropriate templating engine to render a template file. - * - * @param array|string $template_name The file name of the template to render. - * @param array $data The data to pass to the template. - * @param string $relevant_dir The path to a subdirectory where the template is located - * (relative to $template_dir). - * @param bool $compile A boolean to compile the template. - */ - public function view_template( - array|string $template_name, - array $data, - string $relevant_dir = '', - bool $compile = false - ): string|null { - Timber::$locations = $this->get_template_dir($template_name, $relevant_dir); - - if ($compile) { - return Timber::compile([$relevant_dir . $template_name . '.twig'], $data); - } - - Timber::render([$relevant_dir . $template_name . '.twig'], $data); - return null; - } - - /** - * Overrides the template file if a child theme is active and contains one. - * - * @param array|string $template_name The file name of the template to render. - * @param string $relevant_dir The path to a subdirectory where the template is located - * (relative to $template_dir or $template_override_subdir). - * @param string $template_ext The extension of the template (php, twig, ...). - * - * @return string The returned output - */ - private function get_template_dir( - array|string $template_name, - string $relevant_dir = 'block_templates/', - string $template_ext = 'twig' - ): string { - if (is_child_theme()) { - $override_dir = get_stylesheet_directory() . $this->template_override_subdir; - if (file_exists($override_dir . $relevant_dir . $template_name . '.' . $template_ext)) { - return $override_dir; - } - } - - return $this->template_dir; - } - - /** - * Render the settings page of the plugin. - * - * @param array $data All the data needed to render the template. - */ - public function settings(array $data): void - { - $this->view_template(__FUNCTION__, $data, 'block_templates/'); - } - - /** - * Uses the appropriate templating engine to render a template file. - * - * @param array|string $template_name The file name of the template to render. - * @param array $data The data to pass to the template. - * @param string $template_ext The extension of the template (php, twig, ...). - * @param string $relevant_dir The path to a subdirectory where the template is located - * (relative to $template_dir). - */ - public function block( - array|string $template_name, - array $data, - string $template_ext = 'twig', - string $relevant_dir = 'block_templates/' - ): void { - $template_dir = $this->get_template_dir($template_name, $relevant_dir, $template_ext); - if ('twig' === $template_ext) { - Timber::$locations = $template_dir; - Timber::render([$relevant_dir . $template_name . '.' . $template_ext], $data); - } else { - include_once $template_dir . $relevant_dir . $template_name . '.' . $template_ext; - } - } - - /** - * Render EN Form Post. - * - * @param array $data All the data needed to render the template. - */ - public function enform_post(array $data): void - { - $this->view_template(__FUNCTION__, $data, '/block_templates/enform/'); - } - - /** - * Render the Selected Components meta box for EN Forms. - * - * @param array $data All the data needed to render the template. - */ - public function en_selected_meta_box(array $data): void - { - $this->view_template(__FUNCTION__, $data, 'block_templates/'); - } -} diff --git a/templates/block_templates/block-error-message.twig b/templates/block_templates/block-error-message.twig deleted file mode 100644 index f79ca23e3d..0000000000 --- a/templates/block_templates/block-error-message.twig +++ /dev/null @@ -1 +0,0 @@ -

{{ category }}: {{ message }}

'; \ No newline at end of file diff --git a/templates/block_templates/en_selected_meta_box.twig b/templates/block_templates/en_selected_meta_box.twig deleted file mode 100644 index 491832ba45..0000000000 --- a/templates/block_templates/en_selected_meta_box.twig +++ /dev/null @@ -1,56 +0,0 @@ -{% block selected_meta_box %} -

- {{ __( 'Hover over %s icons to get more information about each field attribute.', 'planet4-engagingnetworks-backend' )|format("")|raw }} -
- {{ __( 'Form fields will be saved only on publish/update.', 'planet4-engagingnetworks-backend' ) }} -

- - - - - - - - - - - - - - - - - - - - - - - - - -
{{ __( 'Name', 'planet4-engagingnetworks-backend' ) }} - - - {{ __( 'EN Type', 'planet4-engagingnetworks-backend' ) }} - - - - {{ __( 'Required', 'planet4-engagingnetworks-backend' ) }} - - - {{ __( 'Label', 'planet4-engagingnetworks-backend' ) }} - - - {{ __( 'P4 field type', 'planet4-engagingnetworks-backend' ) }} - - - {{ __( 'Actions', 'planet4-engagingnetworks-backend' ) }}
{{ __( 'Name', 'planet4-engagingnetworks-backend' ) }}{{ __( 'EN Type', 'planet4-engagingnetworks-backend' ) }}{{ __( 'Required', 'planet4-engagingnetworks-backend' ) }}{{ __( 'Label', 'planet4-engagingnetworks-backend' ) }}{{ __( 'Type', 'planet4-engagingnetworks-backend' ) }}{{ __( 'Actions', 'planet4-engagingnetworks-backend' ) }}
- -{% endblock %} diff --git a/templates/block_templates/enform.twig b/templates/block_templates/enform.twig deleted file mode 100644 index e448952f71..0000000000 --- a/templates/block_templates/enform.twig +++ /dev/null @@ -1,90 +0,0 @@ -{% block enblock %} - -{% endblock %} diff --git a/templates/block_templates/enform/country_select.twig b/templates/block_templates/enform/country_select.twig deleted file mode 100644 index e9e66e7882..0000000000 --- a/templates/block_templates/enform/country_select.twig +++ /dev/null @@ -1,267 +0,0 @@ -{% block country_options %} -
- -
-{% endblock %} - - diff --git a/templates/block_templates/enform/enblock.twig b/templates/block_templates/enform/enblock.twig deleted file mode 100644 index e57b8da319..0000000000 --- a/templates/block_templates/enform/enblock.twig +++ /dev/null @@ -1,84 +0,0 @@ -{% block enblock %} - -{% endblock %} diff --git a/templates/block_templates/enform/enform_post.twig b/templates/block_templates/enform/enform_post.twig deleted file mode 100644 index 430e200d96..0000000000 --- a/templates/block_templates/enform/enform_post.twig +++ /dev/null @@ -1,161 +0,0 @@ -{% block enform_post %} - - {# Render enform's hidden fields #} - {% for key, field in form_fields %} - {% if 'hidden' == field.input_type and ('Field' == field.en_type or 'OPT' == field.en_type) %} - {% if field.en_type == 'OPT' %} - {% set en_input_name = 'supporter.questions.'~field.id %} - {% elseif field.en_type == 'Field' %} - {% set en_input_name = 'supporter.'~field.property %} - {% endif %} - - - {% endif %} - {% endfor %} - -
- - {# Iterate over form fields and render each field #} - {% for key,field in form_fields %} - {% set errorMessage = __( 'This field is required', 'planet4-engagingnetworks' ) %} - - {# Construct input field name based on en type #} - {% if field.en_type == 'GEN' or field.en_type == 'OPT' %} - {% set en_input_name = 'supporter.questions.'~field.id %} - {% elseif field.en_type == 'Field' %} - {% set en_input_name = 'supporter.'~field.property %} - {% endif %} - - {% if ('text' == field.input_type or 'email' == field.input_type ) %} - {% if 'email' == field.input_type %} - {% set errorMessage = __( 'Please enter a valid e-mail address.', 'planet4-engagingnetworks' ) %} - {% endif %} -
-
- - -
-
- {% elseif 'checkbox' == field.input_type %} - {% if field.dependency %} - {% set dependent_field = field.dependency %} - {% endif %} - {% if 'GEN' == field.en_type %} - {% set i = 0 %} - {% for locale, question_options in field.question_options|object_to_array_theme %} - {% if ( locale == field.selected_locale ) %} - {% for question_option in question_options %} - {% set question_option = question_option|object_to_array_theme %} -
-
- -
-
- {% set i = i+1 %} - {% endfor %} - {% endif %} - {% endfor %} - {% elseif 'OPT' == field.en_type %} -
-
- -
-
- {% endif %} - {% elseif 'radio' == field.input_type %} - - {{ field.label|e('wp_kses_post')|raw }} -
- {% set i = 0 %} - {% for locale, radio_options in field.radio_options|object_to_array_theme %} - {% if ( locale == field.selected_locale ) %} - {% for radio_option in radio_options %} - {% set radio_option = radio_option|object_to_array_theme %} -
-
- -
-
- {% set i = i+1 %} - {% endfor %} - {% endif %} - {% endfor %} - {% elseif 'country' == field.input_type %} - {% set errorMessage = __( 'Please select a country.', 'planet4-engagingnetworks' ) %} -
-
- {% include 'block_templates/enform/country_select.twig' with { errorMessage: errorMessage } %} -
-
- {% elseif 'position' == field.input_type %} - {% set errorMessage = __( 'Please select a position.', 'planet4-engagingnetworks' ) %} -
-
- {% include 'block_templates/enform/position_select.twig' with { errorMessage: errorMessage } %} -
-
- {% endif %} - {% endfor %} -
-{% endblock %} diff --git a/templates/block_templates/enform/position_select.twig b/templates/block_templates/enform/position_select.twig deleted file mode 100644 index a73a2c2b02..0000000000 --- a/templates/block_templates/enform/position_select.twig +++ /dev/null @@ -1,32 +0,0 @@ -{% block position_options %} -
- -
-{% endblock %} - - diff --git a/templates/block_templates/enform/tease-thankyou.twig b/templates/block_templates/enform/tease-thankyou.twig deleted file mode 100644 index d2dbbee07c..0000000000 --- a/templates/block_templates/enform/tease-thankyou.twig +++ /dev/null @@ -1,33 +0,0 @@ - diff --git a/templates/block_templates/selected_enform_fields.twig b/templates/block_templates/selected_enform_fields.twig deleted file mode 100644 index 962d143712..0000000000 --- a/templates/block_templates/selected_enform_fields.twig +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - - - - - - - diff --git a/templates/block_templates/settings.twig b/templates/block_templates/settings.twig deleted file mode 100644 index eb1b33864c..0000000000 --- a/templates/block_templates/settings.twig +++ /dev/null @@ -1,65 +0,0 @@ -{% block settings_content %} - -
-

{{ __( 'Settings', domain ) }}

-
- - {{ fn( 'settings_errors' ) }} - -
{# ../../../../wp-admin/options.php #} - - {{ fn( 'settings_fields', 'p4en_main_settings_group' ) }} - {{ fn( 'do_settings_sections', 'p4en_main_settings_group' ) }} - - - - - - - - - - -
{{ __( 'Full Admin Public API Key', domain ) }}: - -
{{ __( 'Full Admin Private/Secret API Key', domain ) }}: - -
-
- - - - - - - - - -
{{ __( 'Frontend Public API Key', domain ) }}: - -
{{ __( 'Frontend Private/Secret API Key', domain ) }}: - -
- {{ fn( 'submit_button', __( 'Save Changes', domain ), 'primary', 'p4en_main_settings_save_button' ) }} -
-
- -{% endblock %} diff --git a/tests/e2e/blocks/enform.spec.js b/tests/e2e/blocks/enform.spec.js deleted file mode 100644 index 4d9386c8d7..0000000000 --- a/tests/e2e/blocks/enform.spec.js +++ /dev/null @@ -1,264 +0,0 @@ -import {test, expect} from '../tools/lib/test-utils.js'; -import {publishPost, createPostWithFeaturedImage} from '../tools/lib/post.js'; - -import fieldsData from '../fixtures/enform/ensapi_sample_fields_response.json'; -import questionsData from '../fixtures/enform/ensapi_sample_questions_response.json'; -import questionData from '../fixtures/enform/ensapi_sample_question_236734_response.json'; -import optinData from '../fixtures/enform/ensapi_sample_question_3877_response.json'; -import depOptinData from '../fixtures/enform/ensapi_sample_question_220954_response.json'; -import {formFields, formFieldsAttributes} from '../fixtures/enform/enformData.js'; - -test.describe.configure({mode: 'serial'}); -let enFormId; -let pageUrl; -let featureIsActiveOnInstance; - -test.useAdminLoggedIn(); - -test.describe('create, use and submit EN Form', () => { - test('activate EN Form block', async ({page, admin}) => { - // Enable EN Form block - await admin.visitAdminPage('admin.php', 'page=planet4_settings_features'); - const checkbox = page.getByRole('checkbox', {name: ' Activate the EN Form block, as well as the "Progress Bar inside EN Form" Counter block style.'}); - featureIsActiveOnInstance = await checkbox.isChecked(); - if (!featureIsActiveOnInstance) { - await checkbox.click(); - await page.locator('input[type="submit"]').click(); - } - - // Complete EN API settings to avoid api/cache issues - await page.goto('./wp-admin/admin.php?page=en-settings'); - - const adminPublicApiKey = page.locator('input#p4en_public_api'); - const adminPrivateApiKey = page.locator('input#p4en_private_api'); - const frontendPublicApiKey = page.locator('input#p4en_frontend_public_api'); - const frontendPrivateApiKey = page.locator('input#p4en_frontend_private_api'); - - const apubKey = await adminPublicApiKey.inputValue(); - const aprvKey = await adminPrivateApiKey.inputValue(); - const fpubKey = await frontendPublicApiKey.inputValue(); - const fprvKey = await frontendPrivateApiKey.inputValue(); - - if (!apubKey) { - await adminPublicApiKey.fill('admin-public'); - } - if (!aprvKey) { - await adminPrivateApiKey.fill('admin-private'); - } - if (!fpubKey) { - await frontendPublicApiKey.fill('frontend-public'); - } - if (!fprvKey) { - await frontendPrivateApiKey.fill('frontend-private'); - } - await page.locator('input[type="submit"]').click(); - }); - - test('create simple EN Form', async ({page, admin, requestUtils}) => { - // Insert relevant data in transient cache - const postData = { - ens_auth_public_token: 'public-token', - ens_auth_token: 'private-token', - ens_supporter_fields_response: fieldsData.supporter, - ens_supporter_questions_response: questionsData.questions, - ens_supporter_question_by_id_response_236734: questionData['question.236734'], - ens_supporter_question_by_id_response_3887: optinData['question.3887'], - ens_supporter_question_by_id_response_220954: depOptinData['question.220954'], - }; - const items = []; - for (const key in postData) { - items.push({key, value: JSON.stringify(postData[key])}); - } - - await requestUtils.rest({ - path: '/planet4/v1/transient', - method: 'POST', - data: {items}, - }); - - // Create a new form - await admin.visitAdminPage('post-new.php', 'post_type=p4en_form'); - const metaboxHeadings = await page.locator('h2').allInnerTexts(); - expect(metaboxHeadings.includes('Form preview')).toBeTruthy(); - expect(metaboxHeadings.includes('Selected Components')).toBeTruthy(); - expect(metaboxHeadings.includes('Available Fields')).toBeTruthy(); - expect(metaboxHeadings.includes('Available Questions')).toBeTruthy(); - expect(metaboxHeadings.includes('Available Opt-ins')).toBeTruthy(); - - await page.locator('input[name="post_title"]').fill('Acceptance Test - ENForm'); - const fields = [].concat(formFields.fields, formFields.questions); - for (const field of fields) { - if (field.name === 'Email') { - continue; // Email field is there by default - } - const element = await page.waitForSelector(`button[data-name="${field.name}"]`); - await element.scrollIntoViewIfNeeded(); - await element.click(); - } - - // Set fields attributes. - for (const field of fields) { - const element = await page.waitForSelector(`tr[data-en-id="${field.id}"] .field-type-select`); - await element.scrollIntoViewIfNeeded(); - if (field.name !== 'Email') { // Email field type is not modifiable - await element.selectOption(formFieldsAttributes[field.name].type); - } - if (formFieldsAttributes[field.name]?.required && field.name !== 'Email') { - await page.locator(`tr[data-en-id="${field.id}"] input[type="checkbox"]`).click(); - } - if (formFieldsAttributes[field.name]?.label?.length > 0 && field.type !== 'OPT') { - await page.locator(`tr[data-en-id="${field.id}"] input[type="text"]`).fill(formFieldsAttributes[field.name].label); - } - if (formFieldsAttributes[field.name]?.default_value?.length > 0) { - await page.locator(`tr[data-en-id="${field.id}"] .dashicons-edit`).click(); - const defaultValField = await page.waitForSelector(`.dialog-${field.id} input[data-attribute="default_value"]`); - await defaultValField.fill(formFieldsAttributes[field.name].default_value); - await page.locator(`.dialog-${field.id} button[title='Close']`).click(); - } - } - - // Set dependency field value. - for (const field of fields) { - if (!formFieldsAttributes[field.name]?.dependency) { - continue; - } - await page.locator(`#en_form_selected_fields_table tr[data-en-id="${field.id}"] .dashicons-edit`).click(); - const element = await page.waitForSelector(`.dialog-${field.id} .dependency-select`); - await element.selectOption(formFieldsAttributes[field.name].dependency); - await page.locator(`.dialog-${field.id} button[title='Close']`).click(); - } - - // Reorder last field with the second to last field to assert that ordering fields works. - const source = page.locator('tr:last-child span.dashicons-sort'); - const target = page.locator('tr:nth-last-child(2) span.dashicons-sort'); - await source.dragTo(target); - - await page.locator('#publish').click(); - - // Assert that the fields were saved with the expected attributes/values. - for (const field of fields) { - const element = page.locator(`tr[data-en-id="${field.id}"]`); - await expect(element).toHaveAttribute('data-en-name', field.name); - if (formFieldsAttributes[field.name]?.required) { - await page.locator(`tr[data-en-id="${field.id}"] input[type="checkbox"]`).isChecked(); - } - if (formFieldsAttributes[field.name]?.label?.length > 0 && field.type !== 'OPT') { - const labelField = page.locator(`tr[data-en-id="${field.id}"] input[type="text"]`); - expect(labelField).toHaveValue(formFieldsAttributes[field.name].label); - } - if (formFieldsAttributes[field.name]?.default_value?.length > 0) { - await page.locator(`tr[data-en-id="${field.id}"] .dashicons-edit`).click(); - const defaultValField = page.locator(`.dialog-${field.id} input[data-attribute="default_value"]`); - await expect(defaultValField).toHaveValue(formFieldsAttributes[field.name].default_value); - await page.locator(`.dialog-${field.id} button[title="Close"]`).click(); - } - } - - const currentUrl = page.url(); - enFormId = new URL(currentUrl).searchParams.get('post'); - }); - - test('create Page with EN Form side style', async ({page, admin, editor}) => { - pageUrl = await createPageWithENForm(page, admin, editor, 'side'); - }); - - test('fill EN Form (side style) on frontend', async ({page}) => { - await fillENFormAndSubmit(page); - }); - - test('create Page with EN Form full-width-bg style', async ({page, admin, editor}) => { - pageUrl = await createPageWithENForm(page, admin, editor, 'full-width-bg'); - }); - - test('fill EN Form (full-width-bg style) on frontend', async ({page}) => { - await fillENFormAndSubmit(page); - }); - - test('disable EN Form block', async ({page, admin}) => { - await admin.visitAdminPage('admin.php', 'page=planet4_settings_features'); - - if (featureIsActiveOnInstance) { - return; - } - - const checkbox = page.getByRole('checkbox', {name: ' Activate the EN Form block, as well as the "Progress Bar inside EN Form" Counter block style.'}); - const checked = await checkbox.isChecked(); - if (checked) { - await checkbox.click(); - await page.locator('input[type="submit"]').click(); - } - }); -}); - -async function createPageWithENForm(page, admin, editor, style) { - await createPostWithFeaturedImage({admin, editor}, { - title: 'Test page with enform (style)', - postType: 'page', - }); - - await editor.canvas.getByRole('button', {name: 'Add default block'}).click(); - await page.keyboard.type('/enform'); - await page.getByRole('option', {name: 'EN Form'}).click(); - await page.waitForSelector('.block.enform-wrap'); - - if (style === 'full-width-bg') { - await page.getByRole('button', {name: 'Full page width with background'}).click(); - } - const goalSelector = await page.getByRole('combobox', {name: 'Select Goal'}); - await goalSelector.selectOption('Petition Signup'); - const formSelector = await page.getByRole('combobox', {name: 'Planet 4 Engaging Networks form'}); - await formSelector.selectOption(enFormId); - - await page.waitForSelector('#en__field_supporter_emailAddress'); - - // Publish page. - const url = await publishPost({page, editor}); - return url; -} - -async function fillENFormAndSubmit(page) { - const fields = [].concat(formFields.fields, formFields.questions); - - await page.goto(pageUrl); - - // Check dependency field. - for (const field of fields) { - const dep = formFieldsAttributes[field.name]?.dependency; - if (formFieldsAttributes[field.name].type === 'Checkbox' && dep) { - await expect(page.locator(`.dependency-${field.name}`)).toBeDisabled(); - } - } - - // Fill the form's fields - for (const field of fields) { - if (['Email', 'Text'].includes(formFieldsAttributes[field.name].type)) { - const name = field.questionId ? `supporter.questions.${field.id}` : `supporter.${field.property}`; - await page.locator(`[name="${name}"]`).fill('Lorem ipsum'); - } else if (formFieldsAttributes[field.name].type === 'Checkbox') { - await page.locator(`label[for="en__field_supporter_questions_${field.id}"]`).dispatchEvent('click'); - } - } - - await expect(page.locator('#p4en_form')).toContainText('Please enter a valid e-mail address.'); - await page.locator('[name="supporter.emailAddress"]').fill('test@example.com'); - - await page.route('./wp-json/planet4/v1/enform/*', async route => { - expect(route.request().postDataJSON()).toMatchObject({ - standardFieldNames: true, - supporter: { - questions: { - 'question.236734': 'Lorem ipsum', - 'question.220954': 'Y', - 'question.3887': 'Y', - }, - emailAddress: 'test@example.com', - firstName: 'Lorem ipsum', - lastName: 'Lorem ipsum', - NOT_TAGGED_1: 'hidden field ασφ (0287#$%^ 日本語', - }, - }); - - await route.fulfill({json: []}); - }); - await page.getByRole('button', {name: 'Sign'}).click(); -} diff --git a/tests/e2e/fixtures/enform/enformData.js b/tests/e2e/fixtures/enform/enformData.js deleted file mode 100644 index a6823ff95b..0000000000 --- a/tests/e2e/fixtures/enform/enformData.js +++ /dev/null @@ -1,107 +0,0 @@ -export const formFields = { - fields: [ - { - id: 28121, - name: 'Email', - tag: 'Email Address', - property: 'emailAddress', - }, - { - id: 28116, - name: 'First name', - tag: 'First Name', - property: 'firstName', - }, - { - id: 28117, - name: 'Last name', - tag: 'Last Name', - property: 'lastName', - }, - { - id: 28122, - name: 'Country', - tag: 'Country', - property: 'country', - }, - { - id: 67127, - name: 'AwakenMe', - tag: 'Not Tagged', - property: 'NOT_TAGGED_1', - }, - ], - questions: [ - { - id: 236734, - questionId: 25781, - name: 'test question 1', - type: 'GEN', - }, - { - id: 220954, - questionId: 25511, - name: 'nro_data_ok', - type: 'OPT', - }, - { - id: 3887, - questionId: 3665, - name: 'Opt-in', - type: 'OPT', - }, - ], -}; - -export const formFieldsAttributes = { - 'First name': { - default_value: '', - label: 'First Name', - required: false, - type: 'Text', - }, - 'Last name': { - default_value: '', - label: 'Last Name', - required: false, - type: 'Text', - }, - Email: { - default_value: '', - label: 'Email', - required: true, - type: 'Email', - }, - Country: { - default_value: '', - label: 'Country', - required: false, - type: 'Country', - }, - AwakenMe: { - default_value: 'hidden field ασφ (0287#$%^ 日本語', - label: '', - required: false, - type: 'Hidden', - }, - 'test question 1': { - default_value: '', - label: 'What\'s the question?', - required: false, - type: 'Text', - }, - nro_data_ok: { - default_value: '', - label: 'I am happy for my data to be shared with my local Greenpeace office.', - required: false, - type: 'Checkbox', - }, - 'Opt-in': { - default_value: '', - label: 'Opt in', - required: false, - type: 'Checkbox', - dependency: 'nro_data_ok', - }, -}; - diff --git a/tests/e2e/fixtures/enform/ensapi_sample_fields_response.json b/tests/e2e/fixtures/enform/ensapi_sample_fields_response.json deleted file mode 100644 index 544e9b504b..0000000000 --- a/tests/e2e/fixtures/enform/ensapi_sample_fields_response.json +++ /dev/null @@ -1,676 +0,0 @@ -{ - "supporter": [ - { - "id": 28115, - "name": "Title", - "tag": "Title", - "property": "title" - }, - { - "id": 28116, - "name": "First name", - "tag": "First Name", - "property": "firstName" - }, - { - "id": 28117, - "name": "Last name", - "tag": "Last Name", - "property": "lastName" - }, - { - "id": 28118, - "name": "Address 1", - "tag": "Address 1", - "property": "address1" - }, - { - "id": 53481, - "name": "Address 2", - "tag": "Address 2", - "property": "address2" - }, - { - "id": 28119, - "name": "City", - "tag": "City", - "property": "city" - }, - { - "id": 28122, - "name": "Country", - "tag": "Country", - "property": "country" - }, - { - "id": 28120, - "name": "Postcode", - "tag": "Postcode", - "property": "postcode" - }, - { - "id": 42648, - "name": "County", - "tag": "Region", - "property": "region" - }, - { - "id": 53483, - "name": "Phone Number", - "tag": "Phone Number", - "property": "phoneNumber" - }, - { - "id": 53455, - "name": "Credit Card Holder Name", - "tag": "Credit Card Holder Name", - "property": "creditCardHolderName" - }, - { - "id": 53463, - "name": "Password", - "tag": "Password", - "property": "password" - }, - { - "id": 75473, - "name": "Company", - "tag": "Not Tagged", - "property": "NOT_TAGGED_5" - }, - { - "id": 75474, - "name": "email_type", - "tag": "Not Tagged", - "property": "NOT_TAGGED_6" - }, - { - "id": 63628, - "name": "ChallengeDate", - "tag": "P2P Fundraiser Type", - "property": "p2pFundraiserType" - }, - { - "id": 75475, - "name": "title", - "tag": "Not Tagged", - "property": "NOT_TAGGED_7" - }, - { - "id": 75476, - "name": "middle_name", - "tag": "Not Tagged", - "property": "NOT_TAGGED_8" - }, - { - "id": 67127, - "name": "AwakenMe", - "tag": "Not Tagged", - "property": "NOT_TAGGED_1" - }, - { - "id": 75477, - "name": "full_name", - "tag": "Not Tagged", - "property": "NOT_TAGGED_9" - }, - { - "id": 74010, - "name": "MP constituency", - "tag": "Not Tagged", - "property": "NOT_TAGGED_2" - }, - { - "id": 75478, - "name": "date_of_birth", - "tag": "Not Tagged", - "property": "NOT_TAGGED_10" - }, - { - "id": 74011, - "name": "MP party", - "tag": "Not Tagged", - "property": "NOT_TAGGED_3" - }, - { - "id": 75479, - "name": "gender", - "tag": "Not Tagged", - "property": "NOT_TAGGED_11" - }, - { - "id": 75470, - "name": "Country Of Ownership", - "tag": "Not Tagged", - "property": "NOT_TAGGED_4" - }, - { - "id": 75481, - "name": "phone_type", - "tag": "Not Tagged", - "property": "NOT_TAGGED_13" - }, - { - "id": 75482, - "name": "address_1", - "tag": "Not Tagged", - "property": "NOT_TAGGED_14" - }, - { - "id": 75483, - "name": "address_2", - "tag": "Not Tagged", - "property": "NOT_TAGGED_15" - }, - { - "id": 75484, - "name": "address_3", - "tag": "Not Tagged", - "property": "NOT_TAGGED_16" - }, - { - "id": 75485, - "name": "region", - "tag": "Not Tagged", - "property": "NOT_TAGGED_17" - }, - { - "id": 75486, - "name": "language_pref", - "tag": "Not Tagged", - "property": "NOT_TAGGED_18" - }, - { - "id": 75487, - "name": "source", - "tag": "Not Tagged", - "property": "NOT_TAGGED_19" - }, - { - "id": 75488, - "name": "channel", - "tag": "Not Tagged", - "property": "NOT_TAGGED_20" - }, - { - "id": 75489, - "name": "contact_codes", - "tag": "Not Tagged", - "property": "NOT_TAGGED_21" - }, - { - "id": 75490, - "name": "communication_codes", - "tag": "Not Tagged", - "property": "NOT_TAGGED_22" - }, - { - "id": 75491, - "name": "gp_interests", - "tag": "Not Tagged", - "property": "NOT_TAGGED_23" - }, - { - "id": 75492, - "name": "legacy_optin_details", - "tag": "Not Tagged", - "property": "NOT_TAGGED_24" - }, - { - "id": 75493, - "name": "legacy_optin_date", - "tag": "Not Tagged", - "property": "NOT_TAGGED_25" - }, - { - "id": 75494, - "name": "fr_rg_amount", - "tag": "Not Tagged", - "property": "NOT_TAGGED_26" - }, - { - "id": 75495, - "name": "fr_rg_frequency", - "tag": "Not Tagged", - "property": "NOT_TAGGED_27" - }, - { - "id": 75496, - "name": "fr_rg_last_gift_date", - "tag": "Not Tagged", - "property": "NOT_TAGGED_28" - }, - { - "id": 75497, - "name": "fr_donor_id", - "tag": "Not Tagged", - "property": "NOT_TAGGED_29" - }, - { - "id": 75498, - "name": "fr_first_name", - "tag": "Not Tagged", - "property": "NOT_TAGGED_30" - }, - { - "id": 75499, - "name": "fr_last_name", - "tag": "Not Tagged", - "property": "NOT_TAGGED_31" - }, - { - "id": 75500, - "name": "fr_tax_name", - "tag": "Not Tagged", - "property": "NOT_TAGGED_32" - }, - { - "id": 75501, - "name": "fr_amount", - "tag": "Not Tagged", - "property": "NOT_TAGGED_33" - }, - { - "id": 75502, - "name": "fr_frequency", - "tag": "Not Tagged", - "property": "NOT_TAGGED_34" - }, - { - "id": 75503, - "name": "fr_debit_date", - "tag": "Not Tagged", - "property": "NOT_TAGGED_35" - }, - { - "id": 75504, - "name": "fr_account_number", - "tag": "Not Tagged", - "property": "NOT_TAGGED_36" - }, - { - "id": 75505, - "name": "fr_email", - "tag": "Not Tagged", - "property": "NOT_TAGGED_37" - }, - { - "id": 75506, - "name": "fr_email_category", - "tag": "Not Tagged", - "property": "NOT_TAGGED_38" - }, - { - "id": 75507, - "name": "fr_receipt_no", - "tag": "Not Tagged", - "property": "NOT_TAGGED_39" - }, - { - "id": 75508, - "name": "fr_apr", - "tag": "Not Tagged", - "property": "NOT_TAGGED_40" - }, - { - "id": 75509, - "name": "fr_may", - "tag": "Not Tagged", - "property": "NOT_TAGGED_41" - }, - { - "id": 75510, - "name": "fr_jun", - "tag": "Not Tagged", - "property": "NOT_TAGGED_42" - }, - { - "id": 75511, - "name": "fr_jul", - "tag": "Not Tagged", - "property": "NOT_TAGGED_43" - }, - { - "id": 75512, - "name": "fr_aug", - "tag": "Not Tagged", - "property": "NOT_TAGGED_44" - }, - { - "id": 75513, - "name": "fr_sep", - "tag": "Not Tagged", - "property": "NOT_TAGGED_45" - }, - { - "id": 75514, - "name": "fr_oct", - "tag": "Not Tagged", - "property": "NOT_TAGGED_46" - }, - { - "id": 75515, - "name": "fr_nov", - "tag": "Not Tagged", - "property": "NOT_TAGGED_47" - }, - { - "id": 75516, - "name": "fr_dec", - "tag": "Not Tagged", - "property": "NOT_TAGGED_48" - }, - { - "id": 75517, - "name": "fr_jan", - "tag": "Not Tagged", - "property": "NOT_TAGGED_49" - }, - { - "id": 75518, - "name": "fr_feb", - "tag": "Not Tagged", - "property": "NOT_TAGGED_50" - }, - { - "id": 75519, - "name": "fr_mar", - "tag": "Not Tagged", - "property": "NOT_TAGGED_51" - }, - { - "id": 75520, - "name": "is_standard_chartered_customer", - "tag": "Not Tagged", - "property": "NOT_TAGGED_52" - }, - { - "id": 75521, - "name": "email_ok", - "tag": "Not Tagged", - "property": "NOT_TAGGED_53" - }, - { - "id": 75682, - "name": "Groupcode", - "tag": "Not Tagged", - "property": "NOT_TAGGED_54" - }, - { - "id": 75683, - "name": "isDonor", - "tag": "Not Tagged", - "property": "NOT_TAGGED_55" - }, - { - "id": 75684, - "name": "isFDSuc", - "tag": "Not Tagged", - "property": "NOT_TAGGED_56" - }, - { - "id": 75685, - "name": "isFRDonor", - "tag": "Not Tagged", - "property": "NOT_TAGGED_57" - }, - { - "id": 75686, - "name": "isFRNLSubscriber", - "tag": "Not Tagged", - "property": "NOT_TAGGED_58" - }, - { - "id": 75687, - "name": "isReDonor", - "tag": "Not Tagged", - "property": "NOT_TAGGED_59" - }, - { - "id": 75689, - "name": "isSubscriber", - "tag": "Not Tagged", - "property": "NOT_TAGGED_60" - }, - { - "id": 75690, - "name": "isVolunteer", - "tag": "Not Tagged", - "property": "NOT_TAGGED_61" - }, - { - "id": 75691, - "name": "Join date", - "tag": "Not Tagged", - "property": "NOT_TAGGED_62" - }, - { - "id": 75692, - "name": "Supporter birthday", - "tag": "Not Tagged", - "property": "NOT_TAGGED_63" - }, - { - "id": 75693, - "name": "volunteer_apply_reason_shiptour", - "tag": "Not Tagged", - "property": "NOT_TAGGED_64" - }, - { - "id": 75694, - "name": "volunteer_type", - "tag": "Not Tagged", - "property": "NOT_TAGGED_65" - }, - { - "id": 75695, - "name": "volunteer_type_shiptour", - "tag": "Not Tagged", - "property": "NOT_TAGGED_66" - }, - { - "id": 75696, - "name": "city_shiptour", - "tag": "Not Tagged", - "property": "NOT_TAGGED_67" - }, - { - "id": 75697, - "name": "city_shiptour_openboat", - "tag": "Not Tagged", - "property": "NOT_TAGGED_68" - }, - { - "id": 77983, - "name": "testPK", - "tag": "Not Tagged", - "property": "NOT_TAGGED_69" - }, - { - "id": 77990, - "name": "birthdayMonth", - "tag": "Not Tagged", - "property": "NOT_TAGGED_70" - }, - { - "id": 79741, - "name": "Email address", - "tag": "Not Tagged", - "property": "NOT_TAGGED_71" - }, - { - "id": 80867, - "name": "DonorUserRef", - "tag": "Not Tagged", - "property": "NOT_TAGGED_72" - }, - { - "id": 81551, - "name": "DDBatchNo", - "tag": "Not Tagged", - "property": "NOT_TAGGED_73" - }, - { - "id": 81606, - "name": "PaymentRejectReason", - "tag": "Not Tagged", - "property": "NOT_TAGGED_74" - }, - { - "id": 82578, - "name": "Label Text", - "tag": "Not Tagged", - "property": "NOT_TAGGED_75" - }, - { - "id": 88153, - "name": "Card_Declined_Imported_SF", - "tag": "Not Tagged", - "property": "NOT_TAGGED_76" - }, - { - "id": 98272, - "name": "SFDC Contact ID", - "tag": "Not Tagged", - "property": "NOT_TAGGED_77" - }, - { - "id": 98273, - "name": "SFDC Lead ID", - "tag": "Not Tagged", - "property": "NOT_TAGGED_78" - }, - { - "id": 101574, - "name": "email_ok_supporter", - "tag": "Not Tagged", - "property": "NOT_TAGGED_79" - }, - { - "id": 101604, - "name": "supporter ID Friends", - "tag": "Not Tagged", - "property": "NOT_TAGGED_80" - }, - { - "id": 101605, - "name": "date added to friends", - "tag": "Not Tagged", - "property": "NOT_TAGGED_81" - }, - { - "id": 101931, - "name": "Date Added to Friends", - "tag": "Not Tagged", - "property": "NOT_TAGGED_82" - }, - { - "id": 102123, - "name": "demo", - "tag": "Not Tagged", - "property": "NOT_TAGGED_83" - }, - { - "id": 102168, - "name": "owned_PH", - "tag": "Not Tagged", - "property": "NOT_TAGGED_84" - }, - { - "id": 104611, - "name": "lead_id", - "tag": "Not Tagged", - "property": "NOT_TAGGED_85" - }, - { - "id": 104612, - "name": "Contact_id", - "tag": "Not Tagged", - "property": "NOT_TAGGED_86" - }, - { - "id": 104758, - "name": "civi_id", - "tag": "Not Tagged", - "property": "NOT_TAGGED_90" - }, - { - "id": 104759, - "name": "supporter_id", - "tag": "Not Tagged", - "property": "NOT_TAGGED_91" - }, - { - "id": 28121, - "name": "Email", - "tag": "Email Address", - "property": "emailAddress" - }, - { - "id": 104754, - "name": "first_name", - "tag": "Not Tagged", - "property": "NOT_TAGGED_87" - }, - { - "id": 104755, - "name": "last_name", - "tag": "Not Tagged", - "property": "NOT_TAGGED_88" - }, - { - "id": 75480, - "name": "phone_number", - "tag": "Not Tagged", - "property": "NOT_TAGGED_12" - }, - { - "id": 104756, - "name": "supporter_birthday", - "tag": "Supporter Birthday", - "property": "dateOfBirth" - }, - { - "id": 104757, - "name": "owned_hungary", - "tag": "Not Tagged", - "property": "NOT_TAGGED_89" - }, - { - "id": 104762, - "name": "hu_active_donor", - "tag": "Not Tagged", - "property": "NOT_TAGGED_92" - }, - { - "id": 104763, - "name": "hu_recurring_donor", - "tag": "Not Tagged", - "property": "NOT_TAGGED_93" - }, - { - "id": 104764, - "name": "card_expiry", - "tag": "Not Tagged", - "property": "NOT_TAGGED_94" - }, - { - "id": 104765, - "name": "donor_first_donation_date", - "tag": "Not Tagged", - "property": "NOT_TAGGED_95" - }, - { - "id": 105316, - "name": "txn6", - "tag": "Not Tagged", - "property": "NOT_TAGGED_96" - }, - { - "id": 105317, - "name": "txn7", - "tag": "Not Tagged", - "property": "NOT_TAGGED_97" - } - ] -} diff --git a/tests/e2e/fixtures/enform/ensapi_sample_pages_response.json b/tests/e2e/fixtures/enform/ensapi_sample_pages_response.json deleted file mode 100644 index b9186be066..0000000000 --- a/tests/e2e/fixtures/enform/ensapi_sample_pages_response.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "pages": [ - { - "id": 20000, - "campaignId": 9000, - "name": "Testing", - "title": null, - "type": "dc", - "subType": "PET", - "clientId": 1000, - "createdOn": 1519825631000, - "modifiedOn": 1519826239000, - "campaignBaseUrl": "https://act.greenpeace.org", - "campaignStatus": "live", - "defaultLocale": "en-US" - }, - { - "id": 20001, - "campaignId": 1800, - "name": "BFFJ", - "title": "Break Free From Jez", - "type": "dc", - "subType": "PET", - "clientId": 1000, - "createdOn": 1532417882000, - "modifiedOn": null, - "campaignBaseUrl": "https://act.greenpeace.org", - "campaignStatus": "new", - "defaultLocale": "en-US" - }, - { - "id": 20002, - "campaignId": 9001, - "name": "Blank template", - "title": null, - "type": "dc", - "subType": "PET", - "clientId": 1000, - "createdOn": 1473149968000, - "modifiedOn": 1537350723000, - "campaignBaseUrl": "https://act.greenpeace.org", - "campaignStatus": "close", - "defaultLocale": "en-US" - }, - { - "id": 20003, - "campaignId": 9003, - "name": "Demo page", - "title": "Stop using plastic", - "type": "dc", - "subType": "PET", - "clientId": 1000, - "createdOn": 1542747921000, - "modifiedOn": null, - "campaignBaseUrl": "https://act.greenpeace.org", - "campaignStatus": "new", - "defaultLocale": "en-GB" - } - ] -} diff --git a/tests/e2e/fixtures/enform/ensapi_sample_question_220954_response.json b/tests/e2e/fixtures/enform/ensapi_sample_question_220954_response.json deleted file mode 100644 index 642969c6ab..0000000000 --- a/tests/e2e/fixtures/enform/ensapi_sample_question_220954_response.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "question.220954": [ - { - "id": 220954, - "questionId": 25511, - "name": "nro_data_ok", - "type": "OPT", - "locale": "en-US", - "htmlFieldType": "checkbox", - "content": { - "data": [ - { - "forId": "", - "imageUrl": "", - "selected": false, - "value": "N", - "label": "I am happy for my data to be shared with my local Greenpeace office." - } - ] - } - } - ] -} diff --git a/tests/e2e/fixtures/enform/ensapi_sample_question_236734_response.json b/tests/e2e/fixtures/enform/ensapi_sample_question_236734_response.json deleted file mode 100644 index d5e9add991..0000000000 --- a/tests/e2e/fixtures/enform/ensapi_sample_question_236734_response.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "question.236734": [ - { - "id": 236734, - "questionId": 25781, - "name": "test question 1", - "type": "GEN", - "locale": "en-US", - "label": "how many forests are there?", - "htmlFieldType": "text", - "content": null - } - ] -} diff --git a/tests/e2e/fixtures/enform/ensapi_sample_question_3877_response.json b/tests/e2e/fixtures/enform/ensapi_sample_question_3877_response.json deleted file mode 100644 index eaeb92bdf0..0000000000 --- a/tests/e2e/fixtures/enform/ensapi_sample_question_3877_response.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "question.3887": [ - { - "id": 3887, - "questionId": 3665, - "name": "Opt-in", - "type": "OPT", - "locale": "en-US", - "htmlFieldType": "checkbox", - "content": { - "data": [ - { - "forId": "", - "imageUrl": "", - "selected": false, - "value": "Y", - "label": "Yes, I would like to receive updates via email. This is a link example https://www.google.com" - } - ] - } - } - ] -} diff --git a/tests/e2e/fixtures/enform/ensapi_sample_questions_response.json b/tests/e2e/fixtures/enform/ensapi_sample_questions_response.json deleted file mode 100644 index 5bfe24c35e..0000000000 --- a/tests/e2e/fixtures/enform/ensapi_sample_questions_response.json +++ /dev/null @@ -1,268 +0,0 @@ -{ - "questions": [ - { - "id": 3887, - "questionId": 3665, - "name": "Opt-in", - "type": "OPT" - }, - { - "id": 220954, - "questionId": 25511, - "name": "nro_data_ok", - "type": "OPT" - }, - { - "id": 236813, - "questionId": 25792, - "name": "forest survey - score", - "type": "GEN" - }, - { - "id": 237901, - "questionId": 25817, - "name": "forest survey - question 2", - "type": "GEN" - }, - { - "id": 237902, - "questionId": 25818, - "name": "forest survey - question 3", - "type": "GEN" - }, - { - "id": 237903, - "questionId": 25819, - "name": "forest survey - question 4", - "type": "GEN" - }, - { - "id": 237904, - "questionId": 25820, - "name": "forest survey - question 5", - "type": "GEN" - }, - { - "id": 212477, - "questionId": 25318, - "name": "NRO_share_ok", - "type": "OPT" - }, - { - "id": 219998, - "questionId": 25506, - "name": "Letter Text", - "type": "GEN" - }, - { - "id": 271939, - "questionId": 26495, - "name": "IPCC - question 1", - "type": "GEN" - }, - { - "id": 271940, - "questionId": 26496, - "name": "IPCC - question 2", - "type": "GEN" - }, - { - "id": 236734, - "questionId": 25781, - "name": "test question 1", - "type": "GEN" - }, - { - "id": 182157, - "questionId": 24545, - "name": "test multi check", - "type": "GEN" - }, - { - "id": 160201, - "questionId": 23864, - "name": "Language", - "type": "GEN" - }, - { - "id": 258357, - "questionId": 26204, - "name": "Opt In Palm Oil", - "type": "OPT" - }, - { - "id": 178317, - "questionId": 24374, - "name": "Channel - Email", - "type": "GEN" - }, - { - "id": 178318, - "questionId": 24375, - "name": "Purpose - Campaigns", - "type": "GEN" - }, - { - "id": 178319, - "questionId": 24376, - "name": "Purpose - Fundraising", - "type": "GEN" - }, - { - "id": 126685, - "questionId": 22983, - "name": "PTA Opt Out", - "type": "OPT" - }, - { - "id": 174173, - "questionId": 24232, - "name": "Campaigning", - "type": "OPT" - }, - { - "id": 237900, - "questionId": 25816, - "name": "forest survey - question 1", - "type": "GEN" - }, - { - "id": 106418, - "questionId": 22330, - "name": "GPI test", - "type": "OPT" - }, - { - "id": 131366, - "questionId": 23122, - "name": "email_ok", - "type": "OPT" - }, - { - "id": 271943, - "questionId": 26497, - "name": "IPCC - score", - "type": "GEN" - }, - { - "id": 261259, - "questionId": 26257, - "name": "FA test", - "type": "GEN" - }, - { - "id": 174169, - "questionId": 24228, - "name": "SMS", - "type": "OPT" - }, - { - "id": 174171, - "questionId": 24230, - "name": "Mail (post)", - "type": "OPT" - }, - { - "id": 173794, - "questionId": 24217, - "name": "email_ok_radio", - "type": "OPT" - }, - { - "id": 242254, - "questionId": 25903, - "name": "email updates", - "type": "OPT" - }, - { - "id": 237905, - "questionId": 25821, - "name": "forest survey - question 6", - "type": "GEN" - }, - { - "id": 174168, - "questionId": 24227, - "name": "Phone", - "type": "OPT" - }, - { - "id": 174170, - "questionId": 24229, - "name": "Social Media", - "type": "OPT" - }, - { - "id": 249110, - "questionId": 26074, - "name": "q_Rick", - "type": "GEN" - }, - { - "id": 178316, - "questionId": 24373, - "name": "Channel - Phone", - "type": "GEN" - }, - { - "id": 174172, - "questionId": 24231, - "name": "Fundraising", - "type": "OPT" - }, - { - "id": 174174, - "questionId": 24233, - "name": "Volunteering", - "type": "OPT" - }, - { - "id": 261093, - "questionId": 26248, - "name": "JD test", - "type": "OPT" - }, - { - "id": 408173, - "questionId": 29555, - "name": "Call To Target Feedback", - "type": "GEN" - }, - { - "id": 381131, - "questionId": 28782, - "name": "email_ok_hungary", - "type": "OPT" - }, - { - "id": 381132, - "questionId": 28783, - "name": "hu_data_policy_disclaimer", - "type": "OPT" - }, - { - "id": 417462, - "questionId": 29754, - "name": "Animals", - "type": "GEN" - }, - { - "id": 418805, - "questionId": 29788, - "name": "Education", - "type": "GEN" - }, - { - "id": 408507, - "questionId": 29565, - "name": "Call To Target Extended Feedback", - "type": "GEN" - }, - { - "id": 418804, - "questionId": 29787, - "name": "Antarctic", - "type": "GEN" - } - ] -} diff --git a/webpack.config.js b/webpack.config.js index 2f9d005970..5fbea88054 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -56,8 +56,6 @@ module.exports = { SocialMediaEditorScript: './assets/src/blocks/SocialMedia/SocialMediaEditorScript.js', SocialMediaStyle: './assets/src/scss/blocks/SocialMedia/SocialMediaStyle.scss', SocialMediaEditorStyle: './assets/src/scss/blocks/SocialMedia/SocialMediaEditorStyle.scss', - ENFormScript: './assets/src/blocks/ENForm/ENFormScript.js', - ENFormEditorScript: './assets/src/blocks/ENForm/ENFormEditorScript.js', TimelineScript: './assets/src/blocks/Timeline/TimelineScript.js', TimelineEditorScript: './assets/src/blocks/Timeline/TimelineEditorScript.js', TimelineStyle: './assets/src/scss/blocks/Timeline/TimelineStyle.scss',