2 namespace Utility\Comms;
6 * Easy notification functionality for anything that needs it.
13 * Data for repeater functionality.
16 static protected $_data = null;
18 * Send template as newsletter to all subscribers on sendFromTemplate.
21 static protected $_sendAsNewsletter = false;
23 * Skip unsubscribe check on sendFromTemplate.
26 static protected $_skipSubscriptionCheck = false;
31 static protected $_gearClient = false;
35 * Set repeater data for next notification sent.
38 static public function setRepeaterData(array $data)
44 * Set next sendFromTemplate to send to all users subscribed to newsletters.
46 static public function setSendAsNewsletter()
48 self::$_sendAsNewsletter = true;
52 * Skip unsubscribe check on next sendFromTemplate.
54 static public function skipSubscriptionCheck()
56 self::$_skipSubscriptionCheck = false;
60 * Send email and/or sms notification.
61 * @param integer $fromCompanyId
62 * @param integer $fromProfileId
63 * @param integer $toCompanyId
64 * @param integer $toProfileId
65 * @param string $email
66 * @param string $mobile
67 * @param string $subject
68 * @param string $template
69 * @param array $params
70 * @param array $attachments
71 * @param boolean $disableSms
74 static public function sendFromTemplate(
75 $fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId,
76 $email, $mobile, $subject, $templateName, array $params,
77 array $attachments = array(), array $complexAttachments = array(),
78 $disableSms = false, $offline = false
81 #-> Unsubscribe check.
82 $em = \Utility\Registry::getEntityManager();
83 if (!self::$_sendAsNewsletter && !self::$_skipSubscriptionCheck)
85 $oProfile = $em->getRepository('\User\Entity\Profile');
87 ? $oProfile->findOneBy(array('email' => $email))
88 : $oProfile->findOneBy(array('mobile' => $mobile));
89 if (!is_null($profile) && !$profile->subscribeReminders)
94 self::$_skipSubscriptionCheck = false;
96 #-> Retrieve template.
97 $oTemplate = $em->getRepository('\Utility\Entity\Template');
98 $oRepeater = $em->getRepository('\Utility\Entity\RepeaterTemplate');
99 $template = $oTemplate->findOneBy(array('name' => $templateName));
101 if (is_null($template))
103 error_log('Template not found: ' . $templateName);
107 $template = $template->toArray();
109 #-> Compile the template for use.
110 $subject = ($subject)
112 : $template['subject'];
113 $tagList = explode(',', $template['tags']);
114 $search = array('{APP_HOST}');
116 // \Utility\Debug::errorLog('sendFromTemplate IS_BROCHURE', IS_BROCHURE ? 'true' : 'false');
118 $replace = !IS_BROCHURE ? array(\Utility\Registry::getConfigParam('Host')) : array(\Utility\Registry::getConfigParam('CashCarsHost'));
120 #-> Catering for data-grid?
121 if (!is_null($template['repeaterTemplate']))
123 $repeater = $template['repeaterTemplate'];
124 if (!is_array(self::$_data))
126 \Utility\Debug::errorLog(__CLASS__, 'Data required but not provided for template: ' . $templateName);
130 $groupField = ($repeater['groupField'])
131 ? $repeater['groupField']
135 $dateFormat = \Utility\Definitions\Locale::getDateFormat();
136 foreach (self::$_data as $row)
138 $repSearch = array();
139 foreach ($row as $field => $value)
141 if (is_array($value))
143 foreach ($value as $subField => $subValue)
145 $repSearch["$field.$subField"] = "[$field.$subField]";
146 $repReplace["$field.$subField"] = $subValue;
151 $repSearch[$field] = "[$field]";
152 $repReplace[$field] = !is_object($value)
154 : $value->format($dateFormat);
157 if ($groupField && $repReplace[$groupField] != $group)
159 $group = $repReplace[$groupField];
160 $repeatContent .= str_replace($repSearch, $repReplace, $repeater['groupRepeater']) . "\n";
162 $repeatContent .= ($i % 2)
163 ? str_replace($repSearch, $repReplace, $repeater['rowRepeaterOdd']) . "\n"
164 : str_replace($repSearch, $repReplace, $repeater['rowRepeaterEven']) . "\n";
167 $tagList[] = 'repeater';
168 $params['repeater'] = $repeatContent;
171 #-> Build up the template(s)
172 foreach ($tagList as $key)
179 if (!isset($params[$key]))
181 \Utility\Debug::errorLog(__CLASS__, "All template tags not supplied for sending ($templateName): " . $key);
182 \Utility\Debug::errorLog('tags', $tagList);
183 \Utility\Debug::errorLog('params', $params);
186 $search[] = "[$key]";
187 $replace[] = $params[$key];
189 $emailTemplate = !empty($template['emailTemplate'])
190 ? str_replace($search, $replace, $template['emailTemplate'])
192 $smsTemplate = !empty($template['smsTemplate'])
193 ? str_replace($search, $replace, $template['smsTemplate'])
197 if (!self::$_sendAsNewsletter)
201 self::send($fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId,
202 $email, $mobile, $subject, $emailTemplate, $smsTemplate,
203 $attachments, $complexAttachments, $disableSms);
208 self::sendOffline($fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId,
209 $email, $mobile, $subject, $emailTemplate, $smsTemplate,
210 $attachments, $complexAttachments, $disableSms);
215 $profiles = $em->createQuery(
216 'SELECT profile.id AS profileId, IDENTITY(profile.company) AS companyId, profile.email as email '
217 . 'FROM \User\Entity\Profile profile '
218 . 'LEFT JOIN profile.company company '
219 . 'WHERE profile.jobState = :status '
220 . 'AND profile.subscribeNewsletter = 1'
222 ->setParameter('status', 'Active')
228 foreach ($profiles as $profile)
230 self::send($fromCompanyId, $fromProfileId, $profile['companyId'], $profile['profileId'],
231 $profile['email'], false, $subject, $emailTemplate, $smsTemplate,
232 $attachments, $complexAttachments, $disableSms);
239 error_log('newsletter mails: ' . $oo);
240 $em->getConnection()->close();
246 foreach ($profiles as $profile)
248 self::sendOffline($fromCompanyId, $fromProfileId, $profile['companyId'], $profile['profileId'],
249 $profile['email'], false, $subject, $emailTemplate, $smsTemplate,
250 $attachments, $complexAttachments, $disableSms);
257 error_log('newsletter mails: ' . $oo);
258 $em->getConnection()->close();
264 self::$_sendAsNewsletter = false;
268 * Send newsletter to all who are subscribed, or just to admin for a test.
269 * @param integer $newsletterId
270 * @param boolean $test
273 static public function sendNewsletter($newsletterId, $test = false, $testProfileId = null)
275 #-> Retrieve data handler.
276 $em = \Utility\Registry::getEntityManager();
278 #-> Collect some data.
279 $template = $em->getRepository('\Utility\Entity\Template')
280 ->findOneBy(array('name' => 'newsletter-basic'))
282 $newsletter = $em->getRepository('\Newsletter\Entity\Newsletter')
283 ->find($newsletterId)
285 $complexAttachments = array();
286 $search = array('[headerImageSource]', '[footerImageSource]', '[body]');
287 $host = \Utility\Registry::getConfigParam('Host');
289 $host . '/images/EmailHeader.png',
290 $host . '/images/EmailFooter.png',
291 $newsletter['content']
294 $emailTemplate = str_replace($search, $replace, $template['emailTemplate']);
295 $attachments = array();
296 $attachment = $newsletter['attachment'];
297 if (!is_null($attachment))
299 $attachments[$attachment['filename']] = file_get_contents(
300 \Utility\Registry::getConfigParam('DocumentPath') . $attachment['filename']
304 $search = array('[first_name]', '[family_name]', '[mobile]');
310 if (!is_null($testProfileId))
312 $testProfile = $em->getRepository('\User\Entity\Profile')
313 ->find($testProfileId);
315 $testProfile->firstName,
316 $testProfile->familyName,
319 self::send(0, 0, $testProfile->company->id, $testProfileId, $testProfile->email, false,
320 str_replace($search, $replace, $newsletter['subject']),
321 str_replace($search, $replace, $emailTemplate), '',
322 $attachments, $complexAttachments, true);
326 $auth = \Utility\Registry::getAuthData();
328 'John', 'Doe', '0820820820'
330 self::send(0, 0, $auth['company']['id'], $auth['id'], $auth['email'], false,
331 str_replace($search, $replace, $newsletter['subject']),
332 str_replace($search, $replace, $emailTemplate), '',
333 $attachments, $complexAttachments, true);
340 $profiles = $em->createQuery(
341 'SELECT profile.id AS profileId, IDENTITY(profile.company) AS companyId, '
342 . 'profile.firstName as firstName, profile.familyName as familyName, profile.email as email '
343 . 'FROM \User\Entity\Profile profile '
344 . 'LEFT JOIN profile.company company '
345 . 'WHERE profile.jobState = :status '
346 . 'AND profile.subscribeNewsletter = 1'
348 ->setParameter('status', 'Active')
351 foreach ($profiles as $profile)
354 $profile['firstName'], $profile['familyName'], $profile['mobile']
356 self::sendOffline(0, 0, $profile['companyId'], $profile['profileId'],
357 $profile['email'], false,
358 str_replace($search, $replace, $newsletter['subject']),
359 str_replace($search, $replace, $emailTemplate), '',
360 $attachments, $complexAttachments, true);
369 public function sendBasicEmail($email, $subject, $body)
371 $templatesDir = __DIR__ . '/../../../../../data/templates/';
372 $template = file_get_contents($templatesDir . 'general.html');
373 $body = str_replace('[body]', $body, $template);
374 self::send(null, null, null, null, $email, null, $subject, $body, '');
379 * Send email and/or sms notification.
380 * @param integer $fromCompanyId
381 * @param integer $fromProfileId
382 * @param integer $toCompanyId
383 * @param integer $toProfileId
384 * @param string $email
385 * @param string $mobile
386 * @param string $subject
387 * @param string $emailTemplate
388 * @param string $smsTemplate
389 * @param array $attachments
390 * @param array $complexAttachments
391 * @param boolean $disableSms
394 static private function sendOffline(
395 $fromCompanyId, $fromProfileId,
396 $toCompanyId, $toProfileId, $email, $mobile,
397 $subject, $emailTemplate, $smsTemplate,
398 array $attachments = array(),
399 array $complexAttachments = array(),
406 $fromCompanyId, $fromProfileId,
407 $toCompanyId, $toProfileId, $email, $mobile,
408 $subject, $emailTemplate, $smsTemplate,
409 $attachments, $complexAttachments, $disableSms
414 $id = 'n' . microtime(true);
415 while (\Utility\FileStore::existsJson($id))
417 time_nanosleep(0, 1000);
418 $id = 'n' . microtime(true);
420 foreach ($attachments as $key => $data)
422 $attachments[$key] = utf8_encode($data);
424 foreach ($complexAttachments as $key => $data)
426 $complexAttachments[$key] = utf8_encode($data);
428 \Utility\FileStore::storeJson(
431 'fromCompanyId' => $fromCompanyId,
432 'fromProfileId' => $fromProfileId,
433 'toCompanyId' => $toCompanyId,
434 'toProfileId' => $toProfileId,
437 'subject' => $subject,
438 'emailTemplate' => $emailTemplate,
439 'smsTemplate' => $smsTemplate,
440 'attachments' => $attachments,
441 'complexAttachments' => $complexAttachments,
442 'disableSms' => $disableSms
445 if (false === self::$_gearClient)
447 self::$_gearClient = new \GearmanClient();
448 self::$_gearClient->addServer();
450 self::$_gearClient->doBackground(
460 * Send email and/or sms notification.
461 * @param integer $fromCompanyId
462 * @param integer $fromProfileId
463 * @param integer $toCompanyId
464 * @param integer $toProfileId
465 * @param string $email
466 * @param string $mobile
467 * @param string $subject
468 * @param string $emailTemplate
469 * @param string $smsTemplate
470 * @param array $attachments
471 * @param array $complexAttachments
472 * @param boolean $disableSms
475 static private function send(
476 $fromCompanyId, $fromProfileId,
477 $toCompanyId, $toProfileId, $email, $mobile,
478 $subject, $emailTemplate, $smsTemplate,
479 array $attachments = array(),
480 array $complexAttachments = array(),
484 #-> Send the email off, into the big wide world, with a message of hope, or something.
487 if ($emailTemplate && $email)
489 // \Utility\Debug::errorLog('Email Sending IS_BROCHURE', IS_BROCHURE ? 'true' : 'false');
491 $emailTemplate = str_replace(
493 !IS_BROCHURE ? \Utility\Registry::getConfigParam('Host') : \Utility\Registry::getConfigParam('CashCarsHost'),
496 // $emailTemplate = str_replace('{APP_HOST}', \Utility\Registry::getConfigParam('Host'), $emailTemplate);
497 $mailer = new Email();
499 'From' => IS_BROCHURE
500 ? 'noreply@wepay4cars.co.za'
501 : \Utility\Registry::getConfigParam('sourceEmailAddress'),
503 'Subject' => $subject,
504 'Html' => $emailTemplate,
505 'Attachment' => $attachments,
506 'ComplexAttachment' => $complexAttachments
510 catch (\Exception $e)
512 \Utility\Debug::errorLog('Email Sending', "$e");
513 \Utility\Debug::errorLog('Email Sending', '-----------------------------------------------------------------------------------');
514 \Utility\Debug::errorLog('Email Sending', $emailTemplate);
515 \Utility\Debug::errorLog('Email Sending', '-----------------------------------------------------------------------------------');
518 #-> Send the sms hurtling through cyberspace at insane speeds.
522 if (!$disableSms && $smsTemplate && $mobile)
524 if (IS_STAGE_ENV || 'production' == \Utility\Registry::getConfigParam('Instance'))
528 $mobile = '+27722208069';
531 $apiMsgId = $sms->send(array(
533 'From' => \Utility\Registry::getConfigParam('smsSourceAddress'),
534 'Subject' => IS_BROCHURE
537 'Body' => $smsTemplate
539 $apiMsgId = (false == $apiMsgId)
545 catch (\Exception $e)
547 \Utility\Debug::errorLog(__CLASS__, "$e");
550 #-> Log notification entry.
551 $em = \Utility\Registry::getEntityManager();
552 $log = new \Utility\Entity\NotificationLog();
555 'emailSubject' => $subject,
556 'emailBody' => $emailTemplate,
558 'smsBody' => $smsTemplate,
559 'apiMsgId' => $apiMsgId
562 && $logData['fromCompany'] = $em->getReference('Company\Entity\Company', $fromCompanyId);
564 && $logData['fromProfile'] = $em->getReference('User\Entity\Profile', $fromProfileId);
566 && $logData['toCompany'] = $em->getReference('Company\Entity\Company', $toCompanyId);
568 && $logData['toProfile'] = $em->getReference('User\Entity\Profile', $toProfileId);
569 $log->fromArray($logData);
572 $em->clear('\Utility\Entity\NotificationLog');