/**
  * @param ObjectManager $manager
  */
 public function load(ObjectManager $manager)
 {
     $factory = $this->container->get('mautic.factory');
     $pageModel = $factory->getModel('page.page');
     $repo = $factory->getModel('form.submission')->getRepository();
     $fixture =& $this;
     $importResults = function ($results) use($factory, $pageModel, $repo, &$fixture) {
         foreach ($results as $count => $rows) {
             $submission = new Submission();
             $submission->setDateSubmitted(new \DateTime());
             foreach ($rows as $col => $val) {
                 if ($val != "NULL") {
                     $setter = "set" . ucfirst($col);
                     if (in_array($col, array('form', 'page', 'ipAddress'))) {
                         $entity = $fixture->getReference($col . '-' . $val);
                         if ($col == 'page') {
                             $submission->setReferer($pageModel->generateUrl($entity));
                         }
                         $submission->{$setter}($entity);
                         unset($rows[$col]);
                     } else {
                         //the rest are custom field values
                         break;
                     }
                 }
             }
             $submission->setResults($rows);
             $repo->saveEntity($submission);
         }
     };
     $results = CsvHelper::csv_to_array(__DIR__ . '/fakeresultdata.csv');
     $importResults($results);
     sleep(2);
     $results2 = CsvHelper::csv_to_array(__DIR__ . '/fakeresult2data.csv');
     $importResults($results2);
 }
 /**
  * @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->factory->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->factory->getModel('form')->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->factory->getModel('page.page')->getEntity((int) $post['mauticpage']);
         if ($page != null) {
             $submission->setPage($page);
         }
     }
     // Add a feedback parameter
     $args['feedback'] = array();
     /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
     $leadModel = $this->factory->getModel('lead');
     // 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'] = $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 = $leadModel->getCurrentLead();
     } else {
         list($lead, $trackingId, $generated) = $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
         /** @var \Mautic\CampaignBundle\Model\CampaignModel $campaignModel */
         $campaignModel = $this->factory->getModel('campaign');
         $campaigns = $campaignModel->getCampaignsByForm($form);
         if (!empty($campaigns)) {
             foreach ($campaigns as $campaign) {
                 $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;
 }
 /**
  * @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;
 }
 /**
  * {@inheritDoc}
  */
 public function setTrackingId($trackingId)
 {
     $this->__initializer__ && $this->__initializer__->__invoke($this, 'setTrackingId', array($trackingId));
     return parent::setTrackingId($trackingId);
 }