Ejemplo n.º 1
0
 /**
  * Create or update existing Mautic lead from the integration's profile data
  *
  * @param mixed      $data    Profile data from integration
  * @param bool|true  $persist Set to false to not persist lead to the database in this method
  * @param array|null $socialCache
  * @param mixed||null $identifiers
  *
  * @return Lead
  */
 public function getMauticLead($data, $persist = true, $socialCache = null, $identifiers = null)
 {
     if (is_object($data)) {
         // Convert to array in all levels
         $data = json_encode(json_decode($data), true);
     } elseif (is_string($data)) {
         // Assume JSON
         $data = json_decode($data, true);
     }
     $config = $this->mergeConfigToFeatureSettings([]);
     // Match that data with mapped lead fields
     $matchedFields = $this->populateMauticLeadData($data, $config);
     if (empty($matchedFields)) {
         return;
     }
     // Find unique identifier fields used by the integration
     /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
     $leadModel = $this->factory->getModel('lead');
     $uniqueLeadFields = $this->factory->getModel('lead.field')->getUniqueIdentiferFields();
     $uniqueLeadFieldData = [];
     foreach ($matchedFields as $leadField => $value) {
         if (array_key_exists($leadField, $uniqueLeadFields) && !empty($value)) {
             $uniqueLeadFieldData[$leadField] = $value;
         }
     }
     // Default to new lead
     $lead = new Lead();
     $lead->setNewlyCreated(true);
     if (count($uniqueLeadFieldData)) {
         $existingLeads = $this->factory->getEntityManager()->getRepository('MauticLeadBundle:Lead')->getLeadsByUniqueFields($uniqueLeadFieldData);
         if (!empty($existingLeads)) {
             $lead = array_shift($existingLeads);
         }
     }
     $leadModel->setFieldValues($lead, $matchedFields, false, false);
     if (!empty($socialCache)) {
         // Update the social cache
         $leadSocialCache = $lead->getSocialCache();
         if (!isset($leadSocialCache[$this->getName()])) {
             $leadSocialCache[$this->getName()] = [];
         }
         $leadSocialCache[$this->getName()] = array_merge($leadSocialCache[$this->getName()], $socialCache);
         // Check for activity while here
         if (null !== $identifiers && in_array('public_activity', $this->getSupportedFeatures())) {
             $this->getPublicActivity($identifiers, $leadSocialCache[$this->getName()]);
         }
         $lead->setSocialCache($leadSocialCache);
     }
     // Update the internal info integration object that has updated the record
     if (isset($data['internal'])) {
         $internalInfo = $lead->getInternal();
         $internalInfo[$this->getName()] = $data['internal'];
         $lead->setInternal($internalInfo);
     }
     if ($persist) {
         // Only persist if instructed to do so as it could be that calling code needs to manipulate the lead prior to executing event listeners
         $leadModel->saveEntity($lead, false);
     }
     return $lead;
 }
Ejemplo n.º 2
0
 /**
  * Get the current lead; if $returnTracking = true then array with lead, trackingId, and boolean of if trackingId
  * was just generated or not
  *
  * @param bool|false $returnTracking
  *
  * @return Lead|array
  */
 public function getCurrentLead($returnTracking = false)
 {
     if (!$returnTracking && $this->systemCurrentLead || defined('IN_MAUTIC_CONSOLE')) {
         // Just return the system set lead
         if (null === $this->systemCurrentLead) {
             $this->systemCurrentLead = new Lead();
         }
         return $this->systemCurrentLead;
     }
     $request = $this->factory->getRequest();
     $cookies = $request->cookies;
     list($trackingId, $generated) = $this->getTrackingCookie();
     if (empty($this->currentLead)) {
         $leadId = $cookies->get($trackingId);
         $ip = $this->factory->getIpAddress();
         if (empty($leadId)) {
             //this lead is not tracked yet so get leads by IP and track that lead or create a new one
             $leads = $this->getLeadsByIp($ip->getIpAddress());
             if (count($leads)) {
                 //just create a tracking cookie for the newest lead
                 $lead = $leads[0];
                 $leadId = $lead->getId();
             } else {
                 //let's create a lead
                 $lead = new Lead();
                 $lead->addIpAddress($ip);
                 $lead->setNewlyCreated(true);
                 // Set to prevent loops
                 $this->currentLead = $lead;
                 $this->saveEntity($lead, false);
                 $leadId = $lead->getId();
             }
             $fields = $this->getLeadDetails($lead);
             $lead->setFields($fields);
         } else {
             $lead = $this->getEntity($leadId);
             if ($lead === null) {
                 //let's create a lead
                 $lead = new Lead();
                 $lead->addIpAddress($ip);
                 $lead->setNewlyCreated(true);
                 // Set to prevent loops
                 $this->currentLead = $lead;
                 $this->saveEntity($lead, false);
                 $leadId = $lead->getId();
                 $fields = $this->getLeadDetails($lead);
                 $lead->setFields($fields);
             }
         }
         $this->currentLead = $lead;
         $this->setLeadCookie($leadId);
     }
     // Log last active
     if (!defined('MAUTIC_LEAD_LASTACTIVE_LOGGED')) {
         $this->getRepository()->updateLastActive($this->currentLead->getId());
         define('MAUTIC_LEAD_LASTACTIVE_LOGGED', 1);
     }
     return $returnTracking ? array($this->currentLead, $trackingId, $generated) : $this->currentLead;
 }
