Exemplo n.º 1
0
 /**
  * @param int $page
  *
  * @return string
  */
 public function getTokenContent($page = 1)
 {
     if (!$this->factory->getSecurity()->isGranted('lead:fields:full')) {
         return;
     }
     $session = $this->factory->getSession();
     //set limits
     $limit = 5;
     $start = $page === 1 ? 0 : ($page - 1) * $limit;
     if ($start < 0) {
         $start = 0;
     }
     $request = $this->factory->getRequest();
     $search = $request->get('search', $session->get('mautic.lead.emailtoken.filter', ''));
     $session->set('mautic.lead.emailtoken.filter', $search);
     $filter = array('string' => $search, 'force' => array(array('column' => 'f.isPublished', 'expr' => 'eq', 'value' => true)));
     $fields = $this->factory->getModel('lead.field')->getEntities(array('start' => $start, 'limit' => $limit, 'filter' => $filter, 'orderBy' => 'f.label', 'orderByDir' => 'ASC', 'hydration_mode' => 'HYDRATE_ARRAY'));
     $count = count($fields);
     if ($count && $count < $start + 1) {
         //the number of entities are now less then the current page so redirect to the last page
         if ($count === 1) {
             $page = 1;
         } else {
             $page = ceil($count / $limit) ?: 1;
         }
         $session->set('mautic.lead.emailtoken.page', $page);
     }
     return $this->factory->getTemplating()->render('MauticLeadBundle:SubscribedEvents\\EmailToken:list.html.php', array('items' => $fields, 'page' => $page, 'limit' => $limit, 'totalCount' => $count, 'tmpl' => $request->get('tmpl', 'index'), 'searchValue' => $search));
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->factory = $this->getContainer()->get('mautic.factory');
     $queueMode = $this->factory->getParameter('queue_mode');
     // check to make sure we are in queue mode
     if ($queueMode != 'command_process') {
         $output->writeLn('Webhook Bundle is in immediate process mode. To use the command function change to command mode.');
         return 0;
     }
     $id = $input->getOption('webhook-id');
     /** @var \Mautic\WebhookBundle\Model\WebhookModel $model */
     $model = $this->factory->getModel('webhook');
     if ($id) {
         $webhook = $model->getEntity($id);
         $webhooks = $webhook !== null && $webhook->isPublished() ? array($id => $webhook) : array();
     } else {
         // make sure we only get published webhook entities
         $webhooks = $model->getEntities(array('filter' => array('force' => array(array('column' => 'e.isPublished', 'expr' => 'eq', 'value' => 1)))));
     }
     if (!count($webhooks)) {
         $output->writeln('<error>No published webhooks found. Try again later.</error>');
         return;
     }
     $output->writeLn('<info>Processing Webhooks</info>');
     try {
         $model->processWebhooks($webhooks);
     } catch (\Exception $e) {
         $output->writeLn('<error>' . $e->getMessage() . '</error>');
     }
     $output->writeLn('<info>Webhook Processing Complete</info>');
 }
 /**
  * @param MauticFactory $factory
  * @param               $lead
  * @param               $event
  *
  * @return bool|mixed
  */
 public static function sendEmailAction(MauticFactory $factory, $lead, $event)
 {
     $emailSent = false;
     if ($lead instanceof Lead) {
         $fields = $lead->getFields();
         /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
         $leadModel = $factory->getModel('lead');
         $leadCredentials = $leadModel->flattenFields($fields);
         $leadCredentials['id'] = $lead->getId();
     } else {
         $leadCredentials = $lead;
     }
     if (!empty($leadCredentials['email'])) {
         /** @var \Mautic\EmailBundle\Model\EmailModel $emailModel */
         $emailModel = $factory->getModel('email');
         $emailId = (int) $event['properties']['email'];
         $email = $emailModel->getEntity($emailId);
         if ($email != null && $email->isPublished()) {
             $options = array('source' => array('campaign', $event['campaign']['id']));
             $emailSent = $emailModel->sendEmail($email, $leadCredentials, $options);
         }
     }
     unset($lead, $leadCredentials, $email, $emailModel, $factory);
     return $emailSent;
 }
