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'])) {
111 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
113 if (!$force && (!empty($w->msgid) || $sent)) {
116 $w->sent = $w->sqlValue("NOW()");
119 $this->errorHandler("message has been sent already.\n");
126 $ev = $this->addEvent('NOTIFY', $w,
127 "Notification event cleared (underlying object does not exist)" );;
129 $w->sent = date('Y-m-d H:i:s');
131 $w->event_id = $ev->id;
133 $this->errorHandler(date('Y-m-d h:i:s ') .
134 "Notification event cleared (underlying object does not exist)"
142 if (isset($p->active) && empty($p->active)) {
143 $ev = $this->addEvent('NOTIFY', $w,
144 "Notification event cleared (not user not active any more)" );;
146 $w->sent = date('Y-m-d H:i:s');
148 $w->event_id = $ev->id;
150 $this->errorHandler(date('Y-m-d h:i:s ') .
151 "Notification event cleared (not user not active any more)"
153 $this->errorHandler("message has been sent already.\n");
157 // let's work out the last notification sent to this user..
158 $l = DB_DataObject::factory($this->table);
160 'ontable' => $w->ontable,
162 'person_id' => $w->person_id,
164 $l->whereAdd('id != '. $w->id);
165 $l->orderBy('sent DESC');
167 $ar = $l->fetchAll('sent');
168 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
171 $ev = DB_DataObject::factory('Events');
172 $ev->on_id = $w->id; // int(11)
173 $ev->on_table = $this->table;
175 $ev->orderBy('event_when DESC');
176 $ar = $ev->fetchAll('event_when');
177 $last_event = empty($ar) ? 0 : $ar[0];
180 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
182 $next_try = $next_try_min . ' MINUTES';
184 // this may modify $p->email. (it will not update it though)
185 $email = $this->makeEmail($o, $p, $last, $w, $force);
187 if ($email === true) {
189 $ev = $this->addEvent('NOTIFY', $w,
190 "Notification event cleared (not required any more)" );;
192 $w->sent = date('Y-m-d H:i:s');
194 $w->event_id = $ev->id;
196 $this->errorHandler(date('Y-m-d h:i:s ') .
197 "Notification event cleared (not required any more)"
203 if ($email === false || isset($email['error'])) {
204 // object returned 'false' - it does not know how to send it..
205 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
206 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
208 $w->sent = date('Y-m-d H:i:s');
210 $w->event_id = $ev->id;
212 $this->errorHandler(date('Y-m-d h:i:s ') .
213 (isset($email['error']) ?
214 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
219 if (isset($email['later'])) {
221 $w->act_when = $email['later'];
223 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
227 if (empty($email['headers']['Message-Id'])) {
228 $HOST = gethostname();
229 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
232 //$p->email = 'alan@akbkhome.com'; //for testing..
233 //print_r($email);exit;
234 // should we fetch the watch that caused it.. - which should contain the method to call..
235 // --send-to=test@xxx.com
237 if (!empty($email['send-to'])) {
238 $p->email = $email['send-to'];
240 if (!empty($opts['send-to'])) {
241 $p->email = $opts['send-to'];
243 // since some of them have spaces?!?!
244 $p->email = trim($p->email);
247 require_once 'Validate.php';
248 if (!Validate::email($p->email, true)) {
249 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
251 $w->sent = date('Y-m-d H:i:s');
253 $w->event_id = $ev->id;
255 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
260 $ff = HTML_FlexyFramework::get();
263 $dom = array_pop(explode('@', $p->email));
265 $mxs = $this->mxs($dom);
268 // we might fail doing this...
269 // need to handle temporary failure..
272 // we try for 3 days..
274 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
275 // older that 1 hour.
279 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
283 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
288 if ($mxs === false) {
289 // only retry for 2 day son the MX issue..
291 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
292 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
294 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED\n");
297 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
298 $w->sent = date('Y-m-d H:i:s');
300 $w->event_id = $ev->id;
302 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
310 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
311 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
312 $w->sent = date('Y-m-d H:i:s');
314 $w->event_id = $ev->id;
316 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
321 $w->to_email = $p->email;
322 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
323 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
329 require_once 'Mail.php';
331 foreach($mxs as $dom) {
335 if (!isset($ff->Mail['helo'])) {
336 $this->errorHandler("config Mail[helo] is not set");
338 $this->debug_str = '';
339 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
340 $mailer = Mail::factory('smtp', array(
342 'localhost' => $ff->Mail['helo'],
344 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
345 //'debug' => isset($opts['debug']) ? 1 : 0,
347 'debug_handler' => array($this, 'debugHandler')
349 $res = $mailer->send($p->email, $email['headers'], $email['body']);
355 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
357 $ev->writeEventLog($this->debug_str);
359 $w->sent = date('Y-m-d H:i:s');
360 $w->msgid = $email['headers']['Message-Id'];
361 $w->event_id = $ev->id; // sent ok.. - no need to record it..
364 // enable cc in notify..
365 if (!empty($email['headers']['Cc'])) {
366 $mailer = Mail::factory('smtp', array(
370 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
371 $mailer->send($email['headers']['Cc'],
372 $email['headers'], $email['body']);
376 if (!empty($email['bcc'])) {
377 $mailer = Mail::factory('smtp', array(
381 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
382 $mailer->send($email['bcc'],
383 $email['headers'], $email['body']);
388 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT\n");
390 // what type of error..
391 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
392 if (!empty($res->code) && $res->code == 10001) {
393 // fake greylist if timed out.
398 $this->debug($res->message);
399 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
401 // give up after 2 days..
402 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
404 // check last event for this item..
405 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
406 if (isset($res->userinfo['smtptext'])) {
407 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
410 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
411 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
413 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED\n");
418 if ($fail || $next_try_min > (2*24*60)) {
419 // fail.. = log and give up..
420 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
421 if (isset($res->userinfo['smtptext'])) {
422 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
425 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
427 $w->sent = date('Y-m-d H:i:s');
429 $w->event_id = $ev->id;
431 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
434 // handle no host availalbe forever...
435 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
436 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
437 $w->sent = date('Y-m-d H:i:s');
439 $w->event_id = $ev->id;
441 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
447 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
448 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
450 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
456 $ff = HTML_FlexyFramework::get();
457 if (isset($ff->Pman_Core_NotifySend['host'])) {
458 return array($ff->Pman_Core_NotifySend['host']);
461 $mx_records = array();
462 $mx_weight = array();
464 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
465 if (!checkdnsrr($fqdn)) {
471 asort($mx_weight,SORT_NUMERIC);
473 foreach($mx_weight as $k => $weight) {
474 $mxs[] = $mx_records[$k];
480 * wrapper to call object->toEmail()
484 headers : {AssocArray},
488 error : {String} // error message in log.
489 send-to: {String} // use to override rcpt
493 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
495 $m = 'notify'. $notify->evtype;
496 //var_dump(get_class($object) . '::' .$m);
497 if (!empty($notify->evtype) && method_exists($object,$m)) {
498 echo "calling :" . get_class($object) . '::' .$m . "\n";
499 return $object->$m($rcpt, $last_sent_date, $notify, $force);
502 $type = explode('::', $notify->evtype);
504 if(!empty($type[1]) && method_exists($object,$type[1])){
506 echo "calling :" . get_class($object) . '::' .$m . "\n";
507 return $object->$m($rcpt, $last_sent_date, $notify, $force);
510 if (!method_exists($object, 'toEmail')) {
515 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
520 if (empty($this->cli_args['debug'])) {
528 $this->errorHandler("done\n");
532 function debugHandler ($smtp, $message)
534 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
535 $this->debug_str .= $message;
538 function errorHandler($msg)
540 if($this->error_handler == 'exception'){
541 throw new Exception($msg);