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';
73 $ff = HTML_FlexyFramework::get();
77 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
82 function get($id,$opts)
86 if ($opts['DB_DataObject-debug']) {
87 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
89 //DB_DataObject::debugLevel(1);
90 //date_default_timezone_set('UTC');
92 $force = empty($opts['force']) ? 0 : 1;
94 $w = DB_DataObject::factory($this->table);
99 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
102 die("send repeat to early\n");
104 if (!empty($opts['debug'])) {
108 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
110 if (!$force && (!empty($w->msgid) || $sent)) {
113 $w->sent = $w->sqlValue("NOW()");
116 die("message has been sent already.\n");
123 $ev = $this->addEvent('NOTIFY', $w,
124 "Notification event cleared (underlying object does not exist)" );;
126 $w->sent = date('Y-m-d H:i:s');
128 $w->event_id = $ev->id;
130 die(date('Y-m-d h:i:s ') .
131 "Notification event cleared (underlying object does not exist)"
139 if (isset($p->active) && empty($p->active)) {
140 $ev = $this->addEvent('NOTIFY', $w,
141 "Notification event cleared (not user not active any more)" );;
143 $w->sent = date('Y-m-d H:i:s');
145 $w->event_id = $ev->id;
147 die(date('Y-m-d h:i:s ') .
148 "Notification event cleared (not user not active any more)"
150 die("message has been sent already.\n");
154 // let's work out the last notification sent to this user..
155 $l = DB_DataObject::factory($this->table);
157 'ontable' => $w->ontable,
159 'person_id' => $w->person_id,
161 $l->whereAdd('id != '. $w->id);
162 $l->orderBy('sent DESC');
164 $ar = $l->fetchAll('sent');
165 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
168 $ev = DB_DataObject::factory('Events');
169 $ev->on_id = $w->id; // int(11)
170 $ev->on_table = $this->table;
172 $ev->orderBy('event_when DESC');
173 $ar = $ev->fetchAll('event_when');
174 $last_event = empty($ar) ? 0 : $ar[0];
177 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
179 $next_try = $next_try_min . ' MINUTES';
181 // this may modify $p->email. (it will not update it though)
182 $email = $this->makeEmail($o, $p, $last, $w, $force);
184 if ($email === true) {
186 $ev = $this->addEvent('NOTIFY', $w,
187 "Notification event cleared (not required any more)" );;
189 $w->sent = date('Y-m-d H:i:s');
191 $w->event_id = $ev->id;
193 die(date('Y-m-d h:i:s ') .
194 "Notification event cleared (not required any more)"
200 if ($email === false || isset($email['error'])) {
201 // object returned 'false' - it does not know how to send it..
202 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
203 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
205 $w->sent = date('Y-m-d H:i:s');
207 $w->event_id = $ev->id;
209 die(date('Y-m-d h:i:s ') .
210 (isset($email['error']) ?
211 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
216 if (isset($email['later'])) {
218 $w->act_when = $email['later'];
220 die(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
224 if (empty($email['headers']['Message-Id'])) {
225 $HOST = gethostname();
226 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
229 //$p->email = 'alan@akbkhome.com'; //for testing..
230 //print_r($email);exit;
231 // should we fetch the watch that caused it.. - which should contain the method to call..
232 // --send-to=test@xxx.com
234 if (!empty($email['send-to'])) {
235 print_r($email);exit;
236 $p->email = $email['send-to'];
238 if (!empty($opts['send-to'])) {
239 $p->email = $opts['send-to'];
241 // since some of them have spaces?!?!
242 $p->email = trim($p->email);
245 require_once 'Validate.php';
246 if (!Validate::email($p->email, true)) {
247 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
249 $w->sent = date('Y-m-d H:i:s');
251 $w->event_id = $ev->id;
253 die(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
258 $ff = HTML_FlexyFramework::get();
261 $dom = array_pop(explode('@', $p->email));
263 $mxs = $this->mxs($dom);
266 // we might fail doing this...
267 // need to handle temporary failure..
270 // we try for 3 days..
272 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
273 // older that 1 hour.
277 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
281 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
286 if ($mxs === false) {
287 // only retry for 2 day son the MX issue..
289 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom . ' ' . $res->toString());
290 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
292 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
295 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
296 $w->sent = date('Y-m-d H:i:s');
298 $w->event_id = $ev->id;
300 die(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
308 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
309 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
310 $w->sent = date('Y-m-d H:i:s');
312 $w->event_id = $ev->id;
314 die(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
319 $w->to_email = $p->email;
320 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
321 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
327 require_once 'Mail.php';
329 foreach($mxs as $dom) {
333 if (!isset($ff->Mail['helo'])) {
334 die("config Mail[helo] is not set");
336 $this->debug_str = '';
337 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
338 $mailer = Mail::factory('smtp', array(
340 'localhost' => $ff->Mail['helo'],
342 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
343 //'debug' => isset($opts['debug']) ? 1 : 0,
345 'debug_handler' => array($this, 'debugHandler')
347 $res = $mailer->send($p->email, $email['headers'], $email['body']);
353 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
355 $ev->writeEventLog($this->debug_str);
357 $w->sent = date('Y-m-d H:i:s');
358 $w->msgid = $email['headers']['Message-Id'];
359 $w->event_id = $ev->id; // sent ok.. - no need to record it..
362 // enable cc in notify..
363 if (!empty($email['headers']['Cc'])) {
364 $mailer = Mail::factory('smtp', array(
368 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
369 $mailer->send($email['headers']['Cc'],
370 $email['headers'], $email['body']);
374 if (!empty($email['bcc'])) {
375 $mailer = Mail::factory('smtp', array(
379 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
380 $mailer->send($email['bcc'],
381 $email['headers'], $email['body']);
386 die(date('Y-m-d h:i:s') . " - SENT\n");
388 // what type of error..
389 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
390 if (!empty($res->code) && $res->code == 10001) {
391 // fake greylist if timed out.
396 $this->debug($res->message);
397 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
399 // give up after 2 days..
400 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
402 // check last event for this item..
403 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
404 if (isset($res->userinfo['smtptext'])) {
405 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
408 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
409 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
411 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
416 if ($fail || $next_try_min > (2*24*60)) {
417 // fail.. = log and give up..
418 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
419 if (isset($res->userinfo['smtptext'])) {
420 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
423 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
425 $w->sent = date('Y-m-d H:i:s');
427 $w->event_id = $ev->id;
429 die(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
432 // handle no host availalbe forever...
433 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
434 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
435 $w->sent = date('Y-m-d H:i:s');
437 $w->event_id = $ev->id;
439 die(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
445 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
446 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
448 die(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
454 $ff = HTML_FlexyFramework::get();
455 if (isset($ff->Pman_Core_NotifySend['host'])) {
456 return array($ff->Pman_Core_NotifySend['host']);
459 $mx_records = array();
460 $mx_weight = array();
462 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
463 if (!checkdnsrr($fqdn)) {
469 asort($mx_weight,SORT_NUMERIC);
471 foreach($mx_weight as $k => $weight) {
472 $mxs[] = $mx_records[$k];
478 * wrapper to call object->toEmail()
482 headers : {AssocArray},
486 error : {String} // error message in log.
487 send-to: {String} // use to override rcpt
491 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
493 $m = 'notify'. $notify->evtype;
494 //var_dump(get_class($object) . '::' .$m);
495 if (!empty($notify->evtype) && method_exists($object,$m)) {
496 echo "calling :" . get_class($object) . '::' .$m . "\n";
497 return $object->$m($rcpt, $last_sent_date, $notify, $force);
500 $type = explode('::', $notify->evtype);
502 if(!empty($type[1]) && method_exists($object,$type[1])){
504 echo "calling :" . get_class($object) . '::' .$m . "\n";
505 return $object->$m($rcpt, $last_sent_date, $notify, $force);
508 if (!method_exists($object, 'toEmail')) {
513 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
518 if (empty($this->cli_args['debug'])) {
530 function debugHandler ($smtp, $message)
532 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
533 $this->debug_str .= $message;