Unsubscribe check. $em = \Utility\Registry::getEntityManager(); if (!self::$_sendAsNewsletter && !self::$_skipSubscriptionCheck) { $oProfile = $em->getRepository('\User\Entity\Profile'); $profile = $email ? $oProfile->findOneBy(array('email' => $email)) : $oProfile->findOneBy(array('mobile' => $mobile)); if (!is_null($profile) && !$profile->subscribeReminders) { return; } } self::$_skipSubscriptionCheck = false; #-> Retrieve template. $oTemplate = $em->getRepository('\Utility\Entity\Template'); $oRepeater = $em->getRepository('\Utility\Entity\RepeaterTemplate'); $template = $oTemplate->findOneBy(array('name' => $templateName)); if (is_null($template)) { error_log('Template not found: ' . $templateName); return; } $template = $template->toArray(); #-> Compile the template for use. $subject = ($subject) ? $subject : $template['subject']; $tagList = explode(',', $template['tags']); $search = array('{APP_HOST}'); // \Utility\Debug::errorLog('sendFromTemplate IS_BROCHURE', IS_BROCHURE ? 'true' : 'false'); $replace = !IS_BROCHURE ? array(\Utility\Registry::getConfigParam('Host')) : array(\Utility\Registry::getConfigParam('CashCarsHost')); #-> Catering for data-grid? if (!is_null($template['repeaterTemplate'])) { $repeater = $template['repeaterTemplate']; if (!is_array(self::$_data)) { \Utility\Debug::errorLog(__CLASS__, 'Data required but not provided for template: ' . $templateName); return; } $repeatContent = ''; $groupField = ($repeater['groupField']) ? $repeater['groupField'] : false; $group = ''; $i = 1; $dateFormat = \Utility\Definitions\Locale::getDateFormat(); foreach (self::$_data as $row) { $repSearch = array(); foreach ($row as $field => $value) { if (is_array($value)) { foreach ($value as $subField => $subValue) { $repSearch["$field.$subField"] = "[$field.$subField]"; $repReplace["$field.$subField"] = $subValue; } } else { $repSearch[$field] = "[$field]"; $repReplace[$field] = !is_object($value) ? $value : $value->format($dateFormat); } } if ($groupField && $repReplace[$groupField] != $group) { $group = $repReplace[$groupField]; $repeatContent .= str_replace($repSearch, $repReplace, $repeater['groupRepeater']) . "\n"; } $repeatContent .= ($i % 2) ? str_replace($repSearch, $repReplace, $repeater['rowRepeaterOdd']) . "\n" : str_replace($repSearch, $repReplace, $repeater['rowRepeaterEven']) . "\n"; $i++; } $tagList[] = 'repeater'; $params['repeater'] = $repeatContent; } #-> Build up the template(s) foreach ($tagList as $key) { $key = trim($key); if (empty($key)) { continue; } if (!isset($params[$key])) { \Utility\Debug::errorLog(__CLASS__, "All template tags not supplied for sending ($templateName): " . $key); \Utility\Debug::errorLog('tags', $tagList); \Utility\Debug::errorLog('params', $params); return; } $search[] = "[$key]"; $replace[] = $params[$key]; } $emailTemplate = !empty($template['emailTemplate']) ? str_replace($search, $replace, $template['emailTemplate']) : false; $smsTemplate = !empty($template['smsTemplate']) ? str_replace($search, $replace, $template['smsTemplate']) : false; if (!self::$_sendAsNewsletter) { if (!$offline) { self::send($fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId, $email, $mobile, $subject, $emailTemplate, $smsTemplate, $attachments, $complexAttachments, $disableSms); } else { self::sendOffline($fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId, $email, $mobile, $subject, $emailTemplate, $smsTemplate, $attachments, $complexAttachments, $disableSms); } } else { $profiles = $em->createQuery( 'SELECT profile.id AS profileId, IDENTITY(profile.company) AS companyId, profile.email as email ' . 'FROM \User\Entity\Profile profile ' . 'LEFT JOIN profile.company company ' . 'WHERE profile.jobState = :status ' . 'AND profile.subscribeNewsletter = 1' ) ->setParameter('status', 'Active') ->getArrayResult(); $ii = 0; $oo = 0; if (!$offline) { foreach ($profiles as $profile) { self::send($fromCompanyId, $fromProfileId, $profile['companyId'], $profile['profileId'], $profile['email'], false, $subject, $emailTemplate, $smsTemplate, $attachments, $complexAttachments, $disableSms); $em->clear(); $ii++; $oo++; if (100 == $ii) { $ii = 0; error_log('newsletter mails: ' . $oo); $em->getConnection()->close(); } } } else { foreach ($profiles as $profile) { self::sendOffline($fromCompanyId, $fromProfileId, $profile['companyId'], $profile['profileId'], $profile['email'], false, $subject, $emailTemplate, $smsTemplate, $attachments, $complexAttachments, $disableSms); $em->clear(); $ii++; $oo++; if (100 == $ii) { $ii = 0; error_log('newsletter mails: ' . $oo); $em->getConnection()->close(); } } } } self::$_data = null; self::$_sendAsNewsletter = false; } /** * Send newsletter to all who are subscribed, or just to admin for a test. * @param integer $newsletterId * @param boolean $test * @return void */ static public function sendNewsletter($newsletterId, $test = false, $testProfileId = null) { #-> Retrieve data handler. $em = \Utility\Registry::getEntityManager(); #-> Collect some data. $template = $em->getRepository('\Utility\Entity\Template') ->findOneBy(array('name' => 'newsletter-basic')) ->toArray(); $newsletter = $em->getRepository('\Newsletter\Entity\Newsletter') ->find($newsletterId) ->toArray(); $complexAttachments = array(); $search = array('[headerImageSource]', '[footerImageSource]', '[body]'); $host = \Utility\Registry::getConfigParam('Host'); $replace = array( $host . '/images/EmailHeader.png', $host . '/images/EmailFooter.png', $newsletter['content'] ); $emailTemplate = str_replace($search, $replace, $template['emailTemplate']); $attachments = array(); $attachment = $newsletter['attachment']; if (!is_null($attachment)) { $attachments[$attachment['filename']] = file_get_contents( \Utility\Registry::getConfigParam('DocumentPath') . $attachment['filename'] ); } $search = array('[first_name]', '[family_name]', '[mobile]'); #-> Send. $sentTo = 0; if ($test) { if (!is_null($testProfileId)) { $testProfile = $em->getRepository('\User\Entity\Profile') ->find($testProfileId); $replace = array( $testProfile->firstName, $testProfile->familyName, $testProfile->mobile ); self::send(0, 0, $testProfile->company->id, $testProfileId, $testProfile->email, false, str_replace($search, $replace, $newsletter['subject']), str_replace($search, $replace, $emailTemplate), '', $attachments, $complexAttachments, true); } else { $auth = \Utility\Registry::getAuthData(); $replace = array( 'John', 'Doe', '0820820820' ); self::send(0, 0, $auth['company']['id'], $auth['id'], $auth['email'], false, str_replace($search, $replace, $newsletter['subject']), str_replace($search, $replace, $emailTemplate), '', $attachments, $complexAttachments, true); } $sentTo++; return $sentTo; } else { $profiles = $em->createQuery( 'SELECT profile.id AS profileId, IDENTITY(profile.company) AS companyId, ' . 'profile.firstName as firstName, profile.familyName as familyName, profile.email as email ' . 'FROM \User\Entity\Profile profile ' . 'LEFT JOIN profile.company company ' . 'WHERE profile.jobState = :status ' . 'AND profile.subscribeNewsletter = 1' ) ->setParameter('status', 'Active') ->getArrayResult(); $sentTo = 0; foreach ($profiles as $profile) { $replace = array( $profile['firstName'], $profile['familyName'], $profile['mobile'] ); self::sendOffline(0, 0, $profile['companyId'], $profile['profileId'], $profile['email'], false, str_replace($search, $replace, $newsletter['subject']), str_replace($search, $replace, $emailTemplate), '', $attachments, $complexAttachments, true); $em->clear(); $sentTo++; } } self::$_data = null; return $sentTo; } public function sendBasicEmail($email, $subject, $body) { $templatesDir = __DIR__ . '/../../../../../data/templates/'; $template = file_get_contents($templatesDir . 'general.html'); $body = str_replace('[body]', $body, $template); self::send(null, null, null, null, $email, null, $subject, $body, ''); } /** * Send email and/or sms notification. * @param integer $fromCompanyId * @param integer $fromProfileId * @param integer $toCompanyId * @param integer $toProfileId * @param string $email * @param string $mobile * @param string $subject * @param string $emailTemplate * @param string $smsTemplate * @param array $attachments * @param array $complexAttachments * @param boolean $disableSms * @return void */ static private function sendOffline( $fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId, $email, $mobile, $subject, $emailTemplate, $smsTemplate, array $attachments = array(), array $complexAttachments = array(), $disableSms = false ) { if (IS_BROCHURE) { self::send( $fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId, $email, $mobile, $subject, $emailTemplate, $smsTemplate, $attachments, $complexAttachments, $disableSms ); } else { $id = 'n' . microtime(true); while (\Utility\FileStore::existsJson($id)) { time_nanosleep(0, 1000); $id = 'n' . microtime(true); }; foreach ($attachments as $key => $data) { $attachments[$key] = utf8_encode($data); } foreach ($complexAttachments as $key => $data) { $complexAttachments[$key] = utf8_encode($data); } \Utility\FileStore::storeJson( $id, array( 'fromCompanyId' => $fromCompanyId, 'fromProfileId' => $fromProfileId, 'toCompanyId' => $toCompanyId, 'toProfileId' => $toProfileId, 'email' => $email, 'mobile' => $mobile, 'subject' => $subject, 'emailTemplate' => $emailTemplate, 'smsTemplate' => $smsTemplate, 'attachments' => $attachments, 'complexAttachments' => $complexAttachments, 'disableSms' => $disableSms ) ); if (false === self::$_gearClient) { self::$_gearClient = new \GearmanClient(); self::$_gearClient->addServer(); } self::$_gearClient->doBackground( 'Notify', $id ); } } /** * Send email and/or sms notification. * @param integer $fromCompanyId * @param integer $fromProfileId * @param integer $toCompanyId * @param integer $toProfileId * @param string $email * @param string $mobile * @param string $subject * @param string $emailTemplate * @param string $smsTemplate * @param array $attachments * @param array $complexAttachments * @param boolean $disableSms * @return void */ static private function send( $fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId, $email, $mobile, $subject, $emailTemplate, $smsTemplate, array $attachments = array(), array $complexAttachments = array(), $disableSms = false ) { #-> Send the email off, into the big wide world, with a message of hope, or something. try { if ($emailTemplate && $email) { // \Utility\Debug::errorLog('Email Sending IS_BROCHURE', IS_BROCHURE ? 'true' : 'false'); $emailTemplate = str_replace( '{APP_HOST}', !IS_BROCHURE ? \Utility\Registry::getConfigParam('Host') : \Utility\Registry::getConfigParam('CashCarsHost'), $emailTemplate ); // $emailTemplate = str_replace('{APP_HOST}', \Utility\Registry::getConfigParam('Host'), $emailTemplate); $mailer = new Email(); $mailer->send(array( 'From' => IS_BROCHURE ? 'noreply@wepay4cars.co.za' : \Utility\Registry::getConfigParam('sourceEmailAddress'), 'To' => $email, 'Subject' => $subject, 'Html' => $emailTemplate, 'Attachment' => $attachments, 'ComplexAttachment' => $complexAttachments )); } } catch (\Exception $e) { \Utility\Debug::errorLog('Email Sending', "$e"); \Utility\Debug::errorLog('Email Sending', '-----------------------------------------------------------------------------------'); \Utility\Debug::errorLog('Email Sending', $emailTemplate); \Utility\Debug::errorLog('Email Sending', '-----------------------------------------------------------------------------------'); } #-> Send the sms hurtling through cyberspace at insane speeds. $apiMsgId = ''; try { \Utility\Debug::errorLog("trying","sms"); if (!$disableSms && $smsTemplate && $mobile) { if (IS_STAGE_ENV || 'production' == \Utility\Registry::getConfigParam('Instance')) { if (IS_STAGE_ENV) { $mobile = '+27722208069'; } $sms = new Sms(); $apiMsgId = $sms->send(array( 'To' => $mobile, 'From' => \Utility\Registry::getConfigParam('smsSourceAddress'), 'Subject' => IS_BROCHURE ? 'CashCars: ' : 'Bid4Cars: ', 'Body' => $smsTemplate )); $apiMsgId = (false == $apiMsgId) ? '' : $apiMsgId; } } } catch (\Exception $e) { \Utility\Debug::errorLog(__CLASS__, "$e"); } #-> Log notification entry. $em = \Utility\Registry::getEntityManager(); $log = new \Utility\Entity\NotificationLog(); $logData = array( 'emailTo' => $email, 'emailSubject' => $subject, 'emailBody' => $emailTemplate, 'smsTo' => $mobile, 'smsBody' => $smsTemplate, 'apiMsgId' => $apiMsgId ); $fromCompanyId && $logData['fromCompany'] = $em->getReference('Company\Entity\Company', $fromCompanyId); $fromProfileId && $logData['fromProfile'] = $em->getReference('User\Entity\Profile', $fromProfileId); $toCompanyId && $logData['toCompany'] = $em->getReference('Company\Entity\Company', $toCompanyId); $toProfileId && $logData['toProfile'] = $em->getReference('User\Entity\Profile', $toProfileId); $log->fromArray($logData); $em->persist($log); $em->flush(); $em->clear('\Utility\Entity\NotificationLog'); return; } }