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");
104 if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
107 $this->errorHandler("send repeat to early\n");
109 if (!empty($opts['debug'])) {
111 $ff = HTML_FlexyFramework::get();
112 if (!isset($ff->Core_Mailer)) {
113 $ff->Core_Mailer = array();
115 HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
118 $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
120 if (!$force && (!empty($w->msgid) || $sent)) {
123 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
126 $this->errorHandler("message has been sent already.\n");
133 $ev = $this->addEvent('NOTIFY', $w,
134 "Notification event cleared (underlying object does not exist)" );;
136 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
138 $w->event_id = $ev->id;
140 $this->errorHandler(date('Y-m-d h:i:s ') .
141 "Notification event cleared (underlying object does not exist)"
149 if (isset($p->active) && empty($p->active)) {
150 $ev = $this->addEvent('NOTIFY', $w,
151 "Notification event cleared (not user not active any more)" );;
153 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
155 $w->event_id = $ev->id;
157 $this->errorHandler(date('Y-m-d h:i:s ') .
158 "Notification event cleared (not user not active any more)"
160 $this->errorHandler("message has been sent already.\n");
164 // let's work out the last notification sent to this user..
165 $l = DB_DataObject::factory($this->table);
168 'ontable' => $w->ontable,
171 // only newer version of the database us this..
172 $personid_col = strtolower($w->person_table).'_id';
173 if (isset($w->{$personid_col})) {
174 $lar[$personid_col] = $w->{$personid_col};
179 $l->whereAdd('id != '. $w->id);
180 $l->orderBy('sent DESC');
182 $ar = $l->fetchAll('sent');
183 $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
186 $ev = DB_DataObject::factory('Events');
187 $ev->on_id = $w->id; // int(11)
188 $ev->on_table = $this->table;
190 $ev->orderBy('event_when DESC');
191 $ar = $ev->fetchAll('event_when');
192 $last_event = empty($ar) ? 0 : $ar[0];
195 $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
197 $next_try = $next_try_min . ' MINUTES';
199 // this may modify $p->email. (it will not update it though)
200 $email = $this->makeEmail($o, $p, $last, $w, $force);
202 if ($email === true) {
204 $ev = $this->addEvent('NOTIFY', $w,
205 "Notification event cleared (not required any more)" );;
207 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
209 $w->event_id = $ev->id;
211 $this->errorHandler(date('Y-m-d h:i:s ') .
212 "Notification event cleared (not required any more)"
215 if (is_a($email, 'PEAR_Error')) {
217 'error' => $email->toString()
221 if (empty($p) && !empty($email['recipients'])) {
222 // make a fake person..
224 'email' => $email['recipients']
228 if ($email === false || isset($email['error']) || empty($p)) {
229 // object returned 'false' - it does not know how to send it..
230 $ev = $this->addEvent('NOTIFY', $w, isset($email['error']) ?
231 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable);
233 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
235 $w->event_id = $ev->id;
237 $this->errorHandler(date('Y-m-d h:i:s ') .
238 (isset($email['error']) ?
239 $email['error'] : "INTERNAL ERROR - We can not handle " . $w->ontable)
244 if (isset($email['later'])) {
246 $w->act_when = $email['later'];
248 $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
252 if (empty($email['headers']['Message-Id'])) {
253 $HOST = gethostname();
254 $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
261 //$p->email = 'alan@akbkhome.com'; //for testing..
262 //print_r($email);exit;
263 // should we fetch the watch that caused it.. - which should contain the method to call..
264 // --send-to=test@xxx.com
266 if (!empty($email['send-to'])) {
267 $p->email = $email['send-to'];
269 if (!empty($opts['send-to'])) {
270 $p->email = $opts['send-to'];
273 // since some of them have spaces?!?!
274 $p->email = trim($p->email);
277 require_once 'Validate.php';
278 if (!Validate::email($p->email, true)) {
279 $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
281 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
283 $w->event_id = $ev->id;
285 $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
290 $ff = HTML_FlexyFramework::get();
293 $dom = array_pop(explode('@', $p->email));
295 $mxs = $this->mxs($dom);
298 // we might fail doing this...
299 // need to handle temporary failure..
302 // we try for 3 days..
304 if (strtotime($w->act_start) < strtotime('NOW - 1 HOUR')) {
305 // older that 1 hour.
309 if (strtotime($w->act_start) < strtotime('NOW - 1 DAY')) {
313 if (strtotime($w->act_start) < strtotime('NOW - 2 DAY')) {
318 if ($mxs === false) {
319 // only retry for 2 day son the MX issue..
321 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
322 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
324 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
327 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
328 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
330 $w->event_id = $ev->id;
332 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - BAD EMAIL - {$p->email} \n");
340 if (!$force && strtotime($w->act_start) < strtotime('NOW - 14 DAY')) {
341 $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
342 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
344 $w->event_id = $ev->id;
346 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - GAVE UP TO OLD - {$p->email} \n");
351 $w->to_email = $p->email;
352 //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
353 // we can only update act_when if it has not been sent already (only happens when running in force mode..)
354 $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;
360 require_once 'Mail.php';
362 $core_domain = DB_DataObject::factory('core_domain');
363 if(!$core_domain->get('domain', $dom)){
364 $core_domain = DB_DataObject::factory('core_domain');
365 $core_domain->setFrom(array(
368 $core_domain->insert();
371 foreach($mxs as $mx) {
373 if (!isset($ff->Mail['helo'])) {
374 $this->errorHandler("config Mail[helo] is not set");
376 $this->debug_str = '';
377 $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
378 $mailer = Mail::factory('smtp', array(
380 'localhost' => $ff->Mail['helo'],
382 'socket_options' => isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
383 //'debug' => isset($opts['debug']) ? 1 : 0,
385 'debug_handler' => array($this, 'debugHandler')
388 // if the host is the mail host + it's authenticated add auth details
389 // this normally will happen if you sent Pman_Core_NotifySend['host']
390 if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
392 $username = $ff->Mail['username'] ;
393 $password = $ff->Mail['password'] ;
395 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
397 foreach ($ff->Core_Notify['routes'] as $server => $settings){
398 if(!in_array($dom, $settings['domains'])){
402 // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
403 // if it's newer that '1' minute...
406 $seconds = floor((60 * 60) / $settings['rate']);
408 $core_notify = DB_DataObject::factory($this->table);
409 $core_notify->domain_id = $core_domain->id;
410 $core_notify->whereAdd("
411 sent >= NOW() - INTERVAL $seconds SECONDS
414 if($core_notify->count()){
416 $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
418 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
421 // that make's this test obsolete...
424 $core_notify = DB_DataObject::factory($this->table);
425 $core_notify->domain_id = $core_domain->id;
426 $core_notify->whereAdd("
427 sent >= NOW() - INTERVAL 1 HOUR
430 if($core_notify->count() >= $settings['rate']){
432 $w->act_when = date("Y-m-d H:i:s", strtotime('+1 HOUR'));
434 $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
440 $mailer->host = $server;
441 $username = $settings['username'];
442 $password = $settings['password'];
449 $mailer->auth = true;
450 $mailer->username = $username;
451 $mailer->password = $password;
454 $res = $mailer->send($p->email, $email['headers'], $email['body']);
460 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
462 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
464 $ev->writeEventLog($this->debug_str);
466 if(strtotime($w->act_when) > strtotime("NOW")){
467 $w->act_when = date('Y-m-d H:i:s');
470 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
471 $w->msgid = $email['headers']['Message-Id'];
472 $w->event_id = $ev->id; // sent ok.. - no need to record it..
473 $w->domain_id = $core_domain->id;
476 // enable cc in notify..
477 if (!empty($email['headers']['Cc'])) {
478 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
479 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
480 $cmailer->send($email['headers']['Cc'],
481 $email['headers'], $email['body']);
485 if (!empty($email['bcc'])) {
486 $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
487 $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
488 $res = $cmailer->send($email['bcc'],
489 $email['headers'], $email['body']);
490 if (!$res || is_a($res, 'PEAR_Error')) {
491 echo "could not send bcc..\n";
493 echo "Sent BCC to {$email['bcc']}\n";
498 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
500 // what type of error..
501 $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
502 if (!empty($res->code) && $res->code == 10001) {
503 // fake greylist if timed out.
508 $this->debug($res->message);
509 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
511 // give up after 2 days..
512 if (in_array($code, array( 421, 450, 451, 452)) && $next_try_min < (2*24*60)) {
514 // check last event for this item..
515 //$errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
516 $errmsg= $res->userinfo['smtpcode'] . ': ' .$res->message ;
517 if (!empty($res->userinfo['smtptext'])) {
518 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
521 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
522 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
523 $w->domain_id = $core_domain->id;
527 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED - $errmsg \n");
532 if ($fail || $next_try_min > (2*24*60)) {
533 // fail.. = log and give up..
534 $errmsg= $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) : " - UNKNOWN ERROR";
535 if (isset($res->userinfo['smtptext'])) {
536 $errmsg= $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
539 $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
541 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
543 $w->event_id = $ev->id;
544 $w->domain_id = $core_domain->id;
546 $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
549 // handle no host availalbe forever...
550 if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
551 $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
552 $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
554 $w->event_id = $ev->id;
555 $w->domain_id = $core_domain->id;
557 $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
561 $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
562 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
563 $w->domain_id = $core_domain->id;
565 $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
571 $ff = HTML_FlexyFramework::get();
572 if (isset($ff->Pman_Core_NotifySend['host'])) {
573 return array($ff->Pman_Core_NotifySend['host']);
576 $mx_records = array();
577 $mx_weight = array();
579 if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
580 if (!checkdnsrr($fqdn)) {
586 asort($mx_weight,SORT_NUMERIC);
588 foreach($mx_weight as $k => $weight) {
589 $mxs[] = $mx_records[$k];
595 * wrapper to call object->toEmail()
599 headers : {AssocArray},
603 error : {String} // error message in log.
604 send-to: {String} // use to override rcpt
608 function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
610 $m = 'notify'. $notify->evtype;
611 //var_dump(get_class($object) . '::' .$m);
612 if (!empty($notify->evtype) && method_exists($object,$m)) {
613 echo "calling :" . get_class($object) . '::' .$m . "\n";
614 return $object->$m($rcpt, $last_sent_date, $notify, $force);
617 $type = explode('::', $notify->evtype);
619 if(!empty($type[1]) && method_exists($object,$type[1])){
621 echo "calling :" . get_class($object) . '::' .$m . "\n";
622 return $object->$m($rcpt, $last_sent_date, $notify, $force);
625 if (!method_exists($object, 'toEmail')) {
630 return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
635 if (empty($this->cli_args['debug'])) {
643 $this->errorHandler("done\n");
647 function debugHandler ($smtp, $message)
649 $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
650 $this->debug_str .= $message;
653 function errorHandler($msg, $success = false)
655 if($this->error_handler == 'exception'){
657 throw new Pman_Core_NotifySend_Exception_Success($msg);
660 throw new Pman_Core_NotifySend_Exception_Fail($msg);