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);
161 'ontable' => $w->ontable,
164 $lar[strtolower($w->person_table).'_id'] = $w->{strtolower($w->person_table).'_id'};
167 $l->whereAdd('id != '. $w->id);
168 $l->orderBy('sent DESC');
170 $ar = $l->fetchAll('sent');
171 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
174 $ev = DB_DataObject::factory('Events');
175 $ev->on_id = $w->id; // int(11)
176 $ev->on_table = $this->table;
178 $ev->orderBy('event_when DESC');
179 $ar = $ev->fetchAll('event_when');
180 $last_event = empty($ar) ? 0 : $ar[0];
183 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
185 $next_try = $next_try_min . ' MINUTES';
187 // this may modify $p->email. (it will not update it though)
188 $email = $this->makeEmail($o, $p, $last, $w, $force);
190 if ($email === true) {
192 $ev = $this->addEvent('NOTIFY', $w,
193 "Notification event cleared (not required any more)" );;
195 $w->sent = date('Y-m-d H:i:s');
197 $w->event_id = $ev->id;
199 $this->errorHandler(date('Y-m-d h:i:s ') .
200 "Notification event cleared (not required any more)"
206 if ($email === false || isset($email['error'])) {
207 // object returned 'false' - it does not know how to send it..
208 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
209 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
211 $w->sent = date('Y-m-d H:i:s');
213 $w->event_id = $ev->id;
215 $this->errorHandler(date('Y-m-d h:i:s ') .
216 (isset($email['error']) ?
217 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
222 if (isset($email['later'])) {
224 $w->act_when = $email['later'];
226 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
230 if (empty($email['headers']['Message-Id'])) {
231 $HOST = gethostname();
232 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
235 //$p->email = 'alan@akbkhome.com'; //for testing..
236 //print_r($email);exit;
237 // should we fetch the watch that caused it.. - which should contain the method to call..
238 // --send-to=test@xxx.com
240 if (!empty($email['send-to'])) {
241 $p->email = $email['send-to'];
243 if (!empty($opts['send-to'])) {
244 $p->email = $opts['send-to'];
246 // since some of them have spaces?!?!
247 $p->email = trim($p->email);
249 require_once 'Validate.php';
250 if (!Validate::email($p->email, true)) {
251 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
253 $w->sent = date('Y-m-d H:i:s');
255 $w->event_id = $ev->id;
257 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
262 $ff = HTML_FlexyFramework::get();
265 $dom = array_pop(explode('@', $p->email));
267 $mxs = $this->mxs($dom);
270 // we might fail doing this...
271 // need to handle temporary failure..
274 // we try for 3 days..
276 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
277 // older that 1 hour.
281 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
285 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
290 if ($mxs === false) {
291 // only retry for 2 day son the MX issue..
293 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
294 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
296 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
299 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
300 $w->sent = date('Y-m-d H:i:s');
302 $w->event_id = $ev->id;
304 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
312 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
313 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
314 $w->sent = date('Y-m-d H:i:s');
316 $w->event_id = $ev->id;
318 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
323 $w->to_email = $p->email;
324 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
325 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
331 require_once 'Mail.php';
333 foreach($mxs as $dom) {
337 if (!isset($ff->Mail['helo'])) {
338 $this->errorHandler("config Mail[helo] is not set");
340 $this->debug_str = '';
341 $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
342 $mailer = Mail::factory('smtp', array(
344 'localhost' => $ff->Mail['helo'],
346 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
347 //'debug' => isset($opts['debug']) ? 1 : 0,
349 'debug_handler' => array($this, 'debugHandler')
351 $res = $mailer->send($p->email, $email['headers'], $email['body']);
357 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
359 $ev->writeEventLog($this->debug_str);
361 $w->sent = date('Y-m-d H:i:s');
362 $w->msgid = $email['headers']['Message-Id'];
363 $w->event_id = $ev->id; // sent ok.. - no need to record it..
366 // enable cc in notify..
367 if (!empty($email['headers']['Cc'])) {
368 $cmailer = Mail::factory('smtp', array(
372 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
373 $cmailer->send($email['headers']['Cc'],
374 $email['headers'], $email['body']);
378 if (!empty($email['bcc'])) {
379 $cmailer = Mail::factory('smtp', array(
383 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
384 $cmailer->send($email['bcc'],
385 $email['headers'], $email['body']);
390 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT\n");
392 // what type of error..
393 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
394 if (!empty($res->code) && $res->code == 10001) {
395 // fake greylist if timed out.
400 $this->debug($res->message);
401 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
403 // give up after 2 days..
404 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
406 // check last event for this item..
407 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
408 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
409 if (!empty($res->userinfo['smtptext'])) {
410 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
413 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
414 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
418 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
423 if ($fail || $next_try_min > (2*24*60)) {
424 // fail.. = log and give up..
425 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
426 if (isset($res->userinfo['smtptext'])) {
427 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
430 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
432 $w->sent = date('Y-m-d H:i:s');
434 $w->event_id = $ev->id;
436 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
439 // handle no host availalbe forever...
440 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
441 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
442 $w->sent = date('Y-m-d H:i:s');
444 $w->event_id = $ev->id;
446 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
452 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
453 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
455 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
461 $ff = HTML_FlexyFramework::get();
462 if (isset($ff->Pman_Core_NotifySend['host'])) {
463 return array($ff->Pman_Core_NotifySend['host']);
466 $mx_records = array();
467 $mx_weight = array();
469 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
470 if (!checkdnsrr($fqdn)) {
476 asort($mx_weight,SORT_NUMERIC);
478 foreach($mx_weight as $k => $weight) {
479 $mxs[] = $mx_records[$k];
485 * wrapper to call object->toEmail()
489 headers : {AssocArray},
493 error : {String} // error message in log.
494 send-to: {String} // use to override rcpt
498 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
500 $m = 'notify'. $notify->evtype;
501 //var_dump(get_class($object) . '::' .$m);
502 if (!empty($notify->evtype) && method_exists($object,$m)) {
503 echo "calling :" . get_class($object) . '::' .$m . "\n";
504 return $object->$m($rcpt, $last_sent_date, $notify, $force);
507 $type = explode('::', $notify->evtype);
509 if(!empty($type[1]) && method_exists($object,$type[1])){
511 echo "calling :" . get_class($object) . '::' .$m . "\n";
512 return $object->$m($rcpt, $last_sent_date, $notify, $force);
515 if (!method_exists($object, 'toEmail')) {
520 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
525 if (empty($this->cli_args['debug'])) {
533 $this->errorHandler("done\n");
537 function debugHandler ($smtp, $message)
539 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
540 $this->debug_str .= $message;
543 function errorHandler($msg)
545 if($this->error_handler == 'exception'){
546 throw new Exception($msg);