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 $lar[strtolower($w->person_table).'_id'] = $w->{strtolower($w->person_table).'_id'};
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) {
197 $ev = $this->addEvent('NOTIFY', $w,
198 "Notification event cleared (not required any more)" );;
200 $w->sent = date('Y-m-d H:i:s');
202 $w->event_id = $ev->id;
204 $this->errorHandler(date('Y-m-d h:i:s ') .
205 "Notification event cleared (not required any more)"
211 if ($email === false || isset($email['error'])) {
212 // object returned 'false' - it does not know how to send it..
213 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
214 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
216 $w->sent = date('Y-m-d H:i:s');
218 $w->event_id = $ev->id;
220 $this->errorHandler(date('Y-m-d h:i:s ') .
221 (isset($email['error']) ?
222 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
227 if (isset($email['later'])) {
229 $w->act_when = $email['later'];
231 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
235 if (empty($email['headers']['Message-Id'])) {
236 $HOST = gethostname();
237 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
240 //$p->email = 'alan@akbkhome.com'; //for testing..
241 //print_r($email);exit;
242 // should we fetch the watch that caused it.. - which should contain the method to call..
243 // --send-to=test@xxx.com
245 if (!empty($email['send-to'])) {
246 $p->email = $email['send-to'];
248 if (!empty($opts['send-to'])) {
249 $p->email = $opts['send-to'];
251 // since some of them have spaces?!?!
252 $p->email = trim($p->email);
254 require_once 'Validate.php';
255 if (!Validate::email($p->email, true)) {
256 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
258 $w->sent = date('Y-m-d H:i:s');
260 $w->event_id = $ev->id;
262 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
267 $ff = HTML_FlexyFramework::get();
270 $dom = array_pop(explode('@', $p->email));
272 $mxs = $this->mxs($dom);
275 // we might fail doing this...
276 // need to handle temporary failure..
279 // we try for 3 days..
281 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
282 // older that 1 hour.
286 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
290 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
295 if ($mxs === false) {
296 // only retry for 2 day son the MX issue..
298 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
299 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
301 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
304 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
305 $w->sent = date('Y-m-d H:i:s');
307 $w->event_id = $ev->id;
309 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
317 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
318 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
319 $w->sent = date('Y-m-d H:i:s');
321 $w->event_id = $ev->id;
323 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
328 $w->to_email = $p->email;
329 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
330 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
336 require_once 'Mail.php';
338 foreach($mxs as $dom) {
342 if (!isset($ff->Mail['helo'])) {
343 $this->errorHandler("config Mail[helo] is not set");
345 $this->debug_str = '';
346 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
347 $mailer = Mail::factory('smtp', array(
349 'localhost' => $ff->Mail['helo'],
351 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
352 //'debug' => isset($opts['debug']) ? 1 : 0,
354 'debug_handler' => array($this, 'debugHandler')
357 // if the host is the mail host + it's authenticated add auth details
358 // this normally will happen if you sent Pman_Core_NotifySend['host']
359 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $dom && !empty($ff->Mail['auth'] )) {
360 $mailer->auth = true;
361 $mailer->username = $ff->Mail['username'] ;
362 $mailer->password = $ff->Mail['password'] ;
365 $res = $mailer->send($p->email, $email['headers'], $email['body']);
371 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
373 $ev->writeEventLog($this->debug_str);
375 $w->sent = date('Y-m-d H:i:s');
376 $w->msgid = $email['headers']['Message-Id'];
377 $w->event_id = $ev->id; // sent ok.. - no need to record it..
380 // enable cc in notify..
381 if (!empty($email['headers']['Cc'])) {
382 $cmailer = Mail::factory('smtp', array(
386 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
387 $cmailer->send($email['headers']['Cc'],
388 $email['headers'], $email['body']);
392 if (!empty($email['bcc'])) {
393 $cmailer = Mail::factory('smtp', array(
397 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
398 $cmailer->send($email['bcc'],
399 $email['headers'], $email['body']);
404 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT\n");
406 // what type of error..
407 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
408 if (!empty($res->code) && $res->code == 10001) {
409 // fake greylist if timed out.
414 $this->debug($res->message);
415 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
417 // give up after 2 days..
418 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
420 // check last event for this item..
421 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
422 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
423 if (!empty($res->userinfo['smtptext'])) {
424 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
427 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
428 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
432 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
437 if ($fail || $next_try_min > (2*24*60)) {
438 // fail.. = log and give up..
439 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
440 if (isset($res->userinfo['smtptext'])) {
441 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
444 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
446 $w->sent = date('Y-m-d H:i:s');
448 $w->event_id = $ev->id;
450 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
453 // handle no host availalbe forever...
454 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
455 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
456 $w->sent = date('Y-m-d H:i:s');
458 $w->event_id = $ev->id;
460 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
466 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
467 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
469 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
475 $ff = HTML_FlexyFramework::get();
476 if (isset($ff->Pman_Core_NotifySend['host'])) {
477 return array($ff->Pman_Core_NotifySend['host']);
480 $mx_records = array();
481 $mx_weight = array();
483 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
484 if (!checkdnsrr($fqdn)) {
490 asort($mx_weight,SORT_NUMERIC);
492 foreach($mx_weight as $k => $weight) {
493 $mxs[] = $mx_records[$k];
499 * wrapper to call object->toEmail()
503 headers : {AssocArray},
507 error : {String} // error message in log.
508 send-to: {String} // use to override rcpt
512 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
514 $m = 'notify'. $notify->evtype;
515 //var_dump(get_class($object) . '::' .$m);
516 if (!empty($notify->evtype) && method_exists($object,$m)) {
517 echo "calling :" . get_class($object) . '::' .$m . "\n";
518 return $object->$m($rcpt, $last_sent_date, $notify, $force);
521 $type = explode('::', $notify->evtype);
523 if(!empty($type[1]) && method_exists($object,$type[1])){
525 echo "calling :" . get_class($object) . '::' .$m . "\n";
526 return $object->$m($rcpt, $last_sent_date, $notify, $force);
529 if (!method_exists($object, 'toEmail')) {
534 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
539 if (empty($this->cli_args['debug'])) {
547 $this->errorHandler("done\n");
551 function debugHandler ($smtp, $message)
553 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
554 $this->debug_str .= $message;
557 function errorHandler($msg)
559 if($this->error_handler == 'exception'){
560 throw new Exception($msg);