Exemplo n.º 4
0
 /**
  * @param MauticFactory $factory
  */
 public function __construct(MauticFactory $factory)
 {
     $this->translator = $factory->getTranslator();
     /** @var \Mautic\LeadBundle\Model\ListModel $listModel */
     $listModel = $factory->getModel('lead.list');
     $this->fieldChoices = $listModel->getChoiceFields();
     // Locales
     $this->timezoneChoices = FormFieldHelper::getTimezonesChoices();
     $this->countryChoices = FormFieldHelper::getCountryChoices();
     $this->regionChoices = FormFieldHelper::getRegionChoices();
     // Segments
     $lists = $listModel->getUserLists();
     foreach ($lists as $list) {
         $this->listChoices[$list['id']] = $list['name'];
     }
     // Emails
     /** @var \Mautic\EmailBundle\Model\EmailModel $emailModel */
     $emailModel = $factory->getModel('email');
     $viewOther = $factory->getSecurity()->isGranted('email:emails:viewother');
     $emails = $emailModel->getRepository()->getEmailList('', 0, 0, $viewOther, true);
     foreach ($emails as $email) {
         $this->emailChoices[$email['language']][$email['id']] = $email['name'];
     }
     ksort($this->emailChoices);
     // Tags
     $leadModel = $factory->getModel('lead');
     $tags = $leadModel->getTagList();
     foreach ($tags as $tag) {
         $this->tagChoices[$tag['value']] = $tag['label'];
     }
 }
Exemplo n.º 5
0
 /**
  * @param array $config
  * @param Lead $lead
  * @param MauticFactory $factory
  *
  * @return boolean
  */
 public static function send(array $config, Lead $lead, MauticFactory $factory)
 {
     /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
     $leadModel = $factory->getModel('lead.lead');
     if ($leadModel->isContactable($lead, 'sms') !== DoNotContact::IS_CONTACTABLE) {
         return array('failed' => 1);
     }
     $leadPhoneNumber = $lead->getFieldValue('mobile');
     if (empty($leadPhoneNumber)) {
         $leadPhoneNumber = $lead->getFieldValue('phone');
     }
     if (empty($leadPhoneNumber)) {
         return array('failed' => 1);
     }
     /** @var \Mautic\SmsBundle\Api\AbstractSmsApi $sms */
     $smsApi = $factory->getKernel()->getContainer()->get('mautic.sms.api');
     /** @var \Mautic\SmsBundle\Model\SmsModel $smsModel */
     $smsModel = $factory->getModel('sms');
     $smsId = (int) $config['sms'];
     /** @var \Mautic\SmsBundle\Entity\Sms $sms */
     $sms = $smsModel->getEntity($smsId);
     if ($sms->getId() !== $smsId) {
         return array('failed' => 1);
     }
     $dispatcher = $factory->getDispatcher();
     $event = new SmsSendEvent($sms->getMessage(), $lead);
     $event->setSmsId($smsId);
     $dispatcher->dispatch(SmsEvents::SMS_ON_SEND, $event);
     $metadata = $smsApi->sendSms($leadPhoneNumber, $event->getContent());
     // If there was a problem sending at this point, it's an API problem and should be requeued
     if ($metadata === false) {
         return false;
     }
     return array('type' => 'mautic.sms.sms', 'status' => 'mautic.sms.timeline.status.delivered', 'id' => $sms->getId(), 'name' => $sms->getName(), 'content' => $event->getContent());
 }
