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");
122 if (!empty($opts['debug'])) {
124 $ff = HTML_FlexyFramework::get();
125 if (!isset($ff->Core_Mailer)) {
126 $ff->Core_Mailer = array();
128 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
131 $sent = (empty($w->sent) || strtotime( $w->sent) < 100 ) ? false : true;
133 if (!$force && (!empty($w->msgid) || $sent)) {
135 if (!$sent) { // fix sent.
136 $w->sent = strtotime( $w->sent) < 100 ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
139 $this->errorHandler("message has been sent already.\n");
142 // we have a bug with msgid not getting filled.
143 $cev = DB_DataObject::Factory('Events');
144 $cev->on_table = $this->table;
145 $cev->on_id = $w->id;
146 $cev->whereAdd("action IN ('NOTIFYSENT', 'NOTIFYFAIL')");
150 $w->flagDone($cev, $cev->action == 'NOTIFYSENT' ? 'alreadysent' : '');
151 $this->errorHandler( $cev->action . " (fix old) ". $cev->remarks);
159 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (underlying object does not exist)" );
160 $w->flagDone($ev, '');
161 $this->errorHandler( $ev->remarks);
168 if (isset($p->active) && empty($p->active)) {
169 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not user not active any more)" );;
170 $w->flagDone($ev, '');
171 $this->errorHandler( $ev->remarks);
173 // has it failed mutliple times..
175 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
176 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (user has to many failures)" );;
177 $w->flagDone($ev, '');
178 $this->errorHandler( $ev->remarks);
181 // let's work out the last notification sent to this user..
182 $l = DB_DataObject::factory($this->table);
185 'ontable' => $w->ontable,
188 // only newer version of the database us this..
189 if (isset($w->person_table)) {
190 $personid_col = strtolower($w->person_table).'_id';
191 if (isset($w->{$personid_col})) {
192 $lar[$personid_col] = $w->{$personid_col};
198 $l->whereAdd('id != '. $w->id);
199 $l->orderBy('sent DESC');
201 $ar = $l->fetchAll('sent');
202 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
205 $ev = DB_DataObject::factory('Events');
206 $ev->on_id = $w->id; // int(11)
207 $ev->on_table = $this->table;
209 $ev->orderBy('event_when DESC');
210 $ar = $ev->fetchAll('event_when');
211 $last_event = empty($ar) ? 0 : $ar[0];
214 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
216 $next_try = $next_try_min . ' MINUTES';
218 // this may modify $p->email. (it will not update it though)
219 $email = $this->makeEmail($o, $p, $last, $w, $force);
221 if ($email === true) {
222 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not required any more) - toEmail=true" );;
223 $w->flagDone($ev, '');
224 $this->errorHandler( $ev->remarks);
226 if (is_a($email, 'PEAR_Error')) {
228 'error' => $email->toString()
232 if (empty($p) && !empty($email['recipients'])) {
233 // make a fake person..
235 'email' => $email['recipients']
239 if ($email === false || isset($email['error']) || empty($p)) {
240 // object returned 'false' - it does not know how to send it..
241 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ? $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
242 $w->flagDone($ev, '');
243 $this->errorHandler( $ev->remarks);
248 if (isset($email['later'])) {
250 $this->server->updateNotifyToNextServer($w, $email['later'],true);
252 $this->errorHandler("Delivery postponed by email creator to {$email['later']}");
256 if (empty($email['headers']['Message-Id'])) {
257 $HOST = gethostname();
258 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
265 //$p->email = 'alan@akbkhome.com'; //for testing..
266 //print_r($email);exit;
267 // should we fetch the watch that caused it.. - which should contain the method to call..
268 // --send-to=test@xxx.com
270 if (!empty($email['send-to'])) {
271 $p->email = $email['send-to'];
273 if (!empty($opts['send-to'])) {
274 $p->email = $opts['send-to'];
277 // since some of them have spaces?!?!
278 $p->email = trim($p->email);
280 $ww->to_email = empty($ww->to_email) ? $p->email : $ww->to_email;
281 $explode_email = explode('@', $ww->to_email);
282 $dom = array_pop($explode_email);
284 $core_domain = DB_DataObject::factory('core_domain')->loadOrCreate($dom);
287 $ww->domain_id = $core_domain->id;
288 // if to_email has not been set!?
289 $ww->update($w); // if nothing has changed this will not do anything.
294 require_once 'Validate.php';
295 if (!Validate::email($p->email, true)) {
296 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
297 $w->flagDone($ev, '');
298 $this->errorHandler($ev->remarks);
303 $ff = HTML_FlexyFramework::get();
306 $mxs = $this->mxs($dom);
309 // we might fail doing this...
310 // need to handle temporary failure..
313 // we try for 2 days..
315 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
316 // older that 1 hour.
320 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
324 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
330 // only retry for 1 day if the MX issue..
332 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
333 $w->flagLater(date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')));
334 $this->errorHandler($ev->remarks);
337 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
338 $w->flagDone($ev, '');
339 $this->errorHandler($ev->remarks);
347 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
348 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
349 $w->flagDone($ev, '');
350 $this->errorHandler( $ev->remarks);
353 $retry_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
355 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
356 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
357 // set act when if it's empty...
358 $w->act_when = (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? $retry_when : $w->act_when;
365 require_once 'Mail.php';
368 $this->server->initHelo();
370 if (!isset($ff->Mail['helo'])) {
371 $this->errorHandler("config Mail[helo] is not set");
376 foreach($mxs as $mx) {
379 $this->debug_str = '';
380 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
381 $mailer = Mail::factory('smtp', array(
383 'localhost' => $ff->Mail['helo'],
385 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
386 //'debug' => isset($opts['debug']) ? 1 : 0,
388 'debug_handler' => array($this, 'debugHandler')
391 // if the host is the mail host + it's authenticated add auth details
392 // this normally will happen if you sent Pman_Core_NotifySend['host']
395 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
397 $mailer->auth = true;
398 $mailer->username = $ff->Mail['username'];
399 $mailer->password = $ff->Mail['password'];
402 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
404 // we might want to regex 'office365 as a mx host
405 foreach ($ff->Core_Notify['routes'] as $server => $settings){
406 if(!in_array($dom, $settings['domains'])){
410 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
411 // if it's newer that '1' minute...
414 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
416 $seconds = floor((60 * 60) / $settings['rate']);
418 $core_notify = DB_DataObject::factory($this->table);
419 $core_notify->domain_id = $core_domain->id;
420 $core_notify->server_id = $this->server->id;
421 $core_notify->whereAdd("
422 sent >= NOW() - INTERVAL $seconds SECOND
425 if($core_notify->count()){
426 $this->server->updateNotifyToNextServer( $w , date("Y-m-d H:i:s", time() + $seconds), true);
427 $this->errorHandler( " Too many emails sent by {$dom} - requeing");
432 $mailer->host = $server;
433 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
434 $mailer->username = $settings['username'];
435 $mailer->password = $settings['password'];
436 if (isset($settings['port'])) {
437 $mailer->port = $settings['port'];
439 if (isset($settings['socket_options'])) {
440 $mailer->socket_options = $settings['socket_options'];
451 $res = $mailer->send($p->email, $email['headers'], $email['body']);
452 if (is_object($res)) {
453 $res->backtrace = array();
455 $this->debug("GOT response to send: ". print_r($res,true));
460 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
462 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
464 $ev->writeEventLog($this->debug_str);
466 $w->flagDone($ev, $email['headers']['Message-Id']);
469 // enable cc in notify..
470 if (!empty($email['headers']['Cc'])) {
471 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
472 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
473 $cmailer->send($email['headers']['Cc'], $email['headers'], $email['body']);
477 if (!empty($email['bcc'])) {
478 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
479 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
480 $res = $cmailer->send($email['bcc'], $email['headers'], $email['body']);
481 if (!$res || is_a($res, 'PEAR_Error')) {
482 echo "could not send bcc..\n";
484 echo "Sent BCC to {$email['bcc']}\n";
488 $this->errorHandler( " SENT {$w->id} - {$ev->remarks}", true);
490 // what type of error..
491 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
492 if (!empty($res->code) && $res->code == 10001) {
493 // fake greylist if timed out.
498 $this->debug($res->message);
499 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
501 // give up after 2 days..
502 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
504 // check last event for this item..
505 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
506 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
507 if (!empty($res->userinfo['smtptext'])) {
508 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
511 $ev = $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
513 $this->server->updateNotifyToNextServer($w, $retry_when,true);
515 $this->errorHandler( $ev->remarks);
522 // after trying all mxs - could not connect...
523 if (!$fail && ($next_try_min > (2*24*60) || strtotime($w->act_start) < strtotime('NOW - 3 DAYS'))) {
525 $errmsg= " - UNKNOWN ERROR";
526 if (isset($res->userinfo['smtptext'])) {
527 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
530 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - " . $errmsg);
531 $w->flagDone($ev, '');
532 $this->errorHandler( $ev->remarks);
535 if ($fail) { //// !!!!<<< BLACKLIST DETECT?
536 // fail.. = log and give up..
537 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->toString();
538 if (isset($res->userinfo['smtptext'])) {
539 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
542 if ($res->userinfo['smtpcode'] == 550) {
543 if ($this->server->checkSmtpResponse($errmsg, $core_domain)) {
544 $ev = $this->addEvent('NOTIFY', $w, 'BLACKLISTED - ' . $errmsg);
545 $this->server->updateNotifyToNextServer($w, $retry_when,true);
546 $this->errorHandler( $ev->remarks);
550 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") . $errmsg);
551 $w->flagDone($ev, '');
553 $this->errorHandler( $ev->remarks);
556 // at this point we just could not find any MX records..
561 $ev = $this->addEvent('NOTIFY', $w, 'GREYLIST - NO HOST CAN BE CONTACTED:' . $p->email);
563 $this->server->updateNotifyToNextServer($w, $retry_when ,true);
567 $this->errorHandler($ev->remarks);
573 $ff = HTML_FlexyFramework::get();
574 if (isset($ff->Pman_Core_NotifySend['host'])) {
575 return array($ff->Pman_Core_NotifySend['host']);
578 $mx_records = array();
579 $mx_weight = array();
581 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
582 if (!checkdnsrr($fqdn)) {
588 asort($mx_weight,SORT_NUMERIC);
590 foreach($mx_weight as $k => $weight) {
591 if (!empty($mx_records[$k])) {
592 $mxs[] = $mx_records[$k];
595 return empty($mxs) ? false : $mxs;
599 * wrapper to call object->toEmail()
603 headers : {AssocArray},
607 error : {String} // error message in log.
608 send-to: {String} // use to override rcpt
612 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
614 $m = 'notify'. $notify->evtype;
615 //var_dump(get_class($object) . '::' .$m);
616 if (!empty($notify->evtype) && method_exists($object,$m)) {
617 echo "calling :" . get_class($object) . '::' .$m . "\n";
618 return $object->$m($rcpt, $last_sent_date, $notify, $force);
621 $type = explode('::', $notify->evtype);
623 if(!empty($type[1]) && method_exists($object,$type[1])){
625 echo "calling :" . get_class($object) . '::' .$m . "\n";
626 return $object->$m($rcpt, $last_sent_date, $notify, $force);
628 // fallback if evtype is empty..
630 if (method_exists($object, 'toMailerData')) {
631 return $object->toMailerData(array(
633 'person'=>$rcpt, // added as mediaoutreach used this?
634 )); //this is core_email - i think it's only used for testing...
638 if (method_exists($object, 'toEmail')) {
639 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
641 // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
648 if (empty($this->cli_args['debug'])) {
656 $this->errorHandler("done\n");
660 function debugHandler ($smtp, $message)
662 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
663 $this->debug_str .= $message;
664 //echo $message ."\n";
667 function errorHandler($msg, $success = false)
669 if($this->error_handler == 'exception'){
671 throw new Pman_Core_NotifySend_Exception_Success($msg);
674 throw new Pman_Core_NotifySend_Exception_Fail($msg);
677 die(date('Y-m-d h:i:s') . ' ' . $msg ."\n");
682 function updateServer($w)
684 $ff = HTML_FlexyFramework::get();
686 if (empty($ff->Core_Notify['servers'])) {
689 // some classes dont support server routing
690 if (!property_exists($w, 'server_id')) {
694 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));