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