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 * Core_NotifySend[host] = 'localhost' << to override direct sending..
30 class Pman_Core_NotifySend extends Pman
32 static $cli_desc = "Send out single notification email (usually called from Core/Notify)";
34 static $cli_opts = array(
36 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
43 'DB_DataObject-debug' => array(
44 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
52 'desc' => 'Force redelivery, even if it has been sent before or not queued...',
59 'desc' => 'Send the message to this address, rather than the one listed.',
69 var $table = 'core_notify';
72 $ff = HTML_FlexyFramework::get();
76 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
81 function get($id,$opts)
85 if ($opts['DB_DataObject-debug']) {
86 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
88 //DB_DataObject::debugLevel(1);
89 //date_default_timezone_set('UTC');
91 $force = empty($opts['force']) ? 0 : 1;
93 $w = DB_DataObject::factory($this->table);
98 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
101 die("send repeat to early\n");
103 if (!empty($opts['debug'])) {
107 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
109 if (!$force && (!empty($w->msgid) || $sent)) {
112 $w->sent = $w->sqlValue("NOW()");
115 die("message has been sent already.\n");
122 $ev = $this->addEvent('NOTIFY', $w,
123 "Notification event cleared (underlying object does not exist)" );;
125 $w->sent = date('Y-m-d H:i:s');
127 $w->event_id = $ev->id;
129 die(date('Y-m-d h:i:s ') .
130 "Notification event cleared (underlying object does not exist)"
138 if (isset($p->active) && empty($p->active)) {
139 $ev = $this->addEvent('NOTIFY', $w,
140 "Notification event cleared (not user not active any more)" );;
142 $w->sent = date('Y-m-d H:i:s');
144 $w->event_id = $ev->id;
146 die(date('Y-m-d h:i:s ') .
147 "Notification event cleared (not user not active any more)"
149 die("message has been sent already.\n");
153 // let's work out the last notification sent to this user..
154 $l = DB_DataObject::factory($this->table);
156 'ontable' => $w->ontable,
158 'person_id' => $w->person_id,
160 $l->whereAdd('id != '. $w->id);
161 $l->orderBy('sent DESC');
163 $ar = $l->fetchAll('sent');
164 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
167 $ev = DB_DataObject::factory('Events');
168 $ev->on_id = $w->id; // int(11)
169 $ev->on_table = $this->table;
171 $ev->orderBy('event_when DESC');
172 $ar = $ev->fetchAll('event_when');
173 $last_event = empty($ar) ? 0 : $ar[0];
176 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
178 $next_try = $next_try_min . ' MINUTES';
180 // this may modify $p->email. (it will not update it though)
181 $email = $this->makeEmail($o, $p, $last, $w, $force);
183 if ($email === true) {
185 $ev = $this->addEvent('NOTIFY', $w,
186 "Notification event cleared (not required any more)" );;
188 $w->sent = date('Y-m-d H:i:s');
190 $w->event_id = $ev->id;
192 die(date('Y-m-d h:i:s ') .
193 "Notification event cleared (not required any more)"
199 if ($email === false || isset($email['error'])) {
200 // object returned 'false' - it does not know how to send it..
201 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
202 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
204 $w->sent = date('Y-m-d H:i:s');
206 $w->event_id = $ev->id;
208 die(date('Y-m-d h:i:s ') .
209 (isset($email['error']) ?
210 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
215 if (isset($email['later'])) {
217 $w->act_when = $email['later'];
219 die(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
223 if (empty($email['headers']['Message-Id'])) {
224 $HOST = gethostname();
225 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
228 //$p->email = 'alan@akbkhome.com'; //for testing..
229 //print_r($email);exit;
230 // should we fetch the watch that caused it.. - which should contain the method to call..
231 // --send-to=test@xxx.com
233 if (!empty($email['send-to'])) {
234 $p->email = $email['send-to'];
236 if (!empty($opts['send-to'])) {
237 $p->email = $opts['send-to'];
239 // since some of them have spaces?!?!
240 $p->email = trim($p->email);
243 require_once 'Validate.php';
244 if (!Validate::email($p->email, true)) {
245 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
247 $w->sent = date('Y-m-d H:i:s');
249 $w->event_id = $ev->id;
251 die(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
256 $ff = HTML_FlexyFramework::get();
259 $dom = array_pop(explode('@', $p->email));
261 $mxs = $this->mxs($dom);
264 // we might fail doing this...
265 // need to handle temporary failure..
268 // we try for 3 days..
270 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
271 // older that 1 hour.
275 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
279 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
284 if ($mxs === false) {
285 // only retry for 2 day son the MX issue..
287 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom . ' ' . $res->toString());
288 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
290 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
293 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
294 $w->sent = date('Y-m-d H:i:s');
296 $w->event_id = $ev->id;
298 die(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
306 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
307 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
308 $w->sent = date('Y-m-d H:i:s');
310 $w->event_id = $ev->id;
312 die(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
317 $w->to_email = $p->email;
318 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
319 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
325 require_once 'Mail.php';
327 foreach($mxs as $dom) {
331 if (!isset($ff->Mail['helo'])) {
332 die("config Mail[helo] is not set");
334 $this->debug_str = '';
335 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
336 $mailer = Mail::factory('smtp', array(
338 'localhost' => $ff->Mail['helo'],
340 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
341 //'debug' => isset($opts['debug']) ? 1 : 0,
343 'debug_handler' => array($this, 'debugHandler')
345 $res = $mailer->send($p->email, $email['headers'], $email['body']);
351 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
353 $ev->writeEventLog($this->debug_str);
355 $w->sent = date('Y-m-d H:i:s');
356 $w->msgid = $email['headers']['Message-Id'];
357 $w->event_id = $ev->id; // sent ok.. - no need to record it..
360 // enable cc in notify..
361 if (!empty($email['headers']['Cc'])) {
362 $mailer = Mail::factory('smtp', array(
366 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
367 $mailer->send($email['headers']['Cc'],
368 $email['headers'], $email['body']);
372 if (!empty($email['bcc'])) {
373 $mailer = Mail::factory('smtp', array(
377 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
378 $mailer->send($email['bcc'],
379 $email['headers'], $email['body']);
384 die(date('Y-m-d h:i:s') . " - SENT\n");
386 // what type of error..
387 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
388 if (!empty($res->code) && $res->code == 10001) {
389 // fake greylist if timed out.
394 $this->debug($res->message);
395 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
397 // give up after 2 days..
398 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
400 // check last event for this item..
401 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
402 if (isset($res->userinfo['smtptext'])) {
403 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
406 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
407 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
409 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
414 if ($fail || $next_try_min > (2*24*60)) {
415 // fail.. = log and give up..
416 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
417 if (isset($res->userinfo['smtptext'])) {
418 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
421 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
423 $w->sent = date('Y-m-d H:i:s');
425 $w->event_id = $ev->id;
427 die(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
430 // handle no host availalbe forever...
431 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
432 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
433 $w->sent = date('Y-m-d H:i:s');
435 $w->event_id = $ev->id;
437 die(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
443 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
444 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
446 die(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
452 $ff = HTML_FlexyFramework::get();
453 if (isset($ff['Core_NotifySend']['host'])) {
454 return array($ff['Core_NotifySend']['host']);
457 $mx_records = array();
458 $mx_weight = array();
460 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
461 if (!checkdnsrr($fqdn)) {
467 asort($mx_weight,SORT_NUMERIC);
469 foreach($mx_weight as $k => $weight) {
470 $mxs[] = $mx_records[$k];
476 * wrapper to call object->toEmail()
480 headers : {AssocArray},
484 error : {String} // error message in log.
485 send-to: {String} // use to override rcpt
489 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
491 $m = 'notify'. $notify->evtype;
492 //var_dump(get_class($object) . '::' .$m);
493 if (!empty($notify->evtype) && method_exists($object,$m)) {
494 echo "calling :" . get_class($object) . '::' .$m . "\n";
495 return $object->$m($rcpt, $last_sent_date, $notify, $force);
498 $type = explode('::', $notify->evtype);
500 if(!empty($type[1]) && method_exists($object,$type[1])){
502 echo "calling :" . get_class($object) . '::' .$m . "\n";
503 return $object->$m($rcpt, $last_sent_date, $notify, $force);
506 if (!method_exists($object, 'toEmail')) {
511 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
516 if (empty($this->cli_args['debug'])) {
528 function debugHandler ($smtp, $message)
530 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
531 $this->debug_str .= $message;