Exemplo n.º 6
0
 /**
  * Convert a non-tracked url to a tracked url.
  *
  * @param string $url
  * @param array  $clickthrough
  *
  * @return string
  */
 public function convertToTrackedUrl($url, array $clickthrough = [])
 {
     /** @var \Mautic\PageBundle\Model\TrackableModel $trackableModel */
     $trackableModel = $this->factory->getModel('page.trackable');
     /* @var \Mautic\PageBundle\Entity\Redirect $redirect */
     $trackable = $trackableModel->getTrackableByUrl($url, 'notification', $clickthrough['notification']);
     return $trackableModel->generateTrackableUrl($trackable, $clickthrough);
 }
Exemplo n.º 7
0
 /**
  * @param string $email
  *
  * @return bool
  */
 public function unsubscribe($email)
 {
     /** @var \Mautic\LeadBundle\Entity\LeadRepository $repo */
     $repo = $this->factory->getEntityManager()->getRepository('MauticLeadBundle:Lead');
     $lead = $repo->getLeadByEmail($email);
     /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
     $leadModel = $this->factory->getModel('lead.lead');
     return $leadModel->addDncForLead($lead, 'notification', null, DoNotContact::UNSUBSCRIBED);
 }
 /**
  * @param FormBuilderInterface $builder
  * @param array                $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $model = $this->factory->getModel('lead.list');
     $lists = $model->getUserLists();
     $segments = [];
     $segments[0] = $this->factory->getTranslator()->trans('mautic.lead.all.leads');
     foreach ($lists as $list) {
         $segments[$list['id']] = $list['name'];
     }
     $builder->add('flag', 'choice', ['label' => 'mautic.lead.list.filter', 'multiple' => true, 'choices' => $segments, 'label_attr' => ['class' => 'control-label'], 'attr' => ['class' => 'form-control'], 'required' => false]);
 }
Exemplo n.º 9
0
 /**
  * {@inheritdoc}
  *
  * @param Request $request
  *
  * @return Response never null
  */
 public function logout(Request $request, Response $response, TokenInterface $token)
 {
     /** @var \Mautic\UserBundle\Model\UserModel $userModel */
     $userModel = $this->factory->getModel('user');
     $userModel->setOnlineStatus('offline');
     $dispatcher = $this->factory->getDispatcher();
     if ($dispatcher->hasListeners(UserEvents::USER_LOGOUT)) {
         $event = new LogoutEvent($this->factory);
         $dispatcher->dispatch(UserEvents::USER_LOGOUT, $event);
     }
     // Clear session
     $this->factory->getSession()->clear();
 }
Exemplo n.º 10
0
 public function buildAddonCache()
 {
     // Populate our addon cache if not present
     /** @var \Mautic\AddonBundle\Entity\IntegrationRepository $repo */
     try {
         $repo = $this->factory->getModel('addon')->getRepository();
         static::$addons = $repo->getBundleStatus();
     } catch (\Exception $exception) {
         //database is probably not installed or there was an issue connecting
         return false;
     }
     static::$loaded = true;
 }
Exemplo n.º 11
0
 /**
  * Determine if this campaign applies
  *
  * @param $eventDetails
  * @param $event
  *
  * @return bool
  */
 public static function validateFormValue(MauticFactory $factory, $event, Lead $lead)
 {
     if (!$lead || !$lead->getId()) {
         return false;
     }
     $model = $factory->getModel('form');
     $operators = $model->getFilterExpressionFunctions();
     $form = $model->getRepository()->findOneById($event['properties']['form']);
     if (!$form || !$form->getId()) {
         return false;
     }
     return $factory->getModel('form.submission')->getRepository()->compareValue($lead->getId(), $form->getId(), $form->getAlias(), $event['properties']['field'], $event['properties']['value'], $operators[$event['properties']['operator']]['expr']);
 }
