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