/** * Let the calendar to edit / create new entities. * * @param EventGeneratorEvent $event */ public function onCalendarEventGenerate(EventGeneratorEvent $event) { $source = $event->getSource(); if ($source != 'page') { return; } $entityId = $event->getEntityId(); $entity = $this->pageModel->getEntity($entityId); $event->setModel($this->pageModel); $event->setEntity($entity); $event->setContentTemplate('MauticPageBundle:SubscribedEvents\\Calendar:modal.html.php'); $event->setFormName('page_publish_dates'); $event->setAccess($this->security->hasEntityAccess('page:pages:viewown', 'page:pages:viewother', $entity->getCreatedBy())); }
/** * Compile events for the lead timeline * * @param LeadTimelineEvent $event */ public function onTimelineGenerate(LeadTimelineEvent $event) { // Set available event types $eventTypeKey = 'form.submitted'; $eventTypeName = $this->translator->trans('mautic.form.event.submitted'); $event->addEventType($eventTypeKey, $eventTypeName); if (!$event->isApplicable($eventTypeKey)) { return; } /** @var \Mautic\FormBundle\Entity\SubmissionRepository $submissionRepository */ $submissionRepository = $this->em->getRepository('MauticFormBundle:Submission'); $rows = $submissionRepository->getSubmissions($event->getQueryOptions()); // Add total to counter $event->addToCounter($eventTypeKey, $rows); if (!$event->isEngagementCount()) { // Add the submissions to the event array foreach ($rows['results'] as $row) { // Convert to local from UTC $form = $this->formModel->getEntity($row['form_id']); $submission = $submissionRepository->getEntity($row['id']); $event->addEvent(['event' => $eventTypeKey, 'eventLabel' => ['label' => $form->getName(), 'href' => $this->router->generate('mautic_form_action', ['objectAction' => 'view', 'objectId' => $form->getId()])], 'eventType' => $eventTypeName, 'timestamp' => $row['dateSubmitted'], 'extra' => ['submission' => $submission, 'form' => $form, 'page' => $this->pageModel->getEntity($row['page_id'])], 'contentTemplate' => 'MauticFormBundle:SubscribedEvents\\Timeline:index.html.php', 'icon' => 'fa-pencil-square-o']); } } }
/** * Compile events for the lead timeline. * * @param LeadTimelineEvent $event */ public function onTimelineGenerate(LeadTimelineEvent $event) { // Set available event types $eventTypeKey = 'page.hit'; $eventTypeName = $this->translator->trans('mautic.page.event.hit'); $event->addEventType($eventTypeKey, $eventTypeName); if (!$event->isApplicable($eventTypeKey)) { return; } $lead = $event->getLead(); /** @var \Mautic\PageBundle\Entity\HitRepository $hitRepository */ $hitRepository = $this->em->getRepository('MauticPageBundle:Hit'); $hits = $hitRepository->getLeadHits($lead->getId(), $event->getQueryOptions()); // Add to counter $event->addToCounter($eventTypeKey, $hits); if (!$event->isEngagementCount()) { // Add the hits to the event array foreach ($hits['results'] as $hit) { $template = 'MauticPageBundle:SubscribedEvents\\Timeline:index.html.php'; $icon = 'fa-link'; if (!empty($hit['source'])) { if ($channelModel = $this->getChannelModel($hit['source'])) { if ($channelModel instanceof ChannelTimelineInterface) { if ($overrideTemplate = $channelModel->getChannelTimelineTemplate($eventTypeKey, $hit)) { $template = $overrideTemplate; } if ($overrideEventTypeName = $channelModel->getChannelTimelineLabel($eventTypeKey, $hit)) { $eventTypeName = $overrideEventTypeName; } if ($overrideIcon = $channelModel->getChannelTimelineIcon($eventTypeKey, $hit)) { $icon = $overrideIcon; } } /* @deprecated - BC support to be removed in 3.0 */ // Allow a custom template if applicable if (method_exists($channelModel, 'getPageHitLeadTimelineTemplate')) { $template = $channelModel->getPageHitLeadTimelineTemplate($hit); } if (method_exists($channelModel, 'getPageHitLeadTimelineLabel')) { $eventTypeName = $channelModel->getPageHitLeadTimelineLabel($hit); } if (method_exists($channelModel, 'getPageHitLeadTimelineIcon')) { $icon = $channelModel->getPageHitLeadTimelineIcon($hit); } /* end deprecation */ if (!empty($hit['sourceId'])) { if ($source = $this->getChannelEntityName($hit['source'], $hit['sourceId'], true)) { $hit['sourceName'] = $source['name']; $hit['sourceRoute'] = $source['url']; } } } } if (!empty($hit['page_id'])) { $page = $this->pageModel->getEntity($hit['page_id']); $eventLabel = ['label' => $page->getTitle(), 'href' => $this->router->generate('mautic_page_action', ['objectAction' => 'view', 'objectId' => $hit['page_id']])]; } else { $eventLabel = ['label' => isset($hit['urlTitle']) ? $hit['urlTitle'] : $hit['url'], 'href' => $hit['url'], 'isExternal' => true]; } $event->addEvent(['event' => $eventTypeKey, 'eventLabel' => $eventLabel, 'eventType' => $eventTypeName, 'timestamp' => $hit['dateHit'], 'extra' => ['hit' => $hit], 'contentTemplate' => $template, 'icon' => $icon]); } } }
/** * @param $post * @param $server * @param Form $form * * @return bool|array */ public function saveSubmission($post, $server, Form $form, Request $request = null, $returnEvent = false) { $leadFields = $this->leadFieldModel->getFieldListWithProperties(false); //everything matches up so let's save the results $submission = new Submission(); $submission->setDateSubmitted(new \DateTime()); $submission->setForm($form); //set the landing page the form was submitted from if applicable if (!empty($post['mauticpage'])) { $page = $this->pageModel->getEntity((int) $post['mauticpage']); if ($page != null) { $submission->setPage($page); } } $ipAddress = $this->ipLookupHelper->getIpAddress(); $submission->setIpAddress($ipAddress); if (!empty($post['return'])) { $referer = $post['return']; } elseif (!empty($server['HTTP_REFERER'])) { $referer = $server['HTTP_REFERER']; } else { $referer = ''; } //clean the referer by removing mauticError and mauticMessage $referer = InputHelper::url($referer, null, null, ['mauticError', 'mauticMessage']); $submission->setReferer($referer); // Create an event to be dispatched through the processes $submissionEvent = new SubmissionEvent($submission, $post, $server, $request); // Get a list of components to build custom fields from $components = $this->formModel->getCustomComponents(); $fields = $form->getFields(); $fieldArray = []; $results = []; $tokens = []; $leadFieldMatches = []; $validationErrors = []; /** @var Field $f */ foreach ($fields as $f) { $id = $f->getId(); $type = $f->getType(); $alias = $f->getAlias(); $value = isset($post[$alias]) ? $post[$alias] : ''; $fieldArray[$id] = ['id' => $id, 'type' => $type, 'alias' => $alias]; if ($type == 'captcha') { $captcha = $this->fieldHelper->validateFieldValue($type, $value, $f); if (!empty($captcha)) { $props = $f->getProperties(); //check for a custom message $validationErrors[$alias] = !empty($props['errorMessage']) ? $props['errorMessage'] : implode('<br />', $captcha); } continue; } if ($f->isRequired() && empty($value)) { //field is required, but hidden from form because of 'ShowWhenValueExists' if ($f->getShowWhenValueExists() === false && !isset($post[$alias])) { continue; } //somehow the user got passed the JS validation $msg = $f->getValidationMessage(); if (empty($msg)) { $msg = $this->translator->trans('mautic.form.field.generic.validationfailed', ['%label%' => $f->getLabel()], 'validators'); } $validationErrors[$alias] = $msg; continue; } if (in_array($type, $components['viewOnlyFields'])) { //don't save items that don't have a value associated with it continue; } //clean and validate the input if ($f->isCustom()) { if (!isset($components['fields'][$f->getType()])) { continue; } $params = $components['fields'][$f->getType()]; if (!empty($value)) { if (isset($params['valueFilter'])) { if (is_string($params['valueFilter']) && is_callable(['\\Mautic\\CoreBundle\\Helper\\InputHelper', $params['valueFilter']])) { $value = InputHelper::_($value, $params['valueFilter']); } elseif (is_callable($params['valueFilter'])) { $value = call_user_func_array($params['valueFilter'], [$f, $value]); } else { $value = InputHelper::_($value, 'clean'); } } else { $value = InputHelper::_($value, 'clean'); } } // @deprecated - BC support; to be removed in 3.0 - be sure to remove support in FormBuilderEvent as well if (isset($params['valueConstraints']) && is_callable($params['valueConstraints'])) { $customErrors = call_user_func_array($params['valueConstraints'], [$f, $value]); if (!empty($customErrors)) { $validationErrors[$alias] = is_array($customErrors) ? implode('<br />', $customErrors) : $customErrors; } } } elseif (!empty($value)) { $filter = $this->fieldHelper->getFieldFilter($type); $value = InputHelper::_($value, $filter); $isValid = $this->validateFieldValue($f, $value); if (true !== $isValid) { $validationErrors[$alias] = is_array($isValid) ? implode('<br />', $isValid) : $isValid; } } // Check for custom validators $isValid = $this->validateFieldValue($f, $value); if (true !== $isValid) { $validationErrors[$alias] = $isValid; } $leadField = $f->getLeadField(); if (!empty($leadField)) { $leadValue = $value; if (is_array($leadValue)) { // Multiselect lead fields store the values with bars $delimeter = 'multiselect' === $leadFields[$leadField]['type'] ? '|' : ', '; $leadValue = implode($delimeter, $leadValue); } $leadFieldMatches[$leadField] = $leadValue; } //convert array from checkbox groups and multiple selects if (is_array($value)) { $value = implode(', ', $value); } $tokens["{formfield={$alias}}"] = $value; //save the result if ($f->getSaveResult() !== false) { $results[$alias] = $value; } } // Set the results $submission->setResults($results); // Update the event $submissionEvent->setFields($fieldArray)->setTokens($tokens)->setResults($results)->setContactFieldMatches($leadFieldMatches); // @deprecated - BC support; to be removed in 3.0 - be sure to remove the validator option from addSubmitAction as well $this->validateActionCallbacks($submissionEvent, $validationErrors, $alias); //return errors if there any - this should be moved to right after foreach($fields) once validateActionCallbacks support is dropped if (!empty($validationErrors)) { return ['errors' => $validationErrors]; } // Create/update lead if (!empty($leadFieldMatches)) { $lead = $this->createLeadFromSubmit($form, $leadFieldMatches, $leadFields); $submission->setLead($lead); } // Get updated lead if applicable with tracking ID if ($form->isInKioskMode()) { $lead = $this->leadModel->getCurrentLead(); } else { list($lead, $trackingId, $generated) = $this->leadModel->getCurrentLead(true); //set tracking ID for stats purposes to determine unique hits $submission->setTrackingId($trackingId); } $submission->setLead($lead); // Save the submission $this->saveEntity($submission); // Now handle post submission actions try { $this->executeFormActions($submissionEvent); } catch (ValidationException $exception) { // The action invalidated the form for whatever reason $this->deleteEntity($submission); if ($validationErrors = $exception->getViolations()) { return ['errors' => $validationErrors]; } return ['errors' => [$exception->getMessage()]]; } if (!$form->isStandalone()) { // Find and add the lead to the associated campaigns $campaigns = $this->campaignModel->getCampaignsByForm($form); if (!empty($campaigns)) { foreach ($campaigns as $campaign) { $this->campaignModel->addLead($campaign, $lead); } } } if ($this->dispatcher->hasListeners(FormEvents::FORM_ON_SUBMIT)) { // Reset action config from executeFormActions() $submissionEvent->setActionConfig(null, []); // Dispatch to on submit listeners $this->dispatcher->dispatch(FormEvents::FORM_ON_SUBMIT, $submissionEvent); } //get callback commands from the submit action if ($submissionEvent->hasPostSubmitCallbacks()) { return ['callback' => $submissionEvent]; } // made it to the end so return the submission event to give the calling method access to tokens, results, etc // otherwise return false that no errors were encountered (to keep BC really) return $returnEvent ? ['submission' => $submissionEvent] : false; }
/** * @param $post * @param $server * @param Form $form * * @return boolean|string false if no error was encountered; otherwise the error message */ public function saveSubmission($post, $server, Form $form) { $fieldHelper = new FormFieldHelper($this->translator); //everything matches up so let's save the results $submission = new Submission(); $submission->setDateSubmitted(new \DateTime()); $submission->setForm($form); $ipAddress = $this->ipLookupHelper->getIpAddress(); $submission->setIpAddress($ipAddress); if (!empty($post['return'])) { $referer = $post['return']; } elseif (!empty($server['HTTP_REFERER'])) { $referer = $server['HTTP_REFERER']; } else { $referer = ''; } //clean the referer by removing mauticError and mauticMessage $referer = InputHelper::url($referer, null, null, array('mauticError', 'mauticMessage')); $submission->setReferer($referer); $fields = $form->getFields(); $fieldArray = array(); $results = array(); $tokens = array(); $leadFieldMatches = array(); $validationErrors = array(); foreach ($fields as $f) { $id = $f->getId(); $type = $f->getType(); $alias = $f->getAlias(); $value = isset($post[$alias]) ? $post[$alias] : ''; $fieldArray[$id] = array('id' => $id, 'type' => $type, 'alias' => $alias); if (in_array($type, array('button', 'freetext'))) { //don't save items that don't have a value associated with it continue; } elseif ($type == 'captcha') { $captcha = $fieldHelper->validateFieldValue($type, $value, $f); if (!empty($captcha)) { $props = $f->getProperties(); //check for a custom message $validationErrors[$alias] = !empty($props['errorMessage']) ? $props['errorMessage'] : implode('<br />', $captcha); } continue; } if ($f->isRequired() && empty($value)) { //somehow the user got passed the JS validation $msg = $f->getValidationMessage(); if (empty($msg)) { $msg = $this->translator->trans('mautic.form.field.generic.validationfailed', array('%label%' => $f->getLabel()), 'validators'); } $validationErrors[$alias] = $msg; continue; } //clean and validate the input if ($f->isCustom()) { $params = $f->getCustomParameters(); if (!empty($value)) { if (isset($params['valueFilter'])) { if (is_string($params['inputFilter'] && method_exists('\\Mautic\\CoreBundle\\Helper\\InputHelper', $params['valueFilter']))) { $value = InputHelper::_($value, $params['valueFilter']); } elseif (is_callable($params['valueFilter'])) { $value = call_user_func_array($params['valueFilter'], array($f, $value)); } else { $value = InputHelper::_($value, 'clean'); } } else { $value = InputHelper::_($value, 'clean'); } } if (isset($params['valueConstraints']) && is_callable($params['valueConstraints'])) { $customErrors = call_user_func_array($params['valueConstraints'], array($f, $value)); if (!empty($customErrors)) { $validationErrors[$alias] = is_array($customErrors) ? implode('<br />', $customErrors) : $customErrors; } } } elseif (!empty($value)) { $filter = $fieldHelper->getFieldFilter($type); $value = InputHelper::_($value, $filter); $validation = $fieldHelper->validateFieldValue($type, $value); if (!empty($validation)) { $validationErrors[$alias] = is_array($validation) ? implode('<br />', $validation) : $validation; } } //convert array from checkbox groups and multiple selects if (is_array($value)) { $value = implode(", ", $value); } $tokens["{formfield={$alias}}"] = $value; //save the result if ($f->getSaveResult() !== false) { $results[$alias] = $value; } $leadField = $f->getLeadField(); if (!empty($leadField)) { $leadFieldMatches[$leadField] = $value; } } $submission->setResults($results); //execute submit actions $actions = $form->getActions(); //get post submit actions to make sure it still exists $components = $this->formModel->getCustomComponents(); $availableActions = $components['actions']; $args = array('post' => $post, 'server' => $server, 'factory' => $this->factory, 'submission' => $submission, 'fields' => $fieldArray, 'form' => $form, 'tokens' => $tokens); foreach ($actions as $action) { $key = $action->getType(); if (!isset($availableActions[$key])) { continue; } $settings = $availableActions[$key]; $args['action'] = $action; $args['config'] = $action->getProperties(); if (array_key_exists('validator', $settings)) { $callback = $settings['validator']; if (is_callable($callback)) { if (is_array($callback)) { $reflection = new \ReflectionMethod($callback[0], $callback[1]); } elseif (strpos($callback, '::') !== false) { $parts = explode('::', $callback); $reflection = new \ReflectionMethod($parts[0], $parts[1]); } else { $reflection = new \ReflectionMethod(null, $callback); } $pass = array(); foreach ($reflection->getParameters() as $param) { if (isset($args[$param->getName()])) { $pass[] = $args[$param->getName()]; } else { $pass[] = null; } } list($validated, $validatedMessage) = $reflection->invokeArgs($this, $pass); if (!$validated) { $validationErrors[$alias] = $validatedMessage; } } } } //return errors if (!empty($validationErrors)) { return array('errors' => $validationErrors); } //set the landing page the form was submitted from if applicable if (!empty($post['mauticpage'])) { $page = $this->pageModel->getEntity((int) $post['mauticpage']); if ($page != null) { $submission->setPage($page); } } // Add a feedback parameter $args['feedback'] = array(); // Create/update lead if (!empty($leadFieldMatches)) { $this->createLeadFromSubmit($form, $leadFieldMatches); } if ($form->isStandalone()) { // Now handle post submission actions foreach ($actions as $action) { $key = $action->getType(); if (!isset($availableActions[$key])) { continue; } $settings = $availableActions[$key]; $args['action'] = $action; $args['config'] = $action->getProperties(); // Set the lead each time in case an action updates it $args['lead'] = $this->leadModel->getCurrentLead(); $callback = $settings['callback']; if (is_callable($callback)) { if (is_array($callback)) { $reflection = new \ReflectionMethod($callback[0], $callback[1]); } elseif (strpos($callback, '::') !== false) { $parts = explode('::', $callback); $reflection = new \ReflectionMethod($parts[0], $parts[1]); } else { $reflection = new \ReflectionMethod(null, $callback); } $pass = array(); foreach ($reflection->getParameters() as $param) { if (isset($args[$param->getName()])) { $pass[] = $args[$param->getName()]; } else { $pass[] = null; } } $returned = $reflection->invokeArgs($this, $pass); $args['feedback'][$key] = $returned; } } } // Get updated lead with tracking ID if ($form->isInKioskMode()) { $lead = $this->leadModel->getCurrentLead(); } else { list($lead, $trackingId, $generated) = $this->leadModel->getCurrentLead(true); //set tracking ID for stats purposes to determine unique hits $submission->setTrackingId($trackingId); } $submission->setLead($lead); if (!$form->isStandalone()) { // Find and add the lead to the associated campaigns $campaigns = $this->campaignModel->getCampaignsByForm($form); if (!empty($campaigns)) { foreach ($campaigns as $campaign) { $this->campaignModel->addLead($campaign, $lead); } } } //save entity after the form submission events are fired in case a new lead is created $this->saveEntity($submission); if ($this->dispatcher->hasListeners(FormEvents::FORM_ON_SUBMIT)) { $event = new SubmissionEvent($submission, $post, $server); $this->dispatcher->dispatch(FormEvents::FORM_ON_SUBMIT, $event); } //last round of callback commands from the submit actions; first come first serve foreach ($args['feedback'] as $k => $data) { if (!empty($data['callback'])) { return array('callback' => $data); } } //made it to the end so return false that there was not an error return false; }