Exemplo n.º 12
0
 public static function createOpportunity(MauticFactory $factory, $lead, $event)
 {
     $model = $factory->getModel('customCrm.opportunity');
     $opportunity = new Opportunity();
     $opportunity->setStatus($event['properties']['status']);
     $opportunity->setConfidence($event['properties']['confidence']);
     $opportunity->setValue($event['properties']['value']);
     $opportunity->setValueType($event['properties']['valueType']);
     $opportunity->setEstimatedClose(self::generateDueDate($event));
     $opportunity->setComments($event['properties']['comments']);
     $opportunity->setOwnerUser($factory->getModel('user')->getEntity($event['properties']['ownerUser']));
     $opportunity->setLead($lead);
     $model->saveEntity($opportunity);
 }
 /**
  * @param mixed      $value
  * @param Constraint $constraint
  */
 public function validate($value, Constraint $constraint)
 {
     $listModel = $this->factory->getModel('lead.list');
     $lists = $listModel->getUserLists();
     if (!count($value)) {
         $this->context->addViolation($constraint->message, array('%string%' => ''));
     }
     foreach ($value as $l) {
         if (!isset($lists[$l->getId()])) {
             $this->context->addViolation($constraint->message, array('%string%' => $l->getName()));
             break;
         }
     }
 }
Exemplo n.º 14
0
 /**
  * @param MauticFactory $factory
  * @param               $lead
  * @param               $event
  *
  * @throws \Doctrine\ORM\ORMException
  */
 public static function addRemoveLead(MauticFactory $factory, $lead, $event)
 {
     /** @var \Mautic\CampaignBundle\Model\CampaignModel $campaignModel */
     $campaignModel = $factory->getModel('campaign');
     $properties = $event['properties'];
     $addToCampaigns = $properties['addTo'];
     $removeFromCampaigns = $properties['removeFrom'];
     $em = $factory->getEntityManager();
     $leadsModified = false;
     if (!empty($addToCampaigns)) {
         foreach ($addToCampaigns as $c) {
             $campaignModel->addLead($em->getReference('MauticCampaignBundle:Campaign', $c), $lead, true);
         }
         $leadsModified = true;
     }
     if (!empty($removeFromCampaigns)) {
         foreach ($removeFromCampaigns as $c) {
             if ($c == 'this') {
                 $c = $event['campaign']['id'];
             }
             $campaignModel->removeLead($em->getReference('MauticCampaignBundle:Campaign', $c), $lead, true);
         }
         $leadsModified = true;
     }
     return $leadsModified;
 }
Exemplo n.º 15
0
 /**
  * @param string              $tokenRegex     Token regex without wrapping regex escape characters.  Use (value) or (.*?) where the ID of the
  *                                            entity should go. i.e. {pagelink=(value)}
  * @param string              $filter         String to filter results by
  * @param string              $labelColumn    The column that houses the label
  * @param string              $valueColumn    The column that houses the value
  * @param CompositeExpression $expr           Use $factory->getDatabase()->getExpressionBuilder()->andX()
  *
  * @return array|void
  */
 public function getTokens($tokenRegex, $filter = '', $labelColumn = 'name', $valueColumn = 'id', CompositeExpression $expr = null)
 {
     //set some permissions
     $permissions = $this->factory->getSecurity()->isGranted($this->permissionSet, "RETURN_ARRAY");
     if (in_array(false, $permissions)) {
         return;
     }
     $repo = $this->factory->getModel($this->modelName)->getRepository();
     $prefix = $repo->getTableAlias();
     if (!empty($prefix)) {
         $prefix .= '.';
     }
     $exprBuilder = $this->factory->getDatabase()->getExpressionBuilder();
     if ($expr == null) {
         $expr = $exprBuilder->andX();
     }
     if (isset($permissions[$this->viewPermissionBase . ':viewother']) && !$permissions[$this->viewPermissionBase . ':viewother']) {
         $expr->add($exprBuilder->eq($prefix . 'createdBy', $this->factory->getUser()->getId()));
     }
     if (!empty($filter)) {
         $expr->add($exprBuilder->like('LOWER(' . $labelColumn . ')', ':label'));
         $parameters = array('label' => strtolower($filter) . '%');
     } else {
         $parameters = array();
     }
     $items = $repo->getSimpleList($expr, $parameters, $labelColumn, $valueColumn);
     $tokens = array();
     foreach ($items as $item) {
         $token = str_replace(array('(value)', '(.*?)'), $item['value'], $tokenRegex);
         $tokens[$token] = $item['label'];
     }
     return $tokens;
 }
