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