Ejemplo n.º 3
0
 /**
  * Create/update lead from form submit
  *
  * @param       $form
  * @param array $leadFieldMatches
  *
  * @return Lead
  */
 protected function createLeadFromSubmit($form, array $leadFieldMatches)
 {
     /** @var \Mautic\LeadBundle\Model\LeadModel $model */
     $model = $this->factory->getModel('lead');
     $em = $this->factory->getEntityManager();
     $logger = $this->factory->getLogger();
     //set the mapped data
     $leadFields = $this->factory->getModel('lead.field')->getRepository()->getAliases(null, true, false);
     $inKioskMode = $form->isInKioskMode();
     if (!$inKioskMode) {
         // Default to currently tracked lead
         $lead = $model->getCurrentLead();
         $leadId = $lead->getId();
         $currentFields = $model->flattenFields($lead->getFields());
         $logger->debug('FORM: Not in kiosk mode so using current contact ID #' . $lead->getId());
     } else {
         // Default to a new lead in kiosk mode
         $lead = new Lead();
         $lead->setNewlyCreated(true);
         $currentFields = $leadFieldMatches;
         $leadId = null;
         $logger->debug('FORM: In kiosk mode so assuming a new contact');
     }
     $uniqueLeadFields = $this->factory->getModel('lead.field')->getUniqueIdentiferFields();
     // Closure to get data and unique fields
     $getData = function ($currentFields, $uniqueOnly = false) use($leadFields, $uniqueLeadFields) {
         $uniqueFieldsWithData = $data = array();
         foreach ($leadFields as $alias) {
             $data[$alias] = '';
             if (isset($currentFields[$alias])) {
                 $value = $currentFields[$alias];
                 $data[$alias] = $value;
                 // make sure the value is actually there and the field is one of our uniques
                 if (!empty($value) && array_key_exists($alias, $uniqueLeadFields)) {
                     $uniqueFieldsWithData[$alias] = $value;
                 }
             }
         }
         return $uniqueOnly ? $uniqueFieldsWithData : array($data, $uniqueFieldsWithData);
     };
     // Closure to help search for a conflict
     $checkForIdentifierConflict = function ($fieldSet1, $fieldSet2) use($logger) {
         // Find fields in both sets
         $potentialConflicts = array_keys(array_intersect_key($fieldSet1, $fieldSet2));
         $logger->debug('FORM: Potential conflicts ' . implode(', ', array_keys($potentialConflicts)) . ' = ' . implode(', ', $potentialConflicts));
         $conflicts = array();
         foreach ($potentialConflicts as $field) {
             if (!empty($fieldSet1[$field]) && !empty($fieldSet2[$field])) {
                 if (strtolower($fieldSet1[$field]) !== strtolower($fieldSet2[$field])) {
                     $conflicts[] = $field;
                 }
             }
         }
         return array(count($conflicts), $conflicts);
     };
     // Get data for the form submission
     list($data, $uniqueFieldsWithData) = $getData($leadFieldMatches);
     $logger->debug('FORM: Unique fields submitted include ' . implode(', ', $uniqueFieldsWithData));
     // Check for duplicate lead
     /** @var \Mautic\LeadBundle\Entity\LeadRepository $leads */
     $leads = !empty($uniqueFieldsWithData) ? $em->getRepository('MauticLeadBundle:Lead')->getLeadsByUniqueFields($uniqueFieldsWithData, $leadId) : array();
     $uniqueFieldsCurrent = $getData($currentFields, true);
     if (count($leads)) {
         $logger->debug(count($leads) . ' found based on unique identifiers');
         /** @var \Mautic\LeadBundle\Entity\Lead $foundLead */
         $foundLead = $leads[0];
         $logger->debug('FORM: Testing contact ID# ' . $foundLead->getId() . ' for conflicts');
         // Check for a conflict with the currently tracked lead
         $foundLeadFields = $model->flattenFields($foundLead->getFields());
         // Get unique identifier fields for the found lead then compare with the lead currently tracked
         $uniqueFieldsFound = $getData($foundLeadFields, true);
         list($hasConflict, $conflicts) = $checkForIdentifierConflict($uniqueFieldsFound, $uniqueFieldsCurrent);
         if ($inKioskMode || $hasConflict) {
             // Use the found lead without merging because there is some sort of conflict with unique identifiers or in kiosk mode and thus should not merge
             $lead = $foundLead;
             if ($hasConflict) {
                 $logger->debug('FORM: Conflicts found in ' . implode(', ', $conflicts) . ' so not merging');
             } else {
                 $logger->debug('FORM: In kiosk mode so not merging');
             }
         } else {
             $logger->debug('FORM: Merging contacts ' . $lead->getId() . ' and ' . $foundLead->getId());
             // Merge the found lead with currently tracked lead
             $lead = $model->mergeLeads($lead, $foundLead);
         }
         // Update unique fields data for comparison with submitted data
         $currentFields = $model->flattenFields($lead->getFields());
         $uniqueFieldsCurrent = $getData($currentFields, true);
     }
     if (!$inKioskMode) {
         // Check for conflicts with the submitted data and the currently tracked lead
         list($hasConflict, $conflicts) = $checkForIdentifierConflict($uniqueFieldsWithData, $uniqueFieldsCurrent);
         $logger->debug('FORM: Current unique contact fields ' . implode(', ', array_keys($uniqueFieldsCurrent)) . ' = ' . implode(', ', $uniqueFieldsCurrent));
         $logger->debug('FORM: Submitted unique contact fields ' . implode(', ', array_keys($uniqueFieldsWithData)) . ' = ' . implode(', ', $uniqueFieldsWithData));
         if ($hasConflict) {
             // There's a conflict so create a new lead
             $lead = new Lead();
             $lead->setNewlyCreated(true);
             $logger->debug('FORM: Conflicts found in ' . implode(', ', $conflicts) . ' between current tracked contact and submitted data so assuming a new contact');
         }
     }
     //check for existing IP address
     $ipAddress = $this->factory->getIpAddress();
     //no lead was found by a mapped email field so create a new one
     if ($lead->isNewlyCreated()) {
         if (!$inKioskMode) {
             $lead->addIpAddress($ipAddress);
             $logger->debug('FORM: Associating ' . $ipAddress->getIpAddress() . ' to contact');
         }
     } elseif (!$inKioskMode) {
         $leadIpAddresses = $lead->getIpAddresses();
         if (!$leadIpAddresses->contains($ipAddress)) {
             $lead->addIpAddress($ipAddress);
             $logger->debug('FORM: Associating ' . $ipAddress->getIpAddress() . ' to contact');
         }
     }
     //set the mapped fields
     $model->setFieldValues($lead, $data, false);
     if (!empty($event)) {
         $event->setIpAddress($ipAddress);
         $lead->addPointsChangeLog($event);
     }
     // last active time
     $lead->setLastActive(new \DateTime());
     //create a new lead
     $model->saveEntity($lead, false);
     if (!$inKioskMode) {
         // Set the current lead which will generate tracking cookies
         $model->setCurrentLead($lead);
     } else {
         // Set system current lead which will still allow execution of events without generating tracking cookies
         $model->setSystemCurrentLead($lead);
     }
     return $lead;
 }
