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->flagSent($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->flagSent($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->flagSent($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->flagSent($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->flagSent($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);
260 require_once 'Validate.php';
261 if (!Validate::email($p->email, true)) {
262 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
264 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
266 $w->event_id = $ev->id;
267 $w->to_email = $p->email;
269 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
274 $ff = HTML_FlexyFramework::get();
276 $explode_email = explode('@', $p->email);
277 $dom = array_pop($explode_email);
279 $mxs = $this->mxs($dom);
282 // we might fail doing this...
283 // need to handle temporary failure..
286 // we try for 2 days..
288 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
289 // older that 1 hour.
293 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
297 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
303 // only retry for 1 day if the MX issue..
305 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
306 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
307 $this->updateServer($w);
309 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED {$dom}\n");
312 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
313 $w->sent = $w->sqlValue('NOW()'); // why not updated - used to leave as is?
315 $w->event_id = $ev->id;
316 $w->to_email = $p->email;
318 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD DOMAIN - {$p->email} \n");
326 if (!$force && strtotime($w->act_start) < strtotime('NOW - 3 DAY')) {
327 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
328 $w->sent = $w->sqlValue('NOW()');
330 $w->event_id = $ev->id;
331 $w->to_email = $p->email;
333 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
338 $w->to_email = $p->email;
339 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
340 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
341 // set act when if it's empty...
342 $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;
349 require_once 'Mail.php';
351 $core_domain = DB_DataObject::factory('core_domain');
352 if(!$core_domain->get('domain', $dom)){
353 $core_domain = DB_DataObject::factory('core_domain');
354 $core_domain->setFrom(array(
357 $core_domain->insert();
363 if (!isset($ff->Mail['helo'])) {
364 $this->errorHandler("config Mail[helo] is not set");
369 foreach($mxs as $mx) {
372 $this->debug_str = '';
373 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
374 $mailer = Mail::factory('smtp', array(
376 'localhost' => $ff->Mail['helo'],
378 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
379 //'debug' => isset($opts['debug']) ? 1 : 0,
381 'debug_handler' => array($this, 'debugHandler')
384 // if the host is the mail host + it's authenticated add auth details
385 // this normally will happen if you sent Pman_Core_NotifySend['host']
388 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
390 $mailer->auth = true;
391 $mailer->username = $ff->Mail['username'];
392 $mailer->password = $ff->Mail['password'];
395 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
397 // we might want to regex 'office365 as a mx host
398 foreach ($ff->Core_Notify['routes'] as $server => $settings){
399 if(!in_array($dom, $settings['domains'])){
403 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
404 // if it's newer that '1' minute...
407 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
409 $seconds = floor((60 * 60) / $settings['rate']);
411 $core_notify = DB_DataObject::factory($this->table);
412 $core_notify->domain_id = $core_domain->id;
413 $core_notify->whereAdd("
414 sent >= NOW() - INTERVAL $seconds SECOND
417 if($core_notify->count()){
419 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
420 $this->updateServer($w);
422 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
427 $mailer->host = $server;
428 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
429 $mailer->username = $settings['username'];
430 $mailer->password = $settings['password'];
431 if (isset($settings['port'])) {
432 $mailer->port = $settings['port'];
434 if (isset($settings['socket_options'])) {
435 $mailer->socket_options = $settings['socket_options'];
446 $res = $mailer->send($p->email, $email['headers'], $email['body']);
452 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
454 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
456 $ev->writeEventLog($this->debug_str);
458 if(strtotime($w->act_when) > strtotime("NOW")){
459 $w->act_when = date('Y-m-d H:i:s');
462 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
463 $w->msgid = $email['headers']['Message-Id'];
464 $w->event_id = $ev->id; // sent ok.. - no need to record it..
465 $w->domain_id = $core_domain->id;
468 // enable cc in notify..
469 if (!empty($email['headers']['Cc'])) {
470 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
471 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
472 $cmailer->send($email['headers']['Cc'],
473 $email['headers'], $email['body']);
477 if (!empty($email['bcc'])) {
478 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
479 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
480 $res = $cmailer->send($email['bcc'],
481 $email['headers'], $email['body']);
482 if (!$res || is_a($res, 'PEAR_Error')) {
483 echo "could not send bcc..\n";
485 echo "Sent BCC to {$email['bcc']}\n";
490 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
492 // what type of error..
493 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
494 if (!empty($res->code) && $res->code == 10001) {
495 // fake greylist if timed out.
500 $this->debug($res->message);
501 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
503 // give up after 2 days..
504 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
506 // check last event for this item..
507 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
508 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
509 if (!empty($res->userinfo['smtptext'])) {
510 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
513 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
514 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
515 $this->updateServer($w);
516 $w->domain_id = $core_domain->id;
520 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
525 if ($fail || $next_try_min > (2*24*60)) {
526 // fail.. = log and give up..
527 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
528 if (isset($res->userinfo['smtptext'])) {
529 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
532 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
534 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
536 $w->event_id = $ev->id;
537 $w->domain_id = $core_domain->id;
539 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
542 // handle no host availalbe forever...
543 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
544 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
545 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
547 $w->event_id = $ev->id;
548 $w->domain_id = $core_domain->id;
550 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
554 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
555 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
557 $this->updateServer($w);
559 $w->domain_id = $core_domain->id;
561 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
567 $ff = HTML_FlexyFramework::get();
568 if (isset($ff->Pman_Core_NotifySend['host'])) {
569 return array($ff->Pman_Core_NotifySend['host']);
572 $mx_records = array();
573 $mx_weight = array();
575 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
576 if (!checkdnsrr($fqdn)) {
582 asort($mx_weight,SORT_NUMERIC);
584 foreach($mx_weight as $k => $weight) {
585 if (!empty($mx_records[$k])) {
586 $mxs[] = $mx_records[$k];
589 return empty($mxs) ? false : $mxs;
593 * wrapper to call object->toEmail()
597 headers : {AssocArray},
601 error : {String} // error message in log.
602 send-to: {String} // use to override rcpt
606 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
608 $m = 'notify'. $notify->evtype;
609 //var_dump(get_class($object) . '::' .$m);
610 if (!empty($notify->evtype) && method_exists($object,$m)) {
611 echo "calling :" . get_class($object) . '::' .$m . "\n";
612 return $object->$m($rcpt, $last_sent_date, $notify, $force);
615 $type = explode('::', $notify->evtype);
617 if(!empty($type[1]) && method_exists($object,$type[1])){
619 echo "calling :" . get_class($object) . '::' .$m . "\n";
620 return $object->$m($rcpt, $last_sent_date, $notify, $force);
622 // fallback if evtype is empty..
624 if (method_exists($object, 'toMailerData')) {
625 return $object->toMailerData(array(
627 'person'=>$rcpt, // added as mediaoutreach used this?
628 )); //this is core_email - i think it's only used for testing...
632 if (method_exists($object, 'toEmail')) {
633 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
635 // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
642 if (empty($this->cli_args['debug'])) {
650 $this->errorHandler("done\n");
654 function debugHandler ($smtp, $message)
656 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
657 $this->debug_str .= $message;
658 //echo $message ."\n";
661 function errorHandler($msg, $success = false)
663 if($this->error_handler == 'exception'){
665 throw new Pman_Core_NotifySend_Exception_Success($msg);
668 throw new Pman_Core_NotifySend_Exception_Fail($msg);
676 function updateServer($w)
678 $ff = HTML_FlexyFramework::get();
680 if (empty($ff->Core_Notify['servers'])) {
683 // some classes dont support server routing
684 if (!property_exists($w, 'server_id')) {
688 $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));
694 $ff = HTML_FlexyFramework::get();
696 if (isset($ff->Core_Notify['servers-non-pool']) &&
697 isset($ff->Core_Notify['servers-non-pool'][gethostname()]) &&
698 isset($ff->Core_Notify['servers-non-pool'][gethostname()]['helo']) ) {
699 $ff->Mail['helo'] = $ff->Core_Notify['servers-non-pool'][gethostname()]['helo'];
703 if (empty($ff->Core_Notify['servers'])) {
706 if (!isset($ff->Core_Notify['servers'][gethostname()]) || !isset($ff->Core_Notify['servers'][gethostname()]['helo']) ) {
707 $this->jerr("Core_Notify['servers']['" . gethostname() . "']['helo'] not set");
709 $ff->Mail['helo'] = $ff->Core_Notify['servers'][gethostname()]['helo'];