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.
31 class Pman_Core_NotifySend extends Pman
33 static $cli_desc = "Send out single notification email (usually called from Core/Notify)";
35 static $cli_opts = array(
37 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
44 'DB_DataObject-debug' => array(
45 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
53 'desc' => 'Force redelivery, even if it has been sent before or not queued...',
60 'desc' => 'Send the message to this address, rather than the one listed.',
70 var $table = 'core_notify';
71 var $error_handler = 'die';
75 $ff = HTML_FlexyFramework::get();
77 $this->errorHandler("access denied");
79 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
84 function get($id,$opts)
88 if (!empty($opts['DB_DataObject-debug'])) {
89 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
92 //DB_DataObject::debugLevel(1);
93 //date_default_timezone_set('UTC');
95 $force = empty($opts['force']) ? 0 : 1;
97 $w = DB_DataObject::factory($this->table);
100 $this->errorHandler("invalid id\n");
102 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
105 $this->errorHandler("send repeat to early\n");
107 if (!empty($opts['debug'])) {
109 $ff = HTML_FlexyFramework::get();
110 if (!isset($ff->Core_Mailer)) {
111 $ff->Core_Mailer = array();
113 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
116 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
118 if (!$force && (!empty($w->msgid) || $sent)) {
121 $w->sent = $w->sqlValue("NOW()");
124 $this->errorHandler("message has been sent already.\n");
131 $ev = $this->addEvent('NOTIFY', $w,
132 "Notification event cleared (underlying object does not exist)" );;
134 $w->sent = date('Y-m-d H:i:s');
136 $w->event_id = $ev->id;
138 $this->errorHandler(date('Y-m-d h:i:s ') .
139 "Notification event cleared (underlying object does not exist)"
147 if (isset($p->active) && empty($p->active)) {
148 $ev = $this->addEvent('NOTIFY', $w,
149 "Notification event cleared (not user not active any more)" );;
151 $w->sent = date('Y-m-d H:i:s');
153 $w->event_id = $ev->id;
155 $this->errorHandler(date('Y-m-d h:i:s ') .
156 "Notification event cleared (not user not active any more)"
158 $this->errorHandler("message has been sent already.\n");
162 // let's work out the last notification sent to this user..
163 $l = DB_DataObject::factory($this->table);
166 'ontable' => $w->ontable,
169 // only newer version of the database us this..
170 $personid_col = strtolower($w->person_table).'_id';
171 if (isset($w->{$personid_col})) {
172 $lar[$personid_col] = $w->{$personid_col};
177 $l->whereAdd('id != '. $w->id);
178 $l->orderBy('sent DESC');
180 $ar = $l->fetchAll('sent');
181 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
184 $ev = DB_DataObject::factory('Events');
185 $ev->on_id = $w->id; // int(11)
186 $ev->on_table = $this->table;
188 $ev->orderBy('event_when DESC');
189 $ar = $ev->fetchAll('event_when');
190 $last_event = empty($ar) ? 0 : $ar[0];
193 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
195 $next_try = $next_try_min . ' MINUTES';
197 // this may modify $p->email. (it will not update it though)
198 $email = $this->makeEmail($o, $p, $last, $w, $force);
200 if ($email === true) {
202 $ev = $this->addEvent('NOTIFY', $w,
203 "Notification event cleared (not required any more)" );;
205 $w->sent = date('Y-m-d H:i:s');
207 $w->event_id = $ev->id;
209 $this->errorHandler(date('Y-m-d h:i:s ') .
210 "Notification event cleared (not required any more)"
213 if (is_a($email, 'PEAR_Error')) {
215 'error' => $email->toString()
219 if (empty($p) && !empty($email['recipients'])) {
220 // make a fake person..
222 'email' => $email['recipients']
226 if ($email === false || isset($email['error']) || empty($p)) {
227 // object returned 'false' - it does not know how to send it..
228 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
229 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
231 $w->sent = date('Y-m-d H:i:s');
233 $w->event_id = $ev->id;
235 $this->errorHandler(date('Y-m-d h:i:s ') .
236 (isset($email['error']) ?
237 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
242 if (isset($email['later'])) {
244 $w->act_when = $email['later'];
246 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
250 if (empty($email['headers']['Message-Id'])) {
251 $HOST = gethostname();
252 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
259 //$p->email = 'alan@akbkhome.com'; //for testing..
260 //print_r($email);exit;
261 // should we fetch the watch that caused it.. - which should contain the method to call..
262 // --send-to=test@xxx.com
264 if (!empty($email['send-to'])) {
265 $p->email = $email['send-to'];
267 if (!empty($opts['send-to'])) {
268 $p->email = $opts['send-to'];
271 // since some of them have spaces?!?!
272 $p->email = trim($p->email);
275 require_once 'Validate.php';
276 if (!Validate::email($p->email, true)) {
277 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
279 $w->sent = date('Y-m-d H:i:s');
281 $w->event_id = $ev->id;
283 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
288 $ff = HTML_FlexyFramework::get();
291 $dom = array_pop(explode('@', $p->email));
293 $mxs = $this->mxs($dom);
296 // we might fail doing this...
297 // need to handle temporary failure..
300 // we try for 3 days..
302 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
303 // older that 1 hour.
307 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
311 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
316 if ($mxs === false) {
317 // only retry for 2 day son the MX issue..
319 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
320 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
322 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
325 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
326 $w->sent = date('Y-m-d H:i:s');
328 $w->event_id = $ev->id;
330 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
338 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
339 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
340 $w->sent = date('Y-m-d H:i:s');
342 $w->event_id = $ev->id;
344 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
349 $w->to_email = $p->email;
350 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
351 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
357 require_once 'Mail.php';
359 $core_domain = DB_DataObject::factory('core_domain');
360 if(!$core_domain->get('domain', $dom)){
361 $core_domain = DB_DataObject::factory('core_domain');
362 $core_domain->setFrom(array(
365 $core_domain->insert();
368 print_R($core_domain);exit;
370 foreach($mxs as $mx) {
372 if (!isset($ff->Mail['helo'])) {
373 $this->errorHandler("config Mail[helo] is not set");
375 $this->debug_str = '';
376 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
377 $mailer = Mail::factory('smtp', array(
379 'localhost' => $ff->Mail['helo'],
381 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
382 //'debug' => isset($opts['debug']) ? 1 : 0,
384 'debug_handler' => array($this, 'debugHandler')
387 // if the host is the mail host + it's authenticated add auth details
388 // this normally will happen if you sent Pman_Core_NotifySend['host']
389 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
391 $username = $ff->Mail['username'] ;
392 $password = $ff->Mail['password'] ;
394 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
396 foreach ($ff->Core_Notify['routes'] as $server => $settings){
397 if(!in_array($dom, $settings['domains'])){
401 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
402 // if it's newer that '1' minute...
405 $seconds = floor((60 * 60) / $settings['rate']);
407 $core_notify = DB_DataObject::factory($this->table);
408 $core_notify->domain_id = $core_domain->id;
409 $core_notify->whereAdd("
410 sent >= NOW() - INTERVAL $seconds SECONDS
413 if($core_notify->count()){
415 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
417 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
420 // that make's this test obsolete...
423 $core_notify = DB_DataObject::factory($this->table);
424 $core_notify->domain_id = $core_domain->id;
425 $core_notify->whereAdd("
426 sent >= NOW() - INTERVAL 1 HOUR
429 if($core_notify->count() >= $settings['rate']){
431 $w->act_when = date("Y-m-d H:i:s", strtotime('+1 HOUR'));
433 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
439 $mailer->host = $server;
440 $username = $settings['username'];
441 $password = $settings['password'];
448 $mailer->auth = true;
449 $mailer->username = $username;
450 $mailer->password = $password;
453 $res = $mailer->send($p->email, $email['headers'], $email['body']);
459 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
461 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
463 $ev->writeEventLog($this->debug_str);
465 $w->sent = date('Y-m-d H:i:s');
466 $w->msgid = $email['headers']['Message-Id'];
467 $w->event_id = $ev->id; // sent ok.. - no need to record it..
468 $w->domain_id = $core_domain->id;
471 // enable cc in notify..
472 if (!empty($email['headers']['Cc'])) {
473 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
474 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
475 $cmailer->send($email['headers']['Cc'],
476 $email['headers'], $email['body']);
480 if (!empty($email['bcc'])) {
481 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
482 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
483 $res = $cmailer->send($email['bcc'],
484 $email['headers'], $email['body']);
485 if (!$res || is_a($res, 'PEAR_Error')) {
486 echo "could not send bcc..\n";
488 echo "Sent BCC to {$email['bcc']}\n";
493 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n");
495 // what type of error..
496 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
497 if (!empty($res->code) && $res->code == 10001) {
498 // fake greylist if timed out.
503 $this->debug($res->message);
504 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
506 // give up after 2 days..
507 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
509 // check last event for this item..
510 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
511 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
512 if (!empty($res->userinfo['smtptext'])) {
513 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
516 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
517 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
518 $w->domain_id = $core_domain->id;
522 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
527 if ($fail || $next_try_min > (2*24*60)) {
528 // fail.. = log and give up..
529 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
530 if (isset($res->userinfo['smtptext'])) {
531 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
534 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
536 $w->sent = date('Y-m-d H:i:s');
538 $w->event_id = $ev->id;
539 $w->domain_id = $core_domain->id;
541 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
544 // handle no host availalbe forever...
545 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
546 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
547 $w->sent = date('Y-m-d H:i:s');
549 $w->event_id = $ev->id;
550 $w->domain_id = $core_domain->id;
552 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
556 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
557 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
558 $w->domain_id = $core_domain->id;
560 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
566 $ff = HTML_FlexyFramework::get();
567 if (isset($ff->Pman_Core_NotifySend['host'])) {
568 return array($ff->Pman_Core_NotifySend['host']);
571 $mx_records = array();
572 $mx_weight = array();
574 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
575 if (!checkdnsrr($fqdn)) {
581 asort($mx_weight,SORT_NUMERIC);
583 foreach($mx_weight as $k => $weight) {
584 $mxs[] = $mx_records[$k];
590 * wrapper to call object->toEmail()
594 headers : {AssocArray},
598 error : {String} // error message in log.
599 send-to: {String} // use to override rcpt
603 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
605 $m = 'notify'. $notify->evtype;
606 //var_dump(get_class($object) . '::' .$m);
607 if (!empty($notify->evtype) && method_exists($object,$m)) {
608 echo "calling :" . get_class($object) . '::' .$m . "\n";
609 return $object->$m($rcpt, $last_sent_date, $notify, $force);
612 $type = explode('::', $notify->evtype);
614 if(!empty($type[1]) && method_exists($object,$type[1])){
616 echo "calling :" . get_class($object) . '::' .$m . "\n";
617 return $object->$m($rcpt, $last_sent_date, $notify, $force);
620 if (!method_exists($object, 'toEmail')) {
625 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
630 if (empty($this->cli_args['debug'])) {
638 $this->errorHandler("done\n");
642 function debugHandler ($smtp, $message)
644 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
645 $this->debug_str .= $message;
648 function errorHandler($msg)
650 if($this->error_handler == 'exception'){
651 throw new Exception($msg);