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
26 class Pman_Core_NotifySend extends Pman
28 static $cli_desc = "Send out single notification email (usually called from Core/Notify)";
30 static $cli_opts = array(
32 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
39 'DB_DataObject-debug' => array(
40 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
48 'desc' => 'Force redelivery, even if it has been sent before or not queued...',
55 'desc' => 'Send the message to this address, rather than the one listed.',
65 var $table = 'core_notify';
68 $ff = HTML_FlexyFramework::get();
72 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
77 function get($id,$opts)
81 if ($opts['DB_DataObject-debug']) {
82 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
84 //DB_DataObject::debugLevel(1);
85 //date_default_timezone_set('UTC');
87 $force = empty($opts['force']) ? 0 : 1;
89 $w = DB_DataObject::factory($this->table);
94 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
97 die("send repeat to early\n");
99 if (!empty($opts['debug'])) {
103 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
105 if (!$force && (!empty($w->msgid) || $sent)) {
108 $w->sent = $w->sqlValue("NOW()");
111 die("message has been sent already.\n");
118 $ev = $this->addEvent('NOTIFY', $w,
119 "Notification event cleared (underlying object does not exist)" );;
121 $w->sent = date('Y-m-d H:i:s');
123 $w->event_id = $ev->id;
125 die(date('Y-m-d h:i:s ') .
126 "Notification event cleared (underlying object does not exist)"
134 if (isset($p->active) && empty($p->active)) {
135 $ev = $this->addEvent('NOTIFY', $w,
136 "Notification event cleared (not user not active any more)" );;
138 $w->sent = date('Y-m-d H:i:s');
140 $w->event_id = $ev->id;
142 die(date('Y-m-d h:i:s ') .
143 "Notification event cleared (not user not active any more)"
145 die("message has been sent already.\n");
149 // let's work out the last notification sent to this user..
150 $l = DB_DataObject::factory($this->table);
152 'ontable' => $w->ontable,
154 'person_id' => $w->person_id,
156 $l->whereAdd('id != '. $w->id);
157 $l->orderBy('sent DESC');
159 $ar = $l->fetchAll('sent');
160 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
163 $ev = DB_DataObject::factory('Events');
164 $ev->on_id = $w->id; // int(11)
165 $ev->on_table = $this->table;
167 $ev->orderBy('event_when DESC');
168 $ar = $ev->fetchAll('event_when');
169 $last_event = empty($ar) ? 0 : $ar[0];
172 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
174 $next_try = $next_try_min . ' MINUTES';
176 // this may modify $p->email. (it will not update it though)
177 $email = $this->makeEmail($o, $p, $last, $w, $force);
179 if ($email === true) {
181 $ev = $this->addEvent('NOTIFY', $w,
182 "Notification event cleared (not required any more)" );;
184 $w->sent = date('Y-m-d H:i:s');
186 $w->event_id = $ev->id;
188 die(date('Y-m-d h:i:s ') .
189 "Notification event cleared (not required any more)"
195 if ($email === false || isset($email['error'])) {
196 // object returned 'false' - it does not know how to send it..
197 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
198 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
200 $w->sent = date('Y-m-d H:i:s');
202 $w->event_id = $ev->id;
204 die(date('Y-m-d h:i:s ') .
205 (isset($email['error']) ?
206 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
211 if (isset($email['later'])) {
213 $w->act_when = $email['later'];
215 die(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
219 if (empty($email['headers']['Message-Id'])) {
220 $HOST = gethostname();
221 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
224 //$p->email = 'alan@akbkhome.com'; //for testing..
225 //print_r($email);exit;
226 // should we fetch the watch that caused it.. - which should contain the method to call..
227 // --send-to=test@xxx.com
229 if (!empty($email['send-to'])) {
230 $p->email = $email['send-to'];
232 if (!empty($opts['send-to'])) {
233 $p->email = $opts['send-to'];
235 // since some of them have spaces?!?!
236 $p->email = trim($p->email);
239 require_once 'Validate.php';
240 if (!Validate::email($p->email, true)) {
241 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
243 $w->sent = date('Y-m-d H:i:s');
245 $w->event_id = $ev->id;
247 die(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
252 $ff = HTML_FlexyFramework::get();
255 $dom = array_pop(explode('@', $p->email));
257 $mxs = $this->mxs($dom);
260 // we might fail doing this...
261 // need to handle temporary failure..
264 // we try for 3 days..
266 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
267 // older that 1 hour.
271 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
275 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
280 if ($mxs === false) {
281 // only retry for 2 day son the MX issue..
283 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom . ' ' . $res->toString());
284 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
286 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
289 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
290 $w->sent = date('Y-m-d H:i:s');
292 $w->event_id = $ev->id;
294 die(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
302 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
303 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
304 $w->sent = date('Y-m-d H:i:s');
306 $w->event_id = $ev->id;
308 die(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
313 $w->to_email = $p->email;
314 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
315 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
321 require_once 'Mail.php';
323 foreach($mxs as $dom) {
327 if (!isset($ff->Mail['helo'])) {
328 die("config Mail[helo] is not set");
330 $this->debug_str = '';
331 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
332 $mailer = Mail::factory('smtp', array(
334 'localhost' => $ff->Mail['helo'],
336 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
337 //'debug' => isset($opts['debug']) ? 1 : 0,
339 'debug_handler' => array($this, 'debugHandler')
341 $res = $mailer->send($p->email, $email['headers'], $email['body']);
347 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
349 $ev->writeEventLog($this->debug_str);
351 $w->sent = date('Y-m-d H:i:s');
352 $w->msgid = $email['headers']['Message-Id'];
353 $w->event_id = $ev->id; // sent ok.. - no need to record it..
356 // enable cc in notify..
357 if (!empty($email['headers']['Cc'])) {
358 $mailer = Mail::factory('smtp', array(
362 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
363 $mailer->send($email['headers']['Cc'],
364 $email['headers'], $email['body']);
368 if (!empty($email['bcc'])) {
369 $mailer = Mail::factory('smtp', array(
373 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
374 $mailer->send($email['bcc'],
375 $email['headers'], $email['body']);
380 die(date('Y-m-d h:i:s') . " - SENT\n");
382 // what type of error..
383 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
384 if (!empty($res->code) && $res->code == 10001) {
385 // fake greylist if timed out.
390 $this->debug($res->message);
391 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
393 // give up after 2 days..
394 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
396 // check last event for this item..
397 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
398 if (isset($res->userinfo['smtptext'])) {
399 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
402 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
403 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
405 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
410 if ($fail || $next_try_min > (2*24*60)) {
411 // fail.. = log and give up..
412 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
413 if (isset($res->userinfo['smtptext'])) {
414 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
417 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
419 $w->sent = date('Y-m-d H:i:s');
421 $w->event_id = $ev->id;
423 die(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
426 // handle no host availalbe forever...
427 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
428 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
429 $w->sent = date('Y-m-d H:i:s');
431 $w->event_id = $ev->id;
433 die(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
439 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
440 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
442 die(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
448 $mx_records = array();
449 $mx_weight = array();
451 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
452 if (!checkdnsrr($fqdn)) {
458 asort($mx_weight,SORT_NUMERIC);
460 foreach($mx_weight as $k => $weight) {
461 $mxs[] = $mx_records[$k];
467 * wrapper to call object->toEmail()
471 headers : {AssocArray},
475 error : {String} // error message in log.
476 send-to: {String} // use to override rcpt
480 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
482 $m = 'notify'. $notify->evtype;
483 //var_dump(get_class($object) . '::' .$m);
484 if (!empty($notify->evtype) && method_exists($object,$m)) {
485 echo "calling :" . get_class($object) . '::' .$m . "\n";
486 return $object->$m($rcpt, $last_sent_date, $notify, $force);
489 $type = explode('::', $notify->evtype);
491 if(!empty($type[1]) && method_exists($object,$type[1])){
493 echo "calling :" . get_class($object) . '::' .$m . "\n";
494 return $object->$m($rcpt, $last_sent_date, $notify, $force);
497 if (!method_exists($object, 'toEmail')) {
502 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
507 if (empty($this->cli_args['debug'])) {
519 function debugHandler ($smtp, $message)
521 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
522 $this->debug_str .= $message;