Ejemplo n.º 4
0
 /**
  * Create/update lead from form submit
  *
  * @param       $form
  * @param array $leadFieldMatches
  *
  * @return Lead
  */
 protected function createLeadFromSubmit($form, array $leadFieldMatches)
 {
     /** @var \Mautic\LeadBundle\Model\LeadModel $model */
     $model = $this->factory->getModel('lead');
     $em = $this->factory->getEntityManager();
     //set the mapped data
     $leadFields = $this->factory->getModel('lead.field')->getRepository()->getAliases(null, true, false);
     $inKioskMode = $form->isInKioskMode();
     if (!$inKioskMode) {
         // Default to currently tracked lead
         $lead = $model->getCurrentLead();
         $leadId = $lead->getId();
         $currentFields = $model->flattenFields($lead->getFields());
     } else {
         // Default to a new lead in kiosk mode
         $lead = new Lead();
         $lead->setNewlyCreated(true);
         $currentFields = $leadFieldMatches;
         $leadId = null;
     }
     $uniqueLeadFields = $this->factory->getModel('lead.field')->getUniqueIdentiferFields();
     // Closure to get data and unique fields
     $getData = function ($currentFields, $uniqueOnly = false) use($leadFields, $uniqueLeadFields) {
         $uniqueFieldsWithData = $data = array();
         foreach ($leadFields as $alias) {
             $data[$alias] = '';
             if (isset($currentFields[$alias])) {
                 $value = $currentFields[$alias];
                 $data[$alias] = $value;
                 // make sure the value is actually there and the field is one of our uniques
                 if (!empty($value) && array_key_exists($alias, $uniqueLeadFields)) {
                     $uniqueFieldsWithData[$alias] = $value;
                 }
             }
         }
         return $uniqueOnly ? $uniqueFieldsWithData : array($data, $uniqueFieldsWithData);
     };
     // Closure to help search for a conflict
     $checkForIdentifierConflict = function ($fieldSet1, $fieldSet2) {
         // Find conflicts
         $diff = array_diff($fieldSet1, $fieldSet2);
         // Remove empty values
         $diff = array_filter($diff);
         return count($diff);
     };
     // Get data for the form submission
     list($data, $uniqueFieldsWithData) = $getData($leadFieldMatches);
     // Check for duplicate lead
     /** @var \Mautic\LeadBundle\Entity\LeadRepository $leads */
     $leads = !empty($uniqueFieldsWithData) ? $em->getRepository('MauticLeadBundle:Lead')->getLeadsByUniqueFields($uniqueFieldsWithData, $leadId) : array();
     $uniqueFieldsCurrent = $getData($currentFields, true);
     if (count($leads)) {
         /** @var \Mautic\LeadBundle\Entity\Lead $foundLead */
         $foundLead = $leads[0];
         // Check for a conflict with the currently tracked lead
         $foundLeadFields = $model->flattenFields($foundLead->getFields());
         // Get unique identifier fields for the found lead then compare with the lead currently tracked
         $uniqueFieldsFound = $getData($foundLeadFields, true);
         $hasConflict = $checkForIdentifierConflict($uniqueFieldsFound, $uniqueFieldsCurrent);
         if ($inKioskMode || $hasConflict) {
             // Use the found lead without merging because there is some sort of conflict with unique identifiers or in kiosk mode and thus should not merge
             $lead = $foundLead;
         } else {
             // Merge the found lead with currently tracked lead
             $lead = $model->mergeLeads($lead, $foundLead);
         }
         // Update unique fields data for comparison with submitted data
         $currentFields = $model->flattenFields($lead->getFields());
         $uniqueFieldsCurrent = $getData($currentFields, true);
     }
     if (!$inKioskMode) {
         // Check for conflicts with the submitted data and the currently tracked lead
         $hasConflict = $checkForIdentifierConflict($uniqueFieldsWithData, $uniqueFieldsCurrent);
         if ($hasConflict) {
             // There's a conflict so create a new lead
             $lead = new Lead();
             $lead->setNewlyCreated(true);
         }
     }
     //check for existing IP address
     $ipAddress = $this->factory->getIpAddress();
     //no lead was found by a mapped email field so create a new one
     if ($lead->isNewlyCreated()) {
         if (!$inKioskMode) {
             $lead->addIpAddress($ipAddress);
         }
         // last active time
         $lead->setLastActive(new \DateTime());
     } elseif (!$inKioskMode) {
         $leadIpAddresses = $lead->getIpAddresses();
         if (!$leadIpAddresses->contains($ipAddress)) {
             $lead->addIpAddress($ipAddress);
         }
     }
     //set the mapped fields
     $model->setFieldValues($lead, $data, false);
     if (!empty($event)) {
         $event->setIpAddress($ipAddress);
         $lead->addPointsChangeLog($event);
     }
     //create a new lead
     $model->saveEntity($lead, false);
     if (!$inKioskMode) {
         // Set the current lead which will generate tracking cookies
         $model->setCurrentLead($lead);
     } else {
         // Set system current lead which will still allow execution of events without generating tracking cookies
         $model->setSystemCurrentLead($lead);
     }
     return $lead;
 }
 /**
  * {@inheritDoc}
  */
 public function setNewlyCreated($newlyCreated)
 {
     $this->__initializer__ && $this->__initializer__->__invoke($this, 'setNewlyCreated', array($newlyCreated));
     return parent::setNewlyCreated($newlyCreated);
 }