Exemplo n.º 16
0
 /**
  * @param MauticFactory $factory
  */
 public function __construct(MauticFactory $factory)
 {
     $this->em = $factory->getEntityManager();
     $this->translator = $factory->getTranslator();
     $this->model = $factory->getModel('category');
     $this->router = $factory->getRouter();
 }
Exemplo n.º 17
0
 /**
  * @param MauticFactory $factory
  */
 public function __construct(MauticFactory $factory)
 {
     $this->translator = $factory->getTranslator();
     $this->em = $factory->getEntityManager();
     $this->model = $factory->getModel('page');
     $this->canViewOther = $factory->getSecurity()->isGranted('page:pages:viewother');
     $this->user = $factory->getUser();
 }
Exemplo n.º 18
0
 /**
  * @param FormBuilderInterface $builder
  * @param array $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     /** @var \Mautic\PluginBundle\Helper\IntegrationHelper $integrationHelper */
     $integrationHelper = $this->factory->getHelper('integration');
     $integrations = '';
     $integrationObjects = $integrationHelper->getIntegrationObjects(null, 'login_button');
     foreach ($integrationObjects as $integrationObject) {
         if ($integrationObject->getIntegrationSettings()->isPublished()) {
             /** @var \Mautic\AssetBundle\Model\AssetModel $model */
             $model = $this->factory->getModel('form');
             $integrations .= $integrationObject->getName() . ",";
             $integration = array('integration' => $integrationObject->getName());
             $builder->add('authUrl_' . $integrationObject->getName(), 'hidden', array('data' => $model->buildUrl('mautic_integration_auth_user', $integration, true, array())));
         }
     }
     $builder->add('integrations', 'hidden', array('data' => $integrations));
 }
Exemplo n.º 19
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);
     }
     // Match that data with mapped lead fields
     $matchedFields = $this->populateMauticLeadData($data);
     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 = array();
     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);
             // Update remaining leads
             if (count($existingLeads)) {
                 foreach ($existingLeads as $existingLead) {
                     $existingLead->setLastActive(new \DateTime());
                 }
             }
         }
     }
     $leadModel->setFieldValues($lead, $matchedFields, false, false);
     // Update the social cache
     $leadSocialCache = $lead->getSocialCache();
     if (!isset($leadSocialCache[$this->getName()])) {
         $leadSocialCache[$this->getName()] = array();
     }
     $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);
     $lead->setLastActive(new \DateTime());
     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;
 }
Exemplo n.º 20
0
 /**
  * @param Lead          $lead
  * @param               $config
  * @param MauticFactory $factory
  *
  * @return bool
  */
 public static function updateTags(Lead $lead, $config, MauticFactory $factory)
 {
     /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
     $leadModel = $factory->getModel('lead');
     $addTags = !empty($config['add_tags']) ? $config['add_tags'] : array();
     $removeTags = !empty($config['remove_tags']) ? $config['remove_tags'] : array();
     $leadModel->modifyTags($lead, $addTags, $removeTags);
     return true;
 }
Exemplo n.º 21
0
 /**
  * @param MauticFactory $factory
  */
 public function __construct(MauticFactory $factory)
 {
     $choices = $factory->getModel('user')->getRepository()->getEntities(array('filter' => array('force' => array(array('column' => 'u.isPublished', 'expr' => 'eq', 'value' => true)))));
     foreach ($choices as $choice) {
         $this->choices[$choice->getId()] = $choice->getName(true);
     }
     //sort by language
     ksort($this->choices);
 }
