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");
118 if (!empty($opts['debug'])) {
120 $ff = HTML_FlexyFramework::get();
121 if (!isset($ff->Core_Mailer)) {
122 $ff->Core_Mailer = array();
124 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
127 $sent = (empty($w->sent) || strtotime( $w->sent) < 100 ) ? false : true;
129 if (!$force && (!empty($w->msgid) || $sent)) {
131 if (!$sent) { // fix sent.
132 $w->sent = strtotime( $w->sent) < 100 ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
135 $this->errorHandler("message has been sent already.\n");
138 // we have a bug with msgid not getting filled.
139 $cev = DB_DataObject::Factory('Events');
140 $cev->on_table = $this->table;
141 $cev->on_id = $w->id;
142 $cev->whereAdd("action IN ('NOTIFYSENT', 'NOTIFYFAIL')");
146 $w->flagDone($cev, $cev->action == 'NOTIFYSENT' ? 'alreadysent' : '');
147 $this->errorHandler( $cev->action . " (fix old) ". $cev->remarks);
155 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (underlying object does not exist)" );
156 $w->flagDone($ev, '');
157 $this->errorHandler( $ev->remarks);
164 if (isset($p->active) && empty($p->active)) {
165 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not user not active any more)" );;
166 $w->flagDone($ev, '');
167 $this->errorHandler( $ev->remarks);
169 // has it failed mutliple times..
171 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
172 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (user has to many failures)" );;
173 $w->flagDone($ev, '');
174 $this->errorHandler( $ev->remarks);
177 // let's work out the last notification sent to this user..
178 $l = DB_DataObject::factory($this->table);
181 'ontable' => $w->ontable,
184 // only newer version of the database us this..
185 if (isset($w->person_table)) {
186 $personid_col = strtolower($w->person_table).'_id';
187 if (isset($w->{$personid_col})) {
188 $lar[$personid_col] = $w->{$personid_col};
194 $l->whereAdd('id != '. $w->id);
195 $l->orderBy('sent DESC');
197 $ar = $l->fetchAll('sent');
198 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
201 $ev = DB_DataObject::factory('Events');
202 $ev->on_id = $w->id; // int(11)
203 $ev->on_table = $this->table;
205 $ev->orderBy('event_when DESC');
206 $ar = $ev->fetchAll('event_when');
207 $last_event = empty($ar) ? 0 : $ar[0];
210 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
212 $next_try = $next_try_min . ' MINUTES';
214 // this may modify $p->email. (it will not update it though)
215 $email = $this->makeEmail($o, $p, $last, $w, $force);
217 if ($email === true) {
218 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not required any more) - toEmail=true" );;
219 $w->flagDone($ev, '');
220 $this->errorHandler( $ev->remarks);
222 if (is_a($email, 'PEAR_Error')) {
224 'error' => $email->toString()
228 if (empty($p) && !empty($email['recipients'])) {
229 // make a fake person..
231 'email' => $email['recipients']
235 if ($email === false || isset($email['error']) || empty($p)) {
236 // object returned 'false' - it does not know how to send it..
237 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ? $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
238 $w->flagDone($ev, '');
239 $this->errorHandler( $ev->remarks);
244 if (isset($email['later'])) {
246 $this->server->updateNotifyToNextServer($w, $email['later'],true);
248 $this->errorHandler("Delivery postponed by email creator to {$email['later']}");
252 if (empty($email['headers']['Message-Id'])) {
253 $HOST = gethostname();
254 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
261 //$p->email = 'alan@akbkhome.com'; //for testing..
262 //print_r($email);exit;
263 // should we fetch the watch that caused it.. - which should contain the method to call..
264 // --send-to=test@xxx.com
266 if (!empty($email['send-to'])) {
267 $p->email = $email['send-to'];
269 if (!empty($opts['send-to'])) {
270 $p->email = $opts['send-to'];
273 // since some of them have spaces?!?!
274 $p->email = trim($p->email);
276 $ww->to_email = empty($ww->to_email) ? $p->email : $ww->to_email;
277 $explode_email = explode('@', $ww->to_email);
278 $dom = array_pop($explode_email);
280 $core_domain = DB_DataObject::factory('core_domain')->loadOrCreate($dom);
283 $ww->domain_id = $core_domain->id;
284 // if to_email has not been set!?
285 $ww->update($w); // if nothing has changed this will not do anything.
290 require_once 'Validate.php';
291 if (!Validate::email($p->email, true)) {
292 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
293 $w->flagDone($ev, '');
294 $this->errorHandler($ev->remarks);
299 $ff = HTML_FlexyFramework::get();
302 $mxs = $this->mxs($dom);
305 // we might fail doing this...
306 // need to handle temporary failure..
309 // we try for 2 days..
311 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
312 // older that 1 hour.
316 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
320 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
326 // only retry for 1 day if the MX issue..
328 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
329 $w->flagLater(date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')));
330 $this->errorHandler($ev->remarks);
333 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
334 $w->flagDone($ev, '');
335 $this->errorHandler($ev->remarks);
343 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
344 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
345 $w->flagDone($ev, '');
346 $this->errorHandler( $ev->remarks);
349 $retry_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
351 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
352 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
353 // set act when if it's empty...
354 $w->act_when = (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? $retry_when : $w->act_when;
361 require_once 'Mail.php';
364 $this->server->initHelo();
366 if (!isset($ff->Mail['helo'])) {
367 $this->errorHandler("config Mail[helo] is not set");
372 foreach($mxs as $mx) {
375 $this->debug_str = '';
376 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
377 $mailer = Mail::factory('smtp', array(
379 'localhost' => $ff->Mail['helo'],
381 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
382 //'debug' => isset($opts['debug']) ? 1 : 0,
384 'debug_handler' => array($this, 'debugHandler')
387 // if the host is the mail host + it's authenticated add auth details
388 // this normally will happen if you sent Pman_Core_NotifySend['host']
391 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
393 $mailer->auth = true;
394 $mailer->username = $ff->Mail['username'];
395 $mailer->password = $ff->Mail['password'];
398 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
400 // we might want to regex 'office365 as a mx host
401 foreach ($ff->Core_Notify['routes'] as $server => $settings){
402 if(!in_array($dom, $settings['domains'])){
406 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
407 // if it's newer that '1' minute...
410 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
412 $seconds = floor((60 * 60) / $settings['rate']);
414 $core_notify = DB_DataObject::factory($this->table);
415 $core_notify->domain_id = $core_domain->id;
416 $core_notify->server_id = $this->server->id;
417 $core_notify->whereAdd("
418 sent >= NOW() - INTERVAL $seconds SECOND
421 if($core_notify->count()){
422 $this->server->updateNotifyToNextServer( $w , date("Y-m-d H:i:s", time() + $seconds), true);
423 $this->errorHandler( " Too many emails sent by {$dom} - requeing");
428 $mailer->host = $server;
429 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
430 $mailer->username = $settings['username'];
431 $mailer->password = $settings['password'];
432 if (isset($settings['port'])) {
433 $mailer->port = $settings['port'];
435 if (isset($settings['socket_options'])) {
436 $mailer->socket_options = $settings['socket_options'];
447 $res = $mailer->send($p->email, $email['headers'], $email['body']);
448 if (is_object($res)) {
449 $res->backtrace = array();
451 $this->debug("GOT response to send: ". print_r($res,true));
456 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
458 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
460 $ev->writeEventLog($this->debug_str);
462 $w->flagDone($ev, $email['headers']['Message-Id']);
465 // enable cc in notify..
466 if (!empty($email['headers']['Cc'])) {
467 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
468 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
469 $cmailer->send($email['headers']['Cc'], $email['headers'], $email['body']);
473 if (!empty($email['bcc'])) {
474 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
475 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
476 $res = $cmailer->send($email['bcc'], $email['headers'], $email['body']);
477 if (!$res || is_a($res, 'PEAR_Error')) {
478 echo "could not send bcc..\n";
480 echo "Sent BCC to {$email['bcc']}\n";
484 $this->errorHandler( " SENT {$w->id} - {$ev->remarks}", true);
486 // what type of error..
487 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
488 if (!empty($res->code) && $res->code == 10001) {
489 // fake greylist if timed out.
494 $this->debug($res->message);
495 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
497 // give up after 2 days..
498 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
500 // check last event for this item..
501 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
502 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
503 if (!empty($res->userinfo['smtptext'])) {
504 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
507 $ev = $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
509 $this->server->updateNotifyToNextServer($w, $retry_when,true);
511 $this->errorHandler( $ev->remarks);
518 // after trying all mxs - could not connect...
519 if (!$fail && ($next_try_min > (2*24*60) || strtotime($w->act_start) < strtotime('NOW - 3 DAYS'))) {
521 $errmsg= " - UNKNOWN ERROR";
522 if (isset($res->userinfo['smtptext'])) {
523 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
526 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - " . $errmsg);
527 $w->flagDone($ev, '');
528 $this->errorHandler( $ev->remarks);
531 if ($fail) { //// !!!!<<< BLACKLIST DETECT?
532 // fail.. = log and give up..
533 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->toString();
534 if (isset($res->userinfo['smtptext'])) {
535 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
538 if ($res->userinfo['smtpcode'] == 550) {
539 if ($this->server->checkSmtpResponse($errmsg, $core_domain)) {
540 $ev = $this->addEvent('NOTIFY', $w, 'BLACKLISTED - ' . $errmsg);
541 $this->server->updateNotifyToNextServer($w, $retry_when,true);
542 $this->errorHandler( $ev->remarks);
546 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") . $errmsg);
547 $w->flagDone($ev, '');
549 $this->errorHandler( $ev->remarks);
552 // at this point we just could not find any MX records..
557 $ev = $this->addEvent('NOTIFY', $w, 'GREYLIST - NO HOST CAN BE CONTACTED:' . $p->email);
559 $this->server->updateNotifyToNextServer($w, $retry_when ,true);
563 $this->errorHandler($ev->remarks);
569 $ff = HTML_FlexyFramework::get();
570 if (isset($ff->Pman_Core_NotifySend['host'])) {
571 return array($ff->Pman_Core_NotifySend['host']);
574 $mx_records = array();
575 $mx_weight = array();
577 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
578 if (!checkdnsrr($fqdn)) {
584 asort($mx_weight,SORT_NUMERIC);
586 foreach($mx_weight as $k => $weight) {
587 if (!empty($mx_records[$k])) {
588 $mxs[] = $mx_records[$k];
591 return empty($mxs) ? false : $mxs;
595 * wrapper to call object->toEmail()
599 headers : {AssocArray},
603 error : {String} // error message in log.
604 send-to: {String} // use to override rcpt
608 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
610 $m = 'notify'. $notify->evtype;
611 //var_dump(get_class($object) . '::' .$m);
612 if (!empty($notify->evtype) && method_exists($object,$m)) {
613 echo "calling :" . get_class($object) . '::' .$m . "\n";
614 return $object->$m($rcpt, $last_sent_date, $notify, $force);
617 $type = explode('::', $notify->evtype);
619 if(!empty($type[1]) && method_exists($object,$type[1])){
621 echo "calling :" . get_class($object) . '::' .$m . "\n";
622 return $object->$m($rcpt, $last_sent_date, $notify, $force);
624 // fallback if evtype is empty..
626 if (method_exists($object, 'toMailerData')) {
627 return $object->toMailerData(array(
629 'person'=>$rcpt, // added as mediaoutreach used this?
630 )); //this is core_email - i think it's only used for testing...
634 if (method_exists($object, 'toEmail')) {
635 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
637 // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
644 if (empty($this->cli_args['debug'])) {
652 $this->errorHandler("done\n");
656 function debugHandler ($smtp, $message)
658 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
659 $this->debug_str .= $message;
660 //echo $message ."\n";
663 function errorHandler($msg, $success = false)
665 if($this->error_handler == 'exception'){
667 throw new Pman_Core_NotifySend_Exception_Success($msg);
670 throw new Pman_Core_NotifySend_Exception_Fail($msg);
673 die(date('Y-m-d h:i:s') . ' ' . $msg ."\n");
678 function updateServer($w)
680 $ff = HTML_FlexyFramework::get();
682 if (empty($ff->Core_Notify['servers'])) {
685 // some classes dont support server routing
686 if (!property_exists($w, 'server_id')) {
690 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));