2 require_once 'Pman.php';
5 * notification script sender - designed to be run by the Notify script - with many children running
8 * called with an id of a core_notify element
10 * uses core_notify - to find an event to object and person.
12 * uses Events table to log failures
15 * calls $object->toEmail($person,$last_send, $notify) to generate an email struct with
23 * Note uses configuration
25 * Pman_Core_NotifySend[host] = 'localhost' << to override direct sending..
26 * Mail[helo] << helo host name
27 * Mail[socket_options] << any socket option.
31 class Pman_Core_NotifySend extends Pman
33 static $cli_desc = "Send out single notification email (usually called from Core/Notify)";
35 static $cli_opts = array(
37 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
44 'DB_DataObject-debug' => array(
45 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
53 'desc' => 'Force redelivery, even if it has been sent before or not queued...',
60 'desc' => 'Send the message to this address, rather than the one listed.',
70 var $table = 'core_notify';
75 $ff = HTML_FlexyFramework::get();
77 $this->errorHandler("access denied");
79 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
84 function get($id,$opts)
88 if (!empty($opts['DB_DataObject-debug'])) {
89 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
92 if(!empty($opts['referer'])){
93 $this->referer = true;
95 //DB_DataObject::debugLevel(1);
96 //date_default_timezone_set('UTC');
98 $force = empty($opts['force']) ? 0 : 1;
100 $w = DB_DataObject::factory($this->table);
103 $this->errorHandler("invalid id\n");
105 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
108 $this->errorHandler("send repeat to early\n");
110 if (!empty($opts['debug'])) {
114 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
116 if (!$force && (!empty($w->msgid) || $sent)) {
119 $w->sent = $w->sqlValue("NOW()");
122 $this->errorHandler("message has been sent already.\n");
129 $ev = $this->addEvent('NOTIFY', $w,
130 "Notification event cleared (underlying object does not exist)" );;
132 $w->sent = date('Y-m-d H:i:s');
134 $w->event_id = $ev->id;
136 $this->errorHandler(date('Y-m-d h:i:s ') .
137 "Notification event cleared (underlying object does not exist)"
145 if (isset($p->active) && empty($p->active)) {
146 $ev = $this->addEvent('NOTIFY', $w,
147 "Notification event cleared (not user not active any more)" );;
149 $w->sent = date('Y-m-d H:i:s');
151 $w->event_id = $ev->id;
153 $this->errorHandler(date('Y-m-d h:i:s ') .
154 "Notification event cleared (not user not active any more)"
156 $this->errorHandler("message has been sent already.\n");
160 // let's work out the last notification sent to this user..
161 $l = DB_DataObject::factory($this->table);
163 'ontable' => $w->ontable,
165 'person_id' => $w->person_id,
167 $l->whereAdd('id != '. $w->id);
168 $l->orderBy('sent DESC');
170 $ar = $l->fetchAll('sent');
171 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
174 $ev = DB_DataObject::factory('Events');
175 $ev->on_id = $w->id; // int(11)
176 $ev->on_table = $this->table;
178 $ev->orderBy('event_when DESC');
179 $ar = $ev->fetchAll('event_when');
180 $last_event = empty($ar) ? 0 : $ar[0];
183 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
185 $next_try = $next_try_min . ' MINUTES';
187 // this may modify $p->email. (it will not update it though)
188 $email = $this->makeEmail($o, $p, $last, $w, $force);
190 if ($email === true) {
192 $ev = $this->addEvent('NOTIFY', $w,
193 "Notification event cleared (not required any more)" );;
195 $w->sent = date('Y-m-d H:i:s');
197 $w->event_id = $ev->id;
199 $this->errorHandler(date('Y-m-d h:i:s ') .
200 "Notification event cleared (not required any more)"
206 if ($email === false || isset($email['error'])) {
207 // object returned 'false' - it does not know how to send it..
208 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
209 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
211 $w->sent = date('Y-m-d H:i:s');
213 $w->event_id = $ev->id;
215 $this->errorHandler(date('Y-m-d h:i:s ') .
216 (isset($email['error']) ?
217 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
222 if (isset($email['later'])) {
224 $w->act_when = $email['later'];
226 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
230 if (empty($email['headers']['Message-Id'])) {
231 $HOST = gethostname();
232 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
235 //$p->email = 'alan@akbkhome.com'; //for testing..
236 //print_r($email);exit;
237 // should we fetch the watch that caused it.. - which should contain the method to call..
238 // --send-to=test@xxx.com
240 if (!empty($email['send-to'])) {
241 $p->email = $email['send-to'];
243 if (!empty($opts['send-to'])) {
244 $p->email = $opts['send-to'];
246 // since some of them have spaces?!?!
247 $p->email = trim($p->email);
250 require_once 'Validate.php';
251 if (!Validate::email($p->email, true)) {
252 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
254 $w->sent = date('Y-m-d H:i:s');
256 $w->event_id = $ev->id;
258 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
263 $ff = HTML_FlexyFramework::get();
266 $dom = array_pop(explode('@', $p->email));
268 $mxs = $this->mxs($dom);
271 // we might fail doing this...
272 // need to handle temporary failure..
275 // we try for 3 days..
277 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
278 // older that 1 hour.
282 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
286 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
291 if ($mxs === false) {
292 // only retry for 2 day son the MX issue..
294 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
295 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
297 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED\n");
300 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
301 $w->sent = date('Y-m-d H:i:s');
303 $w->event_id = $ev->id;
305 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
313 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
314 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
315 $w->sent = date('Y-m-d H:i:s');
317 $w->event_id = $ev->id;
319 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
324 $w->to_email = $p->email;
325 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
326 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
332 require_once 'Mail.php';
334 foreach($mxs as $dom) {
338 if (!isset($ff->Mail['helo'])) {
339 $this->errorHandler("config Mail[helo] is not set");
341 $this->debug_str = '';
342 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
343 $mailer = Mail::factory('smtp', array(
345 'localhost' => $ff->Mail['helo'],
347 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
348 //'debug' => isset($opts['debug']) ? 1 : 0,
350 'debug_handler' => array($this, 'debugHandler')
352 $res = $mailer->send($p->email, $email['headers'], $email['body']);
358 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
360 $ev->writeEventLog($this->debug_str);
362 $w->sent = date('Y-m-d H:i:s');
363 $w->msgid = $email['headers']['Message-Id'];
364 $w->event_id = $ev->id; // sent ok.. - no need to record it..
367 // enable cc in notify..
368 if (!empty($email['headers']['Cc'])) {
369 $mailer = Mail::factory('smtp', array(
373 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
374 $mailer->send($email['headers']['Cc'],
375 $email['headers'], $email['body']);
379 if (!empty($email['bcc'])) {
380 $mailer = Mail::factory('smtp', array(
384 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
385 $mailer->send($email['bcc'],
386 $email['headers'], $email['body']);
391 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT\n");
393 // what type of error..
394 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
395 if (!empty($res->code) && $res->code == 10001) {
396 // fake greylist if timed out.
401 $this->debug($res->message);
402 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
404 // give up after 2 days..
405 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
407 // check last event for this item..
408 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
409 if (isset($res->userinfo['smtptext'])) {
410 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
413 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
414 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
416 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED\n");
421 if ($fail || $next_try_min > (2*24*60)) {
422 // fail.. = log and give up..
423 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
424 if (isset($res->userinfo['smtptext'])) {
425 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
428 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
430 $w->sent = date('Y-m-d H:i:s');
432 $w->event_id = $ev->id;
434 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
437 // handle no host availalbe forever...
438 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
439 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
440 $w->sent = date('Y-m-d H:i:s');
442 $w->event_id = $ev->id;
444 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
450 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
451 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
453 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
459 $ff = HTML_FlexyFramework::get();
460 if (isset($ff->Pman_Core_NotifySend['host'])) {
461 return array($ff->Pman_Core_NotifySend['host']);
464 $mx_records = array();
465 $mx_weight = array();
467 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
468 if (!checkdnsrr($fqdn)) {
474 asort($mx_weight,SORT_NUMERIC);
476 foreach($mx_weight as $k => $weight) {
477 $mxs[] = $mx_records[$k];
483 * wrapper to call object->toEmail()
487 headers : {AssocArray},
491 error : {String} // error message in log.
492 send-to: {String} // use to override rcpt
496 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
498 $m = 'notify'. $notify->evtype;
499 //var_dump(get_class($object) . '::' .$m);
500 if (!empty($notify->evtype) && method_exists($object,$m)) {
501 echo "calling :" . get_class($object) . '::' .$m . "\n";
502 return $object->$m($rcpt, $last_sent_date, $notify, $force);
505 $type = explode('::', $notify->evtype);
507 if(!empty($type[1]) && method_exists($object,$type[1])){
509 echo "calling :" . get_class($object) . '::' .$m . "\n";
510 return $object->$m($rcpt, $last_sent_date, $notify, $force);
513 if (!method_exists($object, 'toEmail')) {
518 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
523 if (empty($this->cli_args['debug'])) {
531 $this->errorHandler("done\n");
535 function debugHandler ($smtp, $message)
537 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
538 $this->debug_str .= $message;
541 function errorHandler($msg)
543 if(empty($this->referer)){