Exemplo n.º 22
0
 /**
  * @param MauticFactory $factory
  */
 public function __construct(MauticFactory $factory)
 {
     $viewOther = $factory->getSecurity()->isGranted('asset:assets:viewother');
     $choices = $factory->getModel('asset')->getRepository()->getAssetList('', 0, 0, $viewOther);
     foreach ($choices as $asset) {
         $this->choices[$asset['language']][$asset['id']] = $asset['title'];
     }
     //sort by language
     ksort($this->choices);
 }
Exemplo n.º 23
0
 /**
  * @param               $event
  * @param Lead          $lead
  * @param MauticFactory $factory
  */
 public static function sendEmail($event, Lead $lead, MauticFactory $factory)
 {
     $properties = $event['properties'];
     $emailId = (int) $properties['email'];
     /** @var \Mautic\EmailBundle\Model\EmailModel $model */
     $model = $factory->getModel('email');
     $email = $model->getEntity($emailId);
     //make sure the email still exists and is published
     if ($email != null && $email->isPublished()) {
         $leadFields = $lead->getFields();
         if (isset($leadFields['core']['email']['value']) && $leadFields['core']['email']['value']) {
             /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
             $leadModel = $factory->getModel('lead');
             $leadCredentials = $leadModel->flattenFields($leadFields);
             $leadCredentials['id'] = $lead->getId();
             $options = ['source' => ['trigger', $event['id']]];
             $model->sendEmail($email, $leadCredentials, $options);
         }
     }
 }
Exemplo n.º 24
0
 /**
  * @param MauticFactory $factory
  */
 public function __construct(MauticFactory $factory)
 {
     $this->translator = $factory->getTranslator();
     /** @var \Mautic\LeadBundle\Model\ListModel $listModel */
     $listModel = $factory->getModel('lead.list');
     $this->fieldChoices = $listModel->getChoiceFields();
     $this->timezoneChoices = FormFieldHelper::getTimezonesChoices();
     $this->countryChoices = FormFieldHelper::getCountryChoices();
     $this->regionChoices = FormFieldHelper::getRegionChoices();
     $lists = $listModel->getUserLists();
     $this->listChoices = array();
     foreach ($lists as $list) {
         $this->listChoices[$list['id']] = $list['name'];
     }
     $leadModel = $factory->getModel('lead');
     $tags = $leadModel->getTagList();
     foreach ($tags as $tag) {
         $this->tagChoices[$tag['value']] = $tag['label'];
     }
 }
Exemplo n.º 25
0
 /**
  * Create an email stat
  *
  * @param bool|true   $persist
  * @param string|null $emailAddress
  * @param null        $listId
  *
  * @return Stat|void
  * @throws \Doctrine\ORM\ORMException
  */
 public function createEmailStat($persist = true, $emailAddress = null, $listId = null)
 {
     static $copies = array();
     //create a stat
     $stat = new Stat();
     $stat->setDateSent(new \DateTime());
     $stat->setEmail($this->email);
     // Note if a lead
     if (null !== $this->lead) {
         $stat->setLead($this->factory->getEntityManager()->getReference('MauticLeadBundle:Lead', $this->lead['id']));
         $emailAddress = $this->lead['email'];
     }
     // Find email if applicable
     if (null === $emailAddress) {
         // Use the last address set
         $emailAddresses = $this->message->getTo();
         if (count($emailAddresses)) {
             end($emailAddresses);
             $emailAddress = key($emailAddresses);
         }
     }
     $stat->setEmailAddress($emailAddress);
     // Note if sent from a lead list
     if (null !== $listId) {
         $stat->setList($this->factory->getEntityManager()->getReference('MauticLeadBundle:LeadList', $listId));
     }
     $stat->setTrackingHash($this->idHash);
     if (!empty($this->source)) {
         $stat->setSource($this->source[0]);
         $stat->setSourceId($this->source[1]);
     }
     $stat->setTokens($this->getTokens());
     /** @var \Mautic\EmailBundle\Model\EmailModel $emailModel */
     $emailModel = $this->factory->getModel('email');
     // Save a copy of the email - use email ID if available simply to prevent from having to rehash over and over
     $id = null !== $this->email ? $this->email->getId() : md5($this->subject . $this->body['content']);
     if (!isset($copies[$id])) {
         $hash = strlen($id) !== 32 ? md5($this->subject . $this->body['content']) : $id;
         $copy = $emailModel->getCopyRepository()->findByHash($hash);
         if (null === $copy) {
             // Create a copy entry
             $copy = new Copy();
             $copy->setId($hash)->setBody($this->body['content'])->setSubject($this->subject)->setDateCreated(new \DateTime())->setEmail($this->email);
             $emailModel->getCopyRepository()->saveEntity($copy);
         }
         $copies[$id] = $copy;
     }
     $stat->setStoredCopy($copies[$id]);
     if ($persist) {
         $emailModel->getStatRepository()->saveEntity($stat);
     }
     return $stat;
 }
