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) || preg_match('/^1000/', $w->sent)) ? false : true;
129 if (!$force && (!empty($w->msgid) || $sent)) {
131 if (!$sent) { // fix sent.
132 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
135 $this->errorHandler("message has been sent already.\n");
142 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (underlying object does not exist)" );
143 $w->flagDone($ev, '');
144 $this->errorHandler( $ev->remarks);
151 if (isset($p->active) && empty($p->active)) {
152 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not user not active any more)" );;
153 $w->flagDone($ev, '');
154 $this->errorHandler( $ev->remarks);
156 // has it failed mutliple times..
158 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
159 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (user has to many failures)" );;
160 $w->flagDone($ev, '');
161 $this->errorHandler( $ev->remarks);
164 // let's work out the last notification sent to this user..
165 $l = DB_DataObject::factory($this->table);
168 'ontable' => $w->ontable,
171 // only newer version of the database us this..
172 if (isset($w->person_table)) {
173 $personid_col = strtolower($w->person_table).'_id';
174 if (isset($w->{$personid_col})) {
175 $lar[$personid_col] = $w->{$personid_col};
181 $l->whereAdd('id != '. $w->id);
182 $l->orderBy('sent DESC');
184 $ar = $l->fetchAll('sent');
185 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
188 $ev = DB_DataObject::factory('Events');
189 $ev->on_id = $w->id; // int(11)
190 $ev->on_table = $this->table;
192 $ev->orderBy('event_when DESC');
193 $ar = $ev->fetchAll('event_when');
194 $last_event = empty($ar) ? 0 : $ar[0];
197 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
199 $next_try = $next_try_min . ' MINUTES';
201 // this may modify $p->email. (it will not update it though)
202 $email = $this->makeEmail($o, $p, $last, $w, $force);
204 if ($email === true) {
205 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not required any more) - toEmail=true" );;
206 $w->flagDone($ev, '');
207 $this->errorHandler( $ev->remarks);
209 if (is_a($email, 'PEAR_Error')) {
211 'error' => $email->toString()
215 if (empty($p) && !empty($email['recipients'])) {
216 // make a fake person..
218 'email' => $email['recipients']
222 if ($email === false || isset($email['error']) || empty($p)) {
223 // object returned 'false' - it does not know how to send it..
224 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ? $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
225 $w->flagDone($ev, '');
226 $this->errorHandler( $ev->remarks);
231 if (isset($email['later'])) {
233 $this->server->updateNotifyToNextServer($w, $email['later'],true);
235 $this->errorHandler("Delivery postponed by email creator to {$email['later']}");
239 if (empty($email['headers']['Message-Id'])) {
240 $HOST = gethostname();
241 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
248 //$p->email = 'alan@akbkhome.com'; //for testing..
249 //print_r($email);exit;
250 // should we fetch the watch that caused it.. - which should contain the method to call..
251 // --send-to=test@xxx.com
253 if (!empty($email['send-to'])) {
254 $p->email = $email['send-to'];
256 if (!empty($opts['send-to'])) {
257 $p->email = $opts['send-to'];
260 // since some of them have spaces?!?!
261 $p->email = trim($p->email);
263 $ww->to_email = empty($ww->to_email) ? $p->email : $ww->to_email;
264 $explode_email = explode('@', $ww->to_email);
265 $dom = array_pop($explode_email);
267 $core_domain = DB_DataObject::factory('core_domain')->loadOrCreate($dom);
270 $ww->domain_id = $core_domain->id;
271 // if to_email has not been set!?
272 $ww->update($w); // if nothing has changed this will not do anything.
277 require_once 'Validate.php';
278 if (!Validate::email($p->email, true)) {
279 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
280 $w->flagDone($ev, '');
281 $this->errorHandler($ev->remarks);
286 $ff = HTML_FlexyFramework::get();
289 $mxs = $this->mxs($dom);
292 // we might fail doing this...
293 // need to handle temporary failure..
296 // we try for 2 days..
298 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
299 // older that 1 hour.
303 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
307 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
313 // only retry for 1 day if the MX issue..
315 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
316 $w->flagLater(date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')));
317 $this->errorHandler($ev->remarks);
320 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
321 $w->flagDone($ev, '');
322 $this->errorHandler($ev->remarks);
330 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
331 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
332 $w->flagDone($ev, '');
333 $this->errorHandler( $ev->remarks);
336 $retry_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
338 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
339 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
340 // set act when if it's empty...
341 $w->act_when = (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? $retry_when : $w->act_when;
348 require_once 'Mail.php';
351 $this->server->initHelo();
353 if (!isset($ff->Mail['helo'])) {
354 $this->errorHandler("config Mail[helo] is not set");
359 foreach($mxs as $mx) {
362 $this->debug_str = '';
363 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
364 $mailer = Mail::factory('smtp', array(
366 'localhost' => $ff->Mail['helo'],
368 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
369 //'debug' => isset($opts['debug']) ? 1 : 0,
371 'debug_handler' => array($this, 'debugHandler')
374 // if the host is the mail host + it's authenticated add auth details
375 // this normally will happen if you sent Pman_Core_NotifySend['host']
378 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
380 $mailer->auth = true;
381 $mailer->username = $ff->Mail['username'];
382 $mailer->password = $ff->Mail['password'];
385 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
387 // we might want to regex 'office365 as a mx host
388 foreach ($ff->Core_Notify['routes'] as $server => $settings){
389 if(!in_array($dom, $settings['domains'])){
393 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
394 // if it's newer that '1' minute...
397 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
399 $seconds = floor((60 * 60) / $settings['rate']);
401 $core_notify = DB_DataObject::factory($this->table);
402 $core_notify->domain_id = $core_domain->id;
403 $core_notify->server_id = $this->server->id;
404 $core_notify->whereAdd("
405 sent >= NOW() - INTERVAL $seconds SECOND
408 if($core_notify->count()){
409 $this->server->updateNotifyToNextServer( $w , date("Y-m-d H:i:s", time() + $seconds), true);
410 $this->errorHandler( " Too many emails sent by {$dom} - requeing");
415 $mailer->host = $server;
416 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
417 $mailer->username = $settings['username'];
418 $mailer->password = $settings['password'];
419 if (isset($settings['port'])) {
420 $mailer->port = $settings['port'];
422 if (isset($settings['socket_options'])) {
423 $mailer->socket_options = $settings['socket_options'];
434 $res = $mailer->send($p->email, $email['headers'], $email['body']);
435 if (is_object($res)) {
436 $res->backtrace = array();
438 $this->debug("GOT response to send: ". print_r($res,true));
443 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
445 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
447 $ev->writeEventLog($this->debug_str);
449 $w->flagDone($ev, $email['headers']['Message-Id']);
452 // enable cc in notify..
453 if (!empty($email['headers']['Cc'])) {
454 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
455 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
456 $cmailer->send($email['headers']['Cc'], $email['headers'], $email['body']);
460 if (!empty($email['bcc'])) {
461 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
462 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
463 $res = $cmailer->send($email['bcc'], $email['headers'], $email['body']);
464 if (!$res || is_a($res, 'PEAR_Error')) {
465 echo "could not send bcc..\n";
467 echo "Sent BCC to {$email['bcc']}\n";
471 $this->errorHandler( " SENT {$w->id} - {$ev->remarks}", true);
473 // what type of error..
474 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
475 if (!empty($res->code) && $res->code == 10001) {
476 // fake greylist if timed out.
481 $this->debug($res->message);
482 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
484 // give up after 2 days..
485 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
487 // check last event for this item..
488 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
489 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
490 if (!empty($res->userinfo['smtptext'])) {
491 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
494 $ev = $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
496 $this->server->updateNotifyToNextServer($w, $retry_when,true);
498 $this->errorHandler( $ev->remarks);
505 // after trying all mxs - could not connect...
506 if (!$fail && ($next_try_min > (2*24*60) || strtotime($w->act_start) < strtotime('NOW - 3 DAYS'))) {
508 $errmsg= " - UNKNOWN ERROR";
509 if (isset($res->userinfo['smtptext'])) {
510 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
513 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - " . $errmsg);
514 $w->flagDone($ev, '');
515 $this->errorHandler( $ev->remarks);
518 if ($fail) { //// !!!!<<< BLACKLIST DETECT?
519 // fail.. = log and give up..
520 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->toString();
521 if (isset($res->userinfo['smtptext'])) {
522 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
525 if ($res->userinfo['smtpcode'] == 550) {
526 if ($this->server->checkSmtpResponse($errmsg, $core_domain)) {
527 $ev = $this->addEvent('NOTIFY', $w, 'BLACKLISTED - ' . $errmsg);
528 $this->server->updateNotifyToNextServer($w, $retry_when,true);
529 $this->errorHandler( $ev->remarks);
533 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") . $errmsg);
534 $w->flagDone($ev, '');
536 $this->errorHandler( $ev->remarks);
539 // at this point we just could not find any MX records..
544 $ev = $this->addEvent('NOTIFY', $w, 'GREYLIST - NO HOST CAN BE CONTACTED:' . $p->email);
546 $this->server->updateNotifyToNextServer($w, $retry_when ,true);
550 $this->errorHandler($ev->remarks);
556 $ff = HTML_FlexyFramework::get();
557 if (isset($ff->Pman_Core_NotifySend['host'])) {
558 return array($ff->Pman_Core_NotifySend['host']);
561 $mx_records = array();
562 $mx_weight = array();
564 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
565 if (!checkdnsrr($fqdn)) {
571 asort($mx_weight,SORT_NUMERIC);
573 foreach($mx_weight as $k => $weight) {
574 if (!empty($mx_records[$k])) {
575 $mxs[] = $mx_records[$k];
578 return empty($mxs) ? false : $mxs;
582 * wrapper to call object->toEmail()
586 headers : {AssocArray},
590 error : {String} // error message in log.
591 send-to: {String} // use to override rcpt
595 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
597 $m = 'notify'. $notify->evtype;
598 //var_dump(get_class($object) . '::' .$m);
599 if (!empty($notify->evtype) && method_exists($object,$m)) {
600 echo "calling :" . get_class($object) . '::' .$m . "\n";
601 return $object->$m($rcpt, $last_sent_date, $notify, $force);
604 $type = explode('::', $notify->evtype);
606 if(!empty($type[1]) && method_exists($object,$type[1])){
608 echo "calling :" . get_class($object) . '::' .$m . "\n";
609 return $object->$m($rcpt, $last_sent_date, $notify, $force);
611 // fallback if evtype is empty..
613 if (method_exists($object, 'toMailerData')) {
614 return $object->toMailerData(array(
616 'person'=>$rcpt, // added as mediaoutreach used this?
617 )); //this is core_email - i think it's only used for testing...
621 if (method_exists($object, 'toEmail')) {
622 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
624 // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
631 if (empty($this->cli_args['debug'])) {
639 $this->errorHandler("done\n");
643 function debugHandler ($smtp, $message)
645 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
646 $this->debug_str .= $message;
647 //echo $message ."\n";
650 function errorHandler($msg, $success = false)
652 if($this->error_handler == 'exception'){
654 throw new Pman_Core_NotifySend_Exception_Success($msg);
657 throw new Pman_Core_NotifySend_Exception_Fail($msg);
660 die(date('Y-m-d h:i:s') . ' ' . $msg ."\n");
665 function updateServer($w)
667 $ff = HTML_FlexyFramework::get();
669 if (empty($ff->Core_Notify['servers'])) {
672 // some classes dont support server routing
673 if (!property_exists($w, 'server_id')) {
677 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));