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)) {
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,
134 "Notification event cleared (underlying object does not exist)" );;
136 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
138 $w->event_id = $ev->id;
140 $this->errorHandler(date('Y-m-d h:i:s ') .
141 "Notification event cleared (underlying object does not exist)"
149 if (isset($p->active) && empty($p->active)) {
150 $ev = $this->addEvent('NOTIFY', $w,
151 "Notification event cleared (not user not active any more)" );;
153 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
155 $w->event_id = $ev->id;
157 $this->errorHandler(date('Y-m-d h:i:s ') .
158 "Notification event cleared (not user not active any more)"
160 $this->errorHandler("message has been sent already.\n");
162 // has it failed mutliple times..
164 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
165 $ev = $this->addEvent('NOTIFY', $w,
166 "Notification event cleared (user has to many failures)" );;
168 $w->sent = $w->sqlValue('NOW()'); // do not update if sent.....
170 $w->event_id = $ev->id;
172 $this->errorHandler(date('Y-m-d h:i:s ') .
173 "Notification event cleared (user has to many failures)"
175 $this->errorHandler("user has to many failures.\n");
178 // let's work out the last notification sent to this user..
179 $l = DB_DataObject::factory($this->table);
182 'ontable' => $w->ontable,
185 // only newer version of the database us this..
186 if (isset($w->person_table)) {
187 $personid_col = strtolower($w->person_table).'_id';
188 if (isset($w->{$personid_col})) {
189 $lar[$personid_col] = $w->{$personid_col};
195 $l->whereAdd('id != '. $w->id);
196 $l->orderBy('sent DESC');
198 $ar = $l->fetchAll('sent');
199 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
202 $ev = DB_DataObject::factory('Events');
203 $ev->on_id = $w->id; // int(11)
204 $ev->on_table = $this->table;
206 $ev->orderBy('event_when DESC');
207 $ar = $ev->fetchAll('event_when');
208 $last_event = empty($ar) ? 0 : $ar[0];
211 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
213 $next_try = $next_try_min . ' MINUTES';
215 // this may modify $p->email. (it will not update it though)
216 $email = $this->makeEmail($o, $p, $last, $w, $force);
218 if ($email === true) {
220 $ev = $this->addEvent('NOTIFY', $w,
221 "Notification event cleared (not required any more)" );;
223 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
225 $w->event_id = $ev->id;
227 $this->errorHandler(date('Y-m-d h:i:s ') .
228 "Notification event cleared (not required any more)"
231 if (is_a($email, 'PEAR_Error')) {
233 'error' => $email->toString()
237 if (empty($p) && !empty($email['recipients'])) {
238 // make a fake person..
240 'email' => $email['recipients']
244 if ($email === false || isset($email['error']) || empty($p)) {
245 // object returned 'false' - it does not know how to send it..
246 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ?
247 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
249 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
251 $w->event_id = $ev->id;
252 $w->to_email = $p->email;
254 $this->errorHandler(date('Y-m-d h:i:s ') .
255 (isset($email['error']) ?
256 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
261 if (isset($email['later'])) {
263 $w->act_when = $email['later'];
264 $this->updateServer($w);
266 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
270 if (empty($email['headers']['Message-Id'])) {
271 $HOST = gethostname();
272 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
279 //$p->email = 'alan@akbkhome.com'; //for testing..
280 //print_r($email);exit;
281 // should we fetch the watch that caused it.. - which should contain the method to call..
282 // --send-to=test@xxx.com
284 if (!empty($email['send-to'])) {
285 $p->email = $email['send-to'];
287 if (!empty($opts['send-to'])) {
288 $p->email = $opts['send-to'];
291 // since some of them have spaces?!?!
292 $p->email = trim($p->email);
295 require_once 'Validate.php';
296 if (!Validate::email($p->email, true)) {
297 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
299 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
301 $w->event_id = $ev->id;
302 $w->to_email = $p->email;
304 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
309 $ff = HTML_FlexyFramework::get();
311 $explode_email = explode('@', $p->email);
312 $dom = array_pop($explode_email);
314 $mxs = $this->mxs($dom);
317 // we might fail doing this...
318 // need to handle temporary failure..
321 // we try for 2 days..
323 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
324 // older that 1 hour.
328 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
332 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
338 // only retry for 1 day if the MX issue..
340 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
341 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
342 $this->updateServer($w);
344 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED {$dom}\n");
347 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
348 $w->sent = $w->sqlValue('NOW()'); // why not updated - used to leave as is?
350 $w->event_id = $ev->id;
351 $w->to_email = $p->email;
353 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD DOMAIN - {$p->email} \n");
361 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
362 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
363 $w->sent = $w->sqlValue('NOW()');
365 $w->event_id = $ev->id;
366 $w->to_email = $p->email;
368 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
373 $w->to_email = $p->email;
374 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
375 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
376 // set act when if it's empty...
377 $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;
384 require_once 'Mail.php';
386 $core_domain = DB_DataObject::factory('core_domain');
387 if(!$core_domain->get('domain', $dom)){
388 $core_domain = DB_DataObject::factory('core_domain');
389 $core_domain->setFrom(array(
392 $core_domain->insert();
398 if (!isset($ff->Mail['helo'])) {
399 $this->errorHandler("config Mail[helo] is not set");
404 foreach($mxs as $mx) {
407 $this->debug_str = '';
408 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
409 $mailer = Mail::factory('smtp', array(
411 'localhost' => $ff->Mail['helo'],
413 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
414 //'debug' => isset($opts['debug']) ? 1 : 0,
416 'debug_handler' => array($this, 'debugHandler')
419 // if the host is the mail host + it's authenticated add auth details
420 // this normally will happen if you sent Pman_Core_NotifySend['host']
423 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
425 $mailer->auth = true;
426 $mailer->username = $ff->Mail['username'];
427 $mailer->password = $ff->Mail['password'];
430 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
432 // we might want to regex 'office365 as a mx host
433 foreach ($ff->Core_Notify['routes'] as $server => $settings){
434 if(!in_array($dom, $settings['domains'])){
438 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
439 // if it's newer that '1' minute...
442 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
444 $seconds = floor((60 * 60) / $settings['rate']);
446 $core_notify = DB_DataObject::factory($this->table);
447 $core_notify->domain_id = $core_domain->id;
448 $core_notify->whereAdd("
449 sent >= NOW() - INTERVAL $seconds SECOND
452 if($core_notify->count()){
454 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
455 $this->updateServer($w);
457 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
462 $mailer->host = $server;
463 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
464 $mailer->username = $settings['username'];
465 $mailer->password = $settings['password'];
466 if (isset($settings['port'])) {
467 $mailer->port = $settings['port'];
469 if (isset($settings['socket_options'])) {
470 $mailer->socket_options = $settings['socket_options'];
481 $res = $mailer->send($p->email, $email['headers'], $email['body']);
487 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
489 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
491 $ev->writeEventLog($this->debug_str);
493 if(strtotime($w->act_when) > strtotime("NOW")){
494 $w->act_when = date('Y-m-d H:i:s');
497 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
498 $w->msgid = $email['headers']['Message-Id'];
499 $w->event_id = $ev->id; // sent ok.. - no need to record it..
500 $w->domain_id = $core_domain->id;
503 // enable cc in notify..
504 if (!empty($email['headers']['Cc'])) {
505 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
506 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
507 $cmailer->send($email['headers']['Cc'],
508 $email['headers'], $email['body']);
512 if (!empty($email['bcc'])) {
513 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
514 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
515 $res = $cmailer->send($email['bcc'],
516 $email['headers'], $email['body']);
517 if (!$res || is_a($res, 'PEAR_Error')) {
518 echo "could not send bcc..\n";
520 echo "Sent BCC to {$email['bcc']}\n";
525 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
527 // what type of error..
528 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
529 if (!empty($res->code) && $res->code == 10001) {
530 // fake greylist if timed out.
535 $this->debug($res->message);
536 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
538 // give up after 2 days..
539 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
541 // check last event for this item..
542 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
543 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
544 if (!empty($res->userinfo['smtptext'])) {
545 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
548 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
549 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
550 $this->updateServer($w);
551 $w->domain_id = $core_domain->id;
555 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
560 if ($fail || $next_try_min > (2*24*60)) {
561 // fail.. = log and give up..
562 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
563 if (isset($res->userinfo['smtptext'])) {
564 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
567 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
569 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
571 $w->event_id = $ev->id;
572 $w->domain_id = $core_domain->id;
574 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
577 // handle no host availalbe forever...
578 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
579 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
580 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
582 $w->event_id = $ev->id;
583 $w->domain_id = $core_domain->id;
585 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
589 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
590 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
592 $this->updateServer($w);
594 $w->domain_id = $core_domain->id;
596 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
602 $ff = HTML_FlexyFramework::get();
603 if (isset($ff->Pman_Core_NotifySend['host'])) {
604 return array($ff->Pman_Core_NotifySend['host']);
607 $mx_records = array();
608 $mx_weight = array();
610 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
611 if (!checkdnsrr($fqdn)) {
617 asort($mx_weight,SORT_NUMERIC);
619 foreach($mx_weight as $k => $weight) {
620 if (!empty($mx_records[$k])) {
621 $mxs[] = $mx_records[$k];
624 return empty($mxs) ? false : $mxs;
628 * wrapper to call object->toEmail()
632 headers : {AssocArray},
636 error : {String} // error message in log.
637 send-to: {String} // use to override rcpt
641 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
643 $m = 'notify'. $notify->evtype;
644 //var_dump(get_class($object) . '::' .$m);
645 if (!empty($notify->evtype) && method_exists($object,$m)) {
646 echo "calling :" . get_class($object) . '::' .$m . "\n";
647 return $object->$m($rcpt, $last_sent_date, $notify, $force);
650 $type = explode('::', $notify->evtype);
652 if(!empty($type[1]) && method_exists($object,$type[1])){
654 echo "calling :" . get_class($object) . '::' .$m . "\n";
655 return $object->$m($rcpt, $last_sent_date, $notify, $force);
658 if (method_exists($object, 'toMailerData')) {
659 return $object->toMailerData(array(
661 'person'=>$rcpt, // added as mediaoutreach used this?
662 )); //this is core_email - i think it's only used for testing...
667 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
672 if (empty($this->cli_args['debug'])) {
680 $this->errorHandler("done\n");
684 function debugHandler ($smtp, $message)
686 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
687 $this->debug_str .= $message;
688 //echo $message ."\n";
691 function errorHandler($msg, $success = false)
693 if($this->error_handler == 'exception'){
695 throw new Pman_Core_NotifySend_Exception_Success($msg);
698 throw new Pman_Core_NotifySend_Exception_Fail($msg);
706 function updateServer($w)
708 $ff = HTML_FlexyFramework::get();
710 if (empty($ff->Core_Notify['servers'])) {
714 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));
720 $ff = HTML_FlexyFramework::get();
721 if (empty($ff->Core_Notify['servers'])) {
724 if (!isset($ff->Core_Notify['servers'][gethostname()]) || !isset($ff->Core_Notify['servers'][gethostname()]['helo']) ) {
725 $this->jerr("Core_Notify['servers']['" . gethostname() . "']['helo'] not set");
727 $ff->Mail['helo'] = $ff->Core_Notify['servers'][gethostname()]['helo'];