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