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);
113 if (!$force && $w->server_id != $this->server->id) {
114 $this->errorHandler("Server id does not match - use force to try again\n");
117 if (!empty($opts['debug'])) {
119 $ff = HTML_FlexyFramework::get();
120 if (!isset($ff->Core_Mailer)) {
121 $ff->Core_Mailer = array();
123 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
126 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
128 if (!$force && (!empty($w->msgid) || $sent)) {
130 if (!$sent) { // fix sent.
131 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
134 $this->errorHandler("message has been sent already.\n");
141 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (underlying object does not exist)" );
142 $w->flagDone($ev, '');
143 $this->errorHandler( $ev->remarks);
150 if (isset($p->active) && empty($p->active)) {
151 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not user not active any more)" );;
152 $w->flagDone($ev, '');
153 $this->errorHandler( $ev->remarks);
155 // has it failed mutliple times..
157 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
158 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (user has to many failures)" );;
159 $w->flagDone($ev, '');
160 $this->errorHandler( $ev->remarks);
163 // let's work out the last notification sent to this user..
164 $l = DB_DataObject::factory($this->table);
167 'ontable' => $w->ontable,
170 // only newer version of the database us this..
171 if (isset($w->person_table)) {
172 $personid_col = strtolower($w->person_table).'_id';
173 if (isset($w->{$personid_col})) {
174 $lar[$personid_col] = $w->{$personid_col};
180 $l->whereAdd('id != '. $w->id);
181 $l->orderBy('sent DESC');
183 $ar = $l->fetchAll('sent');
184 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
187 $ev = DB_DataObject::factory('Events');
188 $ev->on_id = $w->id; // int(11)
189 $ev->on_table = $this->table;
191 $ev->orderBy('event_when DESC');
192 $ar = $ev->fetchAll('event_when');
193 $last_event = empty($ar) ? 0 : $ar[0];
196 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
198 $next_try = $next_try_min . ' MINUTES';
200 // this may modify $p->email. (it will not update it though)
201 $email = $this->makeEmail($o, $p, $last, $w, $force);
203 if ($email === true) {
204 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not required any more) - toEmail=true" );;
205 $w->flagDone($ev, '');
206 $this->errorHandler( $ev->remarks);
208 if (is_a($email, 'PEAR_Error')) {
210 'error' => $email->toString()
214 if (empty($p) && !empty($email['recipients'])) {
215 // make a fake person..
217 'email' => $email['recipients']
221 if ($email === false || isset($email['error']) || empty($p)) {
222 // object returned 'false' - it does not know how to send it..
223 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ? $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
224 $w->flagDone($ev, '');
225 $this->errorHandler( $ev->remarks);
230 if (isset($email['later'])) {
232 $this->server->updateNotifyToNextServer($w, $email['later'],true);
234 $this->errorHandler("Delivery postponed by email creator to {$email['later']}");
238 if (empty($email['headers']['Message-Id'])) {
239 $HOST = gethostname();
240 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
247 //$p->email = 'alan@akbkhome.com'; //for testing..
248 //print_r($email);exit;
249 // should we fetch the watch that caused it.. - which should contain the method to call..
250 // --send-to=test@xxx.com
252 if (!empty($email['send-to'])) {
253 $p->email = $email['send-to'];
255 if (!empty($opts['send-to'])) {
256 $p->email = $opts['send-to'];
259 // since some of them have spaces?!?!
260 $p->email = trim($p->email);
262 $ww->to_email = empty($ww->to_email) ? $p->email : $ww->to_email;
263 $explode_email = explode('@', $ww->to_email);
264 $dom = array_pop($explode_email);
266 $core_domain = DB_DataObject::factory('core_domain')->loadOrCreate($dom);
269 $ww->domain_id = $core_domain->id;
270 // if to_email has not been set!?
271 $ww->update($w); // if nothing has changed this will not do anything.
276 require_once 'Validate.php';
277 if (!Validate::email($p->email, true)) {
278 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
279 $w->flagDone($ev, '');
280 $this->errorHandler($ev->remarks);
285 $ff = HTML_FlexyFramework::get();
288 $mxs = $this->mxs($dom);
291 // we might fail doing this...
292 // need to handle temporary failure..
295 // we try for 2 days..
297 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
298 // older that 1 hour.
302 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
306 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
312 // only retry for 1 day if the MX issue..
314 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
315 $w->flagLater(date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')));
316 $this->errorHandler($ev->remarks);
319 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
320 $w->flagDone($ev, '');
321 $this->errorHandler($ev->remarks);
329 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
330 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
331 $w->flagDone($ev, '');
332 $this->errorHandler( $ev->remarks);
336 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
337 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
338 // set act when if it's empty...
339 $w->act_when = (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')) : $w->act_when;
346 require_once 'Mail.php';
349 $this->server->initHelo();
351 if (!isset($ff->Mail['helo'])) {
352 $this->errorHandler("config Mail[helo] is not set");
357 foreach($mxs as $mx) {
360 $this->debug_str = '';
361 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
362 $mailer = Mail::factory('smtp', array(
364 'localhost' => $ff->Mail['helo'],
366 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
367 //'debug' => isset($opts['debug']) ? 1 : 0,
369 'debug_handler' => array($this, 'debugHandler')
372 // if the host is the mail host + it's authenticated add auth details
373 // this normally will happen if you sent Pman_Core_NotifySend['host']
376 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
378 $mailer->auth = true;
379 $mailer->username = $ff->Mail['username'];
380 $mailer->password = $ff->Mail['password'];
383 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
385 // we might want to regex 'office365 as a mx host
386 foreach ($ff->Core_Notify['routes'] as $server => $settings){
387 if(!in_array($dom, $settings['domains'])){
391 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
392 // if it's newer that '1' minute...
395 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
397 $seconds = floor((60 * 60) / $settings['rate']);
399 $core_notify = DB_DataObject::factory($this->table);
400 $core_notify->domain_id = $core_domain->id;
401 $core_notify->server_id = $this->server->id;
402 $core_notify->whereAdd("
403 sent >= NOW() - INTERVAL $seconds SECOND
406 if($core_notify->count()){
407 $this->server->updateNotifyToNextServer( $w , date("Y-m-d H:i:s", time() + $seconds), true);
408 $this->errorHandler( " Too many emails sent by {$dom} - requeing");
413 $mailer->host = $server;
414 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
415 $mailer->username = $settings['username'];
416 $mailer->password = $settings['password'];
417 if (isset($settings['port'])) {
418 $mailer->port = $settings['port'];
420 if (isset($settings['socket_options'])) {
421 $mailer->socket_options = $settings['socket_options'];
432 $res = $mailer->send($p->email, $email['headers'], $email['body']);
433 if (is_object($res)) {
434 $res->backtrace = array();
436 $this->debug("GOT response to send: ". print_r($res,true));
441 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
443 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
445 $ev->writeEventLog($this->debug_str);
447 $w->flagDone($ev,$email['headers']['Message-Id']);
450 // enable cc in notify..
451 if (!empty($email['headers']['Cc'])) {
452 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
453 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
454 $cmailer->send($email['headers']['Cc'], $email['headers'], $email['body']);
458 if (!empty($email['bcc'])) {
459 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
460 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
461 $res = $cmailer->send($email['bcc'], $email['headers'], $email['body']);
462 if (!$res || is_a($res, 'PEAR_Error')) {
463 echo "could not send bcc..\n";
465 echo "Sent BCC to {$email['bcc']}\n";
469 $this->errorHandler( " SENT {$w->id} - {$ev->remarks}", true);
471 // what type of error..
472 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
473 if (!empty($res->code) && $res->code == 10001) {
474 // fake greylist if timed out.
479 $this->debug($res->message);
480 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
482 // give up after 2 days..
483 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
485 // check last event for this item..
486 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
487 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
488 if (!empty($res->userinfo['smtptext'])) {
489 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
492 $ev = $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
494 $this->server->updateNotifyToNextServer($w, strtotime('NOW + ' . $retry . ' MINUTES'),true);
496 $this->errorHandler( $ev->remarks);
503 // after trying all mxs - could not connect...
504 if (!$fail && ($next_try_min > (2*24*60) || strtotime($w->act_start) < strtotime('NOW - 3 DAYS'))) {
506 $errmsg= " - UNKNOWN ERROR";
507 if (isset($res->userinfo['smtptext'])) {
508 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
511 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - " . $errmsg);
512 $w->flagDone($ev, '');
513 $this->errorHandler( $ev->remarks);
516 if ($fail) { //// !!!!<<< BLACKLIST DETECT?
517 // fail.. = log and give up..
518 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->toString();
519 if (isset($res->userinfo['smtptext'])) {
520 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
523 if ($res->userinfo['smtpcode'] == 550) {
524 if ($this->server->checkSmtpResponse($errmsg, $core_domain)) {
525 $ev = $this->addEvent('NOTIFY', $w, 'BLACKLISTED - ' . $errmsg);
526 $this->server->updateNotifyToNextServer($w, strtotime('NOW + ' . $retry . ' MINUTES'),true);
527 $this->errorHandler( $ev->remarks);
532 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") . $errmsg);
533 $w->flagDone($ev, '');
538 $this->errorHandler( $ev->remarks);
541 // at this point we just could not find any MX records..
546 $ev = $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
548 $this->server->updateNotifyToNextServer($w, strtotime('NOW + ' . $retry . ' MINUTES'),true);
552 $this->errorHandler($ev->remarks);
558 $ff = HTML_FlexyFramework::get();
559 if (isset($ff->Pman_Core_NotifySend['host'])) {
560 return array($ff->Pman_Core_NotifySend['host']);
563 $mx_records = array();
564 $mx_weight = array();
566 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
567 if (!checkdnsrr($fqdn)) {
573 asort($mx_weight,SORT_NUMERIC);
575 foreach($mx_weight as $k => $weight) {
576 if (!empty($mx_records[$k])) {
577 $mxs[] = $mx_records[$k];
580 return empty($mxs) ? false : $mxs;
584 * wrapper to call object->toEmail()
588 headers : {AssocArray},
592 error : {String} // error message in log.
593 send-to: {String} // use to override rcpt
597 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
599 $m = 'notify'. $notify->evtype;
600 //var_dump(get_class($object) . '::' .$m);
601 if (!empty($notify->evtype) && method_exists($object,$m)) {
602 echo "calling :" . get_class($object) . '::' .$m . "\n";
603 return $object->$m($rcpt, $last_sent_date, $notify, $force);
606 $type = explode('::', $notify->evtype);
608 if(!empty($type[1]) && method_exists($object,$type[1])){
610 echo "calling :" . get_class($object) . '::' .$m . "\n";
611 return $object->$m($rcpt, $last_sent_date, $notify, $force);
613 // fallback if evtype is empty..
615 if (method_exists($object, 'toMailerData')) {
616 return $object->toMailerData(array(
618 'person'=>$rcpt, // added as mediaoutreach used this?
619 )); //this is core_email - i think it's only used for testing...
623 if (method_exists($object, 'toEmail')) {
624 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
626 // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
633 if (empty($this->cli_args['debug'])) {
641 $this->errorHandler("done\n");
645 function debugHandler ($smtp, $message)
647 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
648 $this->debug_str .= $message;
649 //echo $message ."\n";
652 function errorHandler($msg, $success = false)
654 if($this->error_handler == 'exception'){
656 throw new Pman_Core_NotifySend_Exception_Success($msg);
659 throw new Pman_Core_NotifySend_Exception_Fail($msg);
662 die(date('Y-m-d h:i:s') . ' ' . $msg ."\n");
667 function updateServer($w)
669 $ff = HTML_FlexyFramework::get();
671 if (empty($ff->Core_Notify['servers'])) {
674 // some classes dont support server routing
675 if (!property_exists($w, 'server_id')) {
679 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));