Ejemplo n.º 6
0
 /**
  * Get the current lead; if $returnTracking = true then array with lead, trackingId, and boolean of if trackingId
  * was just generated or not
  *
  * @param bool|false $returnTracking
  *
  * @return Lead|array
  */
 public function getCurrentLead($returnTracking = false)
 {
     if (!$returnTracking && $this->systemCurrentLead || defined('IN_MAUTIC_CONSOLE')) {
         // Just return the system set lead
         if (null === $this->systemCurrentLead) {
             $this->systemCurrentLead = new Lead();
         }
         return $this->systemCurrentLead;
     }
     if ($this->request) {
         $this->logger->addDebug("LEAD: Tracking session for " . $this->request->getMethod() . " " . $this->request->getRequestUri());
     }
     list($trackingId, $generated) = $this->getTrackingCookie();
     $this->logger->addDebug("LEAD: Tracking ID for this contact is {$trackingId} (" . (int) $generated . ")");
     if (empty($this->currentLead)) {
         $leadId = $this->request->cookies->get($trackingId);
         $ip = $this->ipLookupHelper->getIpAddress();
         if (empty($leadId)) {
             //this lead is not tracked yet so get leads by IP and track that lead or create a new one
             $leads = $this->getLeadsByIp($ip->getIpAddress());
             if (count($leads)) {
                 //just create a tracking cookie for the newest lead
                 $lead = $leads[0];
                 $leadId = $lead->getId();
                 $this->logger->addDebug("LEAD: Existing lead found with ID# {$leadId}.");
             } else {
                 //let's create a lead
                 $lead = new Lead();
                 $lead->addIpAddress($ip);
                 $lead->setNewlyCreated(true);
                 // Set to prevent loops
                 $this->currentLead = $lead;
                 $this->saveEntity($lead, false);
                 $leadId = $lead->getId();
                 $this->logger->addDebug("LEAD: New lead created with ID# {$leadId}.");
             }
             $fields = $this->getLeadDetails($lead);
             $lead->setFields($fields);
         } else {
             $lead = $this->getEntity($leadId);
             if ($lead === null) {
                 //let's create a lead
                 $lead = new Lead();
                 $lead->addIpAddress($ip);
                 $lead->setNewlyCreated(true);
                 // Set to prevent loops
                 $this->currentLead = $lead;
                 $this->saveEntity($lead, false);
                 $leadId = $lead->getId();
                 $fields = $this->getLeadDetails($lead);
                 $lead->setFields($fields);
                 $this->logger->addDebug("LEAD: New lead created with ID# {$leadId}.");
             } else {
                 $this->logger->addDebug("LEAD: Existing lead found with ID# {$leadId}.");
             }
         }
         $this->currentLead = $lead;
         $this->setLeadCookie($leadId);
     }
     // Log last active
     if (!defined('MAUTIC_LEAD_LASTACTIVE_LOGGED')) {
         $this->getRepository()->updateLastActive($this->currentLead->getId());
         define('MAUTIC_LEAD_LASTACTIVE_LOGGED', 1);
     }
     return $returnTracking ? array($this->currentLead, $trackingId, $generated) : $this->currentLead;
 }
