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 Pman_Core_NotifySend_Exception_Success extends Exception {}
30 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     
75     function getAuth()
76     {
77         $ff = HTML_FlexyFramework::get();
78         if (!$ff->cli) {
79             $this->errorHandler("access denied");
80         }
81         //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
82         return true;
83         
84     }
85    
86     function get($id,$opts)
87     {
88         
89         //print_r($opts);
90         if (!empty($opts['DB_DataObject-debug'])) {
91             DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
92         }
93         
94         //DB_DataObject::debugLevel(1);
95         //date_default_timezone_set('UTC');
96         // phpinfo();exit;
97         $force = empty($opts['force']) ? 0 : 1;
98         
99         $w = DB_DataObject::factory($this->table);
100
101         if (!$w->get($id)) {
102             $this->errorHandler("invalid id\n");
103         }
104         if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
105             
106             
107             $this->errorHandler("send repeat to early\n");
108         }
109         if (!empty($opts['debug'])) {
110             print_r($w);
111             $ff = HTML_FlexyFramework::get();
112             if (!isset($ff->Core_Mailer)) {
113                 $ff->Core_Mailer = array();
114             }
115             HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
116         }
117         
118         $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
119         
120         if (!$force && (!empty($w->msgid) || $sent)) {
121             $ww = clone($w);
122             if (!$sent) { 
123                 $w->sent = $w->sqlValue("NOW()");
124                 $w->update($ww);
125             }    
126             $this->errorHandler("message has been sent already.\n");
127         }
128         
129         $o = $w->object();
130         
131         if ($o === false)  {
132             
133             $ev = $this->addEvent('NOTIFY', $w,
134                             "Notification event cleared (underlying object does not exist)" );;
135             $ww = clone($w);
136             $w->sent = date('Y-m-d H:i:s');
137             $w->msgid = '';
138             $w->event_id = $ev->id;
139             $w->update($ww);
140             $this->errorHandler(date('Y-m-d h:i:s ') . 
141                      "Notification event cleared (underlying object does not exist)" 
142                     ."\n");
143         }
144      
145         
146         
147         $p = $w->person();
148         
149         if (isset($p->active) && empty($p->active)) {
150             $ev = $this->addEvent('NOTIFY', $w,
151                             "Notification event cleared (not user not active any more)" );;
152             $ww = clone($w);
153             $w->sent = date('Y-m-d H:i:s');
154             $w->msgid = '';
155             $w->event_id = $ev->id;
156             $w->update($ww);
157             $this->errorHandler(date('Y-m-d h:i:s ') . 
158                      "Notification event cleared (not user not active any more)" 
159                     ."\n");
160             $this->errorHandler("message has been sent already.\n");
161         }
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         $personid_col = strtolower($w->person_table).'_id';
173         if (isset($w->{$personid_col})) {
174             $lar[$personid_col] = $w->{$personid_col};
175         }
176         
177         
178         $l->setFrom( $lar );       
179         $l->whereAdd('id != '. $w->id);
180         $l->orderBy('sent DESC');
181         $l->limit(1);
182         $ar = $l->fetchAll('sent');
183         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
184         
185         // find last event..
186         $ev = DB_DataObject::factory('Events');
187         $ev->on_id = $w->id;                           // int(11)
188         $ev->on_table = $this->table;
189         $ev->limit(1);
190         $ev->orderBy('event_when DESC');
191         $ar = $ev->fetchAll('event_when');
192         $last_event = empty($ar) ? 0 : $ar[0];
193         $next_try_min = 5;
194         if ($last_event) {
195             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
196         }
197         $next_try = $next_try_min . ' MINUTES';
198          
199         // this may modify $p->email. (it will not update it though)
200         $email =  $this->makeEmail($o, $p, $last, $w, $force);
201         
202         if ($email === true)  {
203             
204             $ev = $this->addEvent('NOTIFY', $w,
205                             "Notification event cleared (not required any more)" );;
206             $ww = clone($w);
207             $w->sent = date('Y-m-d H:i:s');
208             $w->msgid = '';
209             $w->event_id = $ev->id;
210             $w->update($ww);
211             $this->errorHandler(date('Y-m-d h:i:s ') . 
212                      "Notification event cleared (not required any more)" 
213                     ."\n");
214         }
215         if (is_a($email, 'PEAR_Error')) {
216             $email =array(
217                 'error' => $email->toString()
218             );
219         }
220         
221         if (empty($p) && !empty($email['recipients'])) {
222             // make a fake person..
223             $p = (object) array(
224                 'email' => $email['recipients']
225             );
226         }
227          
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); 
232             $ww = clone($w);
233             $w->sent = date('Y-m-d H:i:s');
234             $w->msgid = '';
235             $w->event_id = $ev->id;
236             $w->update($ww);
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)
240                     ."\n");
241         }
242         
243         
244         if (isset($email['later'])) {
245             $old = clone($w);
246             $w->act_when = $email['later'];
247             $w->update($old);
248             $this->errorHandler(date('Y-m-d h:i:s ') . " 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       
276         
277         require_once 'Validate.php';
278         if (!Validate::email($p->email, true)) {
279             $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
280             $ww = clone($w);
281             $w->sent = date('Y-m-d H:i:s');
282             $w->msgid = '';
283             $w->event_id = $ev->id;
284             $w->update($ww);
285             $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
286             
287         }
288         
289         
290         $ff = HTML_FlexyFramework::get();
291         
292         
293         $dom = array_pop(explode('@', $p->email));
294         
295         $mxs = $this->mxs($dom);
296         $ww = clone($w);
297
298         // we might fail doing this...
299         // need to handle temporary failure..
300        
301         
302           // we try for 3 days..
303         $retry = 5;
304         if (strtotime($w->act_start) <  strtotime('NOW - 1 HOUR')) {
305             // older that 1 hour.
306             $retry = 15;
307         }
308         
309         if (strtotime($w->act_start) <  strtotime('NOW - 1 DAY')) {
310             // older that 1 day.
311             $retry = 60;
312         }
313         if (strtotime($w->act_start) <  strtotime('NOW - 2 DAY')) {
314             // older that 1 day.
315             $retry = 120;
316         }
317         
318         if ($mxs === false) {
319             // only retry for 2 day son the MX issue..
320             if ($retry < 120) {
321                 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
322                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
323                 $w->update($ww);
324                 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
325             }
326             
327             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
328             $w->sent = date('Y-m-d H:i:s');
329             $w->msgid = '';
330             $w->event_id = $ev->id;
331             $w->update($ww);
332             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  BAD EMAIL - {$p->email} \n");
333             
334             
335         }
336         
337         
338         
339         
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 = date('Y-m-d H:i:s');
343             $w->msgid = '';
344             $w->event_id = $ev->id;
345             $w->update($ww);
346             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  GAVE UP TO OLD - {$p->email} \n");
347         }
348         
349         
350         
351         $w->to_email = $p->email; 
352         //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
353         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
354         $w->update($ww);
355         
356         $ww = clone($w);   
357         
358         $fail = false;
359         require_once 'Mail.php';
360         
361         $core_domain = DB_DataObject::factory('core_domain');
362         if(!$core_domain->get('domain', $dom)){
363             $core_domain = DB_DataObject::factory('core_domain');
364             $core_domain->setFrom(array(
365                 'domain' => $dom
366             ));
367             $core_domain->insert();
368         }
369                         
370         foreach($mxs as $mx) {
371             
372             if (!isset($ff->Mail['helo'])) {
373                 $this->errorHandler("config Mail[helo] is not set");
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             if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
390                 
391                 $username = $ff->Mail['username'] ;
392                 $password = $ff->Mail['password'] ;
393                 
394                 if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
395                     
396                     foreach ($ff->Core_Notify['routes'] as $server => $settings){
397                         if(!in_array($dom, $settings['domains'])){
398                             continue;
399                         }
400                         
401                         // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
402                         // if it's newer that '1' minute...
403                         // then shunt it..
404                         
405                         $seconds = floor((60 * 60) / $settings['rate']);
406                         
407                         $core_notify = DB_DataObject::factory($this->table);
408                         $core_notify->domain_id = $core_domain->id;
409                         $core_notify->whereAdd("
410                             sent >= NOW() - INTERVAL $seconds SECONDS
411                         ");
412                         
413                         if($core_notify->count()){
414                             $old = clone($w);
415                             $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
416                             $w->update($old);
417                             $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
418                         }
419                         
420                         // that make's this test obsolete...
421                         /*
422                         
423                         $core_notify = DB_DataObject::factory($this->table);
424                         $core_notify->domain_id = $core_domain->id;
425                         $core_notify->whereAdd("
426                             sent >= NOW() - INTERVAL 1 HOUR
427                         ");
428                         
429                         if($core_notify->count() >= $settings['rate']){
430                             $old = clone($w);
431                             $w->act_when = date("Y-m-d H:i:s", strtotime('+1 HOUR'));
432                             $w->update($old);
433                             $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
434                         }
435                         */
436                         
437                         
438                         
439                         $mailer->host = $server;
440                         $username = $settings['username'];
441                         $password = $settings['password'];
442                         
443                         break;
444                     }
445                     
446                 }
447                 
448                 $mailer->auth = true;
449                 $mailer->username = $username;
450                 $mailer->password = $password;        
451             }
452             
453             $res = $mailer->send($p->email, $email['headers'], $email['body']);
454              
455             
456             if ($res === true) {
457                 // success....
458                 
459                 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
460                 
461                 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
462                 
463                 $ev->writeEventLog($this->debug_str);
464                 
465                 if(strtotime($w->act_when) > strtotime("NOW")){
466                     $w->act_when = date('Y-m-d H:i:s');
467                 }
468                 
469                 $w->sent = date('Y-m-d H:i:s');
470                 $w->msgid = $email['headers']['Message-Id'];
471                 $w->event_id = $ev->id; // sent ok.. - no need to record it..
472                 $w->domain_id = $core_domain->id;
473                 $w->update($ww);
474                 
475                 // enable cc in notify..
476                 if (!empty($email['headers']['Cc'])) {
477                     $cmailer = Mail::factory('smtp',  isset($ff->Mail) ? $ff->Mail : array() );
478                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
479                     $cmailer->send($email['headers']['Cc'],
480                                   $email['headers'], $email['body']);
481                     
482                 }
483                 
484                 if (!empty($email['bcc'])) {
485                     $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
486                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
487                     $res = $cmailer->send($email['bcc'],
488                                   $email['headers'], $email['body']);
489                     if (!$res || is_a($res, 'PEAR_Error')) {
490                         echo "could not send bcc..\n";
491                     } else {
492                         echo "Sent BCC to {$email['bcc']}\n";
493                     }
494                 }
495                 
496                 
497                 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
498             }
499             // what type of error..
500             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
501             if (!empty($res->code) && $res->code == 10001) {
502                 // fake greylist if timed out.
503                 $code = 421;
504             }
505             
506             if ($code < 0) {
507                 $this->debug($res->message);
508                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
509             }
510             // give up after 2 days..
511             if (in_array($code, array( 421, 450, 451, 452))   && $next_try_min < (2*24*60)) {
512                 // try again later..
513                 // check last event for this item..
514                 //$errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
515                 $errmsg=  $res->userinfo['smtpcode'] . ': ' .$res->message ;
516                 if (!empty($res->userinfo['smtptext'])) {
517                     $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
518                 }
519                 //print_r($res);
520                 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
521                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
522                 $w->domain_id = $core_domain->id;
523                 $w->update($ww);
524                 
525                 
526                 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED -  $errmsg \n");
527             }
528             $fail = true;
529             break;
530         }
531         if ($fail || $next_try_min > (2*24*60)) {
532         // fail.. = log and give up..
533             $errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
534             if (isset($res->userinfo['smtptext'])) {
535                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
536             }
537             
538             $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
539                        $errmsg);
540             $w->sent = date('Y-m-d H:i:s');
541             $w->msgid = '';
542             $w->event_id = $ev->id;
543             $w->domain_id = $core_domain->id;
544             $w->update($ww);
545             $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
546         }
547         
548         // handle no host availalbe forever...
549         if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
550             $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
551             $w->sent = date('Y-m-d H:i:s');
552             $w->msgid = '';
553             $w->event_id = $ev->id;
554             $w->domain_id = $core_domain->id;
555             $w->update($ww);
556             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
557         }
558         
559         
560         $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
561         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
562         $w->domain_id = $core_domain->id;
563         $w->update($ww);
564         $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
565
566         
567     }
568     function mxs($fqdn)
569     {
570         $ff = HTML_FlexyFramework::get();
571         if (isset($ff->Pman_Core_NotifySend['host'])) {
572             return array($ff->Pman_Core_NotifySend['host']);
573         }
574         
575         $mx_records = array();
576         $mx_weight = array();
577         $mxs = array();
578         if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
579             if (!checkdnsrr($fqdn)) {
580                 return false;
581             }
582             return array($fqdn);
583         }
584         
585         asort($mx_weight,SORT_NUMERIC);
586         
587         foreach($mx_weight as $k => $weight) {
588             $mxs[] = $mx_records[$k];
589         }
590         return $mxs;
591     }
592     
593     /**
594      * wrapper to call object->toEmail()
595      *
596      * return
597      *   {
598         headers : {AssocArray},
599         body: {String}
600         
601         // optional..
602         error :  {String} // error message in log.
603         send-to: {String} // use to override rcpt
604          
605      }
606      **/
607     function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
608     {
609         $m = 'notify'. $notify->evtype;
610         //var_dump(get_class($object) . '::' .$m);
611         if (!empty($notify->evtype) && method_exists($object,$m)) {
612             echo "calling :" . get_class($object) . '::' .$m . "\n";
613             return $object->$m($rcpt, $last_sent_date, $notify, $force);
614         }
615         
616         $type = explode('::', $notify->evtype);
617         
618         if(!empty($type[1]) && method_exists($object,$type[1])){
619             $m = $type[1];
620             echo "calling :" . get_class($object) . '::' .$m . "\n";
621             return $object->$m($rcpt, $last_sent_date, $notify, $force);
622         }
623                 
624         if (!method_exists($object, 'toEmail')) {
625             //var_Dump($object);
626             //exit;
627         }
628         
629         return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
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     }
651     
652     function errorHandler($msg, $success = false)
653     {
654         if($this->error_handler == 'exception'){
655             if()
656             throw new Exception($msg);
657         }
658         
659         die($msg);
660         
661         
662     }
663 }