Exemplo n.º 26
0
 /**
  * @param Form          $form
  * @param Asset         $asset
  * @param MauticFactory $factory
  * @param               $message
  * @param               $messageMode
  *
  * @return RedirectResponse|Response
  */
 public static function downloadFile(Form $form, Asset $asset, MauticFactory $factory, $message, $messengerMode)
 {
     /** @var \Mautic\AssetBundle\Model\AssetModel $model */
     $model = $factory->getModel('asset');
     $url = $model->generateUrl($asset, true, array('form', $form->getId()));
     if ($messengerMode) {
         return array('download' => $url);
     }
     $msg = $message . $factory->getTranslator()->trans('mautic.asset.asset.submitaction.downloadfile.msg', array('%url%' => $url));
     $content = $factory->getTemplating()->renderResponse('MauticCoreBundle::message.html.php', array('message' => $msg, 'type' => 'notice', 'template' => $factory->getParameter('theme')))->getContent();
     return new Response($content);
 }
Exemplo n.º 27
0
 /**
  * @param array $config
  * @param Lead $lead
  * @param MauticFactory $factory
  *
  * @return array
  */
 public static function send(array $config, Lead $lead, MauticFactory $factory)
 {
     /** @var \Mautic\LeadBundle\Model\LeadModel $leadModel */
     $leadModel = $factory->getModel('lead.lead');
     $logger = $factory->getLogger();
     if ($leadModel->isContactable($lead, 'notification') !== DoNotContact::IS_CONTACTABLE) {
         $logger->error('Error: Lead ' . $lead->getId() . ' is not contactable on the web push channel.');
         return array('failed' => 1);
     }
     // If lead has subscribed on multiple devices, get all of them.
     /** @var \Mautic\NotificationBundle\Entity\PushID[] $pushIDs */
     $pushIDs = $lead->getPushIDs();
     $playerID = array();
     foreach ($pushIDs as $pushID) {
         $playerID[] = $pushID->getPushID();
     }
     if (empty($playerID)) {
         $logger->error('Error: Lead ' . $lead->getId() . ' has not subscribed to web push channel.');
         return array('failed' => 1);
     }
     /** @var \Mautic\NotificationBundle\Api\AbstractNotificationApi $notification */
     $notificationApi = $factory->getKernel()->getContainer()->get('mautic.notification.api');
     /** @var \Mautic\NotificationBundle\Model\NotificationModel $notificationModel */
     $notificationModel = $factory->getModel('notification');
     $notificationId = (int) $config['notification'];
     /** @var \Mautic\NotificationBundle\Entity\Notification $notification */
     $notification = $notificationModel->getEntity($notificationId);
     if ($notification->getId() !== $notificationId) {
         $logger->error('Error: The requested notification cannot be found.');
         return array('failed' => 1);
     }
     $url = $notificationApi->convertToTrackedUrl($notification->getUrl(), array('notification' => $notification->getId(), 'lead' => $lead->getId()));
     $response = $notificationApi->sendNotification($playerID, $notification->getMessage(), $notification->getHeading(), $url);
     // If for some reason the call failed, tell mautic to try again by return false
     if ($response->code !== 200) {
         $logger->error('Error: The notification failed to send and returned a ' . $response->code . ' HTTP response with a body of: ' . $response->body);
         return false;
     }
     return array('status' => 'mautic.notification.timeline.status.delivered', 'type' => 'mautic.notification.notification', 'id' => $notification->getId(), 'name' => $notification->getName(), 'heading' => $notification->getHeading(), 'content' => $notification->getMessage());
 }
