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.
29 class Pman_Core_NotifySend_Exception_Success extends Exception {}
30 class Pman_Core_NotifySend_Exception_Fail extends Exception {}
33 class Pman_Core_NotifySend extends Pman
35 static $cli_desc = "Send out single notification email (usually called from Core/Notify)";
37 static $cli_opts = array(
39 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
46 'DB_DataObject-debug' => array(
47 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
55 'desc' => 'Force redelivery, even if it has been sent before or not queued...',
62 'desc' => 'Send the message to this address, rather than the one listed.',
72 var $table = 'core_notify';
73 var $error_handler = 'die';
74 var $poolname = 'core';
75 var $server; // core_notify_server
79 $ff = HTML_FlexyFramework::get();
81 $this->errorHandler("access denied");
83 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
88 function get($id,$opts=array())
92 if (!empty($opts['DB_DataObject-debug'])) {
93 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
96 //DB_DataObject::debugLevel(1);
97 //date_default_timezone_set('UTC');
99 $force = empty($opts['force']) ? 0 : 1;
101 $w = DB_DataObject::factory($this->table);
104 $this->errorHandler("invalid id\n");
107 if (!$force && !empty($w->sent) && strtotime($w->act_when) < strtotime($w->sent)) {
109 $this->errorHandler("already sent - repeat to early\n");
112 $this->server = DB_DataObject::Factory('core_notify_server')->getCurrent($this, $force);
113 if (!$force && $w->server_id != $this->server->id) {
114 $this->errorHandler("Server id does not match - use force to try again\n");
119 if (!empty($opts['debug'])) {
121 $ff = HTML_FlexyFramework::get();
122 if (!isset($ff->Core_Mailer)) {
123 $ff->Core_Mailer = array();
125 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
128 $sent = (empty($w->sent) || strtotime( $w->sent) < 100 ) ? false : true;
130 if (!$force && (!empty($w->msgid) || $sent)) {
132 if (!$sent) { // fix sent.
133 $w->sent = strtotime( $w->sent) < 100 ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
136 $this->errorHandler("message has been sent already.\n");
139 // we have a bug with msgid not getting filled.
140 $cev = DB_DataObject::Factory('Events');
141 $cev->on_table = $this->table;
142 $cev->on_id = $w->id;
143 $cev->whereAdd("action IN ('NOTIFYSENT', 'NOTIFYFAIL')");
147 $w->flagDone($cev, $cev->action == 'NOTIFYSENT' ? 'alreadysent' : '');
148 $this->errorHandler( $cev->action . " (fix old) ". $cev->remarks);
156 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (underlying object does not exist)" );
157 $w->flagDone($ev, '');
158 $this->errorHandler( $ev->remarks);
165 if (isset($p->active) && empty($p->active)) {
166 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not user not active any more)" );;
167 $w->flagDone($ev, '');
168 $this->errorHandler( $ev->remarks);
170 // has it failed mutliple times..
172 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
173 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (user has to many failures)" );;
174 $w->flagDone($ev, '');
175 $this->errorHandler( $ev->remarks);
178 // let's work out the last notification sent to this user..
179 $l = DB_DataObject::factory($this->table);
182 'ontable' => $w->ontable,
185 // only newer version of the database us this..
186 if (isset($w->person_table)) {
187 $personid_col = strtolower($w->person_table).'_id';
188 if (isset($w->{$personid_col})) {
189 $lar[$personid_col] = $w->{$personid_col};
195 $l->whereAdd('id != '. $w->id);
196 $l->orderBy('sent DESC');
198 $ar = $l->fetchAll('sent');
199 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
202 $ev = DB_DataObject::factory('Events');
203 $ev->on_id = $w->id; // int(11)
204 $ev->on_table = $this->table;
206 $ev->orderBy('event_when DESC');
207 $ar = $ev->fetchAll('event_when');
208 $last_event = empty($ar) ? 0 : $ar[0];
211 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
213 $next_try = $next_try_min . ' MINUTES';
215 // this may modify $p->email. (it will not update it though)
216 $email = $this->makeEmail($o, $p, $last, $w, $force);
218 if ($email === true) {
219 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not required any more) - toEmail=true" );;
220 $w->flagDone($ev, '');
221 $this->errorHandler( $ev->remarks);
223 if (is_a($email, 'PEAR_Error')) {
225 'error' => $email->toString()
229 if (empty($p) && !empty($email['recipients'])) {
230 // make a fake person..
232 'email' => $email['recipients']
236 if ($email === false || isset($email['error']) || empty($p)) {
237 // object returned 'false' - it does not know how to send it..
238 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ? $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
239 $w->flagDone($ev, '');
240 $this->errorHandler( $ev->remarks);
245 if (isset($email['later'])) {
247 $this->server->updateNotifyToNextServer($w, $email['later'],true);
249 $this->errorHandler("Delivery postponed by email creator to {$email['later']}");
253 if (empty($email['headers']['Message-Id'])) {
254 $HOST = gethostname();
255 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
262 //$p->email = 'alan@akbkhome.com'; //for testing..
263 //print_r($email);exit;
264 // should we fetch the watch that caused it.. - which should contain the method to call..
265 // --send-to=test@xxx.com
267 if (!empty($email['send-to'])) {
268 $p->email = $email['send-to'];
270 if (!empty($opts['send-to'])) {
271 $p->email = $opts['send-to'];
274 // since some of them have spaces?!?!
275 $p->email = trim($p->email);
277 $ww->to_email = empty($ww->to_email) ? $p->email : $ww->to_email;
278 $explode_email = explode('@', $ww->to_email);
279 $dom = array_pop($explode_email);
281 $core_domain = DB_DataObject::factory('core_domain')->loadOrCreate($dom);
284 $ww->domain_id = $core_domain->id;
285 // if to_email has not been set!?
286 $ww->update($w); // if nothing has changed this will not do anything.
291 require_once 'Validate.php';
292 if (!Validate::email($p->email, true)) {
293 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
294 $w->flagDone($ev, '');
295 $this->errorHandler($ev->remarks);
300 $ff = HTML_FlexyFramework::get();
303 $mxs = $this->mxs($dom);
306 // we might fail doing this...
307 // need to handle temporary failure..
310 // we try for 2 days..
312 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
313 // older that 1 hour.
317 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
321 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
327 // only retry for 1 day if the MX issue..
329 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
330 $w->flagLater(date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')));
331 $this->errorHandler($ev->remarks);
334 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
335 $w->flagDone($ev, '');
336 $this->errorHandler($ev->remarks);
344 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
345 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
346 $w->flagDone($ev, '');
347 $this->errorHandler( $ev->remarks);
350 $retry_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
352 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
353 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
354 // set act when if it's empty...
355 $w->act_when = (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? $retry_when : $w->act_when;
362 require_once 'Mail.php';
365 $this->server->initHelo();
367 if (!isset($ff->Mail['helo'])) {
368 $this->errorHandler("config Mail[helo] is not set");
373 foreach($mxs as $mx) {
376 $this->debug_str = '';
377 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
378 $mailer = Mail::factory('smtp', array(
380 'localhost' => $ff->Mail['helo'],
382 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
383 //'debug' => isset($opts['debug']) ? 1 : 0,
385 'debug_handler' => array($this, 'debugHandler')
388 // if the host is the mail host + it's authenticated add auth details
389 // this normally will happen if you sent Pman_Core_NotifySend['host']
392 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
394 $mailer->auth = true;
395 $mailer->username = $ff->Mail['username'];
396 $mailer->password = $ff->Mail['password'];
399 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
401 // we might want to regex 'office365 as a mx host
402 foreach ($ff->Core_Notify['routes'] as $server => $settings){
403 if(!in_array($dom, $settings['domains'])){
407 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
408 // if it's newer that '1' minute...
411 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
413 $seconds = floor((60 * 60) / $settings['rate']);
415 $core_notify = DB_DataObject::factory($this->table);
416 $core_notify->domain_id = $core_domain->id;
417 $core_notify->server_id = $this->server->id;
418 $core_notify->whereAdd("
419 sent >= NOW() - INTERVAL $seconds SECOND
422 if($core_notify->count()){
423 $this->server->updateNotifyToNextServer( $w , date("Y-m-d H:i:s", time() + $seconds), true);
424 $this->errorHandler( " Too many emails sent by {$dom} - requeing");
429 $mailer->host = $server;
430 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
431 $mailer->username = $settings['username'];
432 $mailer->password = $settings['password'];
433 if (isset($settings['port'])) {
434 $mailer->port = $settings['port'];
436 if (isset($settings['socket_options'])) {
437 $mailer->socket_options = $settings['socket_options'];
448 $res = $mailer->send($p->email, $email['headers'], $email['body']);
449 if (is_object($res)) {
450 $res->backtrace = array();
452 $this->debug("GOT response to send: ". print_r($res,true));
457 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
459 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
461 $ev->writeEventLog($this->debug_str);
463 $w->flagDone($ev, $email['headers']['Message-Id']);
466 // enable cc in notify..
467 if (!empty($email['headers']['Cc'])) {
468 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
469 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
470 $cmailer->send($email['headers']['Cc'], $email['headers'], $email['body']);
474 if (!empty($email['bcc'])) {
475 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
476 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
477 $res = $cmailer->send($email['bcc'], $email['headers'], $email['body']);
478 if (!$res || is_a($res, 'PEAR_Error')) {
479 echo "could not send bcc..\n";
481 echo "Sent BCC to {$email['bcc']}\n";
485 $this->errorHandler( " SENT {$w->id} - {$ev->remarks}", true);
487 // what type of error..
488 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
489 if (!empty($res->code) && $res->code == 10001) {
490 // fake greylist if timed out.
495 $this->debug($res->message);
496 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
498 // give up after 2 days..
499 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
501 // check last event for this item..
502 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
503 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
504 if (!empty($res->userinfo['smtptext'])) {
505 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
508 $ev = $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
510 $this->server->updateNotifyToNextServer($w, $retry_when,true);
512 $this->errorHandler( $ev->remarks);
519 // after trying all mxs - could not connect...
520 if (!$fail && ($next_try_min > (2*24*60) || strtotime($w->act_start) < strtotime('NOW - 3 DAYS'))) {
522 $errmsg= " - UNKNOWN ERROR";
523 if (isset($res->userinfo['smtptext'])) {
524 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
527 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - " . $errmsg);
528 $w->flagDone($ev, '');
529 $this->errorHandler( $ev->remarks);
532 if ($fail) { //// !!!!<<< BLACKLIST DETECT?
533 // fail.. = log and give up..
534 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->toString();
535 if (isset($res->userinfo['smtptext'])) {
536 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
539 if ($res->userinfo['smtpcode'] == 550) {
540 if ($this->server->checkSmtpResponse($errmsg, $core_domain)) {
541 $ev = $this->addEvent('NOTIFY', $w, 'BLACKLISTED - ' . $errmsg);
542 $this->server->updateNotifyToNextServer($w, $retry_when,true);
543 $this->errorHandler( $ev->remarks);
547 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") . $errmsg);
548 $w->flagDone($ev, '');
550 $this->errorHandler( $ev->remarks);
553 // at this point we just could not find any MX records..
558 $ev = $this->addEvent('NOTIFY', $w, 'GREYLIST - NO HOST CAN BE CONTACTED:' . $p->email);
560 $this->server->updateNotifyToNextServer($w, $retry_when ,true);
564 $this->errorHandler($ev->remarks);
570 $ff = HTML_FlexyFramework::get();
571 if (isset($ff->Pman_Core_NotifySend['host'])) {
572 return array($ff->Pman_Core_NotifySend['host']);
575 $mx_records = array();
576 $mx_weight = array();
578 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
579 if (!checkdnsrr($fqdn)) {
585 asort($mx_weight,SORT_NUMERIC);
587 foreach($mx_weight as $k => $weight) {
588 if (!empty($mx_records[$k])) {
589 $mxs[] = $mx_records[$k];
592 return empty($mxs) ? false : $mxs;
596 * wrapper to call object->toEmail()
600 headers : {AssocArray},
604 error : {String} // error message in log.
605 send-to: {String} // use to override rcpt
609 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
611 $m = 'notify'. $notify->evtype;
612 //var_dump(get_class($object) . '::' .$m);
613 if (!empty($notify->evtype) && method_exists($object,$m)) {
614 echo "calling :" . get_class($object) . '::' .$m . "\n";
615 return $object->$m($rcpt, $last_sent_date, $notify, $force);
618 $type = explode('::', $notify->evtype);
620 if(!empty($type[1]) && method_exists($object,$type[1])){
622 echo "calling :" . get_class($object) . '::' .$m . "\n";
623 return $object->$m($rcpt, $last_sent_date, $notify, $force);
625 // fallback if evtype is empty..
627 if (method_exists($object, 'toMailerData')) {
628 return $object->toMailerData(array(
630 'person'=>$rcpt, // added as mediaoutreach used this?
631 )); //this is core_email - i think it's only used for testing...
635 if (method_exists($object, 'toEmail')) {
636 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
638 // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
645 if (empty($this->cli_args['debug'])) {
653 $this->errorHandler("done\n");
657 function debugHandler ($smtp, $message)
659 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
660 $this->debug_str .= $message;
661 //echo $message ."\n";
664 function errorHandler($msg, $success = false)
666 if($this->error_handler == 'exception'){
668 throw new Pman_Core_NotifySend_Exception_Success($msg);
671 throw new Pman_Core_NotifySend_Exception_Fail($msg);
674 die(date('Y-m-d h:i:s') . ' ' . $msg ."\n");
679 function updateServer($w)
681 $ff = HTML_FlexyFramework::get();
683 if (empty($ff->Core_Notify['servers'])) {
686 // some classes dont support server routing
687 if (!property_exists($w, 'server_id')) {
691 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));