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)) {
108 $this->errorHandler("send repeat to early\n");
110 if (!empty($opts['debug'])) {
112 $ff = HTML_FlexyFramework::get();
113 if (!isset($ff->Core_Mailer)) {
114 $ff->Core_Mailer = array();
116 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
119 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
121 if (!$force && (!empty($w->msgid) || $sent)) {
124 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
127 $this->errorHandler("message has been sent already.\n");
134 $ev = $this->addEvent('NOTIFY', $w,
135 "Notification event cleared (underlying object does not exist)" );;
137 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
139 $w->event_id = $ev->id;
141 $this->errorHandler(date('Y-m-d h:i:s ') .
142 "Notification event cleared (underlying object does not exist)"
150 if (isset($p->active) && empty($p->active)) {
151 $ev = $this->addEvent('NOTIFY', $w,
152 "Notification event cleared (not user not active any more)" );;
154 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
156 $w->event_id = $ev->id;
158 $this->errorHandler(date('Y-m-d h:i:s ') .
159 "Notification event cleared (not user not active any more)"
161 $this->errorHandler("message has been sent already.\n");
163 // has it failed mutliple times..
165 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
166 $ev = $this->addEvent('NOTIFY', $w,
167 "Notification event cleared (user has to many failures)" );;
169 $w->sent = $w->sqlValue('NOW()'); // do not update if sent.....
171 $w->event_id = $ev->id;
173 $this->errorHandler(date('Y-m-d h:i:s ') .
174 "Notification event cleared (user has to many failures)"
176 $this->errorHandler("user has to many failures.\n");
179 // let's work out the last notification sent to this user..
180 $l = DB_DataObject::factory($this->table);
183 'ontable' => $w->ontable,
186 // only newer version of the database us this..
187 if (isset($w->person_table)) {
188 $personid_col = strtolower($w->person_table).'_id';
189 if (isset($w->{$personid_col})) {
190 $lar[$personid_col] = $w->{$personid_col};
196 $l->whereAdd('id != '. $w->id);
197 $l->orderBy('sent DESC');
199 $ar = $l->fetchAll('sent');
200 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
203 $ev = DB_DataObject::factory('Events');
204 $ev->on_id = $w->id; // int(11)
205 $ev->on_table = $this->table;
207 $ev->orderBy('event_when DESC');
208 $ar = $ev->fetchAll('event_when');
209 $last_event = empty($ar) ? 0 : $ar[0];
212 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
214 $next_try = $next_try_min . ' MINUTES';
216 // this may modify $p->email. (it will not update it though)
217 $email = $this->makeEmail($o, $p, $last, $w, $force);
219 if ($email === true) {
221 $ev = $this->addEvent('NOTIFY', $w,
222 "Notification event cleared (not required any more)" );;
224 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
226 $w->event_id = $ev->id;
228 $this->errorHandler(date('Y-m-d h:i:s ') .
229 "Notification event cleared (not required any more)"
232 if (is_a($email, 'PEAR_Error')) {
234 'error' => $email->toString()
238 if (empty($p) && !empty($email['recipients'])) {
239 // make a fake person..
241 'email' => $email['recipients']
245 if ($email === false || isset($email['error']) || empty($p)) {
246 // object returned 'false' - it does not know how to send it..
247 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ?
248 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
250 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
252 $w->event_id = $ev->id;
253 $w->to_email = $p->email;
255 $this->errorHandler(date('Y-m-d h:i:s ') .
256 (isset($email['error']) ?
257 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
262 if (isset($email['later'])) {
264 $w->act_when = $email['later'];
265 $this->updateServer($w);
267 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
271 if (empty($email['headers']['Message-Id'])) {
272 $HOST = gethostname();
273 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
280 //$p->email = 'alan@akbkhome.com'; //for testing..
281 //print_r($email);exit;
282 // should we fetch the watch that caused it.. - which should contain the method to call..
283 // --send-to=test@xxx.com
285 if (!empty($email['send-to'])) {
286 $p->email = $email['send-to'];
288 if (!empty($opts['send-to'])) {
289 $p->email = $opts['send-to'];
292 // since some of them have spaces?!?!
293 $p->email = trim($p->email);
296 require_once 'Validate.php';
297 if (!Validate::email($p->email, true)) {
298 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
300 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
302 $w->event_id = $ev->id;
303 $w->to_email = $p->email;
305 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
310 $ff = HTML_FlexyFramework::get();
312 $explode_email = explode('@', $p->email);
313 $dom = array_pop($explode_email);
315 $mxs = $this->mxs($dom);
318 // we might fail doing this...
319 // need to handle temporary failure..
322 // we try for 2 days..
324 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
325 // older that 1 hour.
329 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
333 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
338 if ($mxs === false) {
339 // only retry for 1 day if the MX issue..
341 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
342 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
343 $this->updateServer($w);
345 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
348 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
349 $w->sent = $w->sqlValue('NOW()'); // why not updated - used to leave as is?
351 $w->event_id = $ev->id;
352 $w->to_email = $p->email;
354 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
362 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
363 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
364 $w->sent = $w->sqlValue('NOW()');
366 $w->event_id = $ev->id;
367 $w->to_email = $p->email;
369 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
374 $w->to_email = $p->email;
375 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
376 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
377 // set act when if it's empty...
378 $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;
385 require_once 'Mail.php';
387 $core_domain = DB_DataObject::factory('core_domain');
388 if(!$core_domain->get('domain', $dom)){
389 $core_domain = DB_DataObject::factory('core_domain');
390 $core_domain->setFrom(array(
393 $core_domain->insert();
399 if (!isset($ff->Mail['helo'])) {
400 $this->errorHandler("config Mail[helo] is not set");
405 foreach($mxs as $mx) {
408 $this->debug_str = '';
409 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
410 $mailer = Mail::factory('smtp', array(
412 'localhost' => $ff->Mail['helo'],
414 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
415 //'debug' => isset($opts['debug']) ? 1 : 0,
417 'debug_handler' => array($this, 'debugHandler')
420 // if the host is the mail host + it's authenticated add auth details
421 // this normally will happen if you sent Pman_Core_NotifySend['host']
424 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
426 $mailer->auth = true;
427 $mailer->username = $ff->Mail['username'];
428 $mailer->password = $ff->Mail['password'];
431 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
433 // we might want to regex 'office365 as a mx host
434 foreach ($ff->Core_Notify['routes'] as $server => $settings){
435 if(!in_array($dom, $settings['domains'])){
439 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
440 // if it's newer that '1' minute...
443 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
445 $seconds = floor((60 * 60) / $settings['rate']);
447 $core_notify = DB_DataObject::factory($this->table);
448 $core_notify->domain_id = $core_domain->id;
449 $core_notify->whereAdd("
450 sent >= NOW() - INTERVAL $seconds SECOND
453 if($core_notify->count()){
455 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
456 $this->updateServer($w);
458 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
463 $mailer->host = $server;
464 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
465 $mailer->username = $settings['username'];
466 $mailer->password = $settings['password'];
467 if (isset($settings['port'])) {
468 $mailer->port = $settings['port'];
470 if (isset($settings['socket_options'])) {
471 $mailer->socket_options = $settings['socket_options'];
482 $res = $mailer->send($p->email, $email['headers'], $email['body']);
488 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
490 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
492 $ev->writeEventLog($this->debug_str);
494 if(strtotime($w->act_when) > strtotime("NOW")){
495 $w->act_when = date('Y-m-d H:i:s');
498 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
499 $w->msgid = $email['headers']['Message-Id'];
500 $w->event_id = $ev->id; // sent ok.. - no need to record it..
501 $w->domain_id = $core_domain->id;
504 // enable cc in notify..
505 if (!empty($email['headers']['Cc'])) {
506 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
507 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
508 $cmailer->send($email['headers']['Cc'],
509 $email['headers'], $email['body']);
513 if (!empty($email['bcc'])) {
514 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
515 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
516 $res = $cmailer->send($email['bcc'],
517 $email['headers'], $email['body']);
518 if (!$res || is_a($res, 'PEAR_Error')) {
519 echo "could not send bcc..\n";
521 echo "Sent BCC to {$email['bcc']}\n";
526 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
528 // what type of error..
529 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
530 if (!empty($res->code) && $res->code == 10001) {
531 // fake greylist if timed out.
536 $this->debug($res->message);
537 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
539 // give up after 2 days..
540 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
542 // check last event for this item..
543 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
544 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
545 if (!empty($res->userinfo['smtptext'])) {
546 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
549 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
550 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
551 $this->updateServer($w);
552 $w->domain_id = $core_domain->id;
556 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
561 if ($fail || $next_try_min > (2*24*60)) {
562 // fail.. = log and give up..
563 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
564 if (isset($res->userinfo['smtptext'])) {
565 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
568 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
570 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
572 $w->event_id = $ev->id;
573 $w->domain_id = $core_domain->id;
575 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
578 // handle no host availalbe forever...
579 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
580 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
581 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
583 $w->event_id = $ev->id;
584 $w->domain_id = $core_domain->id;
586 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
590 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
591 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
593 $this->updateServer($w);
595 $w->domain_id = $core_domain->id;
597 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
603 $ff = HTML_FlexyFramework::get();
604 if (isset($ff->Pman_Core_NotifySend['host'])) {
605 return array($ff->Pman_Core_NotifySend['host']);
608 $mx_records = array();
609 $mx_weight = array();
611 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
612 if (!checkdnsrr($fqdn)) {
618 asort($mx_weight,SORT_NUMERIC);
620 foreach($mx_weight as $k => $weight) {
621 $mxs[] = $mx_records[$k];
627 * wrapper to call object->toEmail()
631 headers : {AssocArray},
635 error : {String} // error message in log.
636 send-to: {String} // use to override rcpt
640 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
642 $m = 'notify'. $notify->evtype;
643 //var_dump(get_class($object) . '::' .$m);
644 if (!empty($notify->evtype) && method_exists($object,$m)) {
645 echo "calling :" . get_class($object) . '::' .$m . "\n";
646 return $object->$m($rcpt, $last_sent_date, $notify, $force);
649 $type = explode('::', $notify->evtype);
651 if(!empty($type[1]) && method_exists($object,$type[1])){
653 echo "calling :" . get_class($object) . '::' .$m . "\n";
654 return $object->$m($rcpt, $last_sent_date, $notify, $force);
657 if (method_exists($object, 'toMailerData')) {
658 return $object->toMailerData(array(
660 'person'=>$rcpt, // added as mediaoutreach used this?
661 )); //this is core_email - i think it's only used for testing...
666 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
671 if (empty($this->cli_args['debug'])) {
679 $this->errorHandler("done\n");
683 function debugHandler ($smtp, $message)
685 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
686 $this->debug_str .= $message;
687 //echo $message ."\n";
690 function errorHandler($msg, $success = false)
692 if($this->error_handler == 'exception'){
694 throw new Pman_Core_NotifySend_Exception_Success($msg);
697 throw new Pman_Core_NotifySend_Exception_Fail($msg);
705 function updateServer($w)
707 $ff = HTML_FlexyFramework::get();
709 if (empty($ff->Core_Notify['servers'])) {
713 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));
719 $ff = HTML_FlexyFramework::get();
720 if (empty($ff->Core_Notify['servers'])) {
723 if (!isset($ff->Core_Notify['servers'][gethostname()]) || !isset($ff->Core_Notify['servers'][gethostname()]['helo']) ) {
724 $this->jerr("Core_Notify['servers']['" . gethostname() . "']['helo'] not set");
726 $ff->Mail['helo'] = $ff->Core_Notify['servers'][gethostname()]['helo'];