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 var_dump("send from template","sms:".$mobile." email:".$email);
83 var_dump('Template sending: ' . $templateName);
85 #-> Unsubscribe check.
86 $em = \Utility\Registry::getEntityManager();
87 if (!self::$_sendAsNewsletter && !self::$_skipSubscriptionCheck)
89 $oProfile = $em->getRepository('\User\Entity\Profile');
91 ? $oProfile->findOneBy(array('email' => $email))
92 : $oProfile->findOneBy(array('mobile' => $mobile));
93 if (!is_null($profile) && !$profile->subscribeReminders)
98 self::$_skipSubscriptionCheck = false;
100 #-> Retrieve template.
101 $oTemplate = $em->getRepository('\Utility\Entity\Template');
102 $oRepeater = $em->getRepository('\Utility\Entity\RepeaterTemplate');
103 $template = $oTemplate->findOneBy(array('name' => $templateName));
105 if (is_null($template))
107 error_log('Template not found: ' . $templateName);
111 $template = $template->toArray();
113 #-> Compile the template for use.
114 $subject = ($subject)
116 : $template['subject'];
117 $tagList = explode(',', $template['tags']);
118 $search = array('{APP_HOST}');
120 // \Utility\Debug::errorLog('sendFromTemplate IS_BROCHURE', IS_BROCHURE ? 'true' : 'false');
122 $replace = !IS_BROCHURE ? array(\Utility\Registry::getConfigParam('Host')) : array(\Utility\Registry::getConfigParam('CashCarsHost'));
124 #-> Catering for data-grid?
125 if (!is_null($template['repeaterTemplate']))
127 $repeater = $template['repeaterTemplate'];
128 if (!is_array(self::$_data))
130 \Utility\Debug::errorLog(__CLASS__, 'Data required but not provided for template: ' . $templateName);
134 $groupField = ($repeater['groupField'])
135 ? $repeater['groupField']
139 $dateFormat = \Utility\Definitions\Locale::getDateFormat();
140 foreach (self::$_data as $row)
142 $repSearch = array();
143 foreach ($row as $field => $value)
145 if (is_array($value))
147 foreach ($value as $subField => $subValue)
149 $repSearch["$field.$subField"] = "[$field.$subField]";
150 $repReplace["$field.$subField"] = $subValue;
155 $repSearch[$field] = "[$field]";
156 $repReplace[$field] = !is_object($value)
158 : $value->format($dateFormat);
161 if ($groupField && $repReplace[$groupField] != $group)
163 $group = $repReplace[$groupField];
164 $repeatContent .= str_replace($repSearch, $repReplace, $repeater['groupRepeater']) . "\n";
166 $repeatContent .= ($i % 2)
167 ? str_replace($repSearch, $repReplace, $repeater['rowRepeaterOdd']) . "\n"
168 : str_replace($repSearch, $repReplace, $repeater['rowRepeaterEven']) . "\n";
171 $tagList[] = 'repeater';
172 $params['repeater'] = $repeatContent;
175 #-> Build up the template(s)
176 foreach ($tagList as $key)
183 if (!isset($params[$key]))
185 \Utility\Debug::errorLog(__CLASS__, "All template tags not supplied for sending ($templateName): " . $key);
186 \Utility\Debug::errorLog('tags', $tagList);
187 \Utility\Debug::errorLog('params', $params);
190 $search[] = "[$key]";
191 $replace[] = $params[$key];
193 $emailTemplate = !empty($template['emailTemplate'])
194 ? str_replace($search, $replace, $template['emailTemplate'])
196 $smsTemplate = !empty($template['smsTemplate'])
197 ? str_replace($search, $replace, $template['smsTemplate'])
201 if (!self::$_sendAsNewsletter)
205 self::send($fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId,
206 $email, $mobile, $subject, $emailTemplate, $smsTemplate,
207 $attachments, $complexAttachments, $disableSms);
212 self::sendOffline($fromCompanyId, $fromProfileId, $toCompanyId, $toProfileId,
213 $email, $mobile, $subject, $emailTemplate, $smsTemplate,
214 $attachments, $complexAttachments, $disableSms);
219 $profiles = $em->createQuery(
220 'SELECT profile.id AS profileId, IDENTITY(profile.company) AS companyId, profile.email as email '
221 . 'FROM \User\Entity\Profile profile '
222 . 'LEFT JOIN profile.company company '
223 . 'WHERE profile.jobState = :status '
224 . 'AND profile.subscribeNewsletter = 1'
226 ->setParameter('status', 'Active')
232 foreach ($profiles as $profile)
234 self::send($fromCompanyId, $fromProfileId, $profile['companyId'], $profile['profileId'],
235 $profile['email'], false, $subject, $emailTemplate, $smsTemplate,
236 $attachments, $complexAttachments, $disableSms);
243 error_log('newsletter mails: ' . $oo);
244 $em->getConnection()->close();
250 foreach ($profiles as $profile)
252 self::sendOffline($fromCompanyId, $fromProfileId, $profile['companyId'], $profile['profileId'],
253 $profile['email'], false, $subject, $emailTemplate, $smsTemplate,
254 $attachments, $complexAttachments, $disableSms);
261 error_log('newsletter mails: ' . $oo);
262 $em->getConnection()->close();
268 self::$_sendAsNewsletter = false;
272 * Send newsletter to all who are subscribed, or just to admin for a test.
273 * @param integer $newsletterId
274 * @param boolean $test
277 static public function sendNewsletter($newsletterId, $test = false, $testProfileId = null)
279 #-> Retrieve data handler.
280 $em = \Utility\Registry::getEntityManager();
282 #-> Collect some data.
283 $template = $em->getRepository('\Utility\Entity\Template')
284 ->findOneBy(array('name' => 'newsletter-basic'))
286 $newsletter = $em->getRepository('\Newsletter\Entity\Newsletter')
287 ->find($newsletterId)
289 $complexAttachments = array();
290 $search = array('[headerImageSource]', '[footerImageSource]', '[body]');
291 $host = \Utility\Registry::getConfigParam('Host');
293 $host . '/images/EmailHeader.png',
294 $host . '/images/EmailFooter.png',
295 $newsletter['content']
298 $emailTemplate = str_replace($search, $replace, $template['emailTemplate']);
299 $attachments = array();
300 $attachment = $newsletter['attachment'];
301 if (!is_null($attachment))
303 $attachments[$attachment['filename']] = file_get_contents(
304 \Utility\Registry::getConfigParam('DocumentPath') . $attachment['filename']
308 $search = array('[first_name]', '[family_name]', '[mobile]');
314 if (!is_null($testProfileId))
316 $testProfile = $em->getRepository('\User\Entity\Profile')
317 ->find($testProfileId);
319 $testProfile->firstName,
320 $testProfile->familyName,
323 self::send(0, 0, $testProfile->company->id, $testProfileId, $testProfile->email, false,
324 str_replace($search, $replace, $newsletter['subject']),
325 str_replace($search, $replace, $emailTemplate), '',
326 $attachments, $complexAttachments, true);
330 $auth = \Utility\Registry::getAuthData();
332 'John', 'Doe', '0820820820'
334 self::send(0, 0, $auth['company']['id'], $auth['id'], $auth['email'], false,
335 str_replace($search, $replace, $newsletter['subject']),
336 str_replace($search, $replace, $emailTemplate), '',
337 $attachments, $complexAttachments, true);
344 $profiles = $em->createQuery(
345 'SELECT profile.id AS profileId, IDENTITY(profile.company) AS companyId, '
346 . 'profile.firstName as firstName, profile.familyName as familyName, profile.email as email '
347 . 'FROM \User\Entity\Profile profile '
348 . 'LEFT JOIN profile.company company '
349 . 'WHERE profile.jobState = :status '
350 . 'AND profile.subscribeNewsletter = 1'
352 ->setParameter('status', 'Active')
355 foreach ($profiles as $profile)
358 $profile['firstName'], $profile['familyName'], $profile['mobile']
360 self::sendOffline(0, 0, $profile['companyId'], $profile['profileId'],
361 $profile['email'], false,
362 str_replace($search, $replace, $newsletter['subject']),
363 str_replace($search, $replace, $emailTemplate), '',
364 $attachments, $complexAttachments, true);
373 public function sendBasicEmail($email, $subject, $body)
375 $templatesDir = __DIR__ . '/../../../../../data/templates/';
376 $template = file_get_contents($templatesDir . 'general.html');
377 $body = str_replace('[body]', $body, $template);
378 self::send(null, null, null, null, $email, null, $subject, $body, '');
383 * Send email and/or sms notification.
384 * @param integer $fromCompanyId
385 * @param integer $fromProfileId
386 * @param integer $toCompanyId
387 * @param integer $toProfileId
388 * @param string $email
389 * @param string $mobile
390 * @param string $subject
391 * @param string $emailTemplate
392 * @param string $smsTemplate
393 * @param array $attachments
394 * @param array $complexAttachments
395 * @param boolean $disableSms
398 static private function sendOffline(
399 $fromCompanyId, $fromProfileId,
400 $toCompanyId, $toProfileId, $email, $mobile,
401 $subject, $emailTemplate, $smsTemplate,
402 array $attachments = array(),
403 array $complexAttachments = array(),
410 $fromCompanyId, $fromProfileId,
411 $toCompanyId, $toProfileId, $email, $mobile,
412 $subject, $emailTemplate, $smsTemplate,
413 $attachments, $complexAttachments, $disableSms
418 $id = 'n' . microtime(true);
419 while (\Utility\FileStore::existsJson($id))
421 time_nanosleep(0, 1000);
422 $id = 'n' . microtime(true);
424 foreach ($attachments as $key => $data)
426 $attachments[$key] = utf8_encode($data);
428 foreach ($complexAttachments as $key => $data)
430 $complexAttachments[$key] = utf8_encode($data);
432 \Utility\FileStore::storeJson(
435 'fromCompanyId' => $fromCompanyId,
436 'fromProfileId' => $fromProfileId,
437 'toCompanyId' => $toCompanyId,
438 'toProfileId' => $toProfileId,
441 'subject' => $subject,
442 'emailTemplate' => $emailTemplate,
443 'smsTemplate' => $smsTemplate,
444 'attachments' => $attachments,
445 'complexAttachments' => $complexAttachments,
446 'disableSms' => $disableSms
449 if (false === self::$_gearClient)
451 self::$_gearClient = new \GearmanClient();
452 self::$_gearClient->addServer();
454 self::$_gearClient->doBackground(
464 * Send email and/or sms notification.
465 * @param integer $fromCompanyId
466 * @param integer $fromProfileId
467 * @param integer $toCompanyId
468 * @param integer $toProfileId
469 * @param string $email
470 * @param string $mobile
471 * @param string $subject
472 * @param string $emailTemplate
473 * @param string $smsTemplate
474 * @param array $attachments
475 * @param array $complexAttachments
476 * @param boolean $disableSms
479 static private function send(
480 $fromCompanyId, $fromProfileId,
481 $toCompanyId, $toProfileId, $email, $mobile,
482 $subject, $emailTemplate, $smsTemplate,
483 array $attachments = array(),
484 array $complexAttachments = array(),
488 #-> Send the email off, into the big wide world, with a message of hope, or something.
491 if ($emailTemplate && $email)
493 // \Utility\Debug::errorLog('Email Sending IS_BROCHURE', IS_BROCHURE ? 'true' : 'false');
495 $emailTemplate = str_replace(
497 !IS_BROCHURE ? \Utility\Registry::getConfigParam('Host') : \Utility\Registry::getConfigParam('CashCarsHost'),
500 // $emailTemplate = str_replace('{APP_HOST}', \Utility\Registry::getConfigParam('Host'), $emailTemplate);
501 $mailer = new Email();
503 'From' => IS_BROCHURE
504 ? 'noreply@wepay4cars.co.za'
505 : \Utility\Registry::getConfigParam('sourceEmailAddress'),
507 'Subject' => $subject,
508 'Html' => $emailTemplate,
509 'Attachment' => $attachments,
510 'ComplexAttachment' => $complexAttachments
514 catch (\Exception $e)
516 \Utility\Debug::errorLog('Email Sending', "$e");
517 \Utility\Debug::errorLog('Email Sending', '-----------------------------------------------------------------------------------');
518 \Utility\Debug::errorLog('Email Sending', $emailTemplate);
519 \Utility\Debug::errorLog('Email Sending', '-----------------------------------------------------------------------------------');
522 #-> Send the sms hurtling through cyberspace at insane speeds.
526 // \Utility\Debug::errorLog("tryingNotification","sms");
527 error_log("tryingNotification",$mobile);
528 if (!$disableSms && $smsTemplate && $mobile)
530 if (IS_STAGE_ENV || 'production' == \Utility\Registry::getConfigParam('Instance'))
534 $mobile = '+27826147353';
537 $apiMsgId = $sms->send(array(
539 'From' => \Utility\Registry::getConfigParam('smsSourceAddress'),
540 'Subject' => IS_BROCHURE
543 'Body' => $smsTemplate
545 $apiMsgId = (false == $apiMsgId)
551 catch (\Exception $e)
553 \Utility\Debug::errorLog(__CLASS__, "$e");
556 #-> Log notification entry.
557 $em = \Utility\Registry::getEntityManager();
558 $log = new \Utility\Entity\NotificationLog();
561 'emailSubject' => $subject,
562 'emailBody' => $emailTemplate,
564 'smsBody' => $smsTemplate,
565 'apiMsgId' => $apiMsgId
568 && $logData['fromCompany'] = $em->getReference('Company\Entity\Company', $fromCompanyId);
570 && $logData['fromProfile'] = $em->getReference('User\Entity\Profile', $fromProfileId);
572 && $logData['toCompany'] = $em->getReference('Company\Entity\Company', $toCompanyId);
574 && $logData['toProfile'] = $em->getReference('User\Entity\Profile', $toProfileId);
575 $log->fromArray($logData);
578 $em->clear('\Utility\Entity\NotificationLog');