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
30
31 class Pman_Core_NotifySend extends Pman
32 {
33     static $cli_desc = "Send out single notification email (usually called from  Core/Notify)";
34     
35     static $cli_opts = array(
36         'debug' => array(
37             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
38             'default' => 0,
39             'short' => 'v',
40             'min' => 0,
41             'max' => 0,
42             
43         ),
44         'DB_DataObject-debug' => array(
45             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
46             'default' => 0,
47             'short' => 'd',
48             'min' => 1,
49             'max' => 1,
50             
51         ),
52         'force' => array(
53             'desc' => 'Force redelivery, even if it has been sent before or not queued...',
54             'default' => 0,
55             'short' => 'f',
56             'min' => 0,
57             'max' => 0,
58         ),
59         'send-to' => array(
60             'desc' => 'Send the message to this address, rather than the one listed.',
61             'default' => '',
62             'short' => 't',
63             'min' => 0,
64             'max' => 1,
65         )
66         
67         
68         
69     );
70     var $table = 'core_notify';
71     var $error_handler = 'die';
72     
73     function getAuth()
74     {
75         $ff = HTML_FlexyFramework::get();
76         if (!$ff->cli) {
77             $this->errorHandler("access denied");
78         }
79         //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
80         return true;
81         
82     }
83    
84     function get($id,$opts)
85     {
86         
87         //print_r($opts);
88         if (!empty($opts['DB_DataObject-debug'])) {
89             DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
90         }
91         
92         //DB_DataObject::debugLevel(1);
93         //date_default_timezone_set('UTC');
94         // phpinfo();exit;
95         $force = empty($opts['force']) ? 0 : 1;
96         
97         $w = DB_DataObject::factory($this->table);
98         
99         if (!$w->get($id)) {
100             $this->errorHandler("invalid id\n");
101         }
102         if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
103             
104             
105             $this->errorHandler("send repeat to early\n");
106         }
107         if (!empty($opts['debug'])) {
108             print_r($w);
109             $ff = HTML_FlexyFramework::get();
110             if (!isset($ff->Core_Mailer)) {
111                 $ff->Core_Mailer = array();
112             }
113             HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
114         }
115         
116         $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
117         
118         if (!$force && (!empty($w->msgid) || $sent)) {
119             $ww = clone($w);
120             if (!$sent) { 
121                 $w->sent = $w->sqlValue("NOW()");
122                 $w->update($ww);
123             }    
124             $this->errorHandler("message has been sent already.\n");
125         }
126         
127         $o = $w->object();
128         
129         if ($o === false)  {
130             
131             $ev = $this->addEvent('NOTIFY', $w,
132                             "Notification event cleared (underlying object does not exist)" );;
133             $ww = clone($w);
134             $w->sent = date('Y-m-d H:i:s');
135             $w->msgid = '';
136             $w->event_id = $ev->id;
137             $w->update($ww);
138             $this->errorHandler(date('Y-m-d h:i:s ') . 
139                      "Notification event cleared (underlying object does not exist)" 
140                     ."\n");
141         }
142      
143         
144         
145         $p = $w->person();
146         
147         if (isset($p->active) && empty($p->active)) {
148             $ev = $this->addEvent('NOTIFY', $w,
149                             "Notification event cleared (not user not active any more)" );;
150             $ww = clone($w);
151             $w->sent = date('Y-m-d H:i:s');
152             $w->msgid = '';
153             $w->event_id = $ev->id;
154             $w->update($ww);
155             $this->errorHandler(date('Y-m-d h:i:s ') . 
156                      "Notification event cleared (not user not active any more)" 
157                     ."\n");
158             $this->errorHandler("message has been sent already.\n");
159         }
160         
161         
162         // let's work out the last notification sent to this user..
163         $l = DB_DataObject::factory($this->table);
164         
165         $lar = array(
166                 'ontable' => $w->ontable,
167                 'onid' => $w->onid,
168         );
169         // only newer version of the database us this..
170         $personid_col = strtolower($w->person_table).'_id';
171         if (isset($w->{$personid_col})) {
172             $lar[$personid_col] = $w->{$personid_col};
173         }
174         
175         
176         $l->setFrom( $lar );       
177         $l->whereAdd('id != '. $w->id);
178         $l->orderBy('sent DESC');
179         $l->limit(1);
180         $ar = $l->fetchAll('sent');
181         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
182         
183         // find last event..
184         $ev = DB_DataObject::factory('Events');
185         $ev->on_id = $w->id;                           // int(11)
186         $ev->on_table = $this->table;
187         $ev->limit(1);
188         $ev->orderBy('event_when DESC');
189         $ar = $ev->fetchAll('event_when');
190         $last_event = empty($ar) ? 0 : $ar[0];
191         $next_try_min = 5;
192         if ($last_event) {
193             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
194         }
195         $next_try = $next_try_min . ' MINUTES';
196          
197         // this may modify $p->email. (it will not update it though)
198         $email =  $this->makeEmail($o, $p, $last, $w, $force);
199         
200         if ($email === true)  {
201             
202             $ev = $this->addEvent('NOTIFY', $w,
203                             "Notification event cleared (not required any more)" );;
204             $ww = clone($w);
205             $w->sent = date('Y-m-d H:i:s');
206             $w->msgid = '';
207             $w->event_id = $ev->id;
208             $w->update($ww);
209             $this->errorHandler(date('Y-m-d h:i:s ') . 
210                      "Notification event cleared (not required any more)" 
211                     ."\n");
212         }
213         if (is_a($email, 'PEAR_Error')) {
214             $email =array(
215                 'error' => $email->toString()
216             );
217         }
218         
219         if (empty($p) && !empty($email['recipients'])) {
220             // make a fake person..
221             $p = (object) array(
222                 'email' => $email['recipients']
223             );
224         }
225          
226         if ($email === false || isset($email['error']) || empty($p)) {
227             // object returned 'false' - it does not know how to send it..
228             $ev = $this->addEvent('NOTIFY', $w, isset($email['error'])  ?
229                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable); 
230             $ww = clone($w);
231             $w->sent = date('Y-m-d H:i:s');
232             $w->msgid = '';
233             $w->event_id = $ev->id;
234             $w->update($ww);
235             $this->errorHandler(date('Y-m-d h:i:s ') . 
236                     (isset($email['error'])  ?
237                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable)
238                     ."\n");
239         }
240         
241         
242         if (isset($email['later'])) {
243             $old = clone($w);
244             $w->act_when = $email['later'];
245             $w->update($old);
246             $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
247         }
248         
249          
250         if (empty($email['headers']['Message-Id'])) {
251             $HOST = gethostname();
252             $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
253             
254         }
255         
256         
257             
258         
259         //$p->email = 'alan@akbkhome.com'; //for testing..
260         //print_r($email);exit;
261         // should we fetch the watch that caused it.. - which should contain the method to call..
262         // --send-to=test@xxx.com
263        
264         if (!empty($email['send-to'])) {
265             $p->email = $email['send-to'];
266         }
267          if (!empty($opts['send-to'])) {
268             $p->email = $opts['send-to'];
269         }
270         
271             // since some of them have spaces?!?!
272         $p->email = trim($p->email);
273       
274         
275         require_once 'Validate.php';
276         if (!Validate::email($p->email, true)) {
277             $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
278             $ww = clone($w);
279             $w->sent = date('Y-m-d H:i:s');
280             $w->msgid = '';
281             $w->event_id = $ev->id;
282             $w->update($ww);
283             $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
284             
285         }
286         
287         
288         $ff = HTML_FlexyFramework::get();
289         
290         
291         $dom = array_pop(explode('@', $p->email));
292         
293         $mxs = $this->mxs($dom);
294         $ww = clone($w);
295
296         // we might fail doing this...
297         // need to handle temporary failure..
298        
299         
300           // we try for 3 days..
301         $retry = 5;
302         if (strtotime($w->act_start) <  strtotime('NOW - 1 HOUR')) {
303             // older that 1 hour.
304             $retry = 15;
305         }
306         
307         if (strtotime($w->act_start) <  strtotime('NOW - 1 DAY')) {
308             // older that 1 day.
309             $retry = 60;
310         }
311         if (strtotime($w->act_start) <  strtotime('NOW - 2 DAY')) {
312             // older that 1 day.
313             $retry = 120;
314         }
315         
316         if ($mxs === false) {
317             // only retry for 2 day son the MX issue..
318             if ($retry < 120) {
319                 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
320                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
321                 $w->update($ww);
322                 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
323             }
324             
325             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
326             $w->sent = date('Y-m-d H:i:s');
327             $w->msgid = '';
328             $w->event_id = $ev->id;
329             $w->update($ww);
330             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  BAD EMAIL - {$p->email} \n");
331             
332             
333         }
334         
335         
336         
337         
338         if (!$force && strtotime($w->act_start) <  strtotime('NOW - 14 DAY')) {
339             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
340             $w->sent = date('Y-m-d H:i:s');
341             $w->msgid = '';
342             $w->event_id = $ev->id;
343             $w->update($ww);
344             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  GAVE UP TO OLD - {$p->email} \n");
345         }
346         
347         
348         
349         $w->to_email = $p->email; 
350         //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
351         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
352         $w->update($ww);
353         
354         $ww = clone($w);   
355         
356         $fail = false;
357         require_once 'Mail.php';
358         
359         foreach($mxs as $mx) {
360             
361             if (!isset($ff->Mail['helo'])) {
362                 $this->errorHandler("config Mail[helo] is not set");
363             }
364             $this->debug_str = '';
365             $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
366             $mailer = Mail::factory('smtp', array(
367                     'host'    => $mx ,
368                     'localhost' => $ff->Mail['helo'],
369                     'timeout' => 15,
370                     'socket_options' =>  isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
371                     //'debug' => isset($opts['debug']) ?  1 : 0,
372                     'debug' => 1,
373                     'debug_handler' => array($this, 'debugHandler')
374                 ));
375             
376             // if the host is the mail host + it's authenticated add auth details
377             // this normally will happen if you sent  Pman_Core_NotifySend['host']
378             if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
379                 
380                 $username = $ff->Mail['username'] ;
381                 $password = $ff->Mail['password'] ;
382                 
383                 if(!empty($ff->Core_Notify)){
384                     
385                     foreach ($ff->Core_Notify['routes'] as $server => $settings){
386                         if(!in_array($dom, $settings['domains'])){
387                             continue;
388                         }
389                         
390                         $mailer->host = $server;
391                         $username = $settings['username'];
392                         $password = $settings['password'];
393                         
394                         break;
395                     }
396                     
397                 }
398                 
399                 $mailer->auth = true;
400                 $mailer->username = $username;
401                 $mailer->password = $password;        
402             }
403             
404             $res = $mailer->send($p->email, $email['headers'], $email['body']);
405              
406             
407             if ($res === true) {
408                 // success....
409                 
410                 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
411                 
412                 $ev->writeEventLog($this->debug_str);
413                 
414                 $w->sent = date('Y-m-d H:i:s');
415                 $w->msgid = $email['headers']['Message-Id'];
416                 $w->event_id = $ev->id; // sent ok.. - no need to record it..
417                 $w->update($ww);
418                 
419                 // enable cc in notify..
420                 if (!empty($email['headers']['Cc'])) {
421                     $cmailer = Mail::factory('smtp',  isset($ff->Mail) ? $ff->Mail : array() );
422                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
423                     $cmailer->send($email['headers']['Cc'],
424                                   $email['headers'], $email['body']);
425                     
426                 }
427                 
428                 if (!empty($email['bcc'])) {
429                     $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
430                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
431                     $res = $cmailer->send($email['bcc'],
432                                   $email['headers'], $email['body']);
433                     if (!$res || is_a($res, 'PEAR_Error')) {
434                         echo "could not send bcc..\n";
435                     } else {
436                         echo "Sent BCC to {$email['bcc']}\n";
437                     }
438                 }
439                 
440                 
441                 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n");
442             }
443             // what type of error..
444             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
445             if (!empty($res->code) && $res->code == 10001) {
446                 // fake greylist if timed out.
447                 $code = 421;
448             }
449             
450             if ($code < 0) {
451                 $this->debug($res->message);
452                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
453             }
454             // give up after 2 days..
455             if (in_array($code, array( 421, 450, 451, 452))   && $next_try_min < (2*24*60)) {
456                 // try again later..
457                 // check last event for this item..
458                 //$errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
459                 $errmsg=  $res->userinfo['smtpcode'] . ': ' .$res->message ;
460                 if (!empty($res->userinfo['smtptext'])) {
461                     $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
462                 }
463                 //print_r($res);
464                 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
465                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
466                 $w->update($ww);
467                 
468                 
469                 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED -  $errmsg \n");
470             }
471             $fail = true;
472             break;
473         }
474         if ($fail || $next_try_min > (2*24*60)) {
475         // fail.. = log and give up..
476             $errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
477             if (isset($res->userinfo['smtptext'])) {
478                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
479             }
480             
481             $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
482                        $errmsg);
483             $w->sent = date('Y-m-d H:i:s');
484             $w->msgid = '';
485             $w->event_id = $ev->id;
486             $w->update($ww);
487             $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
488         }
489         
490         // handle no host availalbe forever...
491         if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
492             $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
493             $w->sent = date('Y-m-d H:i:s');
494             $w->msgid = '';
495             $w->event_id = $ev->id;
496             $w->update($ww);
497             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
498         }
499         
500         
501         $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
502         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
503         $w->update($ww);
504         $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
505
506         
507     }
508     function mxs($fqdn)
509     {
510         $ff = HTML_FlexyFramework::get();
511         if (isset($ff->Pman_Core_NotifySend['host'])) {
512             return array($ff->Pman_Core_NotifySend['host']);
513         }
514         
515         $mx_records = array();
516         $mx_weight = array();
517         $mxs = array();
518         if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
519             if (!checkdnsrr($fqdn)) {
520                 return false;
521             }
522             return array($fqdn);
523         }
524         
525         asort($mx_weight,SORT_NUMERIC);
526         
527         foreach($mx_weight as $k => $weight) {
528             $mxs[] = $mx_records[$k];
529         }
530         return $mxs;
531     }
532     
533     /**
534      * wrapper to call object->toEmail()
535      *
536      * return
537      *   {
538         headers : {AssocArray},
539         body: {String}
540         
541         // optional..
542         error :  {String} // error message in log.
543         send-to: {String} // use to override rcpt
544          
545      }
546      **/
547     function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
548     {
549         $m = 'notify'. $notify->evtype;
550         //var_dump(get_class($object) . '::' .$m);
551         if (!empty($notify->evtype) && method_exists($object,$m)) {
552             echo "calling :" . get_class($object) . '::' .$m . "\n";
553             return $object->$m($rcpt, $last_sent_date, $notify, $force);
554         }
555         
556         $type = explode('::', $notify->evtype);
557         
558         if(!empty($type[1]) && method_exists($object,$type[1])){
559             $m = $type[1];
560             echo "calling :" . get_class($object) . '::' .$m . "\n";
561             return $object->$m($rcpt, $last_sent_date, $notify, $force);
562         }
563                 
564         if (!method_exists($object, 'toEmail')) {
565             //var_Dump($object);
566             //exit;
567         }
568         
569         return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
570     }
571     
572     function debug($str)
573     {
574         if (empty($this->cli_args['debug'])) {
575             return;
576             
577         }
578         echo $str . "\n";
579     }
580     function output()
581     {
582         $this->errorHandler("done\n");
583     }
584     var $debug_str = '';
585     
586     function debugHandler ($smtp, $message)
587     {
588         $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
589         $this->debug_str .= $message;
590     }
591     
592     function errorHandler($msg)
593     {
594         if($this->error_handler == 'exception'){
595             throw new Exception($msg);
596         }
597         
598         die($msg);
599         
600         
601     }
602 }