Spaces:
No application file
No application file
File size: 35,958 Bytes
d2897cd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 |
<?php
namespace Mautic\FormBundle\Model;
use Doctrine\ORM\EntityManagerInterface;
use Mautic\CoreBundle\Doctrine\Helper\ColumnSchemaHelper;
use Mautic\CoreBundle\Doctrine\Helper\TableSchemaHelper;
use Mautic\CoreBundle\Helper\Chart\ChartQuery;
use Mautic\CoreBundle\Helper\CoreParametersHelper;
use Mautic\CoreBundle\Helper\ThemeHelperInterface;
use Mautic\CoreBundle\Helper\UserHelper;
use Mautic\CoreBundle\Model\FormModel as CommonFormModel;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\CoreBundle\Translation\Translator;
use Mautic\FormBundle\Collector\MappedObjectCollectorInterface;
use Mautic\FormBundle\Entity\Action;
use Mautic\FormBundle\Entity\Field;
use Mautic\FormBundle\Entity\Form;
use Mautic\FormBundle\Entity\FormRepository;
use Mautic\FormBundle\Event\FormBuilderEvent;
use Mautic\FormBundle\Event\FormEvent;
use Mautic\FormBundle\Form\Type\FormType;
use Mautic\FormBundle\FormEvents;
use Mautic\FormBundle\Helper\FormFieldHelper;
use Mautic\FormBundle\Helper\FormUploader;
use Mautic\FormBundle\ProgressiveProfiling\DisplayManager;
use Mautic\LeadBundle\Entity\Lead;
use Mautic\LeadBundle\Helper\FormFieldHelper as ContactFieldHelper;
use Mautic\LeadBundle\Helper\PrimaryCompanyHelper;
use Mautic\LeadBundle\Model\FieldModel as LeadFieldModel;
use Mautic\LeadBundle\Tracker\ContactTracker;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\EventDispatcher\Event;
use Twig\Environment;
/**
* @extends CommonFormModel<Form>
*/
class FormModel extends CommonFormModel
{
public function __construct(
protected RequestStack $requestStack,
protected Environment $twig,
protected ThemeHelperInterface $themeHelper,
protected ActionModel $formActionModel,
protected FieldModel $formFieldModel,
protected FormFieldHelper $fieldHelper,
private PrimaryCompanyHelper $primaryCompanyHelper,
protected LeadFieldModel $leadFieldModel,
private FormUploader $formUploader,
private ContactTracker $contactTracker,
private ColumnSchemaHelper $columnSchemaHelper,
private TableSchemaHelper $tableSchemaHelper,
private MappedObjectCollectorInterface $mappedObjectCollector,
EntityManagerInterface $em,
CorePermissions $security,
EventDispatcherInterface $dispatcher,
UrlGeneratorInterface $router,
Translator $translator,
UserHelper $userHelper,
LoggerInterface $mauticLogger,
CoreParametersHelper $coreParametersHelper
) {
parent::__construct($em, $security, $dispatcher, $router, $translator, $userHelper, $mauticLogger, $coreParametersHelper);
}
/**
* @return FormRepository
*/
public function getRepository()
{
return $this->em->getRepository(Form::class);
}
public function getPermissionBase(): string
{
return 'form:forms';
}
public function getNameGetter(): string
{
return 'getName';
}
public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): \Symfony\Component\Form\FormInterface
{
if (!$entity instanceof Form) {
throw new MethodNotAllowedHttpException(['Form']);
}
if (!empty($action)) {
$options['action'] = $action;
}
return $formFactory->create(FormType::class, $entity, $options);
}
/**
* @param string|int|null $id
*/
public function getEntity($id = null): ?Form
{
if (null === $id) {
return new Form();
}
$entity = parent::getEntity($id);
if ($entity && $entity->getFields()) {
foreach ($entity->getFields() as $field) {
$this->addMappedFieldOptions($field);
}
}
return $entity;
}
/**
* @throws MethodNotAllowedHttpException
*/
protected function dispatchEvent($action, &$entity, $isNew = false, Event $event = null): ?Event
{
if (!$entity instanceof Form) {
throw new MethodNotAllowedHttpException(['Form']);
}
switch ($action) {
case 'pre_save':
$name = FormEvents::FORM_PRE_SAVE;
break;
case 'post_save':
$name = FormEvents::FORM_POST_SAVE;
break;
case 'pre_delete':
$name = FormEvents::FORM_PRE_DELETE;
break;
case 'post_delete':
$name = FormEvents::FORM_POST_DELETE;
break;
default:
return null;
}
if ($this->dispatcher->hasListeners($name)) {
if (empty($event)) {
$event = new FormEvent($entity, $isNew);
$event->setEntityManager($this->em);
}
$this->dispatcher->dispatch($event, $name);
return $event;
} else {
return null;
}
}
public function setFields(Form $entity, $sessionFields): void
{
$order = 1;
$existingFields = $entity->getFields()->toArray();
$formName = $entity->generateFormName();
foreach ($sessionFields as $key => $properties) {
$isNew = (!empty($properties['id']) && isset($existingFields[$properties['id']])) ? false : true;
$field = !$isNew ? $existingFields[$properties['id']] : new Field();
if (!$isNew) {
if (empty($properties['alias'])) {
$properties['alias'] = $field->getAlias();
}
if (empty($properties['label'])) {
$properties['label'] = $field->getLabel();
}
}
if ($formName === $properties['alias']) {
// Change the alias to prevent potential ID collisions in the rendered HTML
$properties['alias'] = 'f_'.$properties['alias'];
}
foreach ($properties as $f => $v) {
if (in_array($f, ['id', 'order'])) {
continue;
}
$func = 'set'.ucfirst($f);
if (method_exists($field, $func)) {
$field->$func($v);
}
}
$field->setForm($entity);
$field->setSessionId($key);
if (!$field->getParent()) {
$field->setOrder($order);
++$order;
} else {
if (isset($sessionFields[$field->getParent()]['order'])) {
$field->setOrder($sessionFields[$field->getParent()]['order']);
} else {
$field->setOrder($order);
}
}
$entity->addField($properties['id'], $field);
}
// Persist if the entity is known
if ($entity->getId()) {
$this->formFieldModel->saveEntities($existingFields);
}
}
public function deleteFields(Form $entity, $sessionFields): void
{
if (empty($sessionFields)) {
return;
}
$existingFields = $entity->getFields()->toArray();
$deleteFields = [];
foreach ($sessionFields as $fieldId) {
if (!isset($existingFields[$fieldId])) {
continue;
}
$this->handleFilesDelete($existingFields[$fieldId]);
$entity->removeField($fieldId, $existingFields[$fieldId]);
$deleteFields[] = $fieldId;
}
// Delete fields from db
if (count($deleteFields)) {
$this->formFieldModel->deleteEntities($deleteFields);
}
}
private function handleFilesDelete(Field $field): void
{
if (!$field->isFileType()) {
return;
}
$this->formUploader->deleteAllFilesOfFormField($field);
}
public function setActions(Form $entity, $sessionActions): void
{
$order = 1;
$existingActions = $entity->getActions()->toArray();
$savedFields = $entity->getFields()->toArray();
// match sessionId with field Id to update mapped fields
$fieldIds = [];
foreach ($savedFields as $field) {
$fieldIds[$field->getSessionId()] = $field->getId();
}
foreach ($sessionActions as $properties) {
$isNew = (!empty($properties['id']) && isset($existingActions[$properties['id']])) ? false : true;
$action = !$isNew ? $existingActions[$properties['id']] : new Action();
foreach ($properties as $f => $v) {
if (in_array($f, ['id', 'order'])) {
continue;
}
$func = 'set'.ucfirst($f);
if ('properties' == $f) {
if (isset($v['mappedFields'])) {
foreach ($v['mappedFields'] as $pk => $pv) {
if (str_contains($pv, 'new')) {
$v['mappedFields'][$pk] = $fieldIds[$pv];
}
}
}
}
if (method_exists($action, $func)) {
$action->$func($v);
}
}
$action->setForm($entity);
$action->setOrder($order);
++$order;
$entity->addAction($properties['id'], $action);
}
// Persist if form is being edited
if ($entity->getId()) {
$this->formActionModel->saveEntities($existingActions);
}
}
/**
* @param array $actions
*/
public function deleteActions(Form $entity, $actions): void
{
if (empty($actions)) {
return;
}
$existingActions = $entity->getActions()->toArray();
$deleteActions = [];
foreach ($actions as $actionId) {
if (isset($existingActions[$actionId])) {
$actionEntity = $this->em->getReference(Action::class, (int) $actionId);
$entity->removeAction($actionEntity);
$deleteActions[] = $actionId;
}
}
// Delete actions from db
if (count($deleteActions)) {
$this->formActionModel->deleteEntities($deleteActions);
}
}
public function saveEntity($entity, $unlock = true): void
{
$isNew = ($entity->getId()) ? false : true;
if ($isNew && !$entity->getAlias()) {
$alias = $this->cleanAlias($entity->getName(), '', 10);
$entity->setAlias($alias);
}
$this->backfillReplacedPropertiesForBc($entity);
// save the form so that the ID is available for the form html
parent::saveEntity($entity, $unlock);
// now build the form table
if ($entity->getId()) {
$this->createTableSchema($entity, $isNew);
}
$this->generateHtml($entity);
}
/**
* Obtains the content.
*
* @param bool|true $withScript
* @param bool|true $useCache
*/
public function getContent(Form $form, $withScript = true, $useCache = true): string
{
$html = $this->getFormHtml($form, $useCache);
if ($withScript) {
$html = $this->getFormScript($form)."\n\n".$this->removeScriptTag($html);
} else {
$html = $this->removeScriptTag($html);
}
return $html;
}
/**
* Obtains the cached HTML of a form and generates it if missing.
*
* @param bool|true $useCache
*
* @return string
*/
public function getFormHtml(Form $form, $useCache = true)
{
if ($useCache && !$form->usesProgressiveProfiling()) {
$cachedHtml = $form->getCachedHtml();
}
if (empty($cachedHtml)) {
$cachedHtml = $this->generateHtml($form, $useCache);
}
if (!$form->getInKioskMode()) {
$this->populateValuesWithLead($form, $cachedHtml);
}
return $cachedHtml;
}
/**
* Get results for a form and lead.
*
* @param int $leadId
* @param int $limit
*/
public function getLeadSubmissions(Form $form, $leadId, $limit = 200): array
{
return $this->getRepository()->getFormResults(
$form,
[
'leadId' => $leadId,
'limit' => $limit,
]
);
}
/**
* Generate the form's html.
*
* @param bool $persist
*/
public function generateHtml(Form $entity, $persist = true): string
{
// Use specific template or system-wide default theme
$theme = $entity->getTemplate() ?? $this->coreParametersHelper->get('theme');
$submissions = null;
$lead = ($this->requestStack->getCurrentRequest()) ? $this->contactTracker->getContact() : null;
$style = '';
$styleToRender = '@MauticForm/Builder/_style.html.twig';
$formToRender = '@MauticForm/Builder/form.html.twig';
if ($this->twig->getLoader()->exists('@themes/'.$theme.'/html/MauticFormBundle/Builder/_style.html.twig')) {
$styleToRender = '@themes/'.$theme.'/html/MauticFormBundle/Builder/_style.html.twig';
}
if ($this->twig->getLoader()->exists('@themes/'.$theme.'/html/MauticFormBundle/Builder/form.html.twig')) {
$formToRender = '@themes/'.$theme.'/html/MauticFormBundle/Builder/form.html.twig';
}
if ($lead instanceof Lead && $lead->getId() && $entity->usesProgressiveProfiling()) {
$submissions = $this->getLeadSubmissions($entity, $lead->getId());
}
if ($entity->getRenderStyle()) {
$styleTheme = $styleToRender;
$style = $this->twig->render($this->themeHelper->checkForTwigTemplate($styleTheme));
}
// Determine pages
$fields = $entity->getFields()->toArray();
// Ensure the correct order in case this is generated right after a form save with new fields
uasort($fields, fn ($a, $b): int => $a->getOrder() <=> $b->getOrder());
$viewOnlyFields = $this->getCustomComponents()['viewOnlyFields'];
$displayManager = new DisplayManager($entity, !empty($viewOnlyFields) ? $viewOnlyFields : []);
[$pages, $lastPage] = $this->getPages($fields);
$html = $this->twig->render(
$formToRender,
[
'fieldSettings' => $this->getCustomComponents()['fields'],
'viewOnlyFields' => $viewOnlyFields,
'fields' => $fields,
'mappedFields' => $this->mappedObjectCollector->buildCollection(...$entity->getMappedFieldObjects()),
'form' => $entity,
'theme' => '@themes/'.$entity->getTemplate().'/Field/',
'submissions' => $submissions,
'lead' => $lead,
'formPages' => $pages,
'lastFormPage' => $lastPage,
'style' => $style,
'inBuilder' => false,
'displayManager' => $displayManager,
'successfulSubmitAction' => $this->coreParametersHelper->get('successful_submit_action'),
]
);
if (!$entity->usesProgressiveProfiling()) {
$entity->setCachedHtml($html);
if ($persist) {
// bypass model function as events aren't needed for this
$this->getRepository()->saveEntity($entity);
}
}
return $html;
}
public function getPages(array $fields): array
{
$pages = ['open' => [], 'close' => []];
$openFieldId =
$previousId =
$lastPage = false;
$pageCount = 1;
foreach ($fields as $fieldId => $field) {
if ('pagebreak' == $field->getType() && $openFieldId) {
// Open the page
$pages['open'][$openFieldId] = $pageCount;
$openFieldId = false;
$lastPage = $fieldId;
// Close the page at the next page break
if ($previousId) {
$pages['close'][$previousId] = $pageCount;
++$pageCount;
}
} else {
if (!$openFieldId) {
$openFieldId = $fieldId;
}
}
$previousId = $fieldId;
}
if ($openFieldId) {
$pages['open'][$openFieldId] = $pageCount;
}
if ($previousId !== $lastPage) {
$pages['close'][$previousId] = $pageCount;
}
return [$pages, $lastPage];
}
/**
* Creates the table structure for form results.
*
* @param bool $isNew
* @param bool $dropExisting
*/
public function createTableSchema(Form $entity, $isNew = false, $dropExisting = false): void
{
// create the field as its own column in the leads table
$name = 'form_results_'.$entity->getId().'_'.$entity->getAlias();
$columns = $this->generateFieldColumns($entity);
if ($isNew || (!$isNew && !$this->tableSchemaHelper->checkTableExists($name))) {
$this->tableSchemaHelper->addTable([
'name' => $name,
'columns' => $columns,
'options' => [
'primaryKey' => ['submission_id'],
'uniqueIndex' => ['submission_id', 'form_id'],
],
], true, $dropExisting);
$this->tableSchemaHelper->executeChanges();
} else {
// check to make sure columns exist
$columnSchemaHelper = $this->columnSchemaHelper->setName($name);
foreach ($columns as $c) {
if (!$columnSchemaHelper->checkColumnExists($c['name'])) {
$columnSchemaHelper->addColumn($c, false);
}
}
$columnSchemaHelper->executeChanges();
}
}
public function deleteEntity($entity): void
{
/* @var Form $entity */
$this->deleteFormFiles($entity);
if (!$entity->getId()) {
// delete the associated results table
$this->tableSchemaHelper->deleteTable('form_results_'.$entity->deletedId.'_'.$entity->getAlias());
$this->tableSchemaHelper->executeChanges();
}
parent::deleteEntity($entity);
}
/**
* @param mixed[] $ids
*
* @return mixed[]
*/
public function deleteEntities($ids): array
{
$entities = parent::deleteEntities($ids);
foreach ($entities as $id => $entity) {
/* @var Form $entity */
// delete the associated results table
$this->tableSchemaHelper->deleteTable('form_results_'.$id.'_'.$entity->getAlias());
$this->deleteFormFiles($entity);
}
$this->tableSchemaHelper->executeChanges();
return $entities;
}
private function deleteFormFiles(Form $form): void
{
$this->formUploader->deleteFilesOfForm($form);
}
/**
* Generate an array of columns from fields.
*/
public function generateFieldColumns(Form $form): array
{
$fields = $form->getFields()->toArray();
$columns = [
[
'name' => 'submission_id',
'type' => 'integer',
],
[
'name' => 'form_id',
'type' => 'integer',
],
];
$ignoreTypes = $this->getCustomComponents()['viewOnlyFields'];
foreach ($fields as $f) {
if (!in_array($f->getType(), $ignoreTypes)) {
$columns[] = [
'name' => $f->getAlias(),
'type' => 'text',
'options' => [
'notnull' => false,
],
];
}
}
return $columns;
}
/**
* Gets array of custom fields and submit actions from bundles subscribed FormEvents::FORM_ON_BUILD.
*
* @return mixed
*/
public function getCustomComponents()
{
static $customComponents;
if (empty($customComponents)) {
// build them
$event = new FormBuilderEvent($this->translator);
$this->dispatcher->dispatch($event, FormEvents::FORM_ON_BUILD);
$customComponents['fields'] = $event->getFormFields();
$customComponents['actions'] = $event->getSubmitActions();
$customComponents['choices'] = $event->getSubmitActionGroups();
$customComponents['validators'] = $event->getValidators();
// Generate a list of fields that are not persisted to the database by default
$notPersist = ['button', 'captcha', 'freetext', 'freehtml', 'pagebreak'];
foreach ($customComponents['fields'] as $type => $field) {
if (isset($field['builderOptions']) && isset($field['builderOptions']['addSaveResult']) && false === $field['builderOptions']['addSaveResult']) {
$notPersist[] = $type;
}
}
$customComponents['viewOnlyFields'] = $notPersist;
}
return $customComponents;
}
/**
* Get the document write javascript for the form.
*/
public function getAutomaticJavascript(Form $form): string
{
$html = $this->getContent($form, false);
$formScript = $this->getFormScript($form);
// replace line breaks with literal symbol and escape quotations
$search = ["\r\n", "\n", '"'];
$replace = ['', '', '\"'];
$html = str_replace($search, $replace, $html);
$oldFormScript = str_replace($search, $replace, $formScript);
$newFormScript = $this->generateJsScript($formScript);
// Write html for all browser and fallback for IE
$script = '
var scr = document.currentScript;
var html = "'.$html.'";
if (scr !== undefined) {
scr.insertAdjacentHTML("afterend", html);
'.$newFormScript.'
} else {
document.write("'.$oldFormScript.'"+html);
}
';
return $script;
}
public function getFormScript(Form $form): string
{
$theme = $form->getTemplate();
$scriptToRender = '@MauticForm/Builder/_script.html.twig';
if (!empty($theme)) {
if ($this->twig->getLoader()->exists('@themes/'.$theme.'/MauticForm/Builder/_script.html.twig')) {
$scriptToRender = '@themes/'.$theme.'/MauticForm/Builder/_script.html.twig';
}
}
$script = $this->twig->render(
$scriptToRender,
[
'form' => $form,
'theme' => $theme,
]
);
$html = $this->getFormHtml($form);
$scripts = $this->extractScriptTag($html);
foreach ($scripts as $item) {
$script .= $item."\n";
}
return $script;
}
/**
* Writes in form values from get parameters.
*/
public function populateValuesWithGetParameters(Form $form, &$formHtml): void
{
$formName = $form->generateFormName();
$request = $this->requestStack->getCurrentRequest();
$fields = $form->getFields()->toArray();
/** @var Field $f */
foreach ($fields as $f) {
$alias = $f->getAlias();
if ($request->query->has($alias)) {
$value = urlencode($request->query->get($alias));
$this->fieldHelper->populateField($f, $value, $formName, $formHtml);
}
}
}
/**
* @param string $formHtml
*/
public function populateValuesWithLead(Form $form, &$formHtml): void
{
$formName = $form->generateFormName();
$fields = $form->getFields();
$autoFillFields = [];
$objectsToAutoFill = ['contact', 'company'];
/** @var Field $field */
foreach ($fields as $key => $field) {
// we want work just with matched autofill fields
if (
$field->getMappedField()
&& $field->getIsAutoFill()
&& in_array($field->getMappedObject(), $objectsToAutoFill)
) {
$autoFillFields[$key] = $field;
}
}
// no fields for populate
if (!count($autoFillFields)) {
return;
}
$lead = $this->contactTracker->getContact();
if (!$lead instanceof Lead) {
return;
}
// get the contact (lead) and primary company field values
$leadArray = $this->primaryCompanyHelper->getProfileFieldsWithPrimaryCompany($lead);
if (!is_array($leadArray) || count($leadArray) <= 0) {
return;
}
foreach ($autoFillFields as $field) {
$value = $leadArray[$field->getMappedField()] ?? '';
// just skip string empty field
if ('' !== $value) {
$this->fieldHelper->populateField($field, $value, $formName, $formHtml);
}
}
}
public function getFilterExpressionFunctions($operator = null): array
{
$operatorOptions = [
'=' => [
'label' => 'mautic.lead.list.form.operator.equals',
'expr' => 'eq',
'negate_expr' => 'neq',
],
'!=' => [
'label' => 'mautic.lead.list.form.operator.notequals',
'expr' => 'neq',
'negate_expr' => 'eq',
],
'gt' => [
'label' => 'mautic.lead.list.form.operator.greaterthan',
'expr' => 'gt',
'negate_expr' => 'lt',
],
'gte' => [
'label' => 'mautic.lead.list.form.operator.greaterthanequals',
'expr' => 'gte',
'negate_expr' => 'lt',
],
'lt' => [
'label' => 'mautic.lead.list.form.operator.lessthan',
'expr' => 'lt',
'negate_expr' => 'gt',
],
'lte' => [
'label' => 'mautic.lead.list.form.operator.lessthanequals',
'expr' => 'lte',
'negate_expr' => 'gt',
],
'like' => [
'label' => 'mautic.lead.list.form.operator.islike',
'expr' => 'like',
'negate_expr' => 'notLike',
],
'!like' => [
'label' => 'mautic.lead.list.form.operator.isnotlike',
'expr' => 'notLike',
'negate_expr' => 'like',
],
'startsWith' => [
'label' => 'mautic.core.operator.starts.with',
'expr' => 'startsWith',
'negate_expr' => 'startsWith',
],
'endsWith' => [
'label' => 'mautic.core.operator.ends.with',
'expr' => 'endsWith',
'negate_expr' => 'endsWith',
],
'contains' => [
'label' => 'mautic.core.operator.contains',
'expr' => 'contains',
'negate_expr' => 'contains',
],
];
return (null === $operator) ? $operatorOptions : $operatorOptions[$operator];
}
/**
* Get a list of assets in a date range.
*
* @param int $limit
* @param array $filters
* @param array $options
*
* @return array
*/
public function getFormList($limit = 10, \DateTime $dateFrom = null, \DateTime $dateTo = null, $filters = [], $options = [])
{
$q = $this->em->getConnection()->createQueryBuilder();
$q->select('t.id, t.name, t.date_added, t.date_modified')
->from(MAUTIC_TABLE_PREFIX.'forms', 't')
->setMaxResults($limit);
if (!empty($options['canViewOthers'])) {
$q->andWhere('t.created_by = :userId')
->setParameter('userId', $this->userHelper->getUser()->getId());
}
$chartQuery = new ChartQuery($this->em->getConnection(), $dateFrom, $dateTo);
$chartQuery->applyFilters($q, $filters);
$chartQuery->applyDateFilters($q, 'date_added');
return $q->execute()->fetchAllAssociative();
}
/**
* Load HTML consider Libxml < 2.7.8.
*/
private function loadHTML(&$dom, $html): void
{
if (defined('LIBXML_HTML_NOIMPLIED') && defined('LIBXML_HTML_NODEFDTD')) {
$dom->loadHTML(mb_encode_numericentity($html, [0x80, 0x10FFFF, 0, 0xFFFFF], 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
} else {
$dom->loadHTML(mb_encode_numericentity($html, [0x80, 0x10FFFF, 0, 0xFFFFF], 'UTF-8'));
}
}
/**
* Save HTML consider Libxml < 2.7.8.
*
* @return string
*/
private function saveHTML($dom, $html)
{
if (defined('LIBXML_HTML_NOIMPLIED') && defined('LIBXML_HTML_NODEFDTD')) {
return $dom->saveHTML($html);
} else {
// remove DOCTYPE, <html>, and <body> tags for old libxml
return preg_replace('/^<!DOCTYPE.+?>/', '', str_replace(['<html>', '</html>', '<body>', '</body>'], ['', '', '', ''], $dom->saveHTML($html)));
}
}
/**
* Extract script from html.
*/
private function extractScriptTag($html): array
{
libxml_use_internal_errors(true);
$dom = new \DOMDocument();
$this->loadHTML($dom, $html);
$items = $dom->getElementsByTagName('script');
$scripts = [];
foreach ($items as $script) {
$scripts[] = $this->saveHTML($dom, $script);
}
return $scripts;
}
/**
* Remove script from html.
*/
private function removeScriptTag($html): string
{
libxml_use_internal_errors(true);
$dom = new \DOMDocument();
$this->loadHTML($dom, '<div>'.$html.'</div>');
$items = $dom->getElementsByTagName('script');
$remove = [];
foreach ($items as $item) {
$remove[] = $item;
}
foreach ($remove as $item) {
$item->parentNode->removeChild($item);
}
$root = $dom->documentElement;
$result = '';
foreach ($root->childNodes as $childNode) {
$result .= $this->saveHTML($dom, $childNode);
}
return $result;
}
/**
* Generate dom manipulation javascript to include all script.
*/
private function generateJsScript($html): string
{
libxml_use_internal_errors(true);
$dom = new \DOMDocument();
$this->loadHTML($dom, '<div>'.$html.'</div>');
$items = $dom->getElementsByTagName('script');
$javascript = '';
foreach ($items as $key => $script) {
if ($script->hasAttribute('src')) {
$javascript .= "
var script$key = document.createElement('script');
script$key.src = '".$script->getAttribute('src')."';
document.getElementsByTagName('head')[0].appendChild(script$key);";
} else {
$scriptContent = $script->nodeValue;
$scriptContent = str_replace(["\r\n", "\n", '"'], ['', '', '\"'], $scriptContent);
$javascript .= "
var inlineScript$key = document.createTextNode(\"$scriptContent\");
var script$key = document.createElement('script');
script$key.appendChild(inlineScript$key);
document.getElementsByTagName('head')[0].appendChild(script$key);";
}
}
return $javascript;
}
/**
* Finds out whether the.
*/
private function addMappedFieldOptions(Field $formField): void
{
$formFieldProps = $formField->getProperties();
$mappedFieldAlias = $formField->getMappedField();
if (empty($formFieldProps['syncList']) || empty($mappedFieldAlias) || 'contact' !== $formField->getMappedObject()) {
return;
}
$list = $this->getContactFieldPropertiesList($mappedFieldAlias);
if (!empty($list)) {
$formFieldProps['list'] = ['list' => $list];
if (array_key_exists('optionlist', $formFieldProps)) {
$formFieldProps['optionlist'] = ['list' => $list];
}
$formField->setProperties($formFieldProps);
}
}
/**
* @return mixed[]|null
*/
public function getContactFieldPropertiesList(string $contactFieldAlias): ?array
{
$contactField = $this->leadFieldModel->getEntityByAlias($contactFieldAlias); // @todo this must use all objects as well. Not just contact.
if (empty($contactField) || !in_array($contactField->getType(), ContactFieldHelper::getListTypes())) {
return null;
}
$contactFieldProps = $contactField->getProperties();
switch ($contactField->getType()) {
case 'select':
case 'multiselect':
case 'lookup':
$list = $contactFieldProps['list'] ?? [];
break;
case 'boolean':
$list = [$contactFieldProps['no'], $contactFieldProps['yes']];
break;
case 'country':
$list = ContactFieldHelper::getCountryChoices();
break;
case 'region':
$list = ContactFieldHelper::getRegionChoices();
break;
case 'timezone':
$list = ContactFieldHelper::getTimezonesChoices();
break;
case 'locale':
$list = ContactFieldHelper::getLocaleChoices();
break;
default:
return null;
}
return $list;
}
/**
* @param string $fieldAlias
*
* @return Field|null
*/
public function findFormFieldByAlias(Form $form, $fieldAlias)
{
foreach ($form->getFields() as $field) {
if ($field->getAlias() === $fieldAlias) {
return $field;
}
}
return null;
}
private function backfillReplacedPropertiesForBc(Form $entity): void
{
/** @var Field $field */
foreach ($entity->getFields() as $field) {
if (!$field->getLeadField() && $field->getMappedField()) {
$field->setLeadField($field->getMappedField());
} elseif ($field->getLeadField() && !$field->getMappedField()) {
$field->setMappedField($field->getLeadField());
$field->setMappedObject(
str_starts_with($field->getLeadField(), 'company') && 'company' !== $field->getLeadField() ? 'company' : 'contact'
);
}
}
}
}
|