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