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