View source
<?php
namespace Drupal\webform\Entity;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Config\Entity\ConfigEntityBundleBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\user\Entity\User;
use Drupal\user\UserInterface;
use Drupal\webform\Plugin\WebformElement\WebformActions;
use Drupal\webform\Plugin\WebformElement\WebformWizardPage;
use Drupal\webform\Plugin\WebformElementAssetInterface;
use Drupal\webform\Plugin\WebformElementAttachmentInterface;
use Drupal\webform\Plugin\WebformElementComputedInterface;
use Drupal\webform\Plugin\WebformElementVariantInterface;
use Drupal\webform\Plugin\WebformElementWizardPageInterface;
use Drupal\webform\Plugin\WebformHandlerMessageInterface;
use Drupal\webform\Plugin\WebformVariantInterface;
use Drupal\webform\Plugin\WebformVariantPluginCollection;
use Drupal\webform\Utility\WebformElementHelper;
use Drupal\webform\Utility\WebformReflectionHelper;
use Drupal\webform\Plugin\WebformHandlerInterface;
use Drupal\webform\Plugin\WebformHandlerPluginCollection;
use Drupal\webform\Utility\WebformTextHelper;
use Drupal\webform\Utility\WebformYaml;
use Drupal\webform\WebformException;
use Drupal\webform\WebformInterface;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\WebformSubmissionStorageInterface;
class Webform extends ConfigEntityBundleBase implements WebformInterface {
use StringTranslationTrait;
protected $id;
protected $uuid;
protected $operation;
protected $override = FALSE;
protected $elementsTranslated = FALSE;
protected $updating = FALSE;
protected $status = WebformInterface::STATUS_OPEN;
protected $open;
protected $close;
protected $weight = 0;
protected $template = FALSE;
protected $archive = FALSE;
protected $title;
protected $description;
protected $category;
protected $uid;
protected $settings = [];
protected $settingsOriginal;
protected $access = [];
protected $elements;
protected $css = '';
protected $javascript = '';
protected $handlers = [];
protected $handlersCollection;
protected $variants = [];
protected $variantsCollection;
protected $elementsOriginal;
protected $elementsDecoded;
protected $elementsInitialized;
protected $elementsDecodedAndFlattened;
protected $elementsInitializedAndFlattened;
protected $elementsInitializedFlattenedAndHasValue;
protected $elementsTranslations;
protected $elementsPrepopulate = [];
protected $elementsActions = [];
protected $elementsWizardPages = [];
protected $elementsManagedFiles = [];
protected $elementsAttachments = [];
protected $elementsComputed = [];
protected $elementsVariant = [];
protected $elementsCss = [];
protected $elementsJavaScript = [];
protected $elementsDefaultData = [];
protected $pages;
protected $hasFlexboxLayout = FALSE;
protected $hasContainer = FALSE;
protected $hasConditions = FALSE;
protected $hasRequired = FALSE;
protected $hasTranslations;
protected $hasMessageHandler;
protected $hasAnonymousSubmissionTrackingHandler;
public function getLangcode() {
return $this->langcode;
}
public function getWeight() {
return $this->weight;
}
public function getOwner() {
return $this->uid ? User::load($this->uid) : NULL;
}
public function setOwner(UserInterface $account) {
$this->uid = $account
->id();
return $this;
}
public function getOwnerId() {
return $this->uid;
}
public function setOwnerId($uid) {
$this->uid = $uid ? $uid : NULL;
return $this;
}
public function getOperation() {
return $this->operation;
}
public function setOperation($operation) {
$this->operation = $operation;
return $this;
}
public function isTest() {
return $this->operation === 'test' ? TRUE : FALSE;
}
public function setOverride($override = TRUE) {
$this->override = $override;
return $this;
}
public function isOverridden() {
return $this->override || $this->elementsTranslated;
}
public function setUpdating($updating = TRUE) {
$this->updating = $updating;
return $this;
}
public function isUpdating() {
return $this->updating;
}
public function setStatus($status) {
if ($status === NULL || $status === WebformInterface::STATUS_SCHEDULED) {
$this->status = WebformInterface::STATUS_SCHEDULED;
}
elseif ($status === WebformInterface::STATUS_OPEN) {
$this->status = WebformInterface::STATUS_OPEN;
}
elseif ($status === WebformInterface::STATUS_CLOSED) {
$this->status = WebformInterface::STATUS_CLOSED;
}
else {
$this->status = (bool) $status ? WebformInterface::STATUS_OPEN : WebformInterface::STATUS_CLOSED;
}
if ($this->status !== WebformInterface::STATUS_SCHEDULED) {
$this->open = NULL;
$this->close = NULL;
}
return $this;
}
public function status() {
return $this
->isOpen();
}
public function isOpen() {
if ($this
->isArchived()) {
return FALSE;
}
switch ($this->status) {
case WebformInterface::STATUS_OPEN:
return TRUE;
case WebformInterface::STATUS_CLOSED:
return FALSE;
case WebformInterface::STATUS_SCHEDULED:
$is_opened = TRUE;
if ($this->open && strtotime($this->open) > time()) {
$is_opened = FALSE;
}
$is_closed = FALSE;
if ($this->close && strtotime($this->close) < time()) {
$is_closed = TRUE;
}
return $is_opened && !$is_closed ? TRUE : FALSE;
}
return FALSE;
}
public function isClosed() {
return !$this
->isOpen();
}
public function isScheduled() {
return $this->status === WebformInterface::STATUS_SCHEDULED;
}
public function isOpening() {
return $this
->isScheduled() && ($this->open && strtotime($this->open) > time()) ? TRUE : FALSE;
}
public function isTemplate() {
return $this->template ? TRUE : FALSE;
}
public function isArchived() {
return $this->archive ? TRUE : FALSE;
}
public function isConfidential() {
return $this
->getSetting('form_confidential');
}
public function hasRemoteAddr() {
$disable_remote_addr = $this
->getSetting('form_disable_remote_addr', TRUE);
return !$this
->isConfidential() && !$disable_remote_addr ? TRUE : FALSE;
}
public function isResultsDisabled() {
$elements = $this
->getElementsDecoded();
$settings = $this
->getSettings();
return !empty($settings['results_disabled']) || !empty($elements['#method']) ? TRUE : FALSE;
}
public function hasSubmissions() {
$submission_storage = \Drupal::entityTypeManager()
->getStorage('webform_submission');
return $submission_storage
->getTotal($this) ? TRUE : FALSE;
}
public function hasSubmissionLog() {
return $this
->getSetting('submission_log', TRUE) ?: FALSE;
}
public function hasTranslations() {
if (isset($this->hasTranslations)) {
return $this->hasTranslations;
}
if (!\Drupal::moduleHandler()
->moduleExists('config_translation')) {
$this->hasTranslations = FALSE;
return $this->hasTranslations;
}
$local_config_manager = \Drupal::service('locale.config_manager');
$languages = \Drupal::languageManager()
->getLanguages();
foreach ($languages as $langcode => $language) {
if ($local_config_manager
->hasTranslation('webform.webform.' . $this
->id(), $langcode)) {
$this->hasTranslations = TRUE;
return $this->hasTranslations;
}
}
$this->hasTranslations = FALSE;
return $this->hasTranslations;
}
public function hasPage() {
$settings = $this
->getSettings();
return $settings['page'] ? TRUE : FALSE;
}
public function hasManagedFile() {
$this
->initElements();
return !empty($this->elementsManagedFiles) ? TRUE : FALSE;
}
public function hasAttachments() {
$this
->initElements();
return !empty($this->elementsAttachments) ? TRUE : FALSE;
}
public function hasComputed() {
$this
->initElements();
return !empty($this->elementsComputed) ? TRUE : FALSE;
}
public function hasVariants() {
$this
->initElements();
return !empty($this->elementsVariant) ? TRUE : FALSE;
}
public function hasFlexboxLayout() {
$this
->initElements();
return $this->hasFlexboxLayout;
}
public function hasContainer() {
$this
->initElements();
return $this->hasContainer;
}
public function hasConditions() {
$this
->initElements();
return $this->hasConditions;
}
public function hasRequired() {
$this
->initElements();
return $this->hasRequired;
}
public function hasActions() {
return $this
->getNumberOfActions() ? TRUE : FALSE;
}
public function getNumberOfActions() {
$this
->initElements();
return count($this->elementsActions);
}
public function hasPreview() {
return $this
->getSetting('preview') !== DRUPAL_DISABLED;
}
public function hasWizardPages() {
return $this
->getNumberOfWizardPages() ? TRUE : FALSE;
}
public function getNumberOfWizardPages() {
$this
->initElements();
return count($this->elementsWizardPages);
}
public function getDescription() {
return $this->description;
}
public function setDescription($description) {
$this->description = $description;
return $this;
}
public function getAssets() {
$this
->initElements();
$css = [];
$shared_css = \Drupal::config('webform.settings')
->get('assets.css') ?: '';
if ($shared_css) {
$css[] = $shared_css;
}
$webform_css = $this->css ?: '';
if ($webform_css) {
$css[] = $webform_css;
}
$css += $this->elementsCss;
$javascript = [];
$shared_javascript = \Drupal::config('webform.settings')
->get('assets.javascript') ?: '';
if ($shared_javascript) {
$javascript[] = $shared_javascript;
}
$webform_javascript = $this->javascript ?: '';
if ($webform_javascript) {
$javascript[] = $webform_javascript;
}
$javascript += $this->elementsJavaScript;
return [
'css' => implode(PHP_EOL, $css),
'javascript' => implode(PHP_EOL, $javascript),
];
}
public function getCss() {
return $this->css;
}
public function setCss($css) {
$this->css = $css;
return $this;
}
public function getJavaScript() {
return $this->javascript;
}
public function setJavaScript($javascript) {
$this->javascript = $javascript;
return $this;
}
public function getSettings() {
return isset($this->settings) ? $this->settings + static::getDefaultSettings() : static::getDefaultSettings();
}
public function setSettings(array $settings) {
$this->settings += static::getDefaultSettings();
foreach ($settings as $name => $value) {
if (array_key_exists($name, $this->settings)) {
$this->settings[$name] = $value;
}
}
return $this;
}
public function getSetting($key, $default = FALSE) {
$settings = $this
->getSettings();
$value = isset($settings[$key]) ? $settings[$key] : NULL;
if ($default) {
return $value ?: \Drupal::config('webform.settings')
->get('settings.default_' . $key);
}
else {
return $value;
}
}
public function setSetting($key, $value) {
$settings = $this
->getSettings();
$settings[$key] = $value;
$this
->setSettings($settings);
return $this;
}
public function resetSettings() {
$this->settings = $this->settingsOriginal;
$this
->setOverride(FALSE);
}
public function setSettingsOverride(array $settings) {
$this
->setSettings($settings);
$this
->setOverride();
return $this;
}
public function setSettingOverride($key, $value) {
$this
->setSetting($key, $value);
$this
->setOverride();
return $this;
}
public function setPropertyOverride($property_name, $value) {
$this
->set($property_name, $value);
$this
->setOverride();
return $this;
}
public function getAccessRules() {
return $this->access;
}
public function setAccessRules(array $access) {
$this->access = $access;
return $this;
}
public static function getDefaultSettings() {
return [
'ajax' => FALSE,
'ajax_scroll_top' => 'form',
'ajax_progress_type' => '',
'ajax_effect' => '',
'ajax_speed' => NULL,
'page' => TRUE,
'page_submit_path' => '',
'page_confirm_path' => '',
'page_theme_name' => '',
'form_title' => 'both',
'form_submit_once' => FALSE,
'form_exception_message' => '',
'form_open_message' => '',
'form_close_message' => '',
'form_previous_submissions' => TRUE,
'form_confidential' => FALSE,
'form_confidential_message' => '',
'form_disable_remote_addr' => FALSE,
'form_convert_anonymous' => FALSE,
'form_prepopulate' => FALSE,
'form_prepopulate_source_entity' => FALSE,
'form_prepopulate_source_entity_required' => FALSE,
'form_prepopulate_source_entity_type' => FALSE,
'form_reset' => FALSE,
'form_disable_autocomplete' => FALSE,
'form_novalidate' => FALSE,
'form_disable_inline_errors' => FALSE,
'form_required' => FALSE,
'form_unsaved' => FALSE,
'form_disable_back' => FALSE,
'form_submit_back' => FALSE,
'form_autofocus' => FALSE,
'form_details_toggle' => FALSE,
'form_access_denied' => WebformInterface::ACCESS_DENIED_DEFAULT,
'form_access_denied_title' => '',
'form_access_denied_message' => '',
'form_access_denied_attributes' => [],
'form_file_limit' => '',
'share' => FALSE,
'share_node' => FALSE,
'share_theme_name' => '',
'share_title' => TRUE,
'share_page_body_attributes' => [],
'submission_label' => '',
'submission_log' => FALSE,
'submission_views' => [],
'submission_views_replace' => [],
'submission_user_columns' => [],
'submission_user_duplicate' => FALSE,
'submission_access_denied' => WebformInterface::ACCESS_DENIED_DEFAULT,
'submission_access_denied_title' => '',
'submission_access_denied_message' => '',
'submission_access_denied_attributes' => [],
'submission_exception_message' => '',
'submission_locked_message' => '',
'submission_excluded_elements' => [],
'submission_exclude_empty' => FALSE,
'submission_exclude_empty_checkbox' => FALSE,
'previous_submission_message' => '',
'previous_submissions_message' => '',
'autofill' => FALSE,
'autofill_message' => '',
'autofill_excluded_elements' => [],
'wizard_progress_bar' => TRUE,
'wizard_progress_pages' => FALSE,
'wizard_progress_percentage' => FALSE,
'wizard_progress_link' => FALSE,
'wizard_progress_states' => FALSE,
'wizard_auto_forward' => TRUE,
'wizard_auto_forward_hide_next_button' => FALSE,
'wizard_keyboard' => TRUE,
'wizard_start_label' => '',
'wizard_preview_link' => FALSE,
'wizard_confirmation' => TRUE,
'wizard_confirmation_label' => '',
'wizard_track' => '',
'wizard_prev_button_label' => '',
'wizard_next_button_label' => '',
'wizard_toggle' => FALSE,
'wizard_toggle_show_label' => '',
'wizard_toggle_hide_label' => '',
'preview' => DRUPAL_DISABLED,
'preview_label' => '',
'preview_title' => '',
'preview_message' => '',
'preview_attributes' => [],
'preview_excluded_elements' => [],
'preview_exclude_empty' => TRUE,
'preview_exclude_empty_checkbox' => FALSE,
'draft' => WebformInterface::DRAFT_NONE,
'draft_multiple' => FALSE,
'draft_auto_save' => FALSE,
'draft_saved_message' => '',
'draft_loaded_message' => '',
'draft_pending_single_message' => '',
'draft_pending_multiple_message' => '',
'confirmation_type' => WebformInterface::CONFIRMATION_PAGE,
'confirmation_title' => '',
'confirmation_message' => '',
'confirmation_url' => '',
'confirmation_attributes' => [],
'confirmation_back' => TRUE,
'confirmation_back_label' => '',
'confirmation_back_attributes' => [],
'confirmation_exclude_query' => FALSE,
'confirmation_exclude_token' => FALSE,
'confirmation_update' => FALSE,
'limit_total' => NULL,
'limit_total_interval' => NULL,
'limit_total_message' => '',
'limit_total_unique' => FALSE,
'limit_user' => NULL,
'limit_user_interval' => NULL,
'limit_user_message' => '',
'limit_user_unique' => FALSE,
'entity_limit_total' => NULL,
'entity_limit_total_interval' => NULL,
'entity_limit_user' => NULL,
'entity_limit_user_interval' => NULL,
'purge' => WebformSubmissionStorageInterface::PURGE_NONE,
'purge_days' => NULL,
'results_disabled' => FALSE,
'results_disabled_ignore' => FALSE,
'results_customize' => FALSE,
'token_view' => FALSE,
'token_update' => FALSE,
'token_delete' => FALSE,
'serial_disabled' => FALSE,
];
}
public function getSubmissionForm(array $values = [], $operation = 'add') {
$webform_variant = \Drupal::request()->query
->get('_webform_variant') ?: [];
if ($webform_variant) {
$is_add_operation = $operation === 'add' && $this
->access('update');
$is_test_operation = $operation === 'test' && $this
->access('test');
$is_share_operation = strpos(\Drupal::routeMatch()
->getRouteName(), 'entity.webform.share_page') === 0;
if ($is_add_operation || $is_test_operation || $is_share_operation) {
$values += [
'data' => [],
];
$values['data'] = $webform_variant + $values['data'];
}
}
$values['webform_id'] = $this
->id();
$webform_submission = $this
->entityTypeManager()
->getStorage('webform_submission')
->create($values);
if ($this
->isOverridden()) {
$webform_submission->webform_id->entity = $this;
}
return \Drupal::service('entity.form_builder')
->getForm($webform_submission, $operation);
}
public function getElementsOriginalRaw() {
return $this->elementsOriginal;
}
public function getElementsOriginalDecoded() {
$this->elementsOriginal;
try {
$elements = WebformYaml::decode($this->elementsOriginal);
return is_array($elements) ? $elements : [];
} catch (\Exception $exception) {
return FALSE;
}
}
public function getElementsRaw() {
return $this->elements;
}
public function getElementsDecoded() {
$this
->initElements();
return $this->elementsDecoded;
}
public function getElementsInitialized() {
$this
->initElements();
return $this->elementsInitialized;
}
public function getElementsInitializedAndFlattened($operation = NULL) {
$this
->initElements();
return $this
->checkElementsFlattenedAccess($operation, $this->elementsInitializedAndFlattened);
}
public function getElementsDecodedAndFlattened($operation = NULL) {
$this
->initElements();
return $this
->checkElementsFlattenedAccess($operation, $this->elementsDecodedAndFlattened);
}
public function getElementsInitializedFlattenedAndHasValue($operation = NULL) {
$this
->initElements();
return $this
->checkElementsFlattenedAccess($operation, $this->elementsInitializedFlattenedAndHasValue);
}
public function getElementsManagedFiles() {
$this
->initElements();
return $this->elementsManagedFiles;
}
public function getElementsAttachments() {
$this
->initElements();
return $this->elementsAttachments;
}
public function getElementsComputed() {
$this
->initElements();
return $this->elementsComputed;
}
public function getElementsVariant() {
$this
->initElements();
return $this->elementsVariant;
}
protected function checkElementsFlattenedAccess($operation = NULL, array $elements = []) {
if ($operation === NULL) {
return $elements;
}
$element_manager = \Drupal::service('plugin.manager.webform.element');
foreach ($elements as $key => $element) {
$element_plugin = $element_manager
->getElementInstance($element, $this);
if (!$element_plugin
->checkAccessRules($operation, $element)) {
unset($elements[$key]);
}
}
return $elements;
}
public function getElementsSelectorOptions(array $options = []) {
$element_manager = \Drupal::service('plugin.manager.webform.element');
$options += [
'excluded_elements' => [
'value',
],
];
$selectors = [];
$elements = $this
->getElementsInitializedAndFlattened();
foreach ($elements as $element) {
$element_plugin = $element_manager
->getElementInstance($element, $this);
if ($options['excluded_elements'] && in_array($element_plugin
->getPluginId(), $options['excluded_elements'])) {
continue;
}
$element_selectors = $element_plugin
->getElementSelectorOptions($element);
foreach ($element_selectors as $element_selector_key => $element_selector_value) {
if (isset($selectors[$element_selector_key]) && is_array($element_selector_value)) {
while (isset($selectors[$element_selector_key])) {
$element_selector_key .= ' ';
}
$selectors[$element_selector_key] = $element_selector_value;
}
else {
$selectors[$element_selector_key] = $element_selector_value;
}
}
$selectors += $element_plugin
->getElementSelectorOptions($element);
}
return $selectors;
}
public function getElementsSelectorSourceValues() {
$element_manager = \Drupal::service('plugin.manager.webform.element');
$source_values = [];
$elements = $this
->getElementsInitializedAndFlattened();
foreach ($elements as $element) {
$element_plugin = $element_manager
->getElementInstance($element, $this);
$source_values += $element_plugin
->getElementSelectorSourceValues($element);
}
return $source_values;
}
public function getElementsPrepopulate() {
$this
->initElements();
return $this->elementsPrepopulate;
}
public function getElementsDefaultData() {
$this
->initElements();
return $this->elementsDefaultData;
}
public function setElements(array $elements) {
$this->elements = WebformYaml::encode($elements);
$this
->resetElements();
return $this;
}
protected function initElements() {
if (isset($this->elementsInitialized)) {
return;
}
$this->hasFlexboxLayout = FALSE;
$this->hasContainer = FALSE;
$this->hasConditions = FALSE;
$this->hasRequired = FALSE;
$this->elementsPrepopulate = [];
$this->elementsActions = [];
$this->elementsWizardPages = [];
$this->elementsDecodedAndFlattened = [];
$this->elementsInitializedAndFlattened = [];
$this->elementsInitializedFlattenedAndHasValue = [];
$this->elementsTranslations = [];
$this->elementsManagedFiles = [];
$this->elementsAttachments = [];
$this->elementsComputed = [];
$this->elementsVariant = [];
$this->elementsCss = [];
$this->elementsJavaScript = [];
$this->elementsDefaultData = [];
try {
$this
->initElementsTranslation();
$elements = WebformYaml::decode($this->elements);
$elements = is_array($elements) ? $elements : [];
$this->elementsDecoded = $elements;
} catch (\Exception $exception) {
$link = $this
->toLink($this
->t('Edit'), 'edit-form')
->toString();
\Drupal::logger('webform')
->notice('%title elements are not valid. @message', [
'%title' => $this
->label(),
'@message' => $exception
->getMessage(),
'link' => $link,
]);
$elements = FALSE;
}
if ($elements !== FALSE) {
$elements = WebformElementHelper::removeIgnoredProperties($elements);
$this
->initElementsRecursive($elements);
$this
->invokeHandlers('alterElements', $elements, $this);
}
$this->elementsInitialized = $elements;
}
protected function initElementsTranslation($elements_translated = FALSE) {
if (!\Drupal::moduleHandler()
->moduleExists('config_translation')) {
return;
}
if ($this->elementsTranslated) {
return;
}
if ($this->updating) {
return;
}
$current_langcode = \Drupal::languageManager()
->getCurrentLanguage()
->getId();
if ($this->langcode === $current_langcode) {
return;
}
$translation_manager = \Drupal::service('webform.translation_manager');
if ($translation_manager
->isAdminRoute()) {
$this->elements = WebformYaml::encode($translation_manager
->getElements($this));
return;
}
$elements = WebformYaml::decode($this->elements);
$elementsTranslations = $translation_manager
->getElements($this, $current_langcode);
if (empty($elementsTranslations) || $elementsTranslations === $elements) {
$elements = $translation_manager
->getElements($this);
$this->elements = WebformYaml::encode($elements);
}
$this->elementsTranslations = $elementsTranslations;
if ($elements_translated && $this->elementsTranslations) {
$this
->initElementsTranslationsRecursive($elements);
$this
->setElements($elements);
$this->elementsTranslations = [];
$this->elementsTranslated = TRUE;
}
}
protected function initElementsTranslationsRecursive(array &$elements) {
foreach ($elements as $key => &$element) {
if (!WebformElementHelper::isElement($element, $key)) {
continue;
}
if (isset($this->elementsTranslations[$key])) {
WebformElementHelper::applyTranslation($element, $this->elementsTranslations[$key]);
}
$this
->initElementsTranslationsRecursive($element);
}
}
protected function resetElements() {
$this->pages = NULL;
$this->hasFlexboxLayout = NULL;
$this->hasContainer = NULL;
$this->hasConditions = NULL;
$this->hasRequired = NULL;
$this->elementsPrepopulate = [];
$this->elementsActions = [];
$this->elementsWizardPages = [];
$this->elementsDecoded = NULL;
$this->elementsInitialized = NULL;
$this->elementsDecodedAndFlattened = NULL;
$this->elementsInitializedAndFlattened = NULL;
$this->elementsInitializedFlattenedAndHasValue = NULL;
$this->elementsTranslations = NULL;
$this->elementsManagedFiles = [];
$this->elementsAttachments = [];
$this->elementsComputed = [];
$this->elementsVariant = [];
$this->elementsCss = [];
$this->elementsJavaScript = [];
$this->elementsDefaultData = [];
}
protected function initElementsRecursive(array &$elements, $parent = '', $depth = 0) {
$element_manager = \Drupal::service('plugin.manager.webform.element');
foreach ($elements as $key => &$element) {
if (!WebformElementHelper::isElement($element, $key)) {
continue;
}
if (isset($this->elementsTranslations[$key])) {
WebformElementHelper::applyTranslation($element, $this->elementsTranslations[$key]);
}
if (isset($element['#type']) && strpos($element['#type'], 'webform_computed_') === 0) {
if (isset($element['#value']) && !isset($element['#template'])) {
$element['#template'] = $element['#value'];
unset($element['#value']);
}
}
$this->elementsDecodedAndFlattened[$key] = WebformElementHelper::getProperties($element);
$element['#webform'] = $this
->id();
$element['#webform_id'] = $this
->id() . '--' . $key;
$element['#webform_key'] = $key;
$element['#webform_parent_key'] = $parent;
$element['#webform_parent_flexbox'] = FALSE;
$element['#webform_depth'] = $depth;
$element['#webform_children'] = [];
$element['#webform_multiple'] = FALSE;
$element['#webform_composite'] = FALSE;
if (!empty($parent)) {
$parent_element =& $this->elementsInitializedAndFlattened[$parent];
$parent_element['#webform_children'][$key] = $key;
$element['#webform_parent_flexbox'] = isset($parent_element['#type']) && $parent_element['#type'] === 'webform_flexbox' ? TRUE : FALSE;
$element['#webform_parents'] = $parent_element['#webform_parents'];
}
$element['#webform_parents'][] = $key;
$element += [
'#title' => NULL,
'#admin_title' => NULL,
];
if (empty($element['#type']) && empty($element['#theme']) && isset($element['#markup'])) {
$element['#type'] = 'webform_markup';
}
$element_plugin = NULL;
if (isset($element['#type'])) {
$element_plugin = $element_manager
->getElementInstance($element, $this);
$element['#webform_plugin_id'] = $element_plugin
->getPluginId();
$element_plugin
->initialize($element);
if ($element['#type'] === 'flexbox' || $element['#type'] === 'webform_flexbox') {
$this->hasFlexboxLayout = TRUE;
}
if ($element_plugin
->isContainer($element)) {
$this->hasContainer = TRUE;
}
if (!empty($element['#states'])) {
$this->hasConditions = TRUE;
}
if (!empty($element['#required']) || !empty($element['#states']) && (!empty($element['#states']['required']) || !empty($element['#states']['optional']))) {
$this->hasRequired = TRUE;
}
if (!empty($element['#prepopulate']) && $element_plugin
->hasProperty('prepopulate')) {
$this->elementsPrepopulate[$key] = $key;
}
if ($element_plugin instanceof WebformActions) {
$this->elementsActions[$key] = $key;
}
if ($element_plugin instanceof WebformWizardPage) {
$this->elementsWizardPages[$key] = $key;
}
if ($element_plugin
->hasManagedFiles($element)) {
$this->elementsManagedFiles[$key] = $key;
}
if ($element_plugin instanceof WebformElementAttachmentInterface) {
$this->elementsAttachments[$key] = $key;
}
if ($element_plugin instanceof WebformElementComputedInterface) {
$this->elementsComputed[$key] = $key;
}
if ($element_plugin instanceof WebformElementVariantInterface) {
$this->elementsVariant[$key] = $key;
}
if ($element_plugin instanceof WebformElementAssetInterface) {
$asset_id = $element_plugin
->getAssetId();
if (!isset($this->elementsCss[$asset_id])) {
if ($css = $element_plugin
->getCss()) {
$this->elementsCss[$asset_id] = $css;
}
}
if (!isset($this->elementsJavaScript[$asset_id])) {
if ($javascript = $element_plugin
->getJavaScript()) {
$this->elementsJavaScript[$asset_id] = $javascript;
}
}
}
if (isset($element['#value'])) {
$this->elementsDefaultData[$key] = $element['#value'];
}
elseif (isset($element['#default_value'])) {
$this->elementsDefaultData[$key] = $element['#default_value'];
}
$element['#webform_multiple'] = $element_plugin
->hasMultipleValues($element);
$element['#webform_composite'] = $element_plugin
->isComposite();
}
$this->elementsInitializedAndFlattened[$key] = WebformElementHelper::getProperties($element);
if ($element_plugin && $element_plugin
->isInput($element)) {
$this->elementsInitializedFlattenedAndHasValue[$key] =& $this->elementsInitializedAndFlattened[$key];
}
$this
->initElementsRecursive($element, $key, $depth + 1);
}
}
public function getElement($key, $include_children = FALSE) {
$elements_flattened = $this
->getElementsInitializedAndFlattened();
$element = isset($elements_flattened[$key]) ? $elements_flattened[$key] : NULL;
if ($element && $include_children) {
$elements = $this
->getElementsInitialized();
return NestedArray::getValue($elements, $element['#webform_parents']);
}
else {
return $element;
}
}
public function getElementDecoded($key) {
$elements = $this
->getElementsDecodedAndFlattened();
return isset($elements[$key]) ? $elements[$key] : NULL;
}
public function getElementInitialized($key) {
$elements = $this
->getElementsInitializedAndFlattened();
return isset($elements[$key]) ? $elements[$key] : NULL;
}
public function setElementProperties($key, array $properties, $parent_key = '') {
$elements = $this
->getElementsDecoded();
if (!$this
->setElementPropertiesRecursive($elements, $key, $properties, $parent_key)) {
if ($this
->hasActions() && array_key_exists(end($this->elementsActions), $elements)) {
$last_action_key = end($this->elementsActions);
$updated_elements = [];
foreach ($elements as $element_key => $element) {
if ($element_key === $last_action_key) {
$updated_elements[$key] = $properties;
}
$updated_elements[$element_key] = $element;
}
$elements = $updated_elements;
}
else {
$elements[$key] = $properties;
}
}
$this
->setElements($elements);
return $this;
}
protected function setElementPropertiesRecursive(array &$elements, $key, array $properties, $parent_key = '') {
foreach ($elements as $element_key => &$element) {
$element_key = (string) $element_key;
if (!WebformElementHelper::isElement($element, $element_key)) {
continue;
}
if ($element_key === $key) {
$element = $properties + WebformElementHelper::removeProperties($element);
return TRUE;
}
if ($element_key === $parent_key) {
$element[$key] = $properties;
return TRUE;
}
if ($this
->setElementPropertiesRecursive($element, $key, $properties, $parent_key)) {
return TRUE;
}
}
return FALSE;
}
public function deleteElement($key) {
$element = $this
->getElementDecoded($key);
$elements = $this
->getElementsDecoded();
$sub_element_keys = $this
->deleteElementRecursive($elements, $key);
$this
->setElements($elements);
$is_variant = isset($element['#type']) && $element['#type'] === 'webform_variant';
if ($is_variant) {
$variants = $this
->getVariants(NULL, NULL, $key);
foreach ($variants as $variant) {
$this
->deleteWebformVariant($variant);
}
}
\Drupal::database()
->delete('webform_submission_data')
->condition('webform_id', $this
->id())
->condition('name', $sub_element_keys, 'IN')
->execute();
}
protected function deleteElementRecursive(array &$elements, $key) {
foreach ($elements as $element_key => &$element) {
$element_key = (string) $element_key;
if (!WebformElementHelper::isElement($element, $element_key)) {
continue;
}
if ($element_key === $key) {
$sub_element_keys = [
$element_key => $element_key,
];
$this
->collectSubElementKeysRecursive($sub_element_keys, $element);
unset($elements[$element_key]);
return $sub_element_keys;
}
if ($sub_element_keys = $this
->deleteElementRecursive($element, $key)) {
return $sub_element_keys;
}
}
return FALSE;
}
protected function collectSubElementKeysRecursive(array &$sub_element_keys, array $elements) {
foreach ($elements as $key => &$element) {
if (!WebformElementHelper::isElement($element, $key)) {
continue;
}
$sub_element_keys[$key] = $key;
$this
->collectSubElementKeysRecursive($sub_element_keys, $element);
}
}
public function getPages($operation = 'default', WebformSubmissionInterface $webform_submission = NULL) {
$pages = $this
->buildPages($operation);
if ($this
->getSetting('wizard_progress_states') && $webform_submission) {
$constraint_validator = \Drupal::service('webform_submission.conditions_validator');
$pages = $constraint_validator
->buildPages($pages, $webform_submission);
}
return $pages;
}
protected function buildPages($operation = 'default') {
if (isset($this->pages[$operation])) {
return $this->pages[$operation];
}
$element_manager = \Drupal::service('plugin.manager.webform.element');
$wizard_properties = [
'#title' => '#title',
'#prev_button_label' => '#prev_button_label',
'#next_button_label' => '#next_button_label',
'#states' => '#states',
];
$pages = [];
$elements = $this
->getElementsInitialized();
if (is_array($elements) && !in_array($operation, [
'edit_all',
'api',
])) {
foreach ($elements as $key => $element) {
if (!isset($element['#type'])) {
continue;
}
$element_plugin = $element_manager
->getElementInstance($element, $this);
if (!$element_plugin instanceof WebformElementWizardPageInterface) {
continue;
}
$access_operation = in_array($operation, [
'default',
'add',
]) ? 'create' : 'update';
if ($element_plugin
->checkAccessRules($access_operation, $element)) {
$pages[$key] = array_intersect_key($element, $wizard_properties) + [
'#type' => 'page',
'#access' => TRUE,
];
}
}
}
$settings = $this
->getSettings();
if ((int) $settings['preview'] !== DRUPAL_DISABLED) {
if (empty($pages)) {
$pages[WebformInterface::PAGE_START] = [
'#title' => $this
->getSetting('wizard_start_label', TRUE),
'#type' => 'page',
'#access' => TRUE,
];
}
$pages[WebformInterface::PAGE_PREVIEW] = [
'#title' => $this
->getSetting('preview_label', TRUE),
'#type' => 'page',
'#access' => TRUE,
];
}
if ($pages && $this
->getSetting('wizard_confirmation')) {
$pages[WebformInterface::PAGE_CONFIRMATION] = [
'#title' => $this
->getSetting('wizard_confirmation_label', TRUE),
'#type' => 'page',
'#access' => TRUE,
];
}
$this->pages[$operation] = $pages;
return $this->pages[$operation];
}
public function getPage($operation, $key) {
$pages = $this
->getPages($operation);
return isset($pages[$key]) ? $pages[$key] : NULL;
}
public function createDuplicate() {
$duplicate = parent::createDuplicate();
$duplicate
->setSetting('page_submit_path', '');
$duplicate
->setSetting('page_confirm_path', '');
$duplicate
->setOwnerId(\Drupal::currentUser()
->id());
$is_template_duplicate = \Drupal::request()
->get('template');
if ($duplicate
->isTemplate() && !$is_template_duplicate) {
$duplicate
->set('description', '');
$duplicate
->set('template', FALSE);
}
if ($duplicate
->isArchived()) {
$duplicate
->set('archive', FALSE);
}
$duplicate
->setStatus(\Drupal::config('webform.settings')
->get('settings.default_status'));
if (isset($duplicate->dependencies['enforced']['module'])) {
$modules = WebformReflectionHelper::getSubModules();
$duplicate->dependencies['enforced']['module'] = array_diff($duplicate->dependencies['enforced']['module'], $modules);
if (empty($duplicate->dependencies['enforced']['module'])) {
unset($duplicate->dependencies['enforced']['module']);
if (empty($duplicate->dependencies['enforced'])) {
unset($duplicate->dependencies['enforced']);
}
}
}
return $duplicate;
}
public static function preCreate(EntityStorageInterface $storage, array &$values) {
$access_rules_manager = \Drupal::service('webform.access_rules_manager');
$values += [
'status' => \Drupal::config('webform.settings')
->get('settings.default_status'),
'uid' => \Drupal::currentUser()
->id(),
'settings' => static::getDefaultSettings(),
'access' => $access_rules_manager
->getDefaultAccessRules(),
];
if ($values['status'] === TRUE) {
$values['status'] = WebformInterface::STATUS_OPEN;
}
elseif ($values['status'] === FALSE) {
$values['status'] = WebformInterface::STATUS_CLOSED;
}
elseif ($values['status'] === NULL) {
$values['status'] = WebformInterface::STATUS_SCHEDULED;
}
}
public static function postLoad(EntityStorageInterface $storage, array &$entities) {
foreach ($entities as $entity) {
$entity->elementsOriginal = $entity->elements;
$entity->settingsOriginal = $entity->settings;
}
}
public static function preDelete(EntityStorageInterface $storage, array $entities) {
parent::preDelete($storage, $entities);
$user_data = \Drupal::service('user.data');
foreach ($entities as $entity) {
$entity
->deletePaths();
\Drupal::state()
->delete('webform.webform.' . $entity
->id());
$user_data
->delete('webform', NULL, $entity
->id());
}
$submission_ids = \Drupal::entityQuery('webform_submission')
->accessCheck(FALSE)
->condition('webform_id', array_keys($entities), 'IN')
->sort('sid')
->execute();
$submission_storage = \Drupal::entityTypeManager()
->getStorage('webform_submission');
$submissions = $submission_storage
->loadMultiple($submission_ids);
$submission_storage
->delete($submissions);
}
public function getCacheTags() {
$cache_tags = parent::getCacheTags();
$cache_tags[] = 'webform:' . $this
->id();
$cache_tags[] = 'config:webform.settings';
return $cache_tags;
}
public function getCacheContexts() {
$cache_contexts = parent::getCacheContexts();
if ($this
->getSetting('form_prepopulate')) {
$cache_contexts[] = 'url.query_args';
}
else {
if ($this
->getSetting('form_prepopulate_source_entity')) {
$cache_contexts[] = 'url.query_args:source_entity_type';
$cache_contexts[] = 'url.query_args:source_entity_id';
}
if ($this
->getSetting('token_view') || $this
->getSetting('token_update') || $this
->getSetting('token_delete')) {
$cache_contexts[] = 'url.query_args:token';
}
}
return $cache_contexts;
}
public function getCacheMaxAge() {
if ($this
->isScheduled()) {
$time = time();
if ($this->open && strtotime($this->open) > $time) {
return strtotime($this->open) - $time;
}
elseif ($this->close && strtotime($this->close) > $time) {
return strtotime($this->close) - $time;
}
}
return parent::getCacheMaxAge();
}
public function preSave(EntityStorageInterface $storage) {
if ($this
->isOverridden()) {
throw new WebformException(sprintf('The %s webform [%s] has overridden settings and/or properties and can not be saved.', $this
->label(), $this
->id()));
}
if ($this
->isTemplate()) {
$this
->setStatus(WebformInterface::STATUS_CLOSED);
}
if (is_array($this->elements)) {
$this->elements = Yaml::encode($this->elements);
}
parent::preSave($storage);
}
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
$this
->invalidateTagsOnSave($update);
$entity_type_manager = $this
->entityTypeManager();
$bundle_of = $this
->getEntityType()
->getBundleOf();
if (!$update) {
\Drupal::service('entity_bundle.listener')
->onBundleCreate($this
->id(), $bundle_of);
}
else {
if ($entity_type_manager
->hasHandler($bundle_of, 'view_builder')) {
$entity_type_manager
->getViewBuilder($bundle_of)
->resetCache();
}
$this
->entityTypeBundleInfo()
->clearCachedBundles();
}
$this
->updatePaths();
$elements_original = $this
->getElementsOriginalDecoded() ?: [];
$elements = $this
->getElementsDecoded() ?: [];
if ($elements_original !== $elements) {
$elements_original = WebformElementHelper::getFlattened($elements_original);
$elements = WebformElementHelper::getFlattened($elements);
$created_elements = array_diff_key($elements, $elements_original) ?: [];
foreach ($created_elements as $element_key => $element) {
$this
->invokeHandlers('createElement', $element_key, $element);
}
$deleted_elements = array_diff_key($elements_original, $elements) ?: [];
foreach ($deleted_elements as $element_key => $element) {
$this
->invokeHandlers('deleteElement', $element_key, $element);
}
foreach ($elements as $element_key => $element) {
if (isset($elements_original[$element_key]) && $elements_original[$element_key] !== $element) {
$this
->invokeHandlers('updateElement', $element_key, $element, $elements_original[$element_key]);
}
}
$element_manager = \Drupal::service('plugin.manager.webform.element');
$checked_elements = $created_elements + $deleted_elements;
foreach ($checked_elements as $element_key => $element) {
$element_plugin = $element_manager
->getElementInstance($element, $this);
if ($element_plugin instanceof WebformElementAssetInterface && $element_plugin
->hasAssets()) {
Cache::invalidateTags([
'library_info',
]);
break;
}
}
}
$this
->resetElements();
$this->elementsOriginal = $this->elements;
$this->settingsOriginal = $this->settings;
$this
->setUpdating(FALSE);
}
public function updatePaths() {
if (!\Drupal::moduleHandler()
->moduleExists('path')) {
return;
}
if (empty($this
->getSetting('page'))) {
$this
->deletePaths();
return;
}
$page_submit_path = $this
->getSetting('page_submit_path');
$default_page_base_path = \Drupal::config('webform.settings')
->get('settings.default_page_base_path');
if (empty($page_submit_path) && empty($default_page_base_path)) {
return;
}
$path_base_alias = $page_submit_path ?: $default_page_base_path . '/' . str_replace('_', '-', $this
->id());
$path_suffixes = [
'',
'/confirmation',
'/submissions',
'/drafts',
];
foreach ($path_suffixes as $path_suffix) {
$path_source = '/webform/' . $this
->id() . $path_suffix;
$path_alias = $path_base_alias . $path_suffix;
if ($path_suffix === '/confirmation' && $this
->getSetting('page_confirm_path')) {
$path_alias = $this
->getSetting('page_confirm_path');
}
$this
->updatePath($path_source, $path_alias, $this->langcode);
$this
->updatePath($path_source, $path_alias, LanguageInterface::LANGCODE_NOT_SPECIFIED);
}
}
public function deletePaths() {
if (!\Drupal::moduleHandler()
->moduleExists('path')) {
return;
}
$path_alias_storage = \Drupal::entityTypeManager()
->getStorage('path_alias');
$query = $path_alias_storage
->getQuery('OR');
$path_suffixes = [
'',
'/confirmation',
'/submissions',
'/drafts',
];
foreach ($path_suffixes as $path_suffix) {
$query
->condition('path', '/webform/' . $this
->id() . $path_suffix);
}
if ($ids = $query
->execute()) {
$path_alias_storage
->delete($path_alias_storage
->loadMultiple($ids));
}
}
protected function updatePath($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED) {
$path_alias_storage = \Drupal::entityTypeManager()
->getStorage('path_alias');
$path_aliases = $path_alias_storage
->loadByProperties([
'path' => $source,
'langcode' => $langcode,
]);
if ($path_aliases) {
$path_alias = reset($path_aliases);
if ($path_alias
->getAlias() === $alias) {
return;
}
}
else {
$path_alias = $path_alias_storage
->create([
'path' => $source,
'langcode' => $langcode,
]);
}
$path_alias
->setAlias($alias);
$path_alias
->save();
}
public function getPluginCollections() {
return [
'handlers' => $this
->getHandlers(),
'variants' => $this
->getVariants(),
];
}
protected function getWebformHandlerPluginManager() {
return \Drupal::service('plugin.manager.webform.handler');
}
protected function resetHandlers() {
$this->hasMessageHandler = NULL;
$this->hasAnonymousSubmissionTrackingHandler = NULL;
}
public function hasMessageHandler() {
if (isset($this->hasMessagehandler)) {
$this->hasMessagehandler;
}
$this->hasMessagehandler = FALSE;
$handlers = $this
->getHandlers();
foreach ($handlers as $handler) {
if ($handler instanceof WebformHandlerMessageInterface) {
$this->hasMessagehandler = TRUE;
break;
}
}
return $this->hasMessagehandler;
}
public function hasAnonymousSubmissionTrackingHandler() {
if (isset($this->hasAnonymousSubmissionTrackingHandler)) {
$this->hasAnonymousSubmissionTrackingHandler;
}
$this->hasAnonymousSubmissionTrackingHandler = FALSE;
$handlers = $this
->getHandlers();
foreach ($handlers as $handler) {
if ($handler
->hasAnonymousSubmissionTracking()) {
$this->hasAnonymousSubmissionTrackingHandler = TRUE;
break;
}
}
return $this->hasAnonymousSubmissionTrackingHandler;
}
public function getHandler($handler_id) {
return $this
->getHandlers()
->get($handler_id);
}
public function getHandlers($plugin_id = NULL, $status = NULL, $results = NULL, $submission = NULL) {
if (!$this->handlersCollection) {
$this->handlersCollection = new WebformHandlerPluginCollection($this
->getWebformHandlerPluginManager(), $this->handlers);
foreach ($this->handlersCollection as $handler) {
$handler
->setWebform($this);
}
$this->handlersCollection
->sort();
}
$handlers = $this->handlersCollection;
if (isset($plugin_id) || isset($status) || isset($results)) {
$handlers = clone $this->handlersCollection;
}
if (isset($plugin_id)) {
foreach ($handlers as $instance_id => $handler) {
if ($handler
->getPluginId() !== $plugin_id) {
$handlers
->removeInstanceId($instance_id);
}
}
}
if (isset($status)) {
foreach ($handlers as $instance_id => $handler) {
if ($handler
->getStatus() !== $status) {
$handlers
->removeInstanceId($instance_id);
}
}
}
if (isset($results)) {
foreach ($handlers as $instance_id => $handler) {
$plugin_definition = $handler
->getPluginDefinition();
if ($plugin_definition['results'] !== $results) {
$handlers
->removeInstanceId($instance_id);
}
}
}
if (isset($submission)) {
foreach ($handlers as $instance_id => $handler) {
$plugin_definition = $handler
->getPluginDefinition();
if ($plugin_definition['submission'] !== $submission) {
$handlers
->removeInstanceId($instance_id);
}
}
}
return $handlers;
}
public function addWebformHandler(WebformHandlerInterface $handler) {
$handler
->setWebform($this);
$handler_id = $handler
->getHandlerId();
$configuration = $handler
->getConfiguration();
$this
->getHandlers()
->addInstanceId($handler_id, $configuration);
$this
->save();
$this
->resetHandlers();
$handler
->createHandler();
return $this;
}
public function updateWebformHandler(WebformHandlerInterface $handler) {
$handler
->setWebform($this);
$handler_id = $handler
->getHandlerId();
$configuration = $handler
->getConfiguration();
$this
->getHandlers()
->setInstanceConfiguration($handler_id, $configuration);
$this
->save();
$this
->resetHandlers();
$handler
->updateHandler();
return $this;
}
public function deleteWebformHandler(WebformHandlerInterface $handler) {
$handler
->setWebform($this);
$this
->getHandlers()
->removeInstanceId($handler
->getHandlerId());
$handler
->deleteHandler();
$this
->save();
$this
->resetHandlers();
return $this;
}
public function invokeHandlers($method, &$data, &$context1 = NULL, &$context2 = NULL, &$context3 = NULL) {
$webform_submission = NULL;
$args = func_get_args();
foreach ($args as $arg) {
if ($arg instanceof WebformSubmissionInterface) {
$webform_submission = $arg;
break;
}
}
$handlers = $this
->getHandlers();
switch ($method) {
case 'overrideSettings':
$this
->resetSettings();
$settings = $this
->getSettings();
foreach ($handlers as $handler) {
$handler
->setWebformSubmission($webform_submission);
$this
->invokeHandlerAlter($handler, $method, $args);
if ($this
->isHandlerEnabled($handler, $webform_submission)) {
$handler
->overrideSettings($settings, $webform_submission);
}
}
if (array_intersect_key($settings, $this->settingsOriginal) !== $this->settingsOriginal) {
$this
->setSettingsOverride($settings);
}
return NULL;
case 'access':
case 'accessElement':
$result = AccessResult::neutral();
foreach ($handlers as $handler) {
$handler
->setWebformSubmission($webform_submission);
$this
->invokeHandlerAlter($handler, $method, $args);
if ($this
->isHandlerEnabled($handler, $webform_submission)) {
$result = $result
->orIf($handler
->{$method}($data, $context1, $context2));
}
}
return $result;
default:
foreach ($handlers as $handler) {
$handler
->setWebformSubmission($webform_submission);
$this
->invokeHandlerAlter($handler, $method, $args);
if ($this
->isHandlerEnabled($handler, $webform_submission)) {
$handler
->{$method}($data, $context1, $context2);
}
}
return NULL;
}
}
protected function isHandlerEnabled(WebformHandlerInterface $handler, WebformSubmissionInterface $webform_submission = NULL) {
if ($handler
->isDisabled()) {
return FALSE;
}
elseif ($webform_submission && !$handler
->checkConditions($webform_submission)) {
return FALSE;
}
else {
return TRUE;
}
}
protected function invokeHandlerAlter(WebformHandlerInterface $handler, $method_name, array $args) {
$method_name = WebformTextHelper::camelToSnake($method_name);
\Drupal::moduleHandler()
->alter('webform_handler_invoke', $handler, $method_name, $args);
\Drupal::moduleHandler()
->alter('webform_handler_invoke_' . $method_name, $handler, $args);
}
public function invokeElements($method, &$data, &$context1 = NULL, &$context2 = NULL) {
$element_manager = \Drupal::service('plugin.manager.webform.element');
$elements = $this
->getElementsInitializedAndFlattened();
foreach ($elements as $element) {
$element_manager
->invokeMethod($method, $element, $data, $context1, $context2);
}
}
protected function getWebformVariantPluginManager() {
return \Drupal::service('plugin.manager.webform.variant');
}
public function hasVariant($variant_id) {
return $this
->getVariants()
->has($variant_id);
}
public function getVariant($variant_id) {
return $this
->getVariants()
->get($variant_id);
}
public function getVariants($plugin_id = NULL, $status = NULL, $element_key = NULL) {
if (!$this->variantsCollection) {
$this->variantsCollection = new WebformVariantPluginCollection($this
->getWebformVariantPluginManager(), $this->variants);
foreach ($this->variantsCollection as $variant) {
$variant
->setWebform($this);
}
$this->variantsCollection
->sort();
}
$variants = $this->variantsCollection;
if (isset($plugin_id) || isset($status) || isset($element_key)) {
$variants = clone $this->variantsCollection;
}
if (isset($plugin_id)) {
foreach ($variants as $instance_id => $variant) {
if ($variant
->getPluginId() !== $plugin_id) {
$variants
->removeInstanceId($instance_id);
}
}
}
if (isset($status)) {
foreach ($variants as $instance_id => $variant) {
if ($variant
->getStatus() !== $status) {
$variants
->removeInstanceId($instance_id);
}
}
}
if (isset($element_key)) {
foreach ($variants as $instance_id => $variant) {
if ($variant
->getElementKey() !== $element_key) {
$variants
->removeInstanceId($instance_id);
}
}
}
return $variants;
}
public function addWebformVariant(WebformVariantInterface $variant) {
$variant
->setWebform($this);
$variant_id = $variant
->getVariantId();
$configuration = $variant
->getConfiguration();
$this
->getVariants()
->addInstanceId($variant_id, $configuration);
$this
->save();
return $this;
}
public function updateWebformVariant(WebformVariantInterface $variant) {
$variant
->setWebform($this);
$variant_id = $variant
->getVariantId();
$configuration = $variant
->getConfiguration();
$this
->getVariants()
->setInstanceConfiguration($variant_id, $configuration);
$this
->save();
return $this;
}
public function deleteWebformVariant(WebformVariantInterface $variant) {
$variant
->setWebform($this);
$this
->getVariants()
->removeInstanceId($variant
->getVariantId());
$this
->save();
return $this;
}
public function applyVariants(WebformSubmissionInterface $webform_submission = NULL, array $variants = [], $force = FALSE) {
if ($webform_submission) {
if ($webform_submission
->getWebform()
->id() !== $this
->id()) {
$t_args = [
'@sid' => $webform_submission
->id(),
'@webform_id' => $this
->id(),
];
throw new \Exception($this
->t('Variants can not be applied because the #@sid submission was not created using @webform_id', $t_args));
}
$variants += $this
->getVariantsData($webform_submission);
}
if (empty($variants)) {
return;
}
$this
->initElementsTranslation(TRUE);
$is_applied = FALSE;
$variant_element_keys = $this
->getElementsVariant();
foreach ($variant_element_keys as $variant_element_key) {
if (!empty($variants[$variant_element_key])) {
$instance_id = $variants[$variant_element_key];
if ($this
->applyVariant($variant_element_key, $instance_id, $force)) {
$is_applied = TRUE;
}
}
}
if ($is_applied) {
$this
->setOverride();
}
}
public function getVariantsData(WebformSubmissionInterface $webform_submission) {
$variants = [];
$element_keys = $this
->getElementsVariant();
foreach ($element_keys as $element_key) {
$variants[$element_key] = $webform_submission
->getElementData($element_key);
}
return $variants;
}
public function applyVariant($element_key, $instance_id, $force = FALSE) {
$element = $this
->getElement($element_key);
if (!$this
->getVariants()
->has($instance_id)) {
$t_args = [
'@title' => $element['#title'],
'@key' => $element_key,
'@instance_id' => $instance_id,
];
\Drupal::logger('webform')
->warning("The '@instance_id' variant id is missing for the '@title (@key)' variant type. <strong>No variant settings have been applied.</strong>", $t_args);
if (\Drupal::currentUser()
->hasPermission('edit webform variants')) {
\Drupal::messenger()
->addWarning($this
->t("The '@instance_id' variant id is missing for the '@title (@key)' variant type. <strong>No variant settings have been applied.</strong>", $t_args));
}
return FALSE;
}
$variant_plugin_id = $element['#variant'];
$variant_plugin = $this
->getVariant($instance_id);
if ($variant_plugin_id !== $variant_plugin
->getPluginId()) {
return FALSE;
}
if (empty($force) && $variant_plugin
->isDisabled()) {
return FALSE;
}
return $variant_plugin
->applyVariant();
}
public function url($rel = 'canonical', $options = []) {
return parent::url($rel, $options);
}
public function toUrl($rel = 'canonical', array $options = []) {
return parent::toUrl($rel, $options);
}
public function urlInfo($rel = 'canonical', array $options = []) {
return parent::urlInfo($rel, $options);
}
public function toLink($text = NULL, $rel = 'canonical', array $options = []) {
return parent::toLink($text, $rel, $options);
}
public function link($text = NULL, $rel = 'canonical', array $options = []) {
return parent::link($text, $rel, $options);
}
public function isDefaultRevision() {
return TRUE;
}
public function getState($key, $default = NULL) {
$namespace = 'webform.webform.' . $this
->id();
$values = \Drupal::state()
->get($namespace, []);
return isset($values[$key]) ? $values[$key] : $default;
}
public function setState($key, $value) {
$namespace = 'webform.webform.' . $this
->id();
$values = \Drupal::state()
->get($namespace, []);
$values[$key] = $value;
\Drupal::state()
->set($namespace, $values);
}
public function deleteState($key) {
$namespace = 'webform.webform.' . $this
->id();
$values = \Drupal::state()
->get($namespace, []);
unset($values[$key]);
\Drupal::state()
->set($namespace, $values);
}
public function hasState($key) {
$namespace = 'webform.webform.' . $this
->id();
$values = \Drupal::state()
->get($namespace, []);
return isset($values[$key]) ? TRUE : FALSE;
}
public function getUserData($key, $default = NULL) {
$account = \Drupal::currentUser();
$user_data = \Drupal::service('user.data');
$values = $user_data
->get('webform', $account
->id(), $this
->id());
return isset($values[$key]) ? $values[$key] : $default;
}
public function setUserData($key, $value) {
$account = \Drupal::currentUser();
$user_data = \Drupal::service('user.data');
$values = $user_data
->get('webform', $account
->id(), $this
->id()) ?: [];
$values[$key] = $value;
$user_data
->set('webform', $account
->id(), $this
->id(), $values);
}
public function deleteUserData($key) {
$account = \Drupal::currentUser();
$user_data = \Drupal::service('user.data');
$values = $user_data
->get('webform', $account
->id(), $this
->id()) ?: [];
unset($values[$key]);
$user_data
->set('webform', $account
->id(), $this
->id(), $values);
}
public function hasUserData($key) {
$account = \Drupal::currentUser();
$user_data = \Drupal::service('user.data');
$values = $user_data
->get('webform', $account
->id(), $this
->id()) ?: [];
return isset($values[$key]) ? TRUE : FALSE;
}
public function unsetThirdPartySettings($module) {
unset($this->third_party_settings[$module]);
}
public function onDependencyRemoval(array $dependencies) {
$changed = parent::onDependencyRemoval($dependencies);
$handlers = $this
->getHandlers();
if (!empty($handlers)) {
foreach ($handlers as $handler) {
$plugin_definition = $handler
->getPluginDefinition();
$provider = $plugin_definition['provider'];
if (in_array($provider, $dependencies['module'])) {
$handler
->setWebform($this);
$this
->getHandlers()
->removeInstanceId($handler
->getHandlerId());
$changed = TRUE;
}
}
}
$variants = $this
->getVariants();
if (!empty($variants)) {
foreach ($variants as $variant) {
$plugin_definition = $variant
->getPluginDefinition();
$provider = $plugin_definition['provider'];
if (in_array($provider, $dependencies['module'])) {
$variant
->setWebform($this);
$this
->getVariants()
->removeInstanceId($variant
->getVariantId());
$changed = TRUE;
}
}
}
return $changed;
}
public static function sort(ConfigEntityInterface $a, ConfigEntityInterface $b) {
$a_label = $a
->get('category') . $a
->label();
$b_label = $b
->get('category') . $b
->label();
return strnatcasecmp($a_label, $b_label);
}
public function getIterator() {
return new \ArrayIterator([]);
}
public function __toString() {
return '';
}
}