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