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';
71 var $error_handler = 'die';
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 //DB_DataObject::debugLevel(1);
93 //date_default_timezone_set('UTC');
95 $force = empty($opts['force']) ? 0 : 1;
97 $w = DB_DataObject::factory($this->table);
100 $this->errorHandler("invalid id\n");
102 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
105 $this->errorHandler("send repeat to early\n");
107 if (!empty($opts['debug'])) {
111 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
113 if (!$force && (!empty($w->msgid) || $sent)) {
116 $w->sent = $w->sqlValue("NOW()");
119 $this->errorHandler("message has been sent already.\n");
126 $ev = $this->addEvent('NOTIFY', $w,
127 "Notification event cleared (underlying object does not exist)" );;
129 $w->sent = date('Y-m-d H:i:s');
131 $w->event_id = $ev->id;
133 $this->errorHandler(date('Y-m-d h:i:s ') .
134 "Notification event cleared (underlying object does not exist)"
142 if (isset($p->active) && empty($p->active)) {
143 $ev = $this->addEvent('NOTIFY', $w,
144 "Notification event cleared (not user not active any more)" );;
146 $w->sent = date('Y-m-d H:i:s');
148 $w->event_id = $ev->id;
150 $this->errorHandler(date('Y-m-d h:i:s ') .
151 "Notification event cleared (not user not active any more)"
153 $this->errorHandler("message has been sent already.\n");
157 // let's work out the last notification sent to this user..
158 $l = DB_DataObject::factory($this->table);
160 'ontable' => $w->ontable,
162 'person_id' => $w->person_id,
164 $l->whereAdd('id != '. $w->id);
165 $l->orderBy('sent DESC');
167 $ar = $l->fetchAll('sent');
168 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
171 $ev = DB_DataObject::factory('Events');
172 $ev->on_id = $w->id; // int(11)
173 $ev->on_table = $this->table;
175 $ev->orderBy('event_when DESC');
176 $ar = $ev->fetchAll('event_when');
177 $last_event = empty($ar) ? 0 : $ar[0];
180 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
182 $next_try = $next_try_min . ' MINUTES';
184 // this may modify $p->email. (it will not update it though)
185 $email = $this->makeEmail($o, $p, $last, $w, $force);
187 if ($email === true) {
189 $ev = $this->addEvent('NOTIFY', $w,
190 "Notification event cleared (not required any more)" );;
192 $w->sent = date('Y-m-d H:i:s');
194 $w->event_id = $ev->id;
196 $this->errorHandler(date('Y-m-d h:i:s ') .
197 "Notification event cleared (not required any more)"
203 if ($email === false || isset($email['error'])) {
204 // object returned 'false' - it does not know how to send it..
205 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
206 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
208 $w->sent = date('Y-m-d H:i:s');
210 $w->event_id = $ev->id;
212 $this->errorHandler(date('Y-m-d h:i:s ') .
213 (isset($email['error']) ?
214 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
219 if (isset($email['later'])) {
221 $w->act_when = $email['later'];
223 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
227 if (empty($email['headers']['Message-Id'])) {
228 $HOST = gethostname();
229 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
232 //$p->email = 'alan@akbkhome.com'; //for testing..
233 //print_r($email);exit;
234 // should we fetch the watch that caused it.. - which should contain the method to call..
235 // --send-to=test@xxx.com
237 if (!empty($email['send-to'])) {
238 $p->email = $email['send-to'];
240 if (!empty($opts['send-to'])) {
241 $p->email = $opts['send-to'];
243 // since some of them have spaces?!?!
244 $p->email = trim($p->email);
246 require_once 'Validate.php';
247 if (!Validate::email($p->email, true)) {
248 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
250 $w->sent = date('Y-m-d H:i:s');
252 $w->event_id = $ev->id;
254 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
259 $ff = HTML_FlexyFramework::get();
262 $dom = array_pop(explode('@', $p->email));
264 $mxs = $this->mxs($dom);
267 // we might fail doing this...
268 // need to handle temporary failure..
271 // we try for 3 days..
273 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
274 // older that 1 hour.
278 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
282 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
287 if ($mxs === false) {
288 // only retry for 2 day son the MX issue..
290 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
291 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
293 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
296 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
297 $w->sent = date('Y-m-d H:i:s');
299 $w->event_id = $ev->id;
301 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
309 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
310 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
311 $w->sent = date('Y-m-d H:i:s');
313 $w->event_id = $ev->id;
315 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
320 $w->to_email = $p->email;
321 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
322 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
328 require_once 'Mail.php';
330 foreach($mxs as $dom) {
334 if (!isset($ff->Mail['helo'])) {
335 $this->errorHandler("config Mail[helo] is not set");
337 $this->debug_str = '';
338 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
339 $mailer = Mail::factory('smtp', array(
341 'localhost' => $ff->Mail['helo'],
343 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
344 //'debug' => isset($opts['debug']) ? 1 : 0,
346 'debug_handler' => array($this, 'debugHandler')
348 $res = $mailer->send($p->email, $email['headers'], $email['body']);
354 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
356 $ev->writeEventLog($this->debug_str);
358 $w->sent = date('Y-m-d H:i:s');
359 $w->msgid = $email['headers']['Message-Id'];
360 $w->event_id = $ev->id; // sent ok.. - no need to record it..
363 // enable cc in notify..
364 if (!empty($email['headers']['Cc'])) {
365 $cmailer = Mail::factory('smtp', array(
369 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
370 $cmailer->send($email['headers']['Cc'],
371 $email['headers'], $email['body']);
375 if (!empty($email['bcc'])) {
376 $cmailer = Mail::factory('smtp', array(
380 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
381 $cmailer->send($email['bcc'],
382 $email['headers'], $email['body']);
387 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT\n");
389 // what type of error..
390 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
391 if (!empty($res->code) && $res->code == 10001) {
392 // fake greylist if timed out.
397 $this->debug($res->message);
398 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
400 // give up after 2 days..
401 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
403 // check last event for this item..
404 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
405 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
406 if (!empty($res->userinfo['smtptext'])) {
407 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
410 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
411 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
415 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
420 if ($fail || $next_try_min > (2*24*60)) {
421 // fail.. = log and give up..
422 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
423 if (isset($res->userinfo['smtptext'])) {
424 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
427 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
429 $w->sent = date('Y-m-d H:i:s');
431 $w->event_id = $ev->id;
433 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
436 // handle no host availalbe forever...
437 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
438 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
439 $w->sent = date('Y-m-d H:i:s');
441 $w->event_id = $ev->id;
443 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
449 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
450 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
452 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
458 $ff = HTML_FlexyFramework::get();
459 if (isset($ff->Pman_Core_NotifySend['host'])) {
460 return array($ff->Pman_Core_NotifySend['host']);
463 $mx_records = array();
464 $mx_weight = array();
466 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
467 if (!checkdnsrr($fqdn)) {
473 asort($mx_weight,SORT_NUMERIC);
475 foreach($mx_weight as $k => $weight) {
476 $mxs[] = $mx_records[$k];
482 * wrapper to call object->toEmail()
486 headers : {AssocArray},
490 error : {String} // error message in log.
491 send-to: {String} // use to override rcpt
495 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
497 $m = 'notify'. $notify->evtype;
498 //var_dump(get_class($object) . '::' .$m);
499 if (!empty($notify->evtype) && method_exists($object,$m)) {
500 echo "calling :" . get_class($object) . '::' .$m . "\n";
501 return $object->$m($rcpt, $last_sent_date, $notify, $force);
504 $type = explode('::', $notify->evtype);
506 if(!empty($type[1]) && method_exists($object,$type[1])){
508 echo "calling :" . get_class($object) . '::' .$m . "\n";
509 return $object->$m($rcpt, $last_sent_date, $notify, $force);
512 if (!method_exists($object, 'toEmail')) {
517 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
522 if (empty($this->cli_args['debug'])) {
530 $this->errorHandler("done\n");
534 function debugHandler ($smtp, $message)
536 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
537 $this->debug_str .= $message;
540 function errorHandler($msg)
542 if($this->error_handler == 'exception'){
543 throw new Exception($msg);