/**
  * Validates a field value.
  *
  * @param Field $field
  * @param       $value
  *
  * @return bool|string True if valid; otherwise string with invalid reason
  */
 protected function validateFieldValue(Field $field, $value)
 {
     $standardValidation = $this->fieldHelper->validateFieldValue($field->getType(), $value);
     if (!empty($standardValidation)) {
         return $standardValidation;
     }
     $components = $this->formModel->getCustomComponents();
     foreach ([$field->getType(), 'form'] as $type) {
         if (isset($components['validators'][$type])) {
             foreach ($components['validators'][$type] as $validator) {
                 $event = $this->dispatcher->dispatch($validator['eventName'], new ValidationEvent($field, $value));
                 if (!$event->isValid()) {
                     return $event->getInvalidReason();
                 }
             }
         }
     }
     return true;
 }
 /**
  * @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;
 }