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';
73 $ff = HTML_FlexyFramework::get();
77 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
82 function get($id,$opts)
86 if ($opts['DB_DataObject-debug']) {
87 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
89 //DB_DataObject::debugLevel(1);
90 //date_default_timezone_set('UTC');
92 $force = empty($opts['force']) ? 0 : 1;
94 $w = DB_DataObject::factory($this->table);
99 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
102 die("send repeat to early\n");
104 if (!empty($opts['debug'])) {
108 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
110 if (!$force && (!empty($w->msgid) || $sent)) {
113 $w->sent = $w->sqlValue("NOW()");
116 die("message has been sent already.\n");
123 $ev = $this->addEvent('NOTIFY', $w,
124 "Notification event cleared (underlying object does not exist)" );;
126 $w->sent = date('Y-m-d H:i:s');
128 $w->event_id = $ev->id;
130 die(date('Y-m-d h:i:s ') .
131 "Notification event cleared (underlying object does not exist)"
139 if (isset($p->active) && empty($p->active)) {
140 $ev = $this->addEvent('NOTIFY', $w,
141 "Notification event cleared (not user not active any more)" );;
143 $w->sent = date('Y-m-d H:i:s');
145 $w->event_id = $ev->id;
147 die(date('Y-m-d h:i:s ') .
148 "Notification event cleared (not user not active any more)"
150 die("message has been sent already.\n");
154 // let's work out the last notification sent to this user..
155 $l = DB_DataObject::factory($this->table);
157 'ontable' => $w->ontable,
159 'person_id' => $w->person_id,
161 $l->whereAdd('id != '. $w->id);
162 $l->orderBy('sent DESC');
164 $ar = $l->fetchAll('sent');
165 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
168 $ev = DB_DataObject::factory('Events');
169 $ev->on_id = $w->id; // int(11)
170 $ev->on_table = $this->table;
172 $ev->orderBy('event_when DESC');
173 $ar = $ev->fetchAll('event_when');
174 $last_event = empty($ar) ? 0 : $ar[0];
177 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
179 $next_try = $next_try_min . ' MINUTES';
181 // this may modify $p->email. (it will not update it though)
182 $email = $this->makeEmail($o, $p, $last, $w, $force);
184 if ($email === true) {
186 $ev = $this->addEvent('NOTIFY', $w,
187 "Notification event cleared (not required any more)" );;
189 $w->sent = date('Y-m-d H:i:s');
191 $w->event_id = $ev->id;
193 die(date('Y-m-d h:i:s ') .
194 "Notification event cleared (not required any more)"
200 if ($email === false || isset($email['error'])) {
201 // object returned 'false' - it does not know how to send it..
202 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
203 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
205 $w->sent = date('Y-m-d H:i:s');
207 $w->event_id = $ev->id;
209 die(date('Y-m-d h:i:s ') .
210 (isset($email['error']) ?
211 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
216 if (isset($email['later'])) {
218 $w->act_when = $email['later'];
220 die(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
224 if (empty($email['headers']['Message-Id'])) {
225 $HOST = gethostname();
226 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
229 //$p->email = 'alan@akbkhome.com'; //for testing..
230 //print_r($email);exit;
231 // should we fetch the watch that caused it.. - which should contain the method to call..
232 // --send-to=test@xxx.com
234 if (!empty($email['send-to'])) {
235 $p->email = $email['send-to'];
237 if (!empty($opts['send-to'])) {
238 $p->email = $opts['send-to'];
240 // since some of them have spaces?!?!
241 $p->email = trim($p->email);
244 require_once 'Validate.php';
245 if (!Validate::email($p->email, true)) {
246 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
248 $w->sent = date('Y-m-d H:i:s');
250 $w->event_id = $ev->id;
252 die(date('Y-m-d h:i:s ') . "INVALID ADDRESS1: " . $p->email. "\n");
257 $ff = HTML_FlexyFramework::get();
260 $dom = array_pop(explode('@', $p->email));
262 $mxs = $this->mxs($dom);
265 // we might fail doing this...
266 // need to handle temporary failure..
269 // we try for 3 days..
271 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
272 // older that 1 hour.
276 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
280 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
285 if ($mxs === false) {
286 // only retry for 2 day son the MX issue..
288 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom . ' ' . $res->toString());
289 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
291 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
294 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
295 $w->sent = date('Y-m-d H:i:s');
297 $w->event_id = $ev->id;
299 die(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
307 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
308 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
309 $w->sent = date('Y-m-d H:i:s');
311 $w->event_id = $ev->id;
313 die(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
318 $w->to_email = $p->email;
319 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
320 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
326 require_once 'Mail.php';
328 foreach($mxs as $dom) {
332 if (!isset($ff->Mail['helo'])) {
333 die("config Mail[helo] is not set");
335 $this->debug_str = '';
336 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
337 $mailer = Mail::factory('smtp', array(
339 'localhost' => $ff->Mail['helo'],
341 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
342 //'debug' => isset($opts['debug']) ? 1 : 0,
344 'debug_handler' => array($this, 'debugHandler')
346 $res = $mailer->send($p->email, $email['headers'], $email['body']);
352 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
354 $ev->writeEventLog($this->debug_str);
356 $w->sent = date('Y-m-d H:i:s');
357 $w->msgid = $email['headers']['Message-Id'];
358 $w->event_id = $ev->id; // sent ok.. - no need to record it..
361 // enable cc in notify..
362 if (!empty($email['headers']['Cc'])) {
363 $mailer = Mail::factory('smtp', array(
367 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
368 $mailer->send($email['headers']['Cc'],
369 $email['headers'], $email['body']);
373 if (!empty($email['bcc'])) {
374 $mailer = Mail::factory('smtp', array(
378 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
379 $mailer->send($email['bcc'],
380 $email['headers'], $email['body']);
385 die(date('Y-m-d h:i:s') . " - SENT\n");
387 // what type of error..
388 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
389 if (!empty($res->code) && $res->code == 10001) {
390 // fake greylist if timed out.
395 $this->debug($res->message);
396 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
398 // give up after 2 days..
399 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
401 // check last event for this item..
402 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
403 if (isset($res->userinfo['smtptext'])) {
404 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
407 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
408 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
410 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
415 if ($fail || $next_try_min > (2*24*60)) {
416 // fail.. = log and give up..
417 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
418 if (isset($res->userinfo['smtptext'])) {
419 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
422 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
424 $w->sent = date('Y-m-d H:i:s');
426 $w->event_id = $ev->id;
428 die(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
431 // handle no host availalbe forever...
432 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
433 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
434 $w->sent = date('Y-m-d H:i:s');
436 $w->event_id = $ev->id;
438 die(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
444 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
445 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
447 die(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
453 $ff = HTML_FlexyFramework::get();
454 if (isset($ff->Pman_Core_NotifySend['host'])) {
455 return array($ff->Pman_Core_NotifySend['host']);
458 $mx_records = array();
459 $mx_weight = array();
461 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
462 if (!checkdnsrr($fqdn)) {
468 asort($mx_weight,SORT_NUMERIC);
470 foreach($mx_weight as $k => $weight) {
471 $mxs[] = $mx_records[$k];
477 * wrapper to call object->toEmail()
481 headers : {AssocArray},
485 error : {String} // error message in log.
486 send-to: {String} // use to override rcpt
490 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
492 $m = 'notify'. $notify->evtype;
493 //var_dump(get_class($object) . '::' .$m);
494 if (!empty($notify->evtype) && method_exists($object,$m)) {
495 echo "calling :" . get_class($object) . '::' .$m . "\n";
496 return $object->$m($rcpt, $last_sent_date, $notify, $force);
499 $type = explode('::', $notify->evtype);
501 if(!empty($type[1]) && method_exists($object,$type[1])){
503 echo "calling :" . get_class($object) . '::' .$m . "\n";
504 return $object->$m($rcpt, $last_sent_date, $notify, $force);
507 if (!method_exists($object, 'toEmail')) {
512 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
517 if (empty($this->cli_args['debug'])) {
529 function debugHandler ($smtp, $message)
531 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
532 $this->debug_str .= $message;