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");
165 // let's work out the last notification sent to this user..
166 $l = DB_DataObject::factory($this->table);
169 'ontable' => $w->ontable,
172 // only newer version of the database us this..
173 $personid_col = strtolower($w->person_table).'_id';
174 if (isset($w->{$personid_col})) {
175 $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) {
205 $ev = $this->addEvent('NOTIFY', $w,
206 "Notification event cleared (not required any more)" );;
208 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
210 $w->event_id = $ev->id;
212 $this->errorHandler(date('Y-m-d h:i:s ') .
213 "Notification event cleared (not required any more)"
216 if (is_a($email, 'PEAR_Error')) {
218 'error' => $email->toString()
222 if (empty($p) && !empty($email['recipients'])) {
223 // make a fake person..
225 'email' => $email['recipients']
229 if ($email === false || isset($email['error']) || empty($p)) {
230 // object returned 'false' - it does not know how to send it..
231 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ?
232 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
234 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
236 $w->event_id = $ev->id;
238 $this->errorHandler(date('Y-m-d h:i:s ') .
239 (isset($email['error']) ?
240 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
245 if (isset($email['later'])) {
247 $w->act_when = $email['later'];
249 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
253 if (empty($email['headers']['Message-Id'])) {
254 $HOST = gethostname();
255 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
262 //$p->email = 'alan@akbkhome.com'; //for testing..
263 //print_r($email);exit;
264 // should we fetch the watch that caused it.. - which should contain the method to call..
265 // --send-to=test@xxx.com
267 if (!empty($email['send-to'])) {
268 $p->email = $email['send-to'];
270 if (!empty($opts['send-to'])) {
271 $p->email = $opts['send-to'];
274 // since some of them have spaces?!?!
275 $p->email = trim($p->email);
278 require_once 'Validate.php';
279 if (!Validate::email($p->email, true)) {
280 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
282 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
284 $w->event_id = $ev->id;
286 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
291 $ff = HTML_FlexyFramework::get();
293 $explode_email = explode('@', $p->email);
294 $dom = array_pop($explode_email);
296 $mxs = $this->mxs($dom);
299 // we might fail doing this...
300 // need to handle temporary failure..
303 // we try for 3 days..
305 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
306 // older that 1 hour.
310 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
314 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
319 if ($mxs === false) {
320 // only retry for 2 day son the MX issue..
322 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
323 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
325 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
328 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
329 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
331 $w->event_id = $ev->id;
333 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
341 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
342 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
343 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
345 $w->event_id = $ev->id;
347 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
352 $w->to_email = $p->email;
353 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
354 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
355 $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;
361 require_once 'Mail.php';
363 $core_domain = DB_DataObject::factory('core_domain');
364 if(!$core_domain->get('domain', $dom)){
365 $core_domain = DB_DataObject::factory('core_domain');
366 $core_domain->setFrom(array(
369 $core_domain->insert();
372 foreach($mxs as $mx) {
374 if (!isset($ff->Mail['helo'])) {
375 $this->errorHandler("config Mail[helo] is not set");
377 $this->debug_str = '';
378 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
379 $mailer = Mail::factory('smtp', array(
381 'localhost' => $ff->Mail['helo'],
383 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
384 //'debug' => isset($opts['debug']) ? 1 : 0,
386 'debug_handler' => array($this, 'debugHandler')
389 // if the host is the mail host + it's authenticated add auth details
390 // this normally will happen if you sent Pman_Core_NotifySend['host']
393 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
395 $mailer->auth = true;
396 $mailer->username = $ff->Mail['username'];
397 $mailer->password = $ff->Mail['password'];
400 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
402 // we might want to regex 'office365 as a mx host
403 foreach ($ff->Core_Notify['routes'] as $server => $settings){
404 if(!in_array($dom, $settings['domains'])){
408 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
409 // if it's newer that '1' minute...
412 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
414 $seconds = floor((60 * 60) / $settings['rate']);
416 $core_notify = DB_DataObject::factory($this->table);
417 $core_notify->domain_id = $core_domain->id;
418 $core_notify->whereAdd("
419 sent >= NOW() - INTERVAL $seconds SECOND
422 if($core_notify->count()){
424 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
426 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
431 $mailer->host = $server;
432 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
433 $mailer->username = $settings['username'];
434 $mailer->password = $settings['password'];
435 if (isset($settings['port'])) {
436 $mailer->port = $settings['port'];
438 if (isset($settings['socket_options'])) {
439 $mailer->socket_options = $settings['socket_options'];
450 $res = $mailer->send($p->email, $email['headers'], $email['body']);
456 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
458 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
460 $ev->writeEventLog($this->debug_str);
462 if(strtotime($w->act_when) > strtotime("NOW")){
463 $w->act_when = date('Y-m-d H:i:s');
466 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
467 $w->msgid = $email['headers']['Message-Id'];
468 $w->event_id = $ev->id; // sent ok.. - no need to record it..
469 $w->domain_id = $core_domain->id;
472 // enable cc in notify..
473 if (!empty($email['headers']['Cc'])) {
474 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
475 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
476 $cmailer->send($email['headers']['Cc'],
477 $email['headers'], $email['body']);
481 if (!empty($email['bcc'])) {
482 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
483 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
484 $res = $cmailer->send($email['bcc'],
485 $email['headers'], $email['body']);
486 if (!$res || is_a($res, 'PEAR_Error')) {
487 echo "could not send bcc..\n";
489 echo "Sent BCC to {$email['bcc']}\n";
494 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
496 // what type of error..
497 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
498 if (!empty($res->code) && $res->code == 10001) {
499 // fake greylist if timed out.
504 $this->debug($res->message);
505 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
507 // give up after 2 days..
508 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
510 // check last event for this item..
511 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
512 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
513 if (!empty($res->userinfo['smtptext'])) {
514 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
517 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
518 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
519 $w->domain_id = $core_domain->id;
523 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
528 if ($fail || $next_try_min > (2*24*60)) {
529 // fail.. = log and give up..
530 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
531 if (isset($res->userinfo['smtptext'])) {
532 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
535 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
537 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
539 $w->event_id = $ev->id;
540 $w->domain_id = $core_domain->id;
542 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
545 // handle no host availalbe forever...
546 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
547 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
548 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
550 $w->event_id = $ev->id;
551 $w->domain_id = $core_domain->id;
553 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
557 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
558 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
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 $mxs[] = $mx_records[$k];
591 * wrapper to call object->toEmail()
595 headers : {AssocArray},
599 error : {String} // error message in log.
600 send-to: {String} // use to override rcpt
604 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
606 $m = 'notify'. $notify->evtype;
607 //var_dump(get_class($object) . '::' .$m);
608 if (!empty($notify->evtype) && method_exists($object,$m)) {
609 echo "calling :" . get_class($object) . '::' .$m . "\n";
610 return $object->$m($rcpt, $last_sent_date, $notify, $force);
613 $type = explode('::', $notify->evtype);
615 if(!empty($type[1]) && method_exists($object,$type[1])){
617 echo "calling :" . get_class($object) . '::' .$m . "\n";
618 return $object->$m($rcpt, $last_sent_date, $notify, $force);
621 if (method_exists($object, 'toMailerData')) {
622 return $object->toMailerData(array(
624 'person'=>$rcpt, // added as mediaoutreach used this?
625 )); //this is core_email - i think it's only used for testing...
630 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
635 if (empty($this->cli_args['debug'])) {
643 $this->errorHandler("done\n");
647 function debugHandler ($smtp, $message)
649 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
650 $this->debug_str .= $message;
651 //echo $message ."\n";
654 function errorHandler($msg, $success = false)
656 if($this->error_handler == 'exception'){
658 throw new Pman_Core_NotifySend_Exception_Success($msg);
661 throw new Pman_Core_NotifySend_Exception_Fail($msg);