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