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