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';
77 $ff = HTML_FlexyFramework::get();
79 $this->errorHandler("access denied");
81 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
86 function get($id,$opts=array())
90 if (!empty($opts['DB_DataObject-debug'])) {
91 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
94 //DB_DataObject::debugLevel(1);
95 //date_default_timezone_set('UTC');
97 $force = empty($opts['force']) ? 0 : 1;
99 $w = DB_DataObject::factory($this->table);
102 $this->errorHandler("invalid id\n");
105 if (!$force && !empty($w->sent) && strtotime($w->act_when) < strtotime($w->sent)) {
107 $this->errorHandler("already sent - repeat to early\n");
109 if (!empty($opts['debug'])) {
111 $ff = HTML_FlexyFramework::get();
112 if (!isset($ff->Core_Mailer)) {
113 $ff->Core_Mailer = array();
115 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
118 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
120 if (!$force && (!empty($w->msgid) || $sent)) {
122 if (!$sent) { // fix sent.
123 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
126 $this->errorHandler("message has been sent already.\n");
133 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (underlying object does not exist)" );
134 $w->flagDone($ev, '');
135 $this->errorHandler(date('Y-m-d h:i:s ') . $ev->remarks);
142 if (isset($p->active) && empty($p->active)) {
143 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not user not active any more)" );;
144 $w->flagDone($ev, '');
145 $this->errorHandler(date('Y-m-d h:i:s ') . $ev->remarks);
147 // has it failed mutliple times..
149 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
150 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (user has to many failures)" );;
151 $w->flagDone($ev, '');
152 $this->errorHandler(date('Y-m-d h:i:s ') . $ev->remarks);
155 // let's work out the last notification sent to this user..
156 $l = DB_DataObject::factory($this->table);
159 'ontable' => $w->ontable,
162 // only newer version of the database us this..
163 if (isset($w->person_table)) {
164 $personid_col = strtolower($w->person_table).'_id';
165 if (isset($w->{$personid_col})) {
166 $lar[$personid_col] = $w->{$personid_col};
172 $l->whereAdd('id != '. $w->id);
173 $l->orderBy('sent DESC');
175 $ar = $l->fetchAll('sent');
176 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
179 $ev = DB_DataObject::factory('Events');
180 $ev->on_id = $w->id; // int(11)
181 $ev->on_table = $this->table;
183 $ev->orderBy('event_when DESC');
184 $ar = $ev->fetchAll('event_when');
185 $last_event = empty($ar) ? 0 : $ar[0];
188 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
190 $next_try = $next_try_min . ' MINUTES';
192 // this may modify $p->email. (it will not update it though)
193 $email = $this->makeEmail($o, $p, $last, $w, $force);
195 if ($email === true) {
196 $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not required any more) - toEmail=true" );;
197 $w->flagDone($ev, '');
198 $this->errorHandler(date('Y-m-d h:i:s ') . $ev->remarks);
200 if (is_a($email, 'PEAR_Error')) {
202 'error' => $email->toString()
206 if (empty($p) && !empty($email['recipients'])) {
207 // make a fake person..
209 'email' => $email['recipients']
213 if ($email === false || isset($email['error']) || empty($p)) {
214 // object returned 'false' - it does not know how to send it..
215 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ? $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
216 $w->flagDone($ev, '');
217 $this->errorHandler(date('Y-m-d h:i:s ') . $ev->remarks);
222 if (isset($email['later'])) {
224 if (false == $this->server->updateNotifyToNextServer($w, $email['later'])) {
225 // we could not find another server - we can try again.
227 $w->act_when = $email['later'];
231 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
235 if (empty($email['headers']['Message-Id'])) {
236 $HOST = gethostname();
237 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
244 //$p->email = 'alan@akbkhome.com'; //for testing..
245 //print_r($email);exit;
246 // should we fetch the watch that caused it.. - which should contain the method to call..
247 // --send-to=test@xxx.com
249 if (!empty($email['send-to'])) {
250 $p->email = $email['send-to'];
252 if (!empty($opts['send-to'])) {
253 $p->email = $opts['send-to'];
256 // since some of them have spaces?!?!
257 $p->email = trim($p->email);
259 // if to_email has not been set!?
260 if (empty($w->to_email) && $w->to_email != $p->email) {
262 $ww->to_email = $p->email;
268 require_once 'Validate.php';
269 if (!Validate::email($p->email, true)) {
270 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
271 $w->flagDone($ev, '');
272 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
277 $ff = HTML_FlexyFramework::get();
279 $explode_email = explode('@', $p->email);
280 $dom = array_pop($explode_email);
282 $mxs = $this->mxs($dom);
285 // we might fail doing this...
286 // need to handle temporary failure..
289 // we try for 2 days..
291 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
292 // older that 1 hour.
296 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
300 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
306 // only retry for 1 day if the MX issue..
308 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
309 $w->flagLater(date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')));
310 $this->errorHandler(date('Y-m-d h:i:s') . $ev->remarks);
313 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
314 $w->flagDone($ev, '');
315 $this->errorHandler(date('Y-m-d h:i:s') . $ev->remarks);
323 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
324 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
325 $w->flagDone($ev, '');
326 $this->errorHandler(date('Y-m-d h:i:s') . $ev->remarks);
330 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
331 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
332 // set act when if it's empty...
333 $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;
340 require_once 'Mail.php';
342 $core_domain = DB_DataObject::factory('core_domain');
343 if(!$core_domain->get('domain', $dom)){
344 $core_domain = DB_DataObject::factory('core_domain');
345 $core_domain->setFrom(array(
348 $core_domain->insert();
354 if (!isset($ff->Mail['helo'])) {
355 $this->errorHandler("config Mail[helo] is not set");
360 foreach($mxs as $mx) {
363 $this->debug_str = '';
364 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
365 $mailer = Mail::factory('smtp', array(
367 'localhost' => $ff->Mail['helo'],
369 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
370 //'debug' => isset($opts['debug']) ? 1 : 0,
372 'debug_handler' => array($this, 'debugHandler')
375 // if the host is the mail host + it's authenticated add auth details
376 // this normally will happen if you sent Pman_Core_NotifySend['host']
379 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
381 $mailer->auth = true;
382 $mailer->username = $ff->Mail['username'];
383 $mailer->password = $ff->Mail['password'];
386 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
388 // we might want to regex 'office365 as a mx host
389 foreach ($ff->Core_Notify['routes'] as $server => $settings){
390 if(!in_array($dom, $settings['domains'])){
394 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
395 // if it's newer that '1' minute...
398 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
400 $seconds = floor((60 * 60) / $settings['rate']);
402 $core_notify = DB_DataObject::factory($this->table);
403 $core_notify->domain_id = $core_domain->id;
404 $core_notify->whereAdd("
405 sent >= NOW() - INTERVAL $seconds SECOND
408 if($core_notify->count()){
410 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
411 $this->updateServer($w);
413 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
418 $mailer->host = $server;
419 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
420 $mailer->username = $settings['username'];
421 $mailer->password = $settings['password'];
422 if (isset($settings['port'])) {
423 $mailer->port = $settings['port'];
425 if (isset($settings['socket_options'])) {
426 $mailer->socket_options = $settings['socket_options'];
437 $res = $mailer->send($p->email, $email['headers'], $email['body']);
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 if(strtotime($w->act_when) > strtotime("NOW")){
450 $w->act_when = date('Y-m-d H:i:s');
453 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
454 $w->msgid = $email['headers']['Message-Id'];
455 $w->event_id = $ev->id; // sent ok.. - no need to record it..
456 $w->domain_id = $core_domain->id;
459 // enable cc in notify..
460 if (!empty($email['headers']['Cc'])) {
461 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
462 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
463 $cmailer->send($email['headers']['Cc'],
464 $email['headers'], $email['body']);
468 if (!empty($email['bcc'])) {
469 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
470 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
471 $res = $cmailer->send($email['bcc'],
472 $email['headers'], $email['body']);
473 if (!$res || is_a($res, 'PEAR_Error')) {
474 echo "could not send bcc..\n";
476 echo "Sent BCC to {$email['bcc']}\n";
481 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
483 // what type of error..
484 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
485 if (!empty($res->code) && $res->code == 10001) {
486 // fake greylist if timed out.
491 $this->debug($res->message);
492 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
494 // give up after 2 days..
495 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
497 // check last event for this item..
498 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
499 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
500 if (!empty($res->userinfo['smtptext'])) {
501 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
504 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
505 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
506 $this->updateServer($w);
507 $w->domain_id = $core_domain->id;
511 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
516 if ($fail || $next_try_min > (2*24*60)) {
517 // fail.. = log and give up..
518 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
519 if (isset($res->userinfo['smtptext'])) {
520 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
523 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
525 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
527 $w->event_id = $ev->id;
528 $w->domain_id = $core_domain->id;
530 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
533 // handle no host availalbe forever...
534 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
535 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
536 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
538 $w->event_id = $ev->id;
539 $w->domain_id = $core_domain->id;
541 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
545 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
546 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
548 $this->updateServer($w);
550 $w->domain_id = $core_domain->id;
552 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
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);
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']));
685 $ff = HTML_FlexyFramework::get();
687 if (isset($ff->Core_Notify['servers-non-pool']) &&
688 isset($ff->Core_Notify['servers-non-pool'][gethostname()]) &&
689 isset($ff->Core_Notify['servers-non-pool'][gethostname()]['helo']) ) {
690 $ff->Mail['helo'] = $ff->Core_Notify['servers-non-pool'][gethostname()]['helo'];
694 if (empty($ff->Core_Notify['servers'])) {
697 if (!isset($ff->Core_Notify['servers'][gethostname()]) || !isset($ff->Core_Notify['servers'][gethostname()]['helo']) ) {
698 $this->jerr("Core_Notify['servers']['" . gethostname() . "']['helo'] not set");
700 $ff->Mail['helo'] = $ff->Core_Notify['servers'][gethostname()]['helo'];