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;
239 $w->to_email = $p->email;
241 $this->errorHandler(date('Y-m-d h:i:s ') .
242 (isset($email['error']) ?
243 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
248 if (isset($email['later'])) {
250 $w->act_when = $email['later'];
252 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
256 if (empty($email['headers']['Message-Id'])) {
257 $HOST = gethostname();
258 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
265 //$p->email = 'alan@akbkhome.com'; //for testing..
266 //print_r($email);exit;
267 // should we fetch the watch that caused it.. - which should contain the method to call..
268 // --send-to=test@xxx.com
270 if (!empty($email['send-to'])) {
271 $p->email = $email['send-to'];
273 if (!empty($opts['send-to'])) {
274 $p->email = $opts['send-to'];
277 // since some of them have spaces?!?!
278 $p->email = trim($p->email);
281 require_once 'Validate.php';
282 if (!Validate::email($p->email, true)) {
283 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
285 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
287 $w->event_id = $ev->id;
288 $w->to_email = $p->email;
290 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
295 $ff = HTML_FlexyFramework::get();
297 $explode_email = explode('@', $p->email);
298 $dom = array_pop($explode_email);
300 $mxs = $this->mxs($dom);
303 // we might fail doing this...
304 // need to handle temporary failure..
307 // we try for 3 days..
309 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
310 // older that 1 hour.
314 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
318 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
323 if ($mxs === false) {
324 // only retry for 2 day son the MX issue..
326 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
327 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
329 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
332 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
333 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
335 $w->event_id = $ev->id;
336 $w->to_email = $p->email;
338 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
346 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
347 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
348 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
350 $w->event_id = $ev->id;
351 $w->to_email = $p->email;
353 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
358 $w->to_email = $p->email;
359 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
360 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
361 $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;
367 require_once 'Mail.php';
369 $core_domain = DB_DataObject::factory('core_domain');
370 if(!$core_domain->get('domain', $dom)){
371 $core_domain = DB_DataObject::factory('core_domain');
372 $core_domain->setFrom(array(
375 $core_domain->insert();
378 foreach($mxs as $mx) {
380 if (!isset($ff->Mail['helo'])) {
381 $this->errorHandler("config Mail[helo] is not set");
383 $this->debug_str = '';
384 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
385 $mailer = Mail::factory('smtp', array(
387 'localhost' => $ff->Mail['helo'],
389 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
390 //'debug' => isset($opts['debug']) ? 1 : 0,
392 'debug_handler' => array($this, 'debugHandler')
395 // if the host is the mail host + it's authenticated add auth details
396 // this normally will happen if you sent Pman_Core_NotifySend['host']
399 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
401 $mailer->auth = true;
402 $mailer->username = $ff->Mail['username'];
403 $mailer->password = $ff->Mail['password'];
406 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
408 // we might want to regex 'office365 as a mx host
409 foreach ($ff->Core_Notify['routes'] as $server => $settings){
410 if(!in_array($dom, $settings['domains'])){
414 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
415 // if it's newer that '1' minute...
418 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
420 $seconds = floor((60 * 60) / $settings['rate']);
422 $core_notify = DB_DataObject::factory($this->table);
423 $core_notify->domain_id = $core_domain->id;
424 $core_notify->whereAdd("
425 sent >= NOW() - INTERVAL $seconds SECOND
428 if($core_notify->count()){
430 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
432 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
437 $mailer->host = $server;
438 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
439 $mailer->username = $settings['username'];
440 $mailer->password = $settings['password'];
441 if (isset($settings['port'])) {
442 $mailer->port = $settings['port'];
444 if (isset($settings['socket_options'])) {
445 $mailer->socket_options = $settings['socket_options'];
456 $res = $mailer->send($p->email, $email['headers'], $email['body']);
462 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
464 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
466 $ev->writeEventLog($this->debug_str);
468 if(strtotime($w->act_when) > strtotime("NOW")){
469 $w->act_when = date('Y-m-d H:i:s');
472 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
473 $w->msgid = $email['headers']['Message-Id'];
474 $w->event_id = $ev->id; // sent ok.. - no need to record it..
475 $w->domain_id = $core_domain->id;
478 // enable cc in notify..
479 if (!empty($email['headers']['Cc'])) {
480 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
481 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
482 $cmailer->send($email['headers']['Cc'],
483 $email['headers'], $email['body']);
487 if (!empty($email['bcc'])) {
488 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
489 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
490 $res = $cmailer->send($email['bcc'],
491 $email['headers'], $email['body']);
492 if (!$res || is_a($res, 'PEAR_Error')) {
493 echo "could not send bcc..\n";
495 echo "Sent BCC to {$email['bcc']}\n";
500 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
502 // what type of error..
503 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
504 if (!empty($res->code) && $res->code == 10001) {
505 // fake greylist if timed out.
510 $this->debug($res->message);
511 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
513 // give up after 2 days..
514 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
516 // check last event for this item..
517 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
518 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
519 if (!empty($res->userinfo['smtptext'])) {
520 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
523 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
524 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
525 $w->domain_id = $core_domain->id;
529 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
534 if ($fail || $next_try_min > (2*24*60)) {
535 // fail.. = log and give up..
536 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
537 if (isset($res->userinfo['smtptext'])) {
538 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
541 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
543 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
545 $w->event_id = $ev->id;
546 $w->domain_id = $core_domain->id;
548 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
551 // handle no host availalbe forever...
552 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
553 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
554 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
556 $w->event_id = $ev->id;
557 $w->domain_id = $core_domain->id;
559 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
563 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
564 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
565 $w->domain_id = $core_domain->id;
567 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
573 $ff = HTML_FlexyFramework::get();
574 if (isset($ff->Pman_Core_NotifySend['host'])) {
575 return array($ff->Pman_Core_NotifySend['host']);
578 $mx_records = array();
579 $mx_weight = array();
581 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
582 if (!checkdnsrr($fqdn)) {
588 asort($mx_weight,SORT_NUMERIC);
590 foreach($mx_weight as $k => $weight) {
591 $mxs[] = $mx_records[$k];
597 * wrapper to call object->toEmail()
601 headers : {AssocArray},
605 error : {String} // error message in log.
606 send-to: {String} // use to override rcpt
610 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
612 $m = 'notify'. $notify->evtype;
613 //var_dump(get_class($object) . '::' .$m);
614 if (!empty($notify->evtype) && method_exists($object,$m)) {
615 echo "calling :" . get_class($object) . '::' .$m . "\n";
616 return $object->$m($rcpt, $last_sent_date, $notify, $force);
619 $type = explode('::', $notify->evtype);
621 if(!empty($type[1]) && method_exists($object,$type[1])){
623 echo "calling :" . get_class($object) . '::' .$m . "\n";
624 return $object->$m($rcpt, $last_sent_date, $notify, $force);
627 if (method_exists($object, 'toMailerData')) {
628 return $object->toMailerData(array(
630 'person'=>$rcpt, // added as mediaoutreach used this?
631 )); //this is core_email - i think it's only used for testing...
636 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
641 if (empty($this->cli_args['debug'])) {
649 $this->errorHandler("done\n");
653 function debugHandler ($smtp, $message)
655 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
656 $this->debug_str .= $message;
657 //echo $message ."\n";
660 function errorHandler($msg, $success = false)
662 if($this->error_handler == 'exception'){
664 throw new Pman_Core_NotifySend_Exception_Success($msg);
667 throw new Pman_Core_NotifySend_Exception_Fail($msg);