testing
[namibia] / workers / Notifier.php
1 <?php
2
3 #-> Root ourselves.
4 date_default_timezone_set('Africa/Johannesburg');
5 chdir(dirname(__DIR__));
6
7 #-> Environmental awareness.
8 $isLive  = true;
9 $isStage = false;
10 $isDev   = false;
11 $uname   = php_uname("n");
12 $appName = 'Bid4Cars';
13 if ('Production.localdomain' == $uname
14     || 'VodacomStage' == $uname
15 )
16 {
17         $isStage = true;
18         $appName = 'Bid4Cars (stage)';
19 }
20 if ('nrad.local' == $uname)
21 {
22         $isDev   = true;
23         $appName = 'Bid4Cars (dev)';
24 }
25 define('APP_KEY', 'namibia');
26 define('IS_DEV_ENV', $isDev);
27 define('IS_STAGE_ENV', $isStage);
28 define('IS_LIVE_ENV', $isLive);
29 define('IS_BROCHURE', false);
30
31 #-> Vendor auto-loading.
32 require 'init_autoloader.php';
33
34 #-> Selective service inclusion.
35 require 'module/Utility/src/Utility/Debug.php';
36 require 'module/Utility/src/Utility/Registry.php';
37 require 'module/Utility/src/Utility/FileStore.php';
38 require 'module/Utility/src/Utility/Comms/Email.php';
39 require 'module/Utility/src/Utility/Comms/Sms.php';
40
41
42
43 #-> Offline notification handler consuming from gearman queue.
44 class Notifier
45 {
46
47         /**
48          * @var \mysqli
49          */
50         static protected $db;
51         /**
52          * @var \Utility\Comms\Email
53          */
54         static protected $emailService;
55         /**
56          * @var \Utility\Comms\Sms
57          */
58         static protected $smsService;
59         /**
60          * @var string
61          */
62         static protected $instance;
63         /**
64          * @var string
65          */
66         static protected $host;
67     /**
68      * @var string
69      */
70     static protected $cashCarsHost;
71         /**
72          * @var string
73          */
74         static protected $sourceEmailAddress;
75         /**
76          * @var string
77          */
78         static protected $smsSourceAddress;
79
80
81         /**
82          * Setup database connection and notification services.
83          */
84         static public function init()
85         {
86                 self::connect();
87                 self::$emailService       = new \Utility\Comms\Email();
88                 self::$smsService         = new \Utility\Comms\Sms();
89                 self::$instance           = \Utility\Registry::getConfigParam('Instance');
90                 self::$host               = \Utility\Registry::getConfigParam('Host');
91         self::$cashCarsHost               = \Utility\Registry::getConfigParam('CashCarsHost');
92
93                 $result = self::$db->query("SELECT * FROM app_config");
94                 if (!$result)
95                 {
96                         echo 'Notifier configuration error: ' . self::$db->error . "\n";
97                         error_log('Notifier configuration error: ' . self::$db->error);
98                         exit();
99                 }
100                 $row = $result->fetch_assoc();
101                 self::$sourceEmailAddress = $row['source_email_address'];
102                 self::$smsSourceAddress   = $row['source_mobile_address'];
103         }
104
105         /**
106          * Connect to database.
107          */
108         static protected function connect()
109         {
110                 $global   = include('config/autoload/global.php');
111                 $global   = $global['doctrine']['connection']['orm_default']['params'];
112                 $local    = include('config/autoload/local.php');
113                 $local    = $local['doctrine']['connection']['orm_default']['params'];
114                 $config   = array_merge($global, $local);
115                 self::$db = new mysqli(
116                         $config['host'],
117                         $config['user'],
118                         $config['password'],
119                         $config['dbname']
120                 );
121                 if (self::$db->connect_errno)
122                 {
123                         echo 'Notifier DB connection error: ' . self::$db->connect_error . "\n";
124                         error_log('Notifier DB connection error: ' . self::$db->connect_error);
125                         exit();
126                 }
127         }
128
129
130         /**
131          * Send a notification.
132          * @param  GearmanJob $job
133          * @return null
134          */
135         static public function notify(GearmanJob $job)
136         {
137                 #-> Ping the db connection.
138                 $id = $job->workload();
139                 if (!self::$db->ping())
140                 {
141                         self::connect();
142                 }
143
144                 #-> Get data to work with.
145                 $data = \Utility\FileStore::fetchJson($id);
146
147                 #-> Send the email off, into the big wide world, with a message of hope, or something.
148                 try
149                 {
150                         if ($data['emailTemplate'] && $data['email'])
151                         {
152                                 foreach ($data['attachments'] as $key => $value)
153                                 {
154                                         $data['attachments'][$key] = utf8_decode($value);
155                                 }
156                                 foreach ($data['complexAttachments'] as $key => $value)
157                                 {
158                                         $data['complexAttachments'][$key] = utf8_decode($value);
159                                 }
160
161 //                \Utility\Debug::errorLog('notify IS_BROCHURE', IS_BROCHURE ? 'true' : 'false');
162
163 //                              $data['emailTemplate'] = str_replace('{APP_HOST}', self::$host, $data['emailTemplate']);
164                 $data['emailTemplate'] = str_replace('{APP_HOST}', !IS_BROCHURE ? self::$host : self::$cashCarsHost, $data['emailTemplate']);
165                                 $mailer                = new \Utility\Comms\Email();
166                                 $mailer->send(
167                                         array(
168                                                 'From'              => self::$sourceEmailAddress,
169                                                 'To'                => $data['email'],
170                                                 'Subject'           => $data['subject'],
171                                                 'Html'              => $data['emailTemplate'],
172                                                 'Attachment'        => $data['attachments'],
173                                                 'ComplexAttachment' => $data['complexAttachments']
174                                         )
175                                 );
176                         }
177                 }
178                 catch (\Exception $e)
179                 {
180                         error_log('Notifier Email EXCEPTION: ' . "$e");
181                 }
182
183                 #-> Send the sms hurtling through cyberspace at insane speeds.
184                 $apiMsgId = '';
185                 try
186                 {
187                         if (!$data['disableSms'] && $data['smsTemplate'] && $data['mobile'])
188                         {
189                                 if (IS_STAGE_ENV || 'production' == self::$instance)
190                                 {
191                                         if (IS_STAGE_ENV)
192                                         {
193                                                 $data['mobile'] = '+27722208069';
194                                         }
195                                         $sms      = new \Utility\Comms\Sms();
196                                         $apiMsgId = $sms->send(array(
197                                                                        'To'      => $data['mobile'],
198                                                                        'From'    => self::$smsSourceAddress,
199                                                                        'Subject' => 'Bid4Cars: ',
200                                                                        'Body'    => $data['smsTemplate']
201                                                                ));
202                                         $apiMsgId = (false == $apiMsgId)
203                                                 ? ''
204                                                 : $apiMsgId;
205                                 }
206                         }
207                 }
208                 catch (\Exception $e)
209                 {
210                         error_log('Notifier SMS EXCEPTION: ' . $e->getMessage());
211                 }
212
213                 #-> Log notification entry.
214                 $tableData = array(
215                         'from_company_id' => !is_null($data['fromCompanyId'])
216                                 ? (int)$data['fromCompanyId']
217                                 : 'null',
218                         'from_profile_id' => !is_null($data['fromProfileId'])
219                                 ? (int)$data['fromProfileId']
220                                 : 'null',
221                         'to_company_id'   => !is_null($data['toCompanyId'])
222                                 ? (int)$data['toCompanyId']
223                                 : 'null',
224                         'to_profile_id'   => !is_null($data['toProfileId'])
225                                 ? (int)$data['toProfileId']
226                                 : 'null',
227                         'email_to'        => !is_null($data['email'])
228                                 ? '"' . self::$db->escape_string($data['email']) . '"'
229                                 : 'null',
230                         'email_subject'   => !is_null($data['subject'])
231                                 ? '"' . self::$db->escape_string($data['subject']) . '"'
232                                 : 'null',
233                         'email_body'      => !is_null($data['emailTemplate'])
234                                 ? '"' . self::$db->escape_string($data['emailTemplate']) . '"'
235                                 : '""',
236                         'sms_to'          => !is_null($data['mobile'])
237                                 ? '"' . self::$db->escape_string($data['mobile']) . '"'
238                                 : 'null',
239                         'sms_body'        => !is_null($data['smsTemplate'])
240                                 ? '"' . self::$db->escape_string($data['smsTemplate']) . '"'
241                                 : '""',
242                         'api_msg_id'      => '"' . self::$db->escape_string($apiMsgId) . '"',
243                         'sms_status'      => 'null',
244                         'created'         => '"' . date('Y-m-d H:i:s') . '"',
245                         'updated'         => 'null',
246                         'archived'        => 0
247                 );
248                 $query     = 'INSERT INTO lib_notification_log '
249                              . '(from_company_id,from_profile_id,to_company_id,to_profile_id,'
250                              . 'email_to,email_subject,email_body,'
251                              . 'sms_to,sms_body,api_msg_id,sms_status,'
252                              . 'created,updated,archived)'
253                              . ' VALUES '
254                              . '(' . implode(',', $tableData) . ')';
255                 $result    = self::$db->query($query);
256                 if (!$result || self::$db->errno)
257                 {
258                         echo 'Notifier DB query error: ' . self::$db->error . "\n";
259                         error_log('Notifier DB query error: ' . self::$db->error);
260                         exit();
261                 }
262
263                 #-> Cleanup.
264                 \Utility\FileStore::deleteJson($id);
265
266                 #-> Give the server a breather.
267                 sleep(2);
268         }
269
270
271 }
272
273
274
275 #-> Get up and running.
276 Notifier::init();
277
278 #-> Register as a gearman worker.
279 $worker = new GearmanWorker();
280 $worker->addServer();
281 $worker->addFunction('Notify', array('Notifier', 'notify'));
282
283 #-> Wait for jobs to come in.
284 while ($worker->work())
285 {
286         ;
287 }
288