Exemplo n.º 28
0
 /**
  * @param MauticFactory $factory
  */
 public function __construct(MauticFactory $factory)
 {
     /** @var \Mautic\LeadBundle\Model\ListModel $listModel */
     $listModel = $factory->getModel('lead.list');
     $operatorChoices = $listModel->getFilterExpressionFunctions();
     $this->operatorChoices = array();
     foreach ($operatorChoices as $key => $value) {
         if (empty($value['hide'])) {
             $this->operatorChoices[$key] = $value['label'];
         }
     }
     $this->translator = $factory->getTranslator();
 }
Exemplo n.º 29
0
 /**
  * @param MauticFactory $factory
  */
 public function __construct(MauticFactory $factory)
 {
     /** @var \Mautic\LeadBundle\Model\ListModel $listModel */
     $listModel = $factory->getModel('lead.list');
     $operatorChoices = $listModel->getFilterExpressionFunctions();
     $this->operatorChoices = [];
     foreach ($operatorChoices as $key => $value) {
         if (empty($value['hide'])) {
             $this->operatorChoices[$key] = $value['label'];
         }
     }
     $this->translator = $factory->getTranslator();
     $this->currentListId = $factory->getRequest()->attributes->get('objectId', false);
 }
Exemplo n.º 30
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('weight', 'integer', ['label' => 'mautic.core.ab_test.form.traffic_weight', 'label_attr' => ['class' => 'control-label'], 'attr' => ['class' => 'form-control', 'tooltip' => 'mautic.core.ab_test.form.traffic_weight.help'], 'constraints' => [new NotBlank(['message' => 'mautic.page.variant.weight.notblank'])]]);
     $abTestWinnerCriteria = $this->factory->getModel('page.page')->getBuilderComponents(null, 'abTestWinnerCriteria');
     if (!empty($abTestWinnerCriteria)) {
         $criteria = $abTestWinnerCriteria['criteria'];
         $choices = $abTestWinnerCriteria['choices'];
         $builder->add('winnerCriteria', 'choice', ['label' => 'mautic.core.ab_test.form.winner', 'label_attr' => ['class' => 'control-label'], 'attr' => ['class' => 'form-control', 'onchange' => 'Mautic.getAbTestWinnerForm(\'page\', \'page\', this);'], 'expanded' => false, 'multiple' => false, 'choices' => $choices, 'empty_value' => 'mautic.core.form.chooseone', 'constraints' => [new NotBlank(['message' => 'mautic.core.ab_test.winner_criteria.not_blank'])]]);
         $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use($options, $criteria) {
             $form = $event->getForm();
             $data = $event->getData();
             if (isset($data['winnerCriteria'])) {
                 if (!empty($criteria[$data['winnerCriteria']]['formType'])) {
                     $formTypeOptions = ['required' => false, 'label' => false];
                     if (!empty($criteria[$data]['formTypeOptions'])) {
                         $formTypeOptions = array_merge($formTypeOptions, $criteria[$data]['formTypeOptions']);
                     }
                     $form->add('properties', $criteria[$data]['formType'], $formTypeOptions);
                 }
             }
         });
     }
 }