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' => 'Return to referer rather then die',
67 'desc' => 'Send the message to this address, rather than the one listed.',
77 var $table = 'core_notify';
82 $ff = HTML_FlexyFramework::get();
84 $this->errorHandler("access denied");
86 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
91 function get($id,$opts)
95 if (!empty($opts['DB_DataObject-debug'])) {
96 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
99 if(!empty($opts['remote'])){
100 $this->remote = true;
102 //DB_DataObject::debugLevel(1);
103 //date_default_timezone_set('UTC');
105 $force = empty($opts['force']) ? 0 : 1;
107 $w = DB_DataObject::factory($this->table);
110 $this->errorHandler("invalid id\n");
112 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
115 $this->errorHandler("send repeat to early\n");
117 if (!empty($opts['debug'])) {
121 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
123 if (!$force && (!empty($w->msgid) || $sent)) {
126 $w->sent = $w->sqlValue("NOW()");
129 $this->errorHandler("message has been sent already.\n");
136 $ev = $this->addEvent('NOTIFY', $w,
137 "Notification event cleared (underlying object does not exist)" );;
139 $w->sent = date('Y-m-d H:i:s');
141 $w->event_id = $ev->id;
143 $this->errorHandler(date('Y-m-d h:i:s ') .
144 "Notification event cleared (underlying object does not exist)"
152 if (isset($p->active) && empty($p->active)) {
153 $ev = $this->addEvent('NOTIFY', $w,
154 "Notification event cleared (not user not active any more)" );;
156 $w->sent = date('Y-m-d H:i:s');
158 $w->event_id = $ev->id;
160 $this->errorHandler(date('Y-m-d h:i:s ') .
161 "Notification event cleared (not user not active any more)"
163 $this->errorHandler("message has been sent already.\n");
167 // let's work out the last notification sent to this user..
168 $l = DB_DataObject::factory($this->table);
170 'ontable' => $w->ontable,
172 'person_id' => $w->person_id,
174 $l->whereAdd('id != '. $w->id);
175 $l->orderBy('sent DESC');
177 $ar = $l->fetchAll('sent');
178 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
181 $ev = DB_DataObject::factory('Events');
182 $ev->on_id = $w->id; // int(11)
183 $ev->on_table = $this->table;
185 $ev->orderBy('event_when DESC');
186 $ar = $ev->fetchAll('event_when');
187 $last_event = empty($ar) ? 0 : $ar[0];
190 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
192 $next_try = $next_try_min . ' MINUTES';
194 // this may modify $p->email. (it will not update it though)
195 $email = $this->makeEmail($o, $p, $last, $w, $force);
197 if ($email === true) {
199 $ev = $this->addEvent('NOTIFY', $w,
200 "Notification event cleared (not required any more)" );;
202 $w->sent = date('Y-m-d H:i:s');
204 $w->event_id = $ev->id;
206 $this->errorHandler(date('Y-m-d h:i:s ') .
207 "Notification event cleared (not required any more)"
213 if ($email === false || isset($email['error'])) {
214 // object returned 'false' - it does not know how to send it..
215 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
216 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
218 $w->sent = date('Y-m-d H:i:s');
220 $w->event_id = $ev->id;
222 $this->errorHandler(date('Y-m-d h:i:s ') .
223 (isset($email['error']) ?
224 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
229 if (isset($email['later'])) {
231 $w->act_when = $email['later'];
233 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
237 if (empty($email['headers']['Message-Id'])) {
238 $HOST = gethostname();
239 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
242 //$p->email = 'alan@akbkhome.com'; //for testing..
243 //print_r($email);exit;
244 // should we fetch the watch that caused it.. - which should contain the method to call..
245 // --send-to=test@xxx.com
247 if (!empty($email['send-to'])) {
248 $p->email = $email['send-to'];
250 if (!empty($opts['send-to'])) {
251 $p->email = $opts['send-to'];
253 // since some of them have spaces?!?!
254 $p->email = trim($p->email);
257 require_once 'Validate.php';
258 if (!Validate::email($p->email, true)) {
259 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
261 $w->sent = date('Y-m-d H:i:s');
263 $w->event_id = $ev->id;
265 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
270 $ff = HTML_FlexyFramework::get();
273 $dom = array_pop(explode('@', $p->email));
275 $mxs = $this->mxs($dom);
278 // we might fail doing this...
279 // need to handle temporary failure..
282 // we try for 3 days..
284 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
285 // older that 1 hour.
289 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
293 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
298 if ($mxs === false) {
299 // only retry for 2 day son the MX issue..
301 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
302 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
304 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED\n");
307 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
308 $w->sent = date('Y-m-d H:i:s');
310 $w->event_id = $ev->id;
312 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
320 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
321 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
322 $w->sent = date('Y-m-d H:i:s');
324 $w->event_id = $ev->id;
326 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
331 $w->to_email = $p->email;
332 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
333 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
339 require_once 'Mail.php';
341 foreach($mxs as $dom) {
345 if (!isset($ff->Mail['helo'])) {
346 $this->errorHandler("config Mail[helo] is not set");
348 $this->debug_str = '';
349 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
350 $mailer = Mail::factory('smtp', array(
352 'localhost' => $ff->Mail['helo'],
354 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
355 //'debug' => isset($opts['debug']) ? 1 : 0,
357 'debug_handler' => array($this, 'debugHandler')
359 $res = $mailer->send($p->email, $email['headers'], $email['body']);
365 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
367 $ev->writeEventLog($this->debug_str);
369 $w->sent = date('Y-m-d H:i:s');
370 $w->msgid = $email['headers']['Message-Id'];
371 $w->event_id = $ev->id; // sent ok.. - no need to record it..
374 // enable cc in notify..
375 if (!empty($email['headers']['Cc'])) {
376 $mailer = Mail::factory('smtp', array(
380 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
381 $mailer->send($email['headers']['Cc'],
382 $email['headers'], $email['body']);
386 if (!empty($email['bcc'])) {
387 $mailer = Mail::factory('smtp', array(
391 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
392 $mailer->send($email['bcc'],
393 $email['headers'], $email['body']);
398 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT\n");
400 // what type of error..
401 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
402 if (!empty($res->code) && $res->code == 10001) {
403 // fake greylist if timed out.
408 $this->debug($res->message);
409 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
411 // give up after 2 days..
412 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
414 // check last event for this item..
415 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
416 if (isset($res->userinfo['smtptext'])) {
417 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
420 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
421 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
423 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED\n");
428 if ($fail || $next_try_min > (2*24*60)) {
429 // fail.. = log and give up..
430 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
431 if (isset($res->userinfo['smtptext'])) {
432 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
435 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
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 - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
444 // handle no host availalbe forever...
445 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
446 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
447 $w->sent = date('Y-m-d H:i:s');
449 $w->event_id = $ev->id;
451 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
457 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
458 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
460 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
466 $ff = HTML_FlexyFramework::get();
467 if (isset($ff->Pman_Core_NotifySend['host'])) {
468 return array($ff->Pman_Core_NotifySend['host']);
471 $mx_records = array();
472 $mx_weight = array();
474 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
475 if (!checkdnsrr($fqdn)) {
481 asort($mx_weight,SORT_NUMERIC);
483 foreach($mx_weight as $k => $weight) {
484 $mxs[] = $mx_records[$k];
490 * wrapper to call object->toEmail()
494 headers : {AssocArray},
498 error : {String} // error message in log.
499 send-to: {String} // use to override rcpt
503 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
505 $m = 'notify'. $notify->evtype;
506 //var_dump(get_class($object) . '::' .$m);
507 if (!empty($notify->evtype) && method_exists($object,$m)) {
508 echo "calling :" . get_class($object) . '::' .$m . "\n";
509 return $object->$m($rcpt, $last_sent_date, $notify, $force);
512 $type = explode('::', $notify->evtype);
514 if(!empty($type[1]) && method_exists($object,$type[1])){
516 echo "calling :" . get_class($object) . '::' .$m . "\n";
517 return $object->$m($rcpt, $last_sent_date, $notify, $force);
520 if (!method_exists($object, 'toEmail')) {
525 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
530 if (empty($this->cli_args['debug'])) {
538 $this->errorHandler("done\n");
542 function debugHandler ($smtp, $message)
544 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
545 $this->debug_str .= $message;
548 function errorHandler($msg)
550 if(empty($this->remote)){