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.
29 class Pman_Core_NotifySend_Exception_Success extends Exception {}
30 class Pman_Core_NotifySend_Exception_Fail extends Exception {}
33 class Pman_Core_NotifySend extends Pman
35 static $cli_desc = "Send out single notification email (usually called from Core/Notify)";
37 static $cli_opts = array(
39 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
46 'DB_DataObject-debug' => array(
47 'desc' => 'Turn on debugging (see DataObjects debugLevel )',
55 'desc' => 'Force redelivery, even if it has been sent before or not queued...',
62 'desc' => 'Send the message to this address, rather than the one listed.',
72 var $table = 'core_notify';
73 var $error_handler = 'die';
77 $ff = HTML_FlexyFramework::get();
79 $this->errorHandler("access denied");
81 //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
86 function get($id,$opts=array())
90 if (!empty($opts['DB_DataObject-debug'])) {
91 DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
94 //DB_DataObject::debugLevel(1);
95 //date_default_timezone_set('UTC');
97 $force = empty($opts['force']) ? 0 : 1;
99 $w = DB_DataObject::factory($this->table);
102 $this->errorHandler("invalid id\n");
105 if (!$force && !empty($w->sent) && strtotime($w->act_when) < strtotime($w->sent)) {
108 $this->errorHandler("send repeat to early\n");
110 if (!empty($opts['debug'])) {
112 $ff = HTML_FlexyFramework::get();
113 if (!isset($ff->Core_Mailer)) {
114 $ff->Core_Mailer = array();
116 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
119 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
121 if (!$force && (!empty($w->msgid) || $sent)) {
124 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
127 $this->errorHandler("message has been sent already.\n");
134 $ev = $this->addEvent('NOTIFY', $w,
135 "Notification event cleared (underlying object does not exist)" );;
137 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
139 $w->event_id = $ev->id;
141 $this->errorHandler(date('Y-m-d h:i:s ') .
142 "Notification event cleared (underlying object does not exist)"
150 if (isset($p->active) && empty($p->active)) {
151 $ev = $this->addEvent('NOTIFY', $w,
152 "Notification event cleared (not user not active any more)" );;
154 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
156 $w->event_id = $ev->id;
158 $this->errorHandler(date('Y-m-d h:i:s ') .
159 "Notification event cleared (not user not active any more)"
161 $this->errorHandler("message has been sent already.\n");
165 // let's work out the last notification sent to this user..
166 $l = DB_DataObject::factory($this->table);
169 'ontable' => $w->ontable,
172 // only newer version of the database us this..
173 if (isset($w->person_table)) {
174 $personid_col = strtolower($w->person_table).'_id';
175 if (isset($w->{$personid_col})) {
176 $lar[$personid_col] = $w->{$personid_col};
182 $l->whereAdd('id != '. $w->id);
183 $l->orderBy('sent DESC');
185 $ar = $l->fetchAll('sent');
186 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
189 $ev = DB_DataObject::factory('Events');
190 $ev->on_id = $w->id; // int(11)
191 $ev->on_table = $this->table;
193 $ev->orderBy('event_when DESC');
194 $ar = $ev->fetchAll('event_when');
195 $last_event = empty($ar) ? 0 : $ar[0];
198 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
200 $next_try = $next_try_min . ' MINUTES';
202 // this may modify $p->email. (it will not update it though)
203 $email = $this->makeEmail($o, $p, $last, $w, $force);
205 if ($email === true) {
207 $ev = $this->addEvent('NOTIFY', $w,
208 "Notification event cleared (not required any more)" );;
210 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
212 $w->event_id = $ev->id;
214 $this->errorHandler(date('Y-m-d h:i:s ') .
215 "Notification event cleared (not required any more)"
218 if (is_a($email, 'PEAR_Error')) {
220 'error' => $email->toString()
224 if (empty($p) && !empty($email['recipients'])) {
225 // make a fake person..
227 'email' => $email['recipients']
231 if ($email === false || isset($email['error']) || empty($p)) {
232 // object returned 'false' - it does not know how to send it..
233 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ?
234 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
236 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
238 $w->event_id = $ev->id;
240 $this->errorHandler(date('Y-m-d h:i:s ') .
241 (isset($email['error']) ?
242 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
247 if (isset($email['later'])) {
249 $w->act_when = $email['later'];
251 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
255 if (empty($email['headers']['Message-Id'])) {
256 $HOST = gethostname();
257 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
264 //$p->email = 'alan@akbkhome.com'; //for testing..
265 //print_r($email);exit;
266 // should we fetch the watch that caused it.. - which should contain the method to call..
267 // --send-to=test@xxx.com
269 if (!empty($email['send-to'])) {
270 $p->email = $email['send-to'];
272 if (!empty($opts['send-to'])) {
273 $p->email = $opts['send-to'];
276 // since some of them have spaces?!?!
277 $p->email = trim($p->email);
280 require_once 'Validate.php';
281 if (!Validate::email($p->email, true)) {
282 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
284 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
286 $w->event_id = $ev->id;
288 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
293 $ff = HTML_FlexyFramework::get();
295 $explode_email = explode('@', $p->email);
296 $dom = array_pop($explode_email);
298 $mxs = $this->mxs($dom);
301 // we might fail doing this...
302 // need to handle temporary failure..
305 // we try for 3 days..
307 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
308 // older that 1 hour.
312 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
316 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
321 if ($mxs === false) {
322 // only retry for 2 day son the MX issue..
324 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
325 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
327 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
330 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
331 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
333 $w->event_id = $ev->id;
335 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
343 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
344 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
345 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
347 $w->event_id = $ev->id;
349 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
354 $w->to_email = $p->email;
355 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
356 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
357 $w->act_when = (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')) : $w->act_when;
363 require_once 'Mail.php';
365 $core_domain = DB_DataObject::factory('core_domain');
366 if(!$core_domain->get('domain', $dom)){
367 $core_domain = DB_DataObject::factory('core_domain');
368 $core_domain->setFrom(array(
371 $core_domain->insert();
374 foreach($mxs as $mx) {
376 if (!isset($ff->Mail['helo'])) {
377 $this->errorHandler("config Mail[helo] is not set");
379 $this->debug_str = '';
380 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
381 $mailer = Mail::factory('smtp', array(
383 'localhost' => $ff->Mail['helo'],
385 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
386 //'debug' => isset($opts['debug']) ? 1 : 0,
388 'debug_handler' => array($this, 'debugHandler')
391 // if the host is the mail host + it's authenticated add auth details
392 // this normally will happen if you sent Pman_Core_NotifySend['host']
395 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
397 $mailer->auth = true;
398 $mailer->username = $ff->Mail['username'];
399 $mailer->password = $ff->Mail['password'];
402 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
404 // we might want to regex 'office365 as a mx host
405 foreach ($ff->Core_Notify['routes'] as $server => $settings){
406 if(!in_array($dom, $settings['domains'])){
410 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
411 // if it's newer that '1' minute...
414 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
416 $seconds = floor((60 * 60) / $settings['rate']);
418 $core_notify = DB_DataObject::factory($this->table);
419 $core_notify->domain_id = $core_domain->id;
420 $core_notify->whereAdd("
421 sent >= NOW() - INTERVAL $seconds SECOND
424 if($core_notify->count()){
426 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
428 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
433 $mailer->host = $server;
434 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
435 $mailer->username = $settings['username'];
436 $mailer->password = $settings['password'];
437 if (isset($settings['port'])) {
438 $mailer->port = $settings['port'];
440 if (isset($settings['socket_options'])) {
441 $mailer->socket_options = $settings['socket_options'];
452 $res = $mailer->send($p->email, $email['headers'], $email['body']);
458 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
460 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
462 $ev->writeEventLog($this->debug_str);
464 if(strtotime($w->act_when) > strtotime("NOW")){
465 $w->act_when = date('Y-m-d H:i:s');
468 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
469 $w->msgid = $email['headers']['Message-Id'];
470 $w->event_id = $ev->id; // sent ok.. - no need to record it..
471 $w->domain_id = $core_domain->id;
474 // enable cc in notify..
475 if (!empty($email['headers']['Cc'])) {
476 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
477 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
478 $cmailer->send($email['headers']['Cc'],
479 $email['headers'], $email['body']);
483 if (!empty($email['bcc'])) {
484 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
485 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
486 $res = $cmailer->send($email['bcc'],
487 $email['headers'], $email['body']);
488 if (!$res || is_a($res, 'PEAR_Error')) {
489 echo "could not send bcc..\n";
491 echo "Sent BCC to {$email['bcc']}\n";
496 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
498 // what type of error..
499 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
500 if (!empty($res->code) && $res->code == 10001) {
501 // fake greylist if timed out.
506 $this->debug($res->message);
507 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
509 // give up after 2 days..
510 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
512 // check last event for this item..
513 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
514 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
515 if (!empty($res->userinfo['smtptext'])) {
516 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
519 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
520 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
521 $w->domain_id = $core_domain->id;
525 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
530 if ($fail || $next_try_min > (2*24*60)) {
531 // fail.. = log and give up..
532 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
533 if (isset($res->userinfo['smtptext'])) {
534 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
537 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
539 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
541 $w->event_id = $ev->id;
542 $w->domain_id = $core_domain->id;
544 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
547 // handle no host availalbe forever...
548 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
549 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
550 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
552 $w->event_id = $ev->id;
553 $w->domain_id = $core_domain->id;
555 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
559 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
560 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
561 $w->domain_id = $core_domain->id;
563 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
569 $ff = HTML_FlexyFramework::get();
570 if (isset($ff->Pman_Core_NotifySend['host'])) {
571 return array($ff->Pman_Core_NotifySend['host']);
574 $mx_records = array();
575 $mx_weight = array();
577 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
578 if (!checkdnsrr($fqdn)) {
584 asort($mx_weight,SORT_NUMERIC);
586 foreach($mx_weight as $k => $weight) {
587 $mxs[] = $mx_records[$k];
593 * wrapper to call object->toEmail()
597 headers : {AssocArray},
601 error : {String} // error message in log.
602 send-to: {String} // use to override rcpt
606 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
608 $m = 'notify'. $notify->evtype;
609 //var_dump(get_class($object) . '::' .$m);
610 if (!empty($notify->evtype) && method_exists($object,$m)) {
611 echo "calling :" . get_class($object) . '::' .$m . "\n";
612 return $object->$m($rcpt, $last_sent_date, $notify, $force);
615 $type = explode('::', $notify->evtype);
617 if(!empty($type[1]) && method_exists($object,$type[1])){
619 echo "calling :" . get_class($object) . '::' .$m . "\n";
620 return $object->$m($rcpt, $last_sent_date, $notify, $force);
623 if (method_exists($object, 'toMailerData')) {
624 return $object->toMailerData(array(
626 'person'=>$rcpt, // added as mediaoutreach used this?
627 )); //this is core_email - i think it's only used for testing...
632 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
637 if (empty($this->cli_args['debug'])) {
645 $this->errorHandler("done\n");
649 function debugHandler ($smtp, $message)
651 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
652 $this->debug_str .= $message;
653 //echo $message ."\n";
656 function errorHandler($msg, $success = false)
658 if($this->error_handler == 'exception'){
660 throw new Pman_Core_NotifySend_Exception_Success($msg);
663 throw new Pman_Core_NotifySend_Exception_Fail($msg);