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");
163 // has it failed mutliple times..
165 if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
166 $ev = $this->addEvent('NOTIFY', $w,
167 "Notification event cleared (user has to many failures)" );;
169 $w->sent = $w->sqlValue('NOW()'); // do not update if sent.....
171 $w->event_id = $ev->id;
173 $this->errorHandler(date('Y-m-d h:i:s ') .
174 "Notification event cleared (user has to many failures)"
176 $this->errorHandler("user has to many failures.\n");
179 // let's work out the last notification sent to this user..
180 $l = DB_DataObject::factory($this->table);
183 'ontable' => $w->ontable,
186 // only newer version of the database us this..
187 if (isset($w->person_table)) {
188 $personid_col = strtolower($w->person_table).'_id';
189 if (isset($w->{$personid_col})) {
190 $lar[$personid_col] = $w->{$personid_col};
196 $l->whereAdd('id != '. $w->id);
197 $l->orderBy('sent DESC');
199 $ar = $l->fetchAll('sent');
200 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
203 $ev = DB_DataObject::factory('Events');
204 $ev->on_id = $w->id; // int(11)
205 $ev->on_table = $this->table;
207 $ev->orderBy('event_when DESC');
208 $ar = $ev->fetchAll('event_when');
209 $last_event = empty($ar) ? 0 : $ar[0];
212 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
214 $next_try = $next_try_min . ' MINUTES';
216 // this may modify $p->email. (it will not update it though)
217 $email = $this->makeEmail($o, $p, $last, $w, $force);
219 if ($email === true) {
221 $ev = $this->addEvent('NOTIFY', $w,
222 "Notification event cleared (not required any more)" );;
224 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
226 $w->event_id = $ev->id;
228 $this->errorHandler(date('Y-m-d h:i:s ') .
229 "Notification event cleared (not required any more)"
232 if (is_a($email, 'PEAR_Error')) {
234 'error' => $email->toString()
238 if (empty($p) && !empty($email['recipients'])) {
239 // make a fake person..
241 'email' => $email['recipients']
245 if ($email === false || isset($email['error']) || empty($p)) {
246 // object returned 'false' - it does not know how to send it..
247 $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error']) ?
248 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
250 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
252 $w->event_id = $ev->id;
253 $w->to_email = $p->email;
255 $this->errorHandler(date('Y-m-d h:i:s ') .
256 (isset($email['error']) ?
257 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
262 if (isset($email['later'])) {
264 $w->act_when = $email['later'];
266 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
270 if (empty($email['headers']['Message-Id'])) {
271 $HOST = gethostname();
272 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
279 //$p->email = 'alan@akbkhome.com'; //for testing..
280 //print_r($email);exit;
281 // should we fetch the watch that caused it.. - which should contain the method to call..
282 // --send-to=test@xxx.com
284 if (!empty($email['send-to'])) {
285 $p->email = $email['send-to'];
287 if (!empty($opts['send-to'])) {
288 $p->email = $opts['send-to'];
291 // since some of them have spaces?!?!
292 $p->email = trim($p->email);
295 require_once 'Validate.php';
296 if (!Validate::email($p->email, true)) {
297 $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
299 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
301 $w->event_id = $ev->id;
302 $w->to_email = $p->email;
304 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
309 $ff = HTML_FlexyFramework::get();
311 $explode_email = explode('@', $p->email);
312 $dom = array_pop($explode_email);
314 $mxs = $this->mxs($dom);
317 // we might fail doing this...
318 // need to handle temporary failure..
321 // we try for 3 days..
323 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
324 // older that 1 hour.
328 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
332 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
337 if ($mxs === false) {
338 // only retry for 2 day son the MX issue..
340 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
341 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
343 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
346 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
347 $w->sent = $w->sqlValue('NOW()'); // why not updated - used to leave as is?
349 $w->event_id = $ev->id;
350 $w->to_email = $p->email;
352 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
360 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
361 $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
362 $w->sent = $w->sqlValue('NOW()');
364 $w->event_id = $ev->id;
365 $w->to_email = $p->email;
367 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
372 $w->to_email = $p->email;
373 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
374 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
375 $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;
381 require_once 'Mail.php';
383 $core_domain = DB_DataObject::factory('core_domain');
384 if(!$core_domain->get('domain', $dom)){
385 $core_domain = DB_DataObject::factory('core_domain');
386 $core_domain->setFrom(array(
389 $core_domain->insert();
392 foreach($mxs as $mx) {
394 if (!isset($ff->Mail['helo'])) {
395 $this->errorHandler("config Mail[helo] is not set");
397 $this->debug_str = '';
398 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
399 $mailer = Mail::factory('smtp', array(
401 'localhost' => $ff->Mail['helo'],
403 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
404 //'debug' => isset($opts['debug']) ? 1 : 0,
406 'debug_handler' => array($this, 'debugHandler')
409 // if the host is the mail host + it's authenticated add auth details
410 // this normally will happen if you sent Pman_Core_NotifySend['host']
413 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
415 $mailer->auth = true;
416 $mailer->username = $ff->Mail['username'];
417 $mailer->password = $ff->Mail['password'];
420 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
422 // we might want to regex 'office365 as a mx host
423 foreach ($ff->Core_Notify['routes'] as $server => $settings){
424 if(!in_array($dom, $settings['domains'])){
428 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
429 // if it's newer that '1' minute...
432 $settings['rate'] = isset( $settings['rate']) ? $settings['rate'] : 360;
434 $seconds = floor((60 * 60) / $settings['rate']);
436 $core_notify = DB_DataObject::factory($this->table);
437 $core_notify->domain_id = $core_domain->id;
438 $core_notify->whereAdd("
439 sent >= NOW() - INTERVAL $seconds SECOND
442 if($core_notify->count()){
444 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
446 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
451 $mailer->host = $server;
452 $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
453 $mailer->username = $settings['username'];
454 $mailer->password = $settings['password'];
455 if (isset($settings['port'])) {
456 $mailer->port = $settings['port'];
458 if (isset($settings['socket_options'])) {
459 $mailer->socket_options = $settings['socket_options'];
470 $res = $mailer->send($p->email, $email['headers'], $email['body']);
476 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
478 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
480 $ev->writeEventLog($this->debug_str);
482 if(strtotime($w->act_when) > strtotime("NOW")){
483 $w->act_when = date('Y-m-d H:i:s');
486 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
487 $w->msgid = $email['headers']['Message-Id'];
488 $w->event_id = $ev->id; // sent ok.. - no need to record it..
489 $w->domain_id = $core_domain->id;
492 // enable cc in notify..
493 if (!empty($email['headers']['Cc'])) {
494 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
495 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
496 $cmailer->send($email['headers']['Cc'],
497 $email['headers'], $email['body']);
501 if (!empty($email['bcc'])) {
502 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
503 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
504 $res = $cmailer->send($email['bcc'],
505 $email['headers'], $email['body']);
506 if (!$res || is_a($res, 'PEAR_Error')) {
507 echo "could not send bcc..\n";
509 echo "Sent BCC to {$email['bcc']}\n";
514 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
516 // what type of error..
517 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
518 if (!empty($res->code) && $res->code == 10001) {
519 // fake greylist if timed out.
524 $this->debug($res->message);
525 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
527 // give up after 2 days..
528 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
530 // check last event for this item..
531 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
532 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
533 if (!empty($res->userinfo['smtptext'])) {
534 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
537 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
538 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
539 $w->domain_id = $core_domain->id;
543 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
548 if ($fail || $next_try_min > (2*24*60)) {
549 // fail.. = log and give up..
550 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
551 if (isset($res->userinfo['smtptext'])) {
552 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
555 $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
557 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
559 $w->event_id = $ev->id;
560 $w->domain_id = $core_domain->id;
562 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
565 // handle no host availalbe forever...
566 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
567 $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
568 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
570 $w->event_id = $ev->id;
571 $w->domain_id = $core_domain->id;
573 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
577 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
578 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
579 $w->domain_id = $core_domain->id;
581 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
587 $ff = HTML_FlexyFramework::get();
588 if (isset($ff->Pman_Core_NotifySend['host'])) {
589 return array($ff->Pman_Core_NotifySend['host']);
592 $mx_records = array();
593 $mx_weight = array();
595 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
596 if (!checkdnsrr($fqdn)) {
602 asort($mx_weight,SORT_NUMERIC);
604 foreach($mx_weight as $k => $weight) {
605 $mxs[] = $mx_records[$k];
611 * wrapper to call object->toEmail()
615 headers : {AssocArray},
619 error : {String} // error message in log.
620 send-to: {String} // use to override rcpt
624 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
626 $m = 'notify'. $notify->evtype;
627 //var_dump(get_class($object) . '::' .$m);
628 if (!empty($notify->evtype) && method_exists($object,$m)) {
629 echo "calling :" . get_class($object) . '::' .$m . "\n";
630 return $object->$m($rcpt, $last_sent_date, $notify, $force);
633 $type = explode('::', $notify->evtype);
635 if(!empty($type[1]) && method_exists($object,$type[1])){
637 echo "calling :" . get_class($object) . '::' .$m . "\n";
638 return $object->$m($rcpt, $last_sent_date, $notify, $force);
641 if (method_exists($object, 'toMailerData')) {
642 return $object->toMailerData(array(
644 'person'=>$rcpt, // added as mediaoutreach used this?
645 )); //this is core_email - i think it's only used for testing...
650 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
655 if (empty($this->cli_args['debug'])) {
663 $this->errorHandler("done\n");
667 function debugHandler ($smtp, $message)
669 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
670 $this->debug_str .= $message;
671 //echo $message ."\n";
674 function errorHandler($msg, $success = false)
676 if($this->error_handler == 'exception'){
678 throw new Pman_Core_NotifySend_Exception_Success($msg);
681 throw new Pman_Core_NotifySend_Exception_Fail($msg);