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