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