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