public function onConfigBeforeSave(ConfigEvent $event) { $values = $event->getConfig(); // Preserve existing value $event->unsetIfEmpty('transifex_password'); // Check if the selected locale has been downloaded already, fetch it if not $installedLanguages = $this->coreParametersHelper->getParameter('supported_languages'); if (!array_key_exists($values['coreconfig']['locale'], $installedLanguages)) { $fetchLanguage = $this->languageHelper->extractLanguagePackage($values['coreconfig']['locale']); // If there is an error, fall back to 'en_US' as it is our system default if ($fetchLanguage['error']) { $values['coreconfig']['locale'] = 'en_US'; $message = 'mautic.core.could.not.set.language'; $messageVars = []; if (isset($fetchLanguage['message'])) { $message = $fetchLanguage['message']; } if (isset($fetchLanguage['vars'])) { $messageVars = $fetchLanguage['vars']; } $event->setError($message, $messageVars); } } $event->setConfig($values); }
/** * WebhookModel constructor. * * @param CoreParametersHelper $coreParametersHelper * @param Serializer $serializer */ public function __construct(CoreParametersHelper $coreParametersHelper, Serializer $serializer) { $this->queueMode = $coreParametersHelper->getParameter('queue_mode'); $this->webhookStart = $coreParametersHelper->getParameter('webhook_start'); $this->webhookLimit = $coreParametersHelper->getParameter('webhook_limit'); $this->serializer = $serializer; $this->logMax = $coreParametersHelper->getParameter('webhook_log_max', 10); }
/** * CampaignModel constructor. * * @param CoreParametersHelper $coreParametersHelper * @param LeadModel $leadModel * @param ListModel $leadListModel * @param FormModel $formModel */ public function __construct(CoreParametersHelper $coreParametersHelper, LeadModel $leadModel, ListModel $leadListModel, FormModel $formModel) { $this->leadModel = $leadModel; $this->leadListModel = $leadListModel; $this->formModel = $formModel; $this->batchSleepTime = $coreParametersHelper->getParameter('mautic.batch_sleep_time'); $this->batchCampaignSleepTime = $coreParametersHelper->getParameter('mautic.batch_campaign_sleep_time'); }
/** * IpLookupHelper constructor. * * @param RequestStack $requestStack * @param EntityManager $em * @param CoreParametersHelper $coreParametersHelper * @param AbstractLookup $ipLookup */ public function __construct(RequestStack $requestStack, EntityManager $em, CoreParametersHelper $coreParametersHelper, AbstractLookup $ipLookup = null) { $this->request = $requestStack->getCurrentRequest(); $this->em = $em; $this->ipLookup = $ipLookup; $this->doNotTrackIps = $coreParametersHelper->getParameter('mautic.do_not_track_ips'); $this->doNotTrackInternalIps = $coreParametersHelper->getParameter('mautic.do_not_track_internal_ips'); }
/** * @param PageDisplayEvent $event */ public function onPageDisplay(PageDisplayEvent $event) { if (!$this->coreParametersHelper->getParameter('notification_enabled')) { return; } $appId = $this->coreParametersHelper->getParameter('notification_app_id'); $safariWebId = $this->coreParametersHelper->getParameter('notification_safari_web_id'); $this->assetsHelper->addScript($this->router->generate('mautic_js', [], UrlGeneratorInterface::ABSOLUTE_URL), 'onPageDisplay_headClose', true, 'mautic_js'); $this->assetsHelper->addScript('https://cdn.onesignal.com/sdks/OneSignalSDK.js', 'onPageDisplay_headClose'); $manifestUrl = $this->router->generate('mautic_onesignal_manifest'); $this->assetsHelper->addCustomDeclaration('<link rel="manifest" href="' . $manifestUrl . '" />', 'onPageDisplay_headClose'); $leadAssociationUrl = $this->router->generate('mautic_subscribe_notification', [], UrlGeneratorInterface::ABSOLUTE_URL); $oneSignalInit = <<<JS var OneSignal = OneSignal || []; OneSignal.push(["init", { appId: "{$appId}", safari_web_id: "{$safariWebId}", autoRegister: true, notifyButton: { enable: false // Set to false to hide } }]); var postUserIdToMautic = function(userId) { var xhr = new XMLHttpRequest(); xhr.open('post', '{$leadAssociationUrl}', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('osid=' + userId); }; OneSignal.getUserId(function(userId) { if (! userId) { OneSignal.on('subscriptionChange', function(isSubscribed) { if (isSubscribed) { OneSignal.getUserId(function(newUserId) { postUserIdToMautic(newUserId); }); } }); } else { postUserIdToMautic(userId); } }); // Just to be sure we've grabbed the ID window.onbeforeunload = function() { OneSignal.getUserId(function(userId) { if (userId) { postUserIdToMautic(userId); } }); }; JS; $this->assetsHelper->addScriptDeclaration($oneSignalInit, 'onPageDisplay_headClose'); }
/** * @param bool $includePlugins * @return mixed */ public function getMauticBundles($includePlugins = true) { $bundles = $this->coreParametersHelper->getParameter('mautic.bundles'); if ($includePlugins) { $plugins = $this->coreParametersHelper->getParameter('mautic.plugin.bundles'); $bundles = array_merge($bundles, $plugins); } return $bundles; }
/** * Check for API requests and throw denied access if API is disabled. * * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $apiEnabled = $this->coreParametersHelper->getParameter('api_enabled'); $request = $event->getRequest(); $requestUrl = $request->getRequestUri(); // Check if /oauth or /api $isApiRequest = strpos($requestUrl, '/oauth') !== false || strpos($requestUrl, '/api') !== false; defined('MAUTIC_API_REQUEST') or define('MAUTIC_API_REQUEST', $isApiRequest); if ($isApiRequest && !$apiEnabled) { throw new AccessDeniedHttpException($this->translator->trans('mautic.core.url.error.401', ['%url%' => $request->getRequestUri()])); } }
/** * Fetch upstream notifications via RSS. */ public function updateUpstreamNotifications() { $url = $this->coreParametersHelper->getParameter('rss_notification_url'); if (empty($url)) { return; } //check to see when we last checked for an update $lastChecked = $this->session->get('mautic.upstream.checked', 0); if (time() - $lastChecked > 3600) { $this->session->set('mautic.upstream.checked', time()); $lastDate = $this->getRepository()->getUpstreamLastDate(); try { /** @var FeedContent $feed */ $feed = $this->rssReader->getFeedContent($url, $lastDate); /** @var Item $item */ foreach ($feed->getItems() as $item) { $description = $item->getDescription(); if (mb_strlen(strip_tags($description)) > 300) { $description = mb_substr(strip_tags($description), 0, 300); $description .= '... <a href="' . $item->getLink() . '" target="_blank">' . $this->translator->trans('mautic.core.notification.read_more') . '</a>'; } $header = $item->getTitle(); $this->addNotification($description, 'upstream', false, $header ? $header : null, 'fa-bullhorn'); } } catch (\Exception $exception) { $this->logger->addWarning($exception->getMessage()); } } }
/** * Authenticate via the form using users defined in authorized_users * * @param AuthenticationEvent $event * * @return bool|void */ public function onUserFormAuthentication(AuthenticationEvent $event) { $username = $event->getUsername(); $password = $event->getToken()->getCredentials(); $user = new User(); $user->setUsername($username); $authorizedUsers = $this->parametersHelper->getParameter('authorized_users'); if (is_array($authorizedUsers) && isset($authorizedUsers[$username])) { $testUser = $authorizedUsers[$username]; $user->setPassword($testUser['password']); if ($this->encoder->isPasswordValid($user, $password)) { $user->setFirstName($testUser['firstname'])->setLastName($testUser['lastname'])->setEmail($testUser['email'])->setRole($this->em->getReference('MauticUserBundle:Role', 1)); $event->setIsAuthenticated('authorized_users', $user, true); } } }
public function __construct(LeadModel $leadModel, CategoryModel $categoryModel, RequestStack $requestStack, IpLookupHelper $ipLookupHelper, CoreParametersHelper $coreParametersHelper) { $this->leadModel = $leadModel; $this->categoryModel = $categoryModel; $this->request = $requestStack->getCurrentRequest(); $this->ipLookupHelper = $ipLookupHelper; $this->maxAssetSize = $coreParametersHelper->getParameter('mautic.max_size'); }
/** * Method to tail (a few last rows) of a file * * @param int $lines * * @return array|null */ public function getLogTail($lines = 10) { $log = $this->coreParametersHelper->getParameter('log_path') . '/mautic_' . MAUTIC_ENV . '-' . date('Y-m-d') . '.php'; if (!file_exists($log)) { return null; } return $this->tail($log, $lines); }
public function onConfigBeforeSave(ConfigEvent $event) { $event->unsetIfEmpty(['mailer_password', 'mailer_api_key']); $data = $event->getConfig('emailconfig'); // Get the original data so that passwords aren't lost $monitoredEmail = $this->coreParametersHelper->getParameter('monitored_email'); if (isset($data['monitored_email'])) { foreach ($data['monitored_email'] as $key => $monitor) { if (empty($monitor['password']) && !empty($monitoredEmail[$key]['password'])) { $data['monitored_email'][$key]['password'] = $monitoredEmail[$key]['password']; } if ($key != 'general') { if (empty($monitor['host']) || empty($monitor['address']) || empty($monitor['folder'])) { $data['monitored_email'][$key]['override_settings'] = ''; $data['monitored_email'][$key]['address'] = ''; $data['monitored_email'][$key]['host'] = ''; $data['monitored_email'][$key]['user'] = ''; $data['monitored_email'][$key]['password'] = ''; $data['monitored_email'][$key]['ssl'] = '1'; $data['monitored_email'][$key]['port'] = '993'; } } } } // Ensure that percent signs are decoded in the unsubscribe/webview settings $decode = ['unsubscribe_text', 'webview_text', 'unsubscribe_message', 'resubscribe_message']; foreach ($decode as $key) { if (strpos($data[$key], '%') !== false) { $data[$key] = urldecode($data[$key]); if (preg_match_all('/([^%]|^)(%{1}[^%]\\S+[^%]%{1})([^%]|$)/i', $data[$key], $matches)) { // Encode any left over to prevent Symfony from crashing foreach ($matches[0] as $matchKey => $match) { $replaceWith = $matches[1][$matchKey] . '%' . $matches[2][$matchKey] . '%' . $matches[3][$matchKey]; $data[$key] = str_replace($match, $replaceWith, $data[$key]); } } } } $event->setConfig($data, 'emailconfig'); }
/** * PathsHelper constructor. * * @param CoreParametersHelper * @param UserHelper $userHelper */ public function __construct(UserHelper $userHelper, CoreParametersHelper $coreParametersHelper) { $this->user = $userHelper->getUser(); $this->paths = $coreParametersHelper->getParameter('paths'); $this->theme = $coreParametersHelper->getParameter('theme'); $this->imagePath = $coreParametersHelper->getParameter('image_path'); $this->dashboardImportDir = $coreParametersHelper->getParameter('dashboard_import_dir'); $this->dashboardImportUserDir = $coreParametersHelper->getParameter('dashboard_import_user_dir'); $this->kernelCacheDir = $coreParametersHelper->getParameter('kernel.cache_dir'); $this->kernelLogsDir = $coreParametersHelper->getParameter('kernel.logs_dir'); }
/** * Obtains a list of entities as defined by the API URL. * * @return Response */ public function getEntitiesAction() { $repo = $this->model->getRepository(); $tableAlias = $repo->getTableAlias(); $publishedOnly = $this->request->get('published', 0); if ($publishedOnly) { $this->listFilters[] = ['column' => $tableAlias . '.isPublished', 'expr' => 'eq', 'value' => true]; } $args = ['start' => $this->request->query->get('start', 0), 'limit' => $this->request->query->get('limit', $this->coreParametersHelper->getParameter('default_pagelimit')), 'filter' => ['string' => $this->request->query->get('search', ''), 'force' => $this->listFilters], 'orderBy' => $this->request->query->get('orderBy', ''), 'orderByDir' => $this->request->query->get('orderByDir', 'ASC'), 'withTotalCount' => true]; $results = $this->model->getEntities($args); list($entities, $totalCount) = $this->prepareEntitiesForView($results); $view = $this->view(['total' => $totalCount, $this->entityNameMulti => $entities], Codes::HTTP_OK); $this->setSerializationContext($view); return $this->handleView($view); }
/** * Batch sleep according to settings */ protected function batchSleep() { $leadSleepTime = $this->coreParametersHelper->getParameter('batch_lead_sleep_time', false); if ($leadSleepTime === false) { $leadSleepTime = $this->coreParametersHelper->getParameter('batch_sleep_time', 1); } if (empty($leadSleepTime)) { return; } if ($leadSleepTime < 1) { usleep($leadSleepTime * 1000000); } else { sleep($leadSleepTime); } }
/** * UserType constructor. * * @param TranslatorInterface $translator * @param EntityManager $em * @param UserModel $model * @param LanguageHelper $languageHelper * @param CoreParametersHelper $parametersHelper */ public function __construct(TranslatorInterface $translator, EntityManager $em, UserModel $model, LanguageHelper $languageHelper, CoreParametersHelper $parametersHelper) { $this->translator = $translator; $this->em = $em; $this->model = $model; // Get the list of available languages $languages = $languageHelper->fetchLanguages(false, false); $langChoices = []; foreach ($languages as $code => $langData) { $langChoices[$code] = $langData['name']; } $langChoices = array_merge($langChoices, $parametersHelper->getParameter('supported_languages')); // Alpha sort the languages by name asort($langChoices); $this->supportedLanguages = $langChoices; }
/** * Validates file before upload * * @param ValidationEvent $event */ public function onUploadValidation(ValidationEvent $event) { $file = $event->getFile(); $extensions = $this->coreParametersHelper->getParameter('allowed_extensions'); $maxSize = $this->assetModel->getMaxUploadSize('B'); if ($file !== null) { if ($file->getSize() > $maxSize) { $message = $this->translator->trans('mautic.asset.asset.error.file.size', ['%fileSize%' => round($file->getSize() / 1048576, 2), '%maxSize%' => round($maxSize / 1048576, 2)], 'validators'); throw new ValidationException($message); } if (!in_array(strtolower($file->getExtension()), array_map('strtolower', $extensions))) { $message = $this->translator->trans('mautic.asset.asset.error.file.extension', ['%fileExtension%' => $file->getExtension(), '%extensions%' => implode(', ', $extensions)], 'validators'); throw new ValidationException($message); } } }
/** * @param EmailSendEvent $event */ public function onEmailGenerate(EmailSendEvent $event) { $idHash = $event->getIdHash(); $lead = $event->getLead(); $email = $event->getEmail(); if ($idHash == null) { // Generate a bogus idHash to prevent errors for routes that may include it $idHash = uniqid(); } $unsubscribeText = $this->coreParametersHelper->getParameter('unsubscribe_text'); if (!$unsubscribeText) { $unsubscribeText = $this->translator->trans('mautic.email.unsubscribe.text', ['%link%' => '|URL|']); } $unsubscribeText = str_replace('|URL|', $this->emailModel->buildUrl('mautic_email_unsubscribe', ['idHash' => $idHash]), $unsubscribeText); $event->addToken('{unsubscribe_text}', $unsubscribeText); $event->addToken('{unsubscribe_url}', $this->emailModel->buildUrl('mautic_email_unsubscribe', ['idHash' => $idHash])); $webviewText = $this->coreParametersHelper->getParameter('webview_text'); if (!$webviewText) { $webviewText = $this->translator->trans('mautic.email.webview.text', ['%link%' => '|URL|']); } $webviewText = str_replace('|URL|', $this->emailModel->buildUrl('mautic_email_webview', ['idHash' => $idHash]), $webviewText); $event->addToken('{webview_text}', $webviewText); // Show public email preview if the lead is not known to prevent 404 if (empty($lead['id']) && $email) { $event->addToken('{webview_url}', $this->emailModel->buildUrl('mautic_email_preview', ['objectId' => $email->getId()])); } else { $event->addToken('{webview_url}', $this->emailModel->buildUrl('mautic_email_webview', ['idHash' => $idHash])); } $signatureText = $this->coreParametersHelper->getParameter('default_signature_text'); $fromName = $this->coreParametersHelper->getParameter('mailer_from_name'); if (!empty($lead['owner_id'])) { $owner = $this->factory->getModel('lead')->getRepository()->getLeadOwner($lead['owner_id']); if ($owner && !empty($owner['signature'])) { $fromName = $owner['first_name'] . ' ' . $owner['last_name']; $signatureText = $owner['signature']; } } $signatureText = str_replace('|FROM_NAME|', $fromName, nl2br($signatureText)); $event->addToken('{signature}', $signatureText); $event->addToken('{subject}', $event->getSubject()); }
/** * Set vars on login. * * @param InteractiveLoginEvent $event */ public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) { if (defined('MAUTIC_INSTALLER')) { return; } $session = $event->getRequest()->getSession(); if ($this->securityContext->isGranted('IS_AUTHENTICATED_FULLY') || $this->securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) { $user = $event->getAuthenticationToken()->getUser(); //set a session var for filemanager to know someone is logged in $session->set('mautic.user', $user->getId()); //mark the user as last logged in $user = $this->userHelper->getUser(); if ($user instanceof User) { $this->userModel->setOnlineStatus('online'); $this->userModel->getRepository()->setLastLogin($user); // Set the timezone and locale in session while we have it since Symfony dispatches the onKernelRequest prior to the // firewall setting the known user $tz = $user->getTimezone(); if (empty($tz)) { $tz = $this->params['default_timezone']; } $session->set('_timezone', $tz); $locale = $user->getLocale(); if (empty($locale)) { $locale = $this->params['locale']; } $session->set('_locale', $locale); } //dispatch on login events if ($this->dispatcher->hasListeners(UserEvents::USER_LOGIN)) { $event = new LoginEvent($this->userHelper->getUser()); $this->dispatcher->dispatch(UserEvents::USER_LOGIN, $event); } } else { $session->remove('mautic.user'); } //set a couple variables used by filemanager $session->set('mautic.docroot', $event->getRequest()->server->get('DOCUMENT_ROOT')); $session->set('mautic.basepath', $event->getRequest()->getBasePath()); $session->set('mautic.imagepath', $this->coreParametersHelper->getParameter('image_path')); }
/** * @param CampaignExecutionEvent $event */ public function onCampaignTriggerAction(CampaignExecutionEvent $event) { $lead = $event->getLead(); if ($this->leadModel->isContactable($lead, 'sms') !== DoNotContact::IS_CONTACTABLE) { return $event->setFailed('mautic.sms.campaign.failed.not_contactable'); } $leadPhoneNumber = $lead->getFieldValue('mobile'); if (empty($leadPhoneNumber)) { $leadPhoneNumber = $lead->getFieldValue('phone'); } if (empty($leadPhoneNumber)) { return $event->setFailed('mautic.sms.campaign.failed.missing_number'); } $smsId = (int) $event->getConfig()['sms']; $sms = $this->smsModel->getEntity($smsId); if ($sms->getId() !== $smsId) { return $event->setFailed('mautic.sms.campaign.failed.missing_entity'); } $smsEvent = new SmsSendEvent($sms->getMessage(), $lead); $smsEvent->setSmsId($smsId); $this->dispatcher->dispatch(SmsEvents::SMS_ON_SEND, $smsEvent); $tokenEvent = $this->dispatcher->dispatch(SmsEvents::TOKEN_REPLACEMENT, new TokenReplacementEvent($smsEvent->getContent(), $lead, ['channel' => ['sms', $sms->getId()]])); $metadata = $this->smsApi->sendSms($leadPhoneNumber, $tokenEvent->getContent()); $defaultFrequencyNumber = $this->coreParametersHelper->getParameter('sms_frequency_number'); $defaultFrequencyTime = $this->coreParametersHelper->getParameter('sms_frequency_time'); /** @var \Mautic\LeadBundle\Entity\FrequencyRuleRepository $frequencyRulesRepo */ $frequencyRulesRepo = $this->leadModel->getFrequencyRuleRepository(); $leadIds = $lead->getId(); $dontSendTo = $frequencyRulesRepo->getAppliedFrequencyRules('sms', $leadIds, $defaultFrequencyNumber, $defaultFrequencyTime); if (!empty($dontSendTo) and $dontSendTo[0]['lead_id'] != $lead->getId()) { $metadata = $this->smsApi->sendSms($leadPhoneNumber, $smsEvent->getContent()); } // If there was a problem sending at this point, it's an API problem and should be requeued if ($metadata === false) { return $event->setResult(false); } $this->smsModel->createStatEntry($sms, $lead); $this->smsModel->getRepository()->upCount($smsId); $event->setChannel('sms', $sms->getId()); $event->setResult(['type' => 'mautic.sms.sms', 'status' => 'mautic.sms.timeline.status.delivered', 'id' => $sms->getId(), 'name' => $sms->getName(), 'content' => $tokenEvent->getContent()]); }
/** * @param CampaignBuilderEvent $event */ public function onCampaignBuild(CampaignBuilderEvent $event) { if ($this->coreParametersHelper->getParameter('notification_enabled')) { $event->addAction('notification.send_notification', ['label' => 'mautic.notification.campaign.send_notification', 'description' => 'mautic.notification.campaign.send_notification.tooltip', 'eventName' => NotificationEvents::ON_CAMPAIGN_TRIGGER_ACTION, 'formType' => 'notificationsend_list', 'formTypeOptions' => ['update_select' => 'campaignevent_properties_notification'], 'formTheme' => 'MauticNotificationBundle:FormTheme\\NotificationSendList', 'timelineTemplate' => 'MauticNotificationBundle:SubscribedEvents\\Timeline:index.html.php']); } }
/** * EventModel constructor. * * @param IpLookupHelper $ipLookupHelper * @param CoreParametersHelper $coreParametersHelper * @param LeadModel $leadModel * @param CampaignModel $campaignModel * @param MauticFactory $factory */ public function __construct(IpLookupHelper $ipLookupHelper, CoreParametersHelper $coreParametersHelper, LeadModel $leadModel, CampaignModel $campaignModel, MauticFactory $factory) { $this->ipLookupHelper = $ipLookupHelper; $this->leadModel = $leadModel; $this->campaignModel = $campaignModel; $this->batchSleepTime = $coreParametersHelper->getParameter('mautic.batch_sleep_time'); $this->batchCampaignSleepTime = $coreParametersHelper->getParameter('mautic.batch_campaign_sleep_time'); $this->scheduleTimeForFailedEvents = $coreParametersHelper->getParameter('campaign_time_wait_on_event_false'); $this->factory = $factory; }
public function __construct(CoreParametersHelper $coreParametersHelper, FormatterHelper $formatterHelper, TemplatingHelper $templatingHelper) { $this->defaultPageLimit = $coreParametersHelper->getParameter('default_pagelimit'); $this->formatterHelper = $formatterHelper; $this->templatingHelper = $templatingHelper; }
/** * Clears the temporary widget cache */ public function clearDashboardCache() { $cacheDir = $this->coreParametersHelper->getParameter('cached_data_dir', $this->pathsHelper->getSystemPath('cache', true)); $cacheStorage = new CacheStorageHelper($cacheDir, $this->user->getId()); $cacheStorage->clear(); }
/** * Mailbox constructor. * * @param CoreParametersHelper $parametersHelper * @param PathsHelper $pathsHelper */ public function __construct(CoreParametersHelper $parametersHelper, PathsHelper $pathsHelper) { $this->mailboxes = $parametersHelper->getParameter('monitored_email', []); if (isset($this->mailboxes['general'])) { $this->settings = $this->mailboxes['general']; } else { $this->settings = ['host' => '', 'port' => '', 'password' => '', 'user' => '', 'encryption' => '']; } // Check that cache attachments directory exists $cacheDir = $pathsHelper->getSystemPath('cache', true); $this->attachmentsDir = $cacheDir . '/attachments'; if (!file_exists($this->attachmentsDir)) { mkdir($this->attachmentsDir); } if ($this->settings['host'] == 'imap.gmail.com') { $this->isGmail = true; } }