Ejemplo n.º 7
0
 /**
  * Create/update lead from form submit
  *
  * @param       $form
  * @param array $leadFieldMatches
  *
  * @return Lead
  */
 protected function createLeadFromSubmit($form, array $leadFieldMatches)
 {
     /** @var \Mautic\LeadBundle\Model\LeadModel $model */
     $model = $this->factory->getModel('lead');
     $em = $this->factory->getEntityManager();
     //set the mapped data
     $leadFields = $this->factory->getModel('lead.field')->getRepository()->getAliases(null, true, false);
     $data = array();
     $inKioskMode = $form->isInKioskMode();
     if (!$inKioskMode) {
         $lead = $model->getCurrentLead();
         $leadId = $lead->getId();
         $currentFields = $lead->getFields();
     } else {
         $lead = new Lead();
         $lead->setNewlyCreated(true);
         $leadId = null;
     }
     $uniqueLeadFields = $this->factory->getModel('lead.field')->getUniqueIdentiferFields();
     $uniqueFieldsWithData = array();
     foreach ($leadFields as $alias) {
         $data[$alias] = '';
         if (isset($leadFieldMatches[$alias])) {
             $value = $leadFieldMatches[$alias];
             $data[$alias] = $value;
             // make sure the value is actually there and the field is one of our uniques
             if (!empty($value) && array_key_exists($alias, $uniqueLeadFields)) {
                 $uniqueFieldsWithData[$alias] = $value;
             }
         }
     }
     //update the lead rather than creating a new one if there is for sure identifier match ($leadId is to exclude lead from getCurrentLead())
     /** @var \Mautic\LeadBundle\Entity\LeadRepository $leads */
     $leads = !empty($uniqueFieldsWithData) ? $em->getRepository('MauticLeadBundle:Lead')->getLeadsByUniqueFields($uniqueFieldsWithData, $leadId) : array();
     if (count($leads)) {
         //merge with current lead if not in kiosk mode
         $lead = $inKioskMode ? $leads[0] : $model->mergeLeads($lead, $leads[0]);
     } elseif (!$inKioskMode) {
         // Flatten current fields
         $currentFields = $model->flattenFields($currentFields);
         // Create a new lead if unique identifiers differ from getCurrentLead() and submitted data
         foreach ($uniqueLeadFields as $alias => $value) {
             //create a new lead if details differ
             $currentValue = $currentFields[$alias];
             if (!empty($currentValue) && strtolower($currentValue) != strtolower($value)) {
                 //for sure a different lead so create a new one
                 $lead = new Lead();
                 $lead->setNewlyCreated(true);
                 break;
             }
         }
     }
     //check for existing IP address
     $ipAddress = $this->factory->getIpAddress();
     //no lead was found by a mapped email field so create a new one
     if ($lead->isNewlyCreated()) {
         if (!$inKioskMode) {
             $lead->addIpAddress($ipAddress);
         }
         // last active time
         $lead->setLastActive(new \DateTime());
     } elseif (!$inKioskMode) {
         $leadIpAddresses = $lead->getIpAddresses();
         if (!$leadIpAddresses->contains($ipAddress)) {
             $lead->addIpAddress($ipAddress);
         }
     }
     //set the mapped fields
     $model->setFieldValues($lead, $data, false);
     if (!empty($event)) {
         $event->setIpAddress($ipAddress);
         $lead->addPointsChangeLog($event);
     }
     //create a new lead
     $model->saveEntity($lead, false);
     if (!$inKioskMode) {
         // Set the current lead which will generate tracking cookies
         $model->setCurrentLead($lead);
     } else {
         // Set system current lead which will still allow execution of events without generating tracking cookies
         $model->setSystemCurrentLead($lead);
     }
     return $lead;
 }
 protected function createLeadsFromStatuses($statusList, $monitor)
 {
     /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
     $leadModel = $this->getContainer()->get('mautic.lead.model.lead');
     /** @var \Mautic\LeadBundle\Model\FieldModel $leadFieldModel */
     $leadFieldModel = $this->getContainer()->get('mautic.lead.model.field');
     // handle field
     $handleField = $this->getContainer()->getParameter('mautic.twitter_handle_field', $this->getNetworkName());
     $leadField = $leadFieldModel->getRepository()->findOneBy(['alias' => $handleField]);
     if (!$leadField) {
         // Field has been deleted or something
         $this->output->writeln('Twitter lead field not found.');
         return;
     }
     $handleFieldGroup = $leadField->getGroup();
     // Just a means to let any LeadEvents listeners know that many leads are likely coming in case that matters to their logic
     defined('MASS_LEADS_MANIPULATION') or define('MASS_LEADS_MANIPULATION', 1);
     defined('SOCIAL_MONITOR_IMPORT') or define('SOCIAL_MONITOR_IMPORT', 1);
     // Get a list of existing leads to tone down on queries
     $twitterLeads = [];
     $qb = $leadModel->getRepository()->createQueryBuilder('f');
     $expr = $qb->expr();
     foreach ($statusList as $status) {
         if ($status['user']['screen_name']) {
             $twitterLeads[$status['user']['screen_name']] = $expr->literal($status['user']['screen_name']);
         }
     }
     unset($qb, $expr);
     if (!empty($twitterLeads)) {
         $leads = $leadModel->getRepository()->getEntities(['filter' => ['force' => [['column' => 'l.' . $handleField, 'expr' => 'in', 'value' => $twitterLeads]]]]);
         // Key by twitter handle
         $twitterLeads = [];
         foreach ($leads as $leadId => $lead) {
             $fields = $lead->getFields();
             $twitterHandle = $fields[$handleFieldGroup][$handleField]['value'];
             $twitterLeads[$twitterHandle] = $lead;
         }
         unset($leads);
     }
     $processedLeads = [];
     foreach ($statusList as $status) {
         if (empty($status['user']['screen_name'])) {
             continue;
         }
         // tweet timestamp
         $tweetTimestamp = $status['created_at'];
         $lastActive = new \DateTime($tweetTimestamp);
         $handle = $status['user']['screen_name'];
         /* @var \Mautic\LeadBundle\Entity\Lead $leadEntity */
         if (!isset($processedLeads[$handle])) {
             $processedLeads[$handle] = 1;
             if (isset($twitterLeads[$handle])) {
                 ++$this->updatedLeads;
                 $isNew = false;
                 $leadEntity = $twitterLeads[$handle];
                 $this->output->writeln('Updating existing lead ID #' . $leadEntity->getId() . ' (' . $handle . ')');
             } else {
                 ++$this->newLeads;
                 $this->output->writeln('Creating new lead');
                 $isNew = true;
                 $leadEntity = new Lead();
                 $leadEntity->setNewlyCreated(true);
                 list($firstName, $lastName) = $this->splitName($status['user']['name']);
                 // build new lead fields
                 $fields = [$handleField => $handle, 'firstname' => $firstName, 'lastname' => $lastName, 'country' => $status['user']['location']];
                 // set field values
                 $leadModel->setFieldValues($leadEntity, $fields, false);
                 // mark as identified just to be sure
                 $leadEntity->setDateIdentified(new \DateTime());
             }
             $leadEntity->setPreferredProfileImage(ucfirst($this->getNetworkName()));
             // save the lead now
             $leadEntity->setLastActive($lastActive->format('Y-m-d H:i:s'));
             try {
                 // save the lead entity
                 $leadModel->saveEntity($leadEntity);
                 // Note lead ids
                 $this->manipulatedLeads[$leadEntity->getId()] = 1;
                 // add lead entity to the lead list
                 $leadModel->addToLists($leadEntity, $monitor->getLists());
                 if ($isNew) {
                     $this->setMonitorLeadStat($monitor, $leadEntity);
                 }
             } catch (ExitMonitorException $e) {
                 $this->output->writeln($e->getMessage());
                 return;
             } catch (\Exception $e) {
                 $this->output->writeln($e->getMessage());
                 continue;
             }
         }
         // Increment the post count
         $this->incrementPostCount($monitor, $status);
     }
     unset($processedLeads);
     return;
 }