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 \Utility\Debug::errorLog("send from template","sms:".$mobile." email:".$email);
82 #-> Unsubscribe check.
83 $em = \Utility\Registry::getEntityManager();
84 if (!self::$_sendAsNewsletter && !self::$_skipSubscriptionCheck)
86 $oProfile = $em->getRepository('\User\Entity\Profile');
88 ? $oProfile->findOneBy(array('email' => $email))
89 : $oProfile->findOneBy(array('mobile' => $mobile));
90 if (!is_null($profile) && !$profile->subscribeReminders)
95 self::$_skipSubscriptionCheck = false;
97 #-> Retrieve template.
98 $oTemplate = $em->getRepository('\Utility\Entity\Template');
99 $oRepeater = $em->getRepository('\Utility\Entity\RepeaterTemplate');
100 $template = $oTemplate->findOneBy(array('name' => $templateName));
102 if (is_null($template))
104 error_log('Template not found: ' . $templateName);
108 $template = $template->toArray();
110 #-> Compile the template for use.
111 $subject = ($subject)
113 : $template['subject'];
114 $tagList = explode(',', $template['tags']);
115 $search = array('{APP_HOST}');
117 // \Utility\Debug::errorLog('sendFromTemplate IS_BROCHURE', IS_BROCHURE ? 'true' : 'false');
119 $replace = !IS_BROCHURE ? array(\Utility\Registry::getConfigParam('Host')) : array(\Utility\Registry::getConfigParam('CashCarsHost'));
121 #-> Catering for data-grid?
122 if (!is_null($template['repeaterTemplate']))
124 $repeater = $template['repeaterTemplate'];
125 if (!is_array(self::$_data))
127 \Utility\Debug::errorLog(__CLASS__, 'Data required but not provided for template: ' . $templateName);
131 $groupField = ($repeater['groupField'])
132 ? $repeater['groupField']
136 $dateFormat = \Utility\Definitions\Locale::getDateFormat();
137 foreach (self::$_data as $row)
139 $repSearch = array();
140 foreach ($row as $field => $value)
142 if (is_array($value))
144 foreach ($value as $subField => $subValue)
146 $repSearch["$field.$subField"] = "[$field.$subField]";
147 $repReplace["$field.$subField"] = $subValue;
152 $repSearch[$field] = "[$field]";
153 $repReplace[$field] = !is_object($value)
155 : $value->format($dateFormat);
158 if ($groupField && $repReplace[$groupField] != $group)
160 $group = $repReplace[$groupField];
161 $repeatContent .= str_replace($repSearch, $repReplace, $repeater['groupRepeater']) . "\n";
163 $repeatContent .= ($i % 2)
164 ? str_replace($repSearch, $repReplace, $repeater['rowRepeaterOdd']) . "\n"
165 : str_replace($repSearch, $repReplace, $repeater['rowRepeaterEven']) . "\n";
168 $tagList[] = 'repeater';
169 $params['repeater'] = $repeatContent;
172 #-> Build up the template(s)
173 foreach ($tagList as $key)
180 if (!isset($params[$key]))
182 \Utility\Debug::errorLog(__CLASS__, "All template tags not supplied for sending ($templateName): " . $key);
183 \Utility\Debug::errorLog('tags', $tagList);
184 \Utility\Debug::errorLog('params', $params);
187 $search[] = "[$key]";
188 $replace[] = $params[$key];
190 $emailTemplate = !empty($template['emailTemplate'])
191 ? str_replace($search, $replace, $template['emailTemplate'])
193 $smsTemplate = !empty($template['smsTemplate'])
194 ? str_replace($search, $replace, $template['smsTemplate'])
198 if (!self::$_sendAsNewsletter)
202 self::send($fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId,
203 $email, $mobile, $subject, $emailTemplate, $smsTemplate,
204 $attachments, $complexAttachments, $disableSms);
209 self::sendOffline($fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId,
210 $email, $mobile, $subject, $emailTemplate, $smsTemplate,
211 $attachments, $complexAttachments, $disableSms);
216 $profiles = $em->createQuery(
217 'SELECT profile.id AS profileId, IDENTITY(profile.company) AS companyId, profile.email as email '
218 . 'FROM \User\Entity\Profile profile '
219 . 'LEFT JOIN profile.company company '
220 . 'WHERE profile.jobState = :status '
221 . 'AND profile.subscribeNewsletter = 1'
223 ->setParameter('status', 'Active')
229 foreach ($profiles as $profile)
231 self::send($fromCompanyId, $fromProfileId, $profile['companyId'], $profile['profileId'],
232 $profile['email'], false, $subject, $emailTemplate, $smsTemplate,
233 $attachments, $complexAttachments, $disableSms);
240 error_log('newsletter mails: ' . $oo);
241 $em->getConnection()->close();
247 foreach ($profiles as $profile)
249 self::sendOffline($fromCompanyId, $fromProfileId, $profile['companyId'], $profile['profileId'],
250 $profile['email'], false, $subject, $emailTemplate, $smsTemplate,
251 $attachments, $complexAttachments, $disableSms);
258 error_log('newsletter mails: ' . $oo);
259 $em->getConnection()->close();
265 self::$_sendAsNewsletter = false;
269 * Send newsletter to all who are subscribed, or just to admin for a test.
270 * @param integer $newsletterId
271 * @param boolean $test
274 static public function sendNewsletter($newsletterId, $test = false, $testProfileId = null)
276 #-> Retrieve data handler.
277 $em = \Utility\Registry::getEntityManager();
279 #-> Collect some data.
280 $template = $em->getRepository('\Utility\Entity\Template')
281 ->findOneBy(array('name' => 'newsletter-basic'))
283 $newsletter = $em->getRepository('\Newsletter\Entity\Newsletter')
284 ->find($newsletterId)
286 $complexAttachments = array();
287 $search = array('[headerImageSource]', '[footerImageSource]', '[body]');
288 $host = \Utility\Registry::getConfigParam('Host');
290 $host . '/images/EmailHeader.png',
291 $host . '/images/EmailFooter.png',
292 $newsletter['content']
295 $emailTemplate = str_replace($search, $replace, $template['emailTemplate']);
296 $attachments = array();
297 $attachment = $newsletter['attachment'];
298 if (!is_null($attachment))
300 $attachments[$attachment['filename']] = file_get_contents(
301 \Utility\Registry::getConfigParam('DocumentPath') . $attachment['filename']
305 $search = array('[first_name]', '[family_name]', '[mobile]');
311 if (!is_null($testProfileId))
313 $testProfile = $em->getRepository('\User\Entity\Profile')
314 ->find($testProfileId);
316 $testProfile->firstName,
317 $testProfile->familyName,
320 self::send(0, 0, $testProfile->company->id, $testProfileId, $testProfile->email, false,
321 str_replace($search, $replace, $newsletter['subject']),
322 str_replace($search, $replace, $emailTemplate), '',
323 $attachments, $complexAttachments, true);
327 $auth = \Utility\Registry::getAuthData();
329 'John', 'Doe', '0820820820'
331 self::send(0, 0, $auth['company']['id'], $auth['id'], $auth['email'], false,
332 str_replace($search, $replace, $newsletter['subject']),
333 str_replace($search, $replace, $emailTemplate), '',
334 $attachments, $complexAttachments, true);
341 $profiles = $em->createQuery(
342 'SELECT profile.id AS profileId, IDENTITY(profile.company) AS companyId, '
343 . 'profile.firstName as firstName, profile.familyName as familyName, profile.email as email '
344 . 'FROM \User\Entity\Profile profile '
345 . 'LEFT JOIN profile.company company '
346 . 'WHERE profile.jobState = :status '
347 . 'AND profile.subscribeNewsletter = 1'
349 ->setParameter('status', 'Active')
352 foreach ($profiles as $profile)
355 $profile['firstName'], $profile['familyName'], $profile['mobile']
357 self::sendOffline(0, 0, $profile['companyId'], $profile['profileId'],
358 $profile['email'], false,
359 str_replace($search, $replace, $newsletter['subject']),
360 str_replace($search, $replace, $emailTemplate), '',
361 $attachments, $complexAttachments, true);
370 public function sendBasicEmail($email, $subject, $body)
372 $templatesDir = __DIR__ . '/../../../../../data/templates/';
373 $template = file_get_contents($templatesDir . 'general.html');
374 $body = str_replace('[body]', $body, $template);
375 self::send(null, null, null, null, $email, null, $subject, $body, '');
380 * Send email and/or sms notification.
381 * @param integer $fromCompanyId
382 * @param integer $fromProfileId
383 * @param integer $toCompanyId
384 * @param integer $toProfileId
385 * @param string $email
386 * @param string $mobile
387 * @param string $subject
388 * @param string $emailTemplate
389 * @param string $smsTemplate
390 * @param array $attachments
391 * @param array $complexAttachments
392 * @param boolean $disableSms
395 static private function sendOffline(
396 $fromCompanyId, $fromProfileId,
397 $toCompanyId, $toProfileId, $email, $mobile,
398 $subject, $emailTemplate, $smsTemplate,
399 array $attachments = array(),
400 array $complexAttachments = array(),
407 $fromCompanyId, $fromProfileId,
408 $toCompanyId, $toProfileId, $email, $mobile,
409 $subject, $emailTemplate, $smsTemplate,
410 $attachments, $complexAttachments, $disableSms
415 $id = 'n' . microtime(true);
416 while (\Utility\FileStore::existsJson($id))
418 time_nanosleep(0, 1000);
419 $id = 'n' . microtime(true);
421 foreach ($attachments as $key => $data)
423 $attachments[$key] = utf8_encode($data);
425 foreach ($complexAttachments as $key => $data)
427 $complexAttachments[$key] = utf8_encode($data);
429 \Utility\FileStore::storeJson(
432 'fromCompanyId' => $fromCompanyId,
433 'fromProfileId' => $fromProfileId,
434 'toCompanyId' => $toCompanyId,
435 'toProfileId' => $toProfileId,
438 'subject' => $subject,
439 'emailTemplate' => $emailTemplate,
440 'smsTemplate' => $smsTemplate,
441 'attachments' => $attachments,
442 'complexAttachments' => $complexAttachments,
443 'disableSms' => $disableSms
446 if (false === self::$_gearClient)
448 self::$_gearClient = new \GearmanClient();
449 self::$_gearClient->addServer();
451 self::$_gearClient->doBackground(
461 * Send email and/or sms notification.
462 * @param integer $fromCompanyId
463 * @param integer $fromProfileId
464 * @param integer $toCompanyId
465 * @param integer $toProfileId
466 * @param string $email
467 * @param string $mobile
468 * @param string $subject
469 * @param string $emailTemplate
470 * @param string $smsTemplate
471 * @param array $attachments
472 * @param array $complexAttachments
473 * @param boolean $disableSms
476 static private function send(
477 $fromCompanyId, $fromProfileId,
478 $toCompanyId, $toProfileId, $email, $mobile,
479 $subject, $emailTemplate, $smsTemplate,
480 array $attachments = array(),
481 array $complexAttachments = array(),
485 #-> Send the email off, into the big wide world, with a message of hope, or something.
488 if ($emailTemplate && $email)
490 // \Utility\Debug::errorLog('Email Sending IS_BROCHURE', IS_BROCHURE ? 'true' : 'false');
492 $emailTemplate = str_replace(
494 !IS_BROCHURE ? \Utility\Registry::getConfigParam('Host') : \Utility\Registry::getConfigParam('CashCarsHost'),
497 // $emailTemplate = str_replace('{APP_HOST}', \Utility\Registry::getConfigParam('Host'), $emailTemplate);
498 $mailer = new Email();
500 'From' => IS_BROCHURE
501 ? 'noreply@wepay4cars.co.za'
502 : \Utility\Registry::getConfigParam('sourceEmailAddress'),
504 'Subject' => $subject,
505 'Html' => $emailTemplate,
506 'Attachment' => $attachments,
507 'ComplexAttachment' => $complexAttachments
511 catch (\Exception $e)
513 \Utility\Debug::errorLog('Email Sending', "$e");
514 \Utility\Debug::errorLog('Email Sending', '-----------------------------------------------------------------------------------');
515 \Utility\Debug::errorLog('Email Sending', $emailTemplate);
516 \Utility\Debug::errorLog('Email Sending', '-----------------------------------------------------------------------------------');
519 #-> Send the sms hurtling through cyberspace at insane speeds.
523 // \Utility\Debug::errorLog("tryingNotification","sms");
524 error_log("tryingNotification",$mobile);
525 if (!$disableSms && $smsTemplate && $mobile)
527 if (IS_STAGE_ENV || 'production' == \Utility\Registry::getConfigParam('Instance'))
531 $mobile = '+27722208069';
534 $apiMsgId = $sms->send(array(
536 'From' => \Utility\Registry::getConfigParam('smsSourceAddress'),
537 'Subject' => IS_BROCHURE
540 'Body' => $smsTemplate
542 $apiMsgId = (false == $apiMsgId)
548 catch (\Exception $e)
550 \Utility\Debug::errorLog(__CLASS__, "$e");
553 #-> Log notification entry.
554 $em = \Utility\Registry::getEntityManager();
555 $log = new \Utility\Entity\NotificationLog();
558 'emailSubject' => $subject,
559 'emailBody' => $emailTemplate,
561 'smsBody' => $smsTemplate,
562 'apiMsgId' => $apiMsgId
565 && $logData['fromCompany'] = $em->getReference('Company\Entity\Company', $fromCompanyId);
567 && $logData['fromProfile'] = $em->getReference('User\Entity\Profile', $fromProfileId);
569 && $logData['toCompany'] = $em->getReference('Company\Entity\Company', $toCompanyId);
571 && $logData['toProfile'] = $em->getReference('User\Entity\Profile', $toProfileId);
572 $log->fromArray($logData);
575 $em->clear('\Utility\Entity\NotificationLog');