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