fix old sent
[Pman.Core] / NotifySend.php
1 <?php
2 require_once 'Pman.php';
3
4 /**
5  * notification script sender - designed to be run by the Notify script - with many children running
6  * in parallel.
7  *
8  * called with an id of a core_notify element
9  *
10  * uses core_notify - to find an event to object and person.
11  *
12  * uses Events table to log failures
13  * 
14  * 
15  * calls $object->toEmail($person,$last_send, $notify) to generate an email struct with
16  *  array (
17  *      headers =>
18  *      recipients =>
19  *      body =>
20  *  )
21  *
22  *
23  * Note uses configuration
24  *
25  * Pman_Core_NotifySend[host] = 'localhost' << to override direct sending..
26  * Mail[helo] << helo host name
27  * Mail[socket_options] << any socket option.
28  */
29 class Pman_Core_NotifySend_Exception_Success extends Exception {}
30 class Pman_Core_NotifySend_Exception_Fail extends Exception {}
31
32
33 class Pman_Core_NotifySend extends Pman
34 {
35     static $cli_desc = "Send out single notification email (usually called from  Core/Notify)";
36     
37     static $cli_opts = array(
38         'debug' => array(
39             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
40             'default' => 0,
41             'short' => 'v',
42             'min' => 0,
43             'max' => 0,
44             
45         ),
46         'DB_DataObject-debug' => array(
47             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
48             'default' => 0,
49             'short' => 'd',
50             'min' => 1,
51             'max' => 1,
52             
53         ),
54         'force' => array(
55             'desc' => 'Force redelivery, even if it has been sent before or not queued...',
56             'default' => 0,
57             'short' => 'f',
58             'min' => 0,
59             'max' => 0,
60         ),
61         'send-to' => array(
62             'desc' => 'Send the message to this address, rather than the one listed.',
63             'default' => '',
64             'short' => 't',
65             'min' => 0,
66             'max' => 1,
67         )
68         
69         
70         
71     );
72     var $table = 'core_notify';
73     var $error_handler = 'die';
74     var $poolname = 'core';
75     var $server; // core_notify_server
76     
77     function getAuth()
78     {
79         $ff = HTML_FlexyFramework::get();
80         if (!$ff->cli) {
81             $this->errorHandler("access denied");
82         }
83         //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
84         return true;
85         
86     }
87    
88     function get($id,$opts=array())
89     {
90
91         //print_r($opts);
92         if (!empty($opts['DB_DataObject-debug'])) {
93             DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
94         }
95         
96         //DB_DataObject::debugLevel(1);
97         //date_default_timezone_set('UTC');
98         // phpinfo();exit;
99         $force = empty($opts['force']) ? 0 : 1;
100         
101         $w = DB_DataObject::factory($this->table);
102
103         if (!$w->get($id)) {
104             $this->errorHandler("invalid id\n");
105         }
106
107         if (!$force && !empty($w->sent) && strtotime($w->act_when) < strtotime($w->sent)) {
108              
109             $this->errorHandler("already sent - repeat to early\n");
110         }
111         
112         $this->server = DB_DataObject::Factory('core_notify_server')->getCurrent($this, $force);
113         if (!$force &&  $w->server_id != $this->server->id) {
114             $this->errorHandler("Server id does not match - use force to try again\n");
115         }
116         
117         
118         if (!empty($opts['debug'])) {
119             print_r($w);
120             $ff = HTML_FlexyFramework::get();
121             if (!isset($ff->Core_Mailer)) {
122                 $ff->Core_Mailer = array();
123             }
124             HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
125         }
126         
127         $sent = (empty($w->sent) || preg_match('/^1000/', $w->sent)) ? false : true;
128         
129         if (!$force && (!empty($w->msgid) || $sent)) {
130             $ww = clone($w);
131             if (!$sent) {   // fix sent.
132                 $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
133                 $w->update($ww);
134             }    
135             $this->errorHandler("message has been sent already.\n");
136         }
137         
138         // we have a bug with msgid not getting filled.
139         $cev = DB_DataObject::Factory('Events');
140         $cev->on_table =  $this->table;
141         $cev->on_id =  $w->id;
142         $cev->action = 'NOTIFYSENT';
143         $cev->limit(1);
144         if ($cev->count()) {
145             $cev->find(true);
146             $w->flagDone($cev, 'alreadysent');
147             $this->errorHandler( "SENT (fix old) ".  $cev->remarks);
148         }
149         
150         
151         $o = $w->object();
152         
153         if ($o === false)  {
154              
155             $ev = $this->addEvent('NOTIFY', $w,   "Notification event cleared (underlying object does not exist)" );
156             $w->flagDone($ev, '');
157             $this->errorHandler(  $ev->remarks);
158         }
159      
160         
161         
162         $p = $w->person();
163         
164         if (isset($p->active) && empty($p->active)) {
165             $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not user not active any more)" );;
166              $w->flagDone($ev, '');
167             $this->errorHandler(  $ev->remarks);
168         }
169         // has it failed mutliple times..
170         
171         if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
172             $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (user has to many failures)" );;
173             $w->flagDone($ev, '');
174             $this->errorHandler(  $ev->remarks);
175         }
176         
177         // let's work out the last notification sent to this user..
178         $l = DB_DataObject::factory($this->table);
179         
180         $lar = array(
181                 'ontable' => $w->ontable,
182                 'onid' => $w->onid,
183         );
184         // only newer version of the database us this..
185         if (isset($w->person_table)) {
186             $personid_col = strtolower($w->person_table).'_id';
187             if (isset($w->{$personid_col})) {
188                 $lar[$personid_col] = $w->{$personid_col};
189             }
190         }
191         
192         
193         $l->setFrom( $lar );       
194         $l->whereAdd('id != '. $w->id);
195         $l->orderBy('sent DESC');
196         $l->limit(1);
197         $ar = $l->fetchAll('sent');
198         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
199         
200         // find last event..
201         $ev = DB_DataObject::factory('Events');
202         $ev->on_id = $w->id;                           // int(11)
203         $ev->on_table = $this->table;
204         $ev->limit(1);
205         $ev->orderBy('event_when DESC');
206         $ar = $ev->fetchAll('event_when');
207         $last_event = empty($ar) ? 0 : $ar[0];
208         $next_try_min = 5;
209         if ($last_event) {
210             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
211         }
212         $next_try = $next_try_min . ' MINUTES';
213          
214         // this may modify $p->email. (it will not update it though)
215         $email =  $this->makeEmail($o, $p, $last, $w, $force);
216         
217         if ($email === true)  {
218             $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not required any more) - toEmail=true" );;
219             $w->flagDone($ev, '');
220             $this->errorHandler( $ev->remarks);
221         }
222         if (is_a($email, 'PEAR_Error')) {
223             $email =array(
224                 'error' => $email->toString()
225             );
226         }
227         
228         if (empty($p) && !empty($email['recipients'])) {
229             // make a fake person..
230             $p = (object) array(
231                 'email' => $email['recipients']
232             );
233         }
234          
235         if ($email === false || isset($email['error']) || empty($p)) {
236             // object returned 'false' - it does not know how to send it..
237             $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error'])  ? $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable); 
238             $w->flagDone($ev, '');
239             $this->errorHandler(  $ev->remarks);
240         }
241         
242          
243         
244         if (isset($email['later'])) {
245             
246             $this->server->updateNotifyToNextServer($w, $email['later'],true);
247              
248             $this->errorHandler("Delivery postponed by email creator to {$email['later']}");
249         }
250         
251          
252         if (empty($email['headers']['Message-Id'])) {
253             $HOST = gethostname();
254             $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
255             
256         }
257         
258         
259             
260         
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
265        
266         if (!empty($email['send-to'])) {
267             $p->email = $email['send-to'];
268         }
269          if (!empty($opts['send-to'])) {
270             $p->email = $opts['send-to'];
271         }
272         
273             // since some of them have spaces?!?!
274         $p->email = trim($p->email);
275         $ww = clone($w);
276         $ww->to_email = empty($ww->to_email) ? $p->email : $ww->to_email;
277         $explode_email = explode('@', $ww->to_email);
278         $dom = array_pop($explode_email);
279         
280         $core_domain = DB_DataObject::factory('core_domain')->loadOrCreate($dom);
281
282         
283         $ww->domain_id = $core_domain->id;
284         // if to_email has not been set!?
285         $ww->update($w); // if nothing has changed this will not do anything.
286         $w = clone($ww);
287     
288       
289         
290         require_once 'Validate.php';
291         if (!Validate::email($p->email, true)) {
292             $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
293             $w->flagDone($ev, '');
294             $this->errorHandler($ev->remarks);
295             
296         }
297         
298         
299         $ff = HTML_FlexyFramework::get();
300         
301      
302         $mxs = $this->mxs($dom);
303         $ww = clone($w);
304
305         // we might fail doing this...
306         // need to handle temporary failure..
307        
308         
309           // we try for 2 days..
310         $retry = 15;
311         if (strtotime($w->act_start) <  strtotime('NOW - 1 HOUR')) {
312             // older that 1 hour.
313             $retry = 60;
314         }
315         
316         if (strtotime($w->act_start) <  strtotime('NOW - 1 DAY')) {
317             // older that 1 day.
318             $retry = 120;
319         }
320         if (strtotime($w->act_start) <  strtotime('NOW - 2 DAY')) {
321             // older that 1 day.
322             $retry = 240;
323         }
324         
325         if (empty($mxs)) {
326             // only retry for 1 day if the MX issue..
327             if ($retry < 240) {
328                 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
329                 $w->flagLater(date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')));
330                 $this->errorHandler($ev->remarks);
331             }
332             
333             $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
334             $w->flagDone($ev, '');
335             $this->errorHandler($ev->remarks);
336             
337             
338         }
339         
340         
341         
342         
343         if (!$force && strtotime($w->act_start) <  strtotime('NOW - 3 DAY')) {
344             $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
345             $w->flagDone($ev, '');
346             $this->errorHandler(  $ev->remarks);
347         }
348         
349         $retry_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
350         
351         //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
352         // we can only update act_when if it has not been sent already (only happens when running in force mode..)
353         // set act when if it's empty...
354         $w->act_when =  (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? $retry_when : $w->act_when;
355         
356         $w->update($ww);
357         
358         $ww = clone($w);   
359         
360         $fail = false;
361         require_once 'Mail.php';
362         
363         
364         $this->server->initHelo();
365         
366         if (!isset($ff->Mail['helo'])) {
367             $this->errorHandler("config Mail[helo] is not set");
368         }
369         
370         
371                         
372         foreach($mxs as $mx) {
373             
374            
375             $this->debug_str = '';
376             $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
377             $mailer = Mail::factory('smtp', array(
378                     'host'    => $mx ,
379                     'localhost' => $ff->Mail['helo'],
380                     'timeout' => 15,
381                     'socket_options' =>  isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
382                     //'debug' => isset($opts['debug']) ?  1 : 0,
383                     'debug' => 1,
384                     'debug_handler' => array($this, 'debugHandler')
385             ));
386             
387             // if the host is the mail host + it's authenticated add auth details
388             // this normally will happen if you sent  Pman_Core_NotifySend['host']
389              
390             
391             if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
392                 
393                 $mailer->auth = true;
394                 $mailer->username = $ff->Mail['username'];
395                 $mailer->password = $ff->Mail['password'];        
396             }
397             
398             if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
399                 
400                 // we might want to regex 'office365 as a mx host 
401                 foreach ($ff->Core_Notify['routes'] as $server => $settings){
402                     if(!in_array($dom, $settings['domains'])){
403                         continue;
404                     }
405                     
406                     // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
407                     // if it's newer that '1' minute...
408                     // then shunt it..
409                     
410                     $settings['rate'] = isset( $settings['rate']) ?  $settings['rate']  : 360;
411                     
412                     $seconds = floor((60 * 60) / $settings['rate']);
413                     
414                     $core_notify = DB_DataObject::factory($this->table);
415                     $core_notify->domain_id = $core_domain->id;
416                     $core_notify->server_id = $this->server->id;
417                     $core_notify->whereAdd("
418                         sent >= NOW() - INTERVAL $seconds SECOND
419                     ");
420                     
421                     if($core_notify->count()){
422                         $this->server->updateNotifyToNextServer( $w , date("Y-m-d H:i:s", time() + $seconds), true);
423                         $this->errorHandler( " Too many emails sent by {$dom} - requeing");
424                     }
425                      
426                     
427                     
428                     $mailer->host = $server;
429                     $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
430                     $mailer->username = $settings['username'];
431                     $mailer->password = $settings['password'];
432                     if (isset($settings['port'])) {
433                         $mailer->port = $settings['port'];
434                     }
435                     if (isset($settings['socket_options'])) {
436                         $mailer->socket_options = $settings['socket_options'];
437                         
438                     }
439                     
440                     
441                     break;
442                 }
443                 
444             }
445         
446             
447             $res = $mailer->send($p->email, $email['headers'], $email['body']);
448             if (is_object($res)) {
449                 $res->backtrace = array(); 
450             }
451             $this->debug("GOT response to send: ". print_r($res,true)); 
452             
453             if ($res === true) {
454                 // success....
455                 
456                 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
457                 
458                 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
459                 
460                 $ev->writeEventLog($this->debug_str);
461                  
462                 $w->flagDone($ev, $email['headers']['Message-Id']);
463                 
464                  
465                 // enable cc in notify..
466                 if (!empty($email['headers']['Cc'])) {
467                     $cmailer = Mail::factory('smtp',  isset($ff->Mail) ? $ff->Mail : array() );
468                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
469                     $cmailer->send($email['headers']['Cc'],    $email['headers'], $email['body']);
470                     
471                 }
472                 
473                 if (!empty($email['bcc'])) {
474                     $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
475                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
476                     $res = $cmailer->send($email['bcc'],  $email['headers'], $email['body']);
477                     if (!$res || is_a($res, 'PEAR_Error')) {
478                         echo "could not send bcc..\n";
479                     } else {
480                         echo "Sent BCC to {$email['bcc']}\n";
481                     }
482                 }
483                  
484                 $this->errorHandler( " SENT {$w->id} - {$ev->remarks}", true);
485             }
486             // what type of error..
487             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
488             if (!empty($res->code) && $res->code == 10001) {
489                 // fake greylist if timed out.
490                 $code = -1; 
491             }
492             
493             if ($code < 0) {
494                 $this->debug($res->message);
495                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
496             }
497             // give up after 2 days..
498             if (in_array($code, array( 421, 450, 451, 452))   && $next_try_min < (2*24*60)) {
499                 // try again later..
500                 // check last event for this item..
501                 //$errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
502                 $errmsg=  $res->userinfo['smtpcode'] . ': ' .$res->message ;
503                 if (!empty($res->userinfo['smtptext'])) {
504                     $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
505                 }
506                 //print_r($res);
507                 $ev = $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
508                 
509                 $this->server->updateNotifyToNextServer($w,  $retry_when,true);
510                 
511                 $this->errorHandler(  $ev->remarks);
512             }
513             
514             $fail = true;
515             break;
516         }
517         
518         // after trying all mxs - could not connect...
519         if  (!$fail && ($next_try_min > (2*24*60) || strtotime($w->act_start) < strtotime('NOW - 3 DAYS'))) {
520             
521             $errmsg=  " - UNKNOWN ERROR";
522             if (isset($res->userinfo['smtptext'])) {
523                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
524             }
525             
526             $ev = $this->addEvent('NOTIFYFAIL', $w,  "RETRY TIME EXCEEDED - " .  $errmsg);
527             $w->flagDone($ev, '');
528             $this->errorHandler( $ev->remarks);
529         }
530         
531         if ($fail) { //// !!!!<<< BLACKLIST DETECT?
532         // fail.. = log and give up..
533             $errmsg=   $res->userinfo['smtpcode'] . ': ' .$res->toString();
534             if (isset($res->userinfo['smtptext'])) {
535                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
536             }
537             
538             if ($res->userinfo['smtpcode'] == 550) {
539                 if ($this->server->checkSmtpResponse($errmsg, $core_domain)) {
540                     $ev = $this->addEvent('NOTIFY', $w, 'BLACKLISTED  - ' . $errmsg);
541                     $this->server->updateNotifyToNextServer($w,  $retry_when,true);
542                     $this->errorHandler( $ev->remarks);
543                 }
544             }
545              
546             $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .  $errmsg);
547             $w->flagDone($ev, '');
548              
549             $this->errorHandler( $ev->remarks);
550         }
551         
552         // at this point we just could not find any MX records..
553         
554         
555         // try again.
556         
557         $ev = $this->addEvent('NOTIFY', $w, 'GREYLIST - NO HOST CAN BE CONTACTED:' . $p->email);
558         
559         $this->server->updateNotifyToNextServer($w,  $retry_when ,true);
560
561         
562          
563         $this->errorHandler($ev->remarks);
564
565         
566     }
567     function mxs($fqdn)
568     {
569         $ff = HTML_FlexyFramework::get();
570         if (isset($ff->Pman_Core_NotifySend['host'])) {
571             return array($ff->Pman_Core_NotifySend['host']);
572         }
573         
574         $mx_records = array();
575         $mx_weight = array();
576         $mxs = array();
577         if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
578             if (!checkdnsrr($fqdn)) {
579                 return false;
580             }
581             return array($fqdn);
582         }
583         
584         asort($mx_weight,SORT_NUMERIC);
585         
586         foreach($mx_weight as $k => $weight) {
587             if (!empty($mx_records[$k])) {
588                 $mxs[] = $mx_records[$k];
589             }
590         }
591         return empty($mxs) ? false : $mxs;
592     }
593     
594     /**
595      * wrapper to call object->toEmail()
596      *
597      * return
598      *   {
599         headers : {AssocArray},
600         body: {String}
601         
602         // optional..
603         error :  {String} // error message in log.
604         send-to: {String} // use to override rcpt
605          
606      }
607      **/
608     function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
609     {
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);
615         }
616         
617         $type = explode('::', $notify->evtype);
618         
619         if(!empty($type[1]) && method_exists($object,$type[1])){
620             $m = $type[1];
621             echo "calling :" . get_class($object) . '::' .$m . "\n";
622             return $object->$m($rcpt, $last_sent_date, $notify, $force);
623         }
624         // fallback if evtype is empty..
625         
626         if (method_exists($object, 'toMailerData')) {
627             return $object->toMailerData(array(
628                 'rcpts'=>$rcpt,
629                 'person'=>$rcpt, // added as mediaoutreach used this?
630             )); //this is core_email - i think it's only used for testing...
631             //var_Dump($object);
632             //exit;
633         }
634         if (method_exists($object, 'toEmail')) {
635             return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
636         }
637         // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
638         
639         return false;
640     }
641     
642     function debug($str)
643     {
644         if (empty($this->cli_args['debug'])) {
645             return;
646             
647         }
648         echo $str . "\n";
649     }
650     function output()
651     {
652         $this->errorHandler("done\n");
653     }
654     var $debug_str = '';
655     
656     function debugHandler ($smtp, $message)
657     {
658         $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
659         $this->debug_str .= $message;
660         //echo $message ."\n";
661     }
662     
663     function errorHandler($msg, $success = false)
664     {
665         if($this->error_handler == 'exception'){
666             if($success){
667                 throw new Pman_Core_NotifySend_Exception_Success($msg);
668             }
669             
670             throw new Pman_Core_NotifySend_Exception_Fail($msg);
671         }
672         
673         die(date('Y-m-d h:i:s') . ' ' . $msg ."\n");
674         
675         
676     }
677     
678     function updateServer($w)
679     {
680         $ff = HTML_FlexyFramework::get();
681          
682         if (empty($ff->Core_Notify['servers'])) {
683             return;
684         }
685         // some classes dont support server routing
686         if (!property_exists($w, 'server_id')) {
687             return;
688         }
689         // next server..
690         $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));
691          
692     }
693     
694
695     
696 }