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");
370 $email = DB_DataObject::factory('core_notify_sender')->filterEmail($email, $w);
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'];
450 $res = $mailer->send($p->email, $email['headers'], $email['body']);
451 if (is_object($res)) {
452 $res->backtrace = array();
454 $this->debug("GOT response to send: ". print_r($res,true));
459 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
461 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
463 $ev->writeEventLog($this->debug_str);
465 $w->flagDone($ev, $email['headers']['Message-Id']);
468 // enable cc in notify..
469 if (!empty($email['headers']['Cc'])) {
470 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
471 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
472 $cmailer->send($email['headers']['Cc'], $email['headers'], $email['body']);
476 if (!empty($email['bcc'])) {
477 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
478 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
479 $res = $cmailer->send($email['bcc'], $email['headers'], $email['body']);
480 if (!$res || is_a($res, 'PEAR_Error')) {
481 echo "could not send bcc..\n";
483 echo "Sent BCC to {$email['bcc']}\n";
487 $this->errorHandler( " SENT {$w->id} - {$ev->remarks}", true);
489 // what type of error..
490 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
491 if (!empty($res->code) && $res->code == 10001) {
492 // fake greylist if timed out.
497 $this->debug($res->message);
498 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
500 // give up after 2 days..
501 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
503 // check last event for this item..
504 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
505 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
506 if (!empty($res->userinfo['smtptext'])) {
507 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
510 $ev = $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
512 $this->server->updateNotifyToNextServer($w, $retry_when,true);
514 $this->errorHandler( $ev->remarks);
521 // after trying all mxs - could not connect...
522 if (!$fail && ($next_try_min > (2*24*60) || strtotime($w->act_start) < strtotime('NOW - 3 DAYS'))) {
524 $errmsg= " - UNKNOWN ERROR";
525 if (isset($res->userinfo['smtptext'])) {
526 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
529 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - " . $errmsg);
530 $w->flagDone($ev, '');
531 $this->errorHandler( $ev->remarks);
534 if ($fail) { //// !!!!<<< BLACKLIST DETECT?
535 // fail.. = log and give up..
536 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->toString();
537 if (isset($res->userinfo['smtptext'])) {
538 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
541 if ( $res->userinfo['smtpcode']> 500 ) {
543 DB_DataObject::factory('core_notify_sender')->checkSmtpResponse($email, $w, $errmsg);
546 if ($this->server->checkSmtpResponse($errmsg, $core_domain)) {
547 $ev = $this->addEvent('NOTIFY', $w, 'BLACKLISTED - ' . $errmsg);
548 $this->server->updateNotifyToNextServer($w, $retry_when,true);
549 $this->errorHandler( $ev->remarks);
553 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") . $errmsg);
554 $w->flagDone($ev, '');
556 $this->errorHandler( $ev->remarks);
559 // at this point we just could not find any MX records..
564 $ev = $this->addEvent('NOTIFY', $w, 'GREYLIST - NO HOST CAN BE CONTACTED:' . $p->email);
566 $this->server->updateNotifyToNextServer($w, $retry_when ,true);
570 $this->errorHandler($ev->remarks);
576 $ff = HTML_FlexyFramework::get();
577 if (isset($ff->Pman_Core_NotifySend['host'])) {
578 return array($ff->Pman_Core_NotifySend['host']);
581 $mx_records = array();
582 $mx_weight = array();
584 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
585 if (!checkdnsrr($fqdn)) {
591 asort($mx_weight,SORT_NUMERIC);
593 foreach($mx_weight as $k => $weight) {
594 if (!empty($mx_records[$k])) {
595 $mxs[] = $mx_records[$k];
598 return empty($mxs) ? false : $mxs;
602 * wrapper to call object->toEmail()
606 headers : {AssocArray},
610 error : {String} // error message in log.
611 send-to: {String} // use to override rcpt
615 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
617 $m = 'notify'. $notify->evtype;
618 //var_dump(get_class($object) . '::' .$m);
619 if (!empty($notify->evtype) && method_exists($object,$m)) {
620 echo "calling :" . get_class($object) . '::' .$m . "\n";
621 return $object->$m($rcpt, $last_sent_date, $notify, $force);
624 $type = explode('::', $notify->evtype);
626 if(!empty($type[1]) && method_exists($object,$type[1])){
628 echo "calling :" . get_class($object) . '::' .$m . "\n";
629 return $object->$m($rcpt, $last_sent_date, $notify, $force);
631 // fallback if evtype is empty..
633 if (method_exists($object, 'toMailerData')) {
634 return $object->toMailerData(array(
636 'person'=>$rcpt, // added as mediaoutreach used this?
637 )); //this is core_email - i think it's only used for testing...
641 if (method_exists($object, 'toEmail')) {
642 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
644 // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
651 if (empty($this->cli_args['debug'])) {
659 $this->errorHandler("done\n");
663 function debugHandler ($smtp, $message)
665 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
666 $this->debug_str .= $message;
667 //echo $message ."\n";
670 function errorHandler($msg, $success = false)
672 if($this->error_handler == 'exception'){
674 throw new Pman_Core_NotifySend_Exception_Success($msg);
677 throw new Pman_Core_NotifySend_Exception_Fail($msg);
680 die(date('Y-m-d h:i:s') . ' ' . $msg ."\n");
685 function updateServer($w)
687 $ff = HTML_FlexyFramework::get();
689 if (empty($ff->Core_Notify['servers'])) {
692 // some classes dont support server routing
693 if (!property_exists($w, 'server